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/render_panel.py ADDED
@@ -0,0 +1,1293 @@
1
+ """Codis - Native Render / Preview panel.
2
+
3
+ Modos de renderização:
4
+ - tkinterweb - HtmlFrame com CSS/JS real (quando tkinterweb estiver instalado)
5
+ - Interno - tk.Text com formatação rica (fallback sem dependências extras)
6
+ - Navegador - abre no browser padrão do sistema
7
+
8
+ Tipos suportados: .html .htm .xhtml .md .markdown .svg .rst
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import contextlib
14
+ import importlib.util
15
+ import re
16
+ import threading
17
+ import time
18
+ import tkinter as tk
19
+ import webbrowser
20
+ from collections.abc import Callable
21
+ from pathlib import Path
22
+ from tkinter import ttk
23
+
24
+ from src.constants import FONT_MONO, FONT_UI
25
+ from src.i18n import _t
26
+
27
+ _TKWEB = importlib.util.find_spec("tkinterweb") is not None
28
+ _tkweb = None # type: ignore
29
+
30
+
31
+ def _load_tkweb():
32
+ """Importa ``tkinterweb`` sob demanda; marca como indisponível se falhar."""
33
+ global _tkweb, _TKWEB
34
+ if _tkweb is None:
35
+ try:
36
+ import tkinterweb as mod # type: ignore
37
+
38
+ _tkweb = mod
39
+ except Exception:
40
+ _TKWEB = False
41
+ raise
42
+ return _tkweb
43
+
44
+
45
+ _H_RE = re.compile(r"^(#{1,6})\s+(.+)$", re.M)
46
+ _BOLD_RE = re.compile(r"\*\*(.+?)\*\*", re.DOTALL)
47
+ _IT_RE = re.compile(r"\*(.+?)\*", re.DOTALL)
48
+ _CODE_RE = re.compile(r"`(.+?)`")
49
+ _LINK_RE = re.compile(r"\[([^\]]+)\]\(([^\)]+)\)")
50
+ _HR_RE = re.compile(r"^(?:-{3,}|_{3,}|\*{3,})$", re.M)
51
+ _BCODE_RE = re.compile(r"```(\w*)\n(.*?)```", re.DOTALL)
52
+ _BQ_RE = re.compile(r"^> (.+)$", re.M)
53
+ _UL_RE = re.compile(r"^[*\-+] (.+)$", re.M)
54
+ _OL_RE = re.compile(r"^\d+\. (.+)$", re.M)
55
+ _TABLE_RE = re.compile(r"(\|.+\|\n\|[-| :]+\|\n(?:\|.+\|\n?)+)")
56
+ _STRIKE_RE = re.compile(r"~~(.+?)~~", re.DOTALL)
57
+ _HTML_TAG_RE = re.compile(r"<[^>]+>")
58
+ _HTML_ENTITY_RE = re.compile(r"&(amp|lt|gt|quot|apos|nbsp);")
59
+ _ENTITIES = {"amp": "&", "lt": "<", "gt": ">",
60
+ "quot": '"', "apos": "'", "nbsp": " "}
61
+
62
+
63
+ def _md_table(m: re.Match) -> str:
64
+ lines = [l_.strip() for l_ in m.group(0).strip().splitlines()]
65
+ html = ["<table>"]
66
+ first = True
67
+ for line in lines:
68
+ if re.match(r"^\|[-| :]+\|$", line):
69
+ continue
70
+ cells = [c.strip() for c in line.strip("|").split("|")]
71
+ tag = "th" if first else "td"
72
+ html.append(
73
+ "<tr>" + "".join(f"<{tag}>{c}</{tag}>" for c in cells) + "</tr>")
74
+ first = False
75
+ html.append("</table>")
76
+ return "\n".join(html)
77
+
78
+
79
+ def markdown_to_html(text: str) -> str:
80
+ """Converte texto Markdown para HTML usando regras internas do Codis."""
81
+ text = _BCODE_RE.sub(
82
+ lambda m: f'<pre><code class="language-{m.group(1)}">{m.group(2)}</code></pre>',
83
+ text,
84
+ )
85
+ text = _TABLE_RE.sub(_md_table, text)
86
+ text = _BQ_RE.sub(r"<blockquote>\1</blockquote>", text)
87
+ text = _HR_RE.sub("<hr>", text)
88
+ text = _H_RE.sub(
89
+ lambda m: f"<h{len(m.group(1))}>{m.group(2)}</h{len(m.group(1))}>", text
90
+ )
91
+ text = _STRIKE_RE.sub(r"<del>\1</del>", text)
92
+ text = _BOLD_RE.sub(r"<strong>\1</strong>", text)
93
+ text = _IT_RE.sub(r"<em>\1</em>", text)
94
+ text = _CODE_RE.sub(r"<code>\1</code>", text)
95
+ text = _LINK_RE.sub(r'<a href="\2">\1</a>', text)
96
+ text = _UL_RE.sub(r"<li>\1</li>", text)
97
+ text = _OL_RE.sub(r"<li>\1</li>", text)
98
+ paragraphs = []
99
+ for block in re.split(r"\n{2,}", text.strip()):
100
+ block = block.strip()
101
+ if not block:
102
+ continue
103
+ if re.match(r"^<(h[1-6]|ul|ol|li|table|pre|blockquote|hr)", block):
104
+ paragraphs.append(block)
105
+ else:
106
+ paragraphs.append(f"<p>{block}</p>")
107
+ return "\n".join(paragraphs)
108
+
109
+
110
+ _TEMPLATE = """<!DOCTYPE html>
111
+ <html data-theme="{theme}"><head>
112
+ <meta charset="utf-8"><title>{title}</title>
113
+ <style>
114
+ :root {{
115
+ --bg: {bg};
116
+ --fg: {fg};
117
+ --muted: {muted};
118
+ --code-bg: {code_bg};
119
+ --border: {border};
120
+ --accent: {accent};
121
+ --link: {link};
122
+ }}
123
+ *, *::before, *::after {{ box-sizing: border-box; }}
124
+ html {{ scroll-behavior: smooth; }}
125
+ body {{
126
+ font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
127
+ font-size: 15px;
128
+ line-height: 1.75;
129
+ max-width: 860px;
130
+ margin: 0 auto;
131
+ padding: 2rem 1.5rem 4rem;
132
+ color: var(--fg);
133
+ background: var(--bg);
134
+ -webkit-font-smoothing: antialiased;
135
+ }}
136
+ h1, h2, h3, h4, h5, h6 {{
137
+ color: var(--accent);
138
+ margin-top: 1.8em;
139
+ margin-bottom: 0.5em;
140
+ font-weight: 700;
141
+ line-height: 1.25;
142
+ }}
143
+ h1 {{
144
+ font-size: 2em;
145
+ border-bottom: 2px solid var(--border);
146
+ padding-bottom: 0.3em;
147
+ margin-top: 0;
148
+ }}
149
+ h2 {{
150
+ font-size: 1.5em;
151
+ border-bottom: 1px solid var(--border);
152
+ padding-bottom: 0.2em;
153
+ }}
154
+ h3 {{ font-size: 1.25em; }}
155
+ h4 {{ font-size: 1.1em; }}
156
+ h5, h6 {{ font-size: 1em; color: var(--muted); }}
157
+ p {{ margin: 0.75em 0 1em; }}
158
+ a {{ color: var(--link); text-decoration: none; }}
159
+ a:hover {{ text-decoration: underline; }}
160
+ code {{
161
+ font-family: 'Cascadia Code', 'Fira Code', 'Consolas', monospace;
162
+ font-size: 0.875em;
163
+ background: var(--code-bg);
164
+ color: var(--accent);
165
+ padding: 0.18em 0.4em;
166
+ border-radius: 5px;
167
+ border: 1px solid var(--border);
168
+ }}
169
+ pre {{
170
+ font-family: 'Cascadia Code', 'Fira Code', 'Consolas', monospace;
171
+ background: var(--code-bg);
172
+ border: 1px solid var(--border);
173
+ border-radius: 10px;
174
+ padding: 1.1em 1.4em;
175
+ overflow: auto;
176
+ font-size: 0.875em;
177
+ line-height: 1.6;
178
+ margin: 1.2em 0;
179
+ }}
180
+ pre code {{
181
+ background: transparent;
182
+ color: var(--fg);
183
+ padding: 0;
184
+ border: none;
185
+ border-radius: 0;
186
+ font-size: inherit;
187
+ }}
188
+ blockquote {{
189
+ border-left: 4px solid var(--accent);
190
+ margin: 1em 0;
191
+ padding: 0.6em 1.2em;
192
+ color: var(--muted);
193
+ background: var(--code-bg);
194
+ border-radius: 0 8px 8px 0;
195
+ }}
196
+ blockquote p {{ margin: 0.3em 0; }}
197
+ table {{
198
+ border-collapse: collapse;
199
+ width: 100%;
200
+ margin: 1.2em 0;
201
+ font-size: 0.95em;
202
+ overflow-x: auto;
203
+ display: block;
204
+ }}
205
+ th, td {{
206
+ border: 1px solid var(--border);
207
+ padding: 0.55em 0.9em;
208
+ text-align: left;
209
+ }}
210
+ th {{
211
+ background: var(--code-bg);
212
+ font-weight: 600;
213
+ color: var(--accent);
214
+ }}
215
+ tr:nth-child(even) {{ background: var(--code-bg); }}
216
+ tr:hover {{ background: color-mix(in srgb, var(--accent) 8%, var(--bg)); }}
217
+ ul, ol {{
218
+ padding-left: 1.8em;
219
+ margin: 0.5em 0 1em;
220
+ }}
221
+ li {{ margin-bottom: 0.35em; }}
222
+ li > ul, li > ol {{ margin: 0.25em 0; }}
223
+ hr {{
224
+ border: none;
225
+ border-top: 2px solid var(--border);
226
+ margin: 2em 0;
227
+ }}
228
+ img {{
229
+ max-width: 100%;
230
+ height: auto;
231
+ border-radius: 8px;
232
+ display: block;
233
+ margin: 1em auto;
234
+ }}
235
+ kbd {{
236
+ display: inline-block;
237
+ padding: 0.1em 0.45em;
238
+ font-size: 0.85em;
239
+ font-family: monospace;
240
+ background: var(--code-bg);
241
+ border: 1px solid var(--border);
242
+ border-radius: 4px;
243
+ box-shadow: 0 1px 0 var(--border);
244
+ }}
245
+ details {{ margin: 1em 0; }}
246
+ summary {{
247
+ cursor: pointer;
248
+ font-weight: 600;
249
+ color: var(--accent);
250
+ padding: 0.3em 0;
251
+ }}
252
+ mark {{
253
+ background: color-mix(in srgb, var(--accent) 30%, transparent);
254
+ color: var(--fg);
255
+ padding: 0 0.2em;
256
+ border-radius: 3px;
257
+ }}
258
+ del {{ color: var(--muted); text-decoration: line-through; }}
259
+ .task-list-item {{ list-style: none; }}
260
+ .task-list-item input {{ margin-right: 0.5em; }}
261
+ /* TOC */
262
+ .toc {{
263
+ background: var(--code-bg);
264
+ border: 1px solid var(--border);
265
+ border-radius: 8px;
266
+ padding: 1em 1.5em;
267
+ margin: 1.5em 0;
268
+ font-size: 0.9em;
269
+ }}
270
+ {extra_head}
271
+ </style>
272
+ </head>
273
+ <body>
274
+ {body}
275
+ {extra_scripts}
276
+ </body></html>"""
277
+
278
+ _SERVERS: dict = {}
279
+ _SERVERS_LOCK = threading.Lock()
280
+
281
+
282
+ def _start_server(directory: str) -> int:
283
+ """Inicia (ou reutiliza) um servidor HTTP local somente-loopback para *directory*.
284
+
285
+ Usa ``ThreadingHTTPServer`` para que conexões keep-alive do navegador não
286
+ bloqueiem requisições concorrentes. O import de ``http.server`` é adiado
287
+ até o primeiro uso para não penalizar o startup.
288
+ """
289
+ import functools
290
+ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
291
+
292
+ class _QuietHandler(SimpleHTTPRequestHandler):
293
+ def log_message(self, *_) -> None:
294
+ """Suprime logs do servidor HTTP embutido - não-op intencional."""
295
+
296
+ with _SERVERS_LOCK:
297
+ port = _SERVERS.get(directory)
298
+ if port is not None:
299
+ return port
300
+ handler = functools.partial(_QuietHandler, directory=directory)
301
+ srv = ThreadingHTTPServer(("127.0.0.1", 0), handler)
302
+ srv.daemon_threads = True
303
+ port = srv.server_address[1]
304
+ threading.Thread(
305
+ target=srv.serve_forever, daemon=True, name="CodisRenderHTTP"
306
+ ).start()
307
+ _SERVERS[directory] = port
308
+ return port
309
+
310
+
311
+ def _strip_html(html: str) -> str:
312
+ text = _HTML_TAG_RE.sub("", html)
313
+ text = _HTML_ENTITY_RE.sub(
314
+ lambda m: _ENTITIES.get(m.group(1), m.group(0)), text)
315
+ return text
316
+
317
+
318
+ def _theme_vars(tmgr=None) -> dict:
319
+ """Extrai variáveis de cor do tema atual."""
320
+ if tmgr:
321
+ t = tmgr.theme
322
+ bh = t.editor_bg.lstrip("#")
323
+ r, g, b = int(bh[0:2], 16), int(bh[2:4], 16), int(bh[4:6], 16)
324
+ dark = (0.299 * r + 0.587 * g + 0.114 * b) < 128
325
+ return {
326
+ "theme": "dark" if dark else "light",
327
+ "bg": t.editor_bg,
328
+ "fg": t.fg,
329
+ "muted": t.fg_muted,
330
+ "code_bg": t.input_bg,
331
+ "border": t.border,
332
+ "accent": t.accent,
333
+ "link": getattr(t, "t_link", "#6699ff" if dark else "#0055cc"),
334
+ }
335
+ return {
336
+ "theme": "light",
337
+ "bg": "#fafafa",
338
+ "fg": "#1a1a1a",
339
+ "muted": "#666",
340
+ "code_bg": "#f0f0f0",
341
+ "border": "#ddd",
342
+ "accent": "#0055cc",
343
+ "link": "#0055cc",
344
+ }
345
+
346
+
347
+ def _inject_style(html: str, tmgr=None) -> str:
348
+ """Injeta CSS bonito num HTML existente ou cria documento completo.
349
+
350
+ Lógica:
351
+ - HTML com DOCTYPE + CSS próprio: injeta apenas variáveis CSS para tematizar
352
+ sem sobrescrever o design do autor.
353
+ - HTML com DOCTYPE sem CSS: injeta nossa stylesheet completa.
354
+ - Fragment HTML (sem DOCTYPE): envolve no template completo.
355
+ """
356
+ tv = _theme_vars(tmgr)
357
+ has_doctype = bool(re.search(r"<!DOCTYPE", html, re.I))
358
+ has_style_already = bool(
359
+ re.search(r"<style|<link[^>]+rel=['\"]stylesheet", html, re.I)
360
+ )
361
+
362
+ if has_doctype and has_style_already:
363
+ css_vars = (
364
+ "<style>"
365
+ ":root{"
366
+ f"--bg:{tv['bg']};--fg:{tv['fg']};--muted:{tv['muted']};"
367
+ f"--code-bg:{tv['code_bg']};--border:{tv['border']};"
368
+ f"--accent:{tv['accent']};--link:{tv['link']};"
369
+ "}"
370
+ f"body{{background:var(--bg,{tv['bg']});color:var(--fg,{tv['fg']});}}"
371
+ "</style>\n"
372
+ )
373
+ return re.sub(
374
+ r"(<style[^>]*>|<link[^>]+rel=['\"]stylesheet[^>]*>)",
375
+ css_vars + r"\1",
376
+ html,
377
+ count=1,
378
+ flags=re.I,
379
+ )
380
+
381
+ if has_doctype:
382
+ style_tag = (
383
+ "<style>\n"
384
+ + _TEMPLATE.split("<style>")[1]
385
+ .split("</style>")[0]
386
+ .format(**tv, extra_head="")
387
+ + "\n</style>"
388
+ )
389
+ return re.sub(r"(<head[^>]*>)", rf"\1\n{style_tag}", html, count=1, flags=re.I)
390
+
391
+ return _TEMPLATE.format(
392
+ title="Preview", body=html, extra_head="", extra_scripts="", **tv
393
+ )
394
+
395
+
396
+ class _TextRenderer(tk.Frame):
397
+ """Renderizador usando tk.Text - fallback quando tkinterweb não está disponível."""
398
+
399
+ def __init__(self, parent: tk.Widget, tmgr) -> None:
400
+ t = tmgr.theme
401
+ super().__init__(parent, bg=t.editor_bg)
402
+ self._tmgr = tmgr
403
+ self._build()
404
+
405
+ def _build(self) -> None:
406
+ t = self._tmgr.theme
407
+ bh = t.editor_bg.lstrip("#")
408
+ r, g, b = int(bh[0:2], 16), int(bh[2:4], 16), int(bh[4:6], 16)
409
+ dark = (0.299 * r + 0.587 * g + 0.114 * b) < 128
410
+
411
+ fg = t.fg
412
+ bg = t.editor_bg
413
+ code_bg = t.input_bg
414
+ muted = t.fg_muted
415
+ border_c = t.border
416
+ accent = t.accent
417
+ link_fg = getattr(t, "t_link", "#6699ff" if dark else "#0055cc")
418
+ sel_bg = t.sel_bg
419
+
420
+ self._text = tk.Text(
421
+ self,
422
+ wrap="word",
423
+ bg=bg,
424
+ fg=fg,
425
+ font=(FONT_UI, 11),
426
+ relief="flat",
427
+ bd=0,
428
+ cursor="arrow",
429
+ state="disabled",
430
+ insertbackground=t.cursor,
431
+ selectbackground=sel_bg,
432
+ padx=30,
433
+ pady=20,
434
+ )
435
+ vsb = ttk.Scrollbar(self, orient="vertical", command=self._text.yview)
436
+ self._text.config(yscrollcommand=vsb.set)
437
+ vsb.pack(side="right", fill="y")
438
+ self._text.pack(fill="both", expand=True)
439
+
440
+ self._text.tag_configure(
441
+ "h1",
442
+ font=(FONT_UI, 22, "bold"),
443
+ foreground=accent,
444
+ spacing3=10,
445
+ spacing1=20,
446
+ )
447
+ self._text.tag_configure(
448
+ "h2", font=(FONT_UI, 17, "bold"), foreground=accent, spacing3=8, spacing1=16
449
+ )
450
+ self._text.tag_configure(
451
+ "h3", font=(FONT_UI, 14, "bold"), foreground=accent, spacing3=6, spacing1=10
452
+ )
453
+ self._text.tag_configure(
454
+ "h4", font=(FONT_UI, 12, "bold"), foreground=fg, spacing3=4, spacing1=8
455
+ )
456
+ self._text.tag_configure("h5", font=(
457
+ FONT_UI, 11, "bold"), foreground=muted)
458
+ self._text.tag_configure("h6", font=(
459
+ FONT_UI, 10, "bold"), foreground=muted)
460
+
461
+ self._text.tag_configure("bold", font=(FONT_UI, 11, "bold"))
462
+ self._text.tag_configure("italic", font=(FONT_UI, 11, "italic"))
463
+ self._text.tag_configure("bold_it", font=(FONT_UI, 11, "bold italic"))
464
+ self._text.tag_configure(
465
+ "strike", font=(FONT_UI, 11), overstrike=True, foreground=muted
466
+ )
467
+ self._text.tag_configure(
468
+ "code",
469
+ font=(FONT_MONO, 9),
470
+ background=code_bg,
471
+ foreground=getattr(
472
+ t, "t_string", "#f38ba8" if dark else "#c0392b"),
473
+ relief="flat",
474
+ )
475
+ self._text.tag_configure(
476
+ "pre",
477
+ font=(FONT_MONO, 9),
478
+ background=code_bg,
479
+ foreground=fg,
480
+ lmargin1=24,
481
+ lmargin2=24,
482
+ rmargin=24,
483
+ spacing1=8,
484
+ spacing3=8,
485
+ )
486
+ self._text.tag_configure(
487
+ "blockquote",
488
+ foreground=muted,
489
+ lmargin1=30,
490
+ lmargin2=30,
491
+ font=(FONT_UI, 11, "italic"),
492
+ spacing1=4,
493
+ spacing3=4,
494
+ )
495
+ self._text.tag_configure("li", lmargin1=20, lmargin2=36, spacing1=3)
496
+ self._text.tag_configure("oli", lmargin1=20, lmargin2=42, spacing1=3)
497
+ self._text.tag_configure(
498
+ "hr", foreground=border_c, font=(FONT_UI, 5), spacing1=10, spacing3=10
499
+ )
500
+ self._text.tag_configure("link", foreground=link_fg, underline=True)
501
+ self._text.tag_configure(
502
+ "svg_info", foreground=muted, font=(FONT_MONO, 8))
503
+ self._text.tag_configure("th", font=(
504
+ FONT_UI, 10, "bold"), foreground=accent)
505
+ self._text.tag_configure("td", font=(FONT_UI, 10))
506
+ self._text.tag_configure("del", foreground=muted, overstrike=True)
507
+ self._text.tag_configure("muted", foreground=muted, font=(FONT_UI, 10))
508
+
509
+ def render_markdown(self, source: str) -> None:
510
+ """Renderiza o texto Markdown no widget de texto."""
511
+ self._text.config(state="normal")
512
+ self._text.delete("1.0", "end")
513
+ try:
514
+ import markdown as mdlib # type: ignore
515
+
516
+ html = mdlib.markdown(
517
+ source,
518
+ extensions=[
519
+ "fenced_code",
520
+ "tables",
521
+ "toc",
522
+ "attr_list",
523
+ "def_list",
524
+ "footnotes",
525
+ ],
526
+ )
527
+ self._render_html_rich(html)
528
+ except ImportError:
529
+ self._render_md_directly(source)
530
+ self._text.config(state="disabled")
531
+
532
+ def render_html(self, source: str) -> None:
533
+ """Renderiza HTML no widget de texto (sem suporte completo)."""
534
+ self._text.config(state="normal")
535
+ self._text.delete("1.0", "end")
536
+ self._render_html_rich(source)
537
+ self._text.config(state="disabled")
538
+
539
+ def render_svg(self, source: str) -> None:
540
+ """Renderiza SVG no widget de texto (descrição textual)."""
541
+ self._text.config(state="normal")
542
+ self._text.delete("1.0", "end")
543
+ self._text.insert(
544
+ "end",
545
+ "ℹ SVG: visualização interna mostra o código-fonte.\n"
546
+ 'Use "Abrir no Navegador" para renderização visual.\n\n',
547
+ "blockquote",
548
+ )
549
+ self._text.insert("end", source, "svg_info")
550
+ self._text.config(state="disabled")
551
+
552
+ def clear(self, msg: str = "") -> None:
553
+ """Limpa o conteúdo do widget de texto."""
554
+ self._text.config(state="normal")
555
+ self._text.delete("1.0", "end")
556
+ if msg:
557
+ self._text.insert("end", msg, "blockquote")
558
+ self._text.config(state="disabled")
559
+
560
+ def _render_md_directly(self, source: str) -> None:
561
+ """Render Markdown diretamente sem biblioteca externa."""
562
+ lines = source.splitlines(keepends=True)
563
+ in_code = False
564
+ code_buf: list = []
565
+ ol_counter = 0
566
+ for line in lines:
567
+ if line.startswith("```"):
568
+ if not in_code:
569
+ in_code = True
570
+ code_buf = []
571
+ else:
572
+ in_code = False
573
+ self._text.insert("end", "".join(code_buf) + "\n", "pre")
574
+ continue
575
+ if in_code:
576
+ code_buf.append(line)
577
+ continue
578
+ s = line.rstrip("\n\r")
579
+ m = re.match(r"^(#{1,6})\s+(.*)", s)
580
+ if m:
581
+ level = len(m.group(1))
582
+ self._insert_inline(m.group(2) + "\n", f"h{level}")
583
+ ol_counter = 0
584
+ continue
585
+ if re.match(r"^(?:-{3,}|_{3,}|\*{3,})$", s):
586
+ self._text.insert("end", "-" * 64 + "\n", "hr")
587
+ ol_counter = 0
588
+ continue
589
+ m = re.match(r"^> (.+)", s)
590
+ if m:
591
+ self._insert_inline(m.group(1) + "\n", "blockquote")
592
+ continue
593
+ m = re.match(r"^(\d+)\. (.+)", s)
594
+ if m:
595
+ ol_counter += 1
596
+ self._text.insert("end", f" {ol_counter}. ", "oli")
597
+ self._insert_inline(m.group(2) + "\n", "oli")
598
+ continue
599
+ m = re.match(r"^[*\-+] (.+)", s)
600
+ if m:
601
+ self._text.insert("end", " - ", "li")
602
+ self._insert_inline(m.group(1) + "\n", "li")
603
+ continue
604
+ if s:
605
+ self._insert_inline(s + "\n")
606
+ else:
607
+ self._text.insert("end", "\n")
608
+
609
+ def _insert_inline(self, text: str, base: str = "") -> None:
610
+ """Insere texto com formatação inline (bold, italic, code, links)."""
611
+ pattern = re.compile(
612
+ r"(`[^`]+`)"
613
+ r"|(\*\*\*[^*]+\*\*\*)"
614
+ r"|(\*\*[^*]+\*\*)"
615
+ r"|(\*[^*]+\*)"
616
+ r"|(~~[^~]+~~)"
617
+ r"|(\[[^\]]+\]\([^\)]+\))"
618
+ )
619
+ parts = pattern.split(text)
620
+ for p in parts:
621
+ if not p:
622
+ continue
623
+ if p.startswith("`") and p.endswith("`"):
624
+ tags = ("code", base) if base else ("code",)
625
+ self._text.insert("end", p[1:-1], tags)
626
+ elif p.startswith("***") and p.endswith("***"):
627
+ tags = ("bold_it", base) if base else ("bold_it",)
628
+ self._text.insert("end", p[3:-3], tags)
629
+ elif p.startswith("**") and p.endswith("**"):
630
+ tags = ("bold", base) if base else ("bold",)
631
+ self._text.insert("end", p[2:-2], tags)
632
+ elif p.startswith("*") and p.endswith("*") and len(p) > 2:
633
+ tags = ("italic", base) if base else ("italic",)
634
+ self._text.insert("end", p[1:-1], tags)
635
+ elif p.startswith("~~") and p.endswith("~~"):
636
+ tags = ("del", base) if base else ("del",)
637
+ self._text.insert("end", p[2:-2], tags)
638
+ elif p.startswith("["):
639
+ m = _LINK_RE.match(p)
640
+ if m:
641
+ self._text.insert("end", m.group(1), "link")
642
+ else:
643
+ self._text.insert("end", p, (base,) if base else ())
644
+ else:
645
+ self._text.insert("end", p, (base,) if base else ())
646
+
647
+ def _render_html_rich(self, html: str) -> None:
648
+ """Converte HTML para inserções no tk.Text com tags de formatação.
649
+
650
+ Usa tokenização por sentinela \x00TYPE\x00value\x01 para blocos
651
+ estruturais; texto entre tokens é renderizado como parágrafo com
652
+ formatação inline. Corrige o bug do 'not tok' que descartava
653
+ texto normal entre tokens.
654
+ """
655
+ html = re.sub(r"<head\b[^>]*>.*?</head\b[^>]*>", "",
656
+ html, flags=re.DOTALL | re.I)
657
+ html = re.sub(r"<script\b[^>]*>.*?</script\b[^>]*>",
658
+ "", html, flags=re.DOTALL | re.I)
659
+ html = re.sub(r"<style\b[^>]*>.*?</style\b[^>]*>", "",
660
+ html, flags=re.DOTALL | re.I)
661
+
662
+ for i in range(1, 7):
663
+ html = re.sub(
664
+ rf"<h{i}[^>]*>(.*?)</h{i}>",
665
+ lambda m, level=i: f"\n\x00H{level}\x00{_strip_html(m.group(1)).strip()}\x01\n",
666
+ html,
667
+ flags=re.DOTALL | re.I,
668
+ )
669
+
670
+ html = re.sub(
671
+ r"<pre[^>]*><code[^>]*>(.*?)</code></pre>|<pre[^>]*>(.*?)</pre>",
672
+ lambda m: (
673
+ f"\n\x00PRE\x00{_strip_html(m.group(1) or m.group(2))}\x01\n"),
674
+ html,
675
+ flags=re.DOTALL | re.I,
676
+ )
677
+ html = re.sub(
678
+ r"<blockquote[^>]*>(.*?)</blockquote>",
679
+ lambda m: f"\n\x00BQ\x00{_strip_html(m.group(1)).strip()}\x01\n",
680
+ html,
681
+ flags=re.DOTALL | re.I,
682
+ )
683
+
684
+ def _table_to_text(m: re.Match) -> str:
685
+ inner = m.group(1)
686
+ rows = re.findall(r"<tr[^>]*>(.*?)</tr>", inner, re.DOTALL | re.I)
687
+ parts = ["\n\x00HR\x00\x01"]
688
+ for row in rows:
689
+ cells = re.findall(
690
+ r"<t[hd][^>]*>(.*?)</t[hd]>", row, re.DOTALL | re.I)
691
+ line = " │ ".join(_strip_html(c).strip() for c in cells)
692
+ is_th = bool(re.search(r"<th", row, re.I))
693
+ parts.append(f"\x00{'TH' if is_th else 'TD'}\x00{line}\x01")
694
+ parts.append("\x00HR\x00\x01\n")
695
+ return "\n".join(parts)
696
+
697
+ html = re.sub(
698
+ r"<table[^>]*>(.*?)</table>", _table_to_text, html, flags=re.DOTALL | re.I
699
+ )
700
+
701
+ def _process_ol(m: re.Match) -> str:
702
+ counter = [0]
703
+
704
+ def _ol_item(mi: re.Match) -> str:
705
+ counter[0] += 1
706
+ return (
707
+ f"\n\x00OLI\x00{counter[0]}. {_strip_html(mi.group(1)).strip()}\x01"
708
+ )
709
+
710
+ return (
711
+ re.sub(
712
+ r"<li[^>]*>(.*?)</li>", _ol_item, m.group(1), flags=re.DOTALL | re.I
713
+ )
714
+ + "\n"
715
+ )
716
+
717
+ html = re.sub(r"<ol[^>]*>(.*?)</ol>", _process_ol,
718
+ html, flags=re.DOTALL | re.I)
719
+ html = re.sub(
720
+ r"<li[^>]*>(.*?)</li>",
721
+ lambda m: f"\n\x00LI\x00{_strip_html(m.group(1)).strip()}\x01",
722
+ html,
723
+ flags=re.DOTALL | re.I,
724
+ )
725
+
726
+ html = re.sub(r"<hr[^>]*/?>", "\n\x00HR\x00\x01\n", html, flags=re.I)
727
+ html = re.sub(r"<br[^>]*/?>", "\n", html, flags=re.I)
728
+ html = re.sub(
729
+ r"<strong[^>]*>(.*?)</strong>|<b[^>]*>(.*?)</b>",
730
+ lambda m: f"\x00BOLD\x00{m.group(1) or m.group(2)}\x01",
731
+ html,
732
+ flags=re.DOTALL | re.I,
733
+ )
734
+ html = re.sub(
735
+ r"<em[^>]*>(.*?)</em>|<i[^>]*>(.*?)</i>",
736
+ lambda m: f"\x00IT\x00{m.group(1) or m.group(2)}\x01",
737
+ html,
738
+ flags=re.DOTALL | re.I,
739
+ )
740
+ html = re.sub(
741
+ r"<del[^>]*>(.*?)</del>|<s[^>]*>(.*?)</s>",
742
+ lambda m: f"\x00DEL\x00{m.group(1) or m.group(2)}\x01",
743
+ html,
744
+ flags=re.DOTALL | re.I,
745
+ )
746
+ html = re.sub(
747
+ r"<code[^>]*>(.*?)</code>",
748
+ lambda m: f"\x00CODE\x00{_strip_html(m.group(1))}\x01",
749
+ html,
750
+ flags=re.DOTALL | re.I,
751
+ )
752
+ html = re.sub(
753
+ r'<a[^>]*href=["\']([^"\']*)["\'][^>]*>(.*?)</a>',
754
+ lambda m: f"\x00LINK\x00{_strip_html(m.group(2))}\x01",
755
+ html,
756
+ flags=re.DOTALL | re.I,
757
+ )
758
+
759
+ html = _HTML_TAG_RE.sub("", html)
760
+ html = _HTML_ENTITY_RE.sub(
761
+ lambda m: _ENTITIES.get(m.group(1), m.group(0)), html
762
+ )
763
+ html = re.sub(r"&#(\d+);", lambda m: chr(int(m.group(1))), html)
764
+ html = re.sub(r"&#x([0-9a-fA-F]+);",
765
+ lambda m: chr(int(m.group(1), 16)), html)
766
+
767
+ tokens = re.split(
768
+ r"\x00([A-Z0-9]+)\x00(.*?)\x01", html, flags=re.DOTALL)
769
+ idx = 0
770
+ while idx < len(tokens):
771
+ plain = tokens[idx]
772
+ if plain:
773
+ plain = re.sub(r"\n{3,}", "\n\n", plain)
774
+ parts = re.split(r"(\n\n+)", plain)
775
+ for part in parts:
776
+ if part.startswith("\n"):
777
+ self._text.insert("end", "\n")
778
+ elif part.strip():
779
+ self._insert_inline(part.rstrip("\n"))
780
+ self._text.insert("end", "\n")
781
+ idx += 1
782
+ if idx >= len(tokens):
783
+ break
784
+
785
+ kind = tokens[idx]
786
+ idx += 1
787
+ val = tokens[idx]
788
+ idx += 1
789
+
790
+ if kind.startswith("H") and kind[1:].isdigit():
791
+ tag = f"h{kind[1]}"
792
+ self._text.insert("end", val.strip() + "\n", tag)
793
+ elif kind == "PRE":
794
+ self._text.insert("end", val + "\n", "pre")
795
+ elif kind == "BQ":
796
+ self._insert_inline(val.strip() + "\n", "blockquote")
797
+ elif kind == "LI":
798
+ self._text.insert("end", " • ", "li")
799
+ self._insert_inline(val.strip() + "\n", "li")
800
+ elif kind == "OLI":
801
+ self._text.insert("end", f" {val.strip()}\n", "oli")
802
+ elif kind == "TH":
803
+ self._text.insert("end", val.strip() + "\n", "th")
804
+ elif kind == "TD":
805
+ self._text.insert("end", val.strip() + "\n", "td")
806
+ elif kind == "HR":
807
+ self._text.insert("end", "─" * 60 + "\n", "hr")
808
+ elif kind == "BOLD":
809
+ self._insert_inline(_strip_html(val), "bold")
810
+ elif kind == "IT":
811
+ self._insert_inline(_strip_html(val), "italic")
812
+ elif kind == "DEL":
813
+ self._text.insert("end", _strip_html(val), "del")
814
+ elif kind == "CODE":
815
+ self._text.insert("end", val, "code")
816
+ elif kind == "LINK":
817
+ self._text.insert("end", val.strip(), "link")
818
+ else:
819
+ self._insert_inline(val)
820
+
821
+
822
+ class _WebRenderer(tk.Frame):
823
+ """Renderizador usando tkinterweb - suporta CSS/JS real."""
824
+
825
+ def __init__(self, parent: tk.Widget, tmgr) -> None:
826
+ t = tmgr.theme
827
+ super().__init__(parent, bg=t.editor_bg)
828
+ self._tmgr = tmgr
829
+ self._file_path: Path | None = None
830
+ self._frame = _load_tkweb().HtmlFrame(
831
+ self,
832
+ messages_enabled=False,
833
+ vertical_scrollbar=True,
834
+ horizontal_scrollbar=False,
835
+ )
836
+ self._frame.pack(fill="both", expand=True)
837
+
838
+ def set_file_path(self, path: Path | None) -> None:
839
+ """Informa o caminho do arquivo sendo renderizado (para resolver recursos relativos)."""
840
+ self._file_path = path
841
+
842
+ def _load_html_string(self, html: str) -> None:
843
+ """Carrega HTML a partir de string, injetando CSS e resolvendo base_url se possível."""
844
+ styled = _inject_style(html, self._tmgr)
845
+ if self._file_path:
846
+ base = self._file_path.parent.as_uri() + "/"
847
+ with contextlib.suppress(Exception):
848
+ self._frame.load_html(styled, base_url=base)
849
+ return
850
+ self._frame.load_html(styled)
851
+
852
+ def _load_file_via_server(self, path: Path) -> bool:
853
+ """Carrega arquivo HTML diretamente via servidor HTTP local.
854
+
855
+ Isso garante que CSS, imagens e fontes com caminhos relativos
856
+ sejam resolvidos corretamente - sem depender de base_url.
857
+
858
+ Returns:
859
+ True se conseguiu usar o servidor, False se deve usar fallback de string.
860
+ """
861
+ with contextlib.suppress(Exception):
862
+ port = _start_server(str(path.parent))
863
+ url = f"http://127.0.0.1:{port}/{path.name}"
864
+ load_fn = getattr(self._frame, "load_url", None)
865
+ if load_fn:
866
+ load_fn(url)
867
+ return True
868
+ load_fn = getattr(self._frame, "load_website", None)
869
+ if load_fn:
870
+ load_fn(url)
871
+ return True
872
+ return False
873
+
874
+ def render_markdown(self, source: str) -> None:
875
+ """Converte Markdown para HTML e renderiza via tkinterweb."""
876
+ try:
877
+ import markdown as mdlib # type: ignore
878
+
879
+ html = mdlib.markdown(
880
+ source,
881
+ extensions=[
882
+ "fenced_code",
883
+ "tables",
884
+ "toc",
885
+ "attr_list",
886
+ "def_list",
887
+ "footnotes",
888
+ ],
889
+ )
890
+ except ImportError:
891
+ html = markdown_to_html(source)
892
+ tv = _theme_vars(self._tmgr)
893
+ full = _TEMPLATE.format(
894
+ title="Preview", body=html, extra_head="", extra_scripts="", **tv
895
+ )
896
+ self._load_html_string(full)
897
+
898
+ def render_html(self, source: str, from_path: Path | None = None) -> None:
899
+ """Renderiza HTML no widget tkinterweb.
900
+
901
+ Se ``from_path`` estiver disponível, usa o servidor HTTP local para
902
+ que recursos relativos (CSS externo, imagens) sejam carregados.
903
+ """
904
+ path = from_path or self._file_path
905
+ if path and path.exists() and self._load_file_via_server(path):
906
+ return
907
+ self._load_html_string(source)
908
+
909
+ def render_svg(self, source: str) -> None:
910
+ """Embute SVG em HTML e renderiza via tkinterweb."""
911
+ tv = _theme_vars(self._tmgr)
912
+ body = f'<div style="text-align:center;padding:2rem">{source}</div>'
913
+ full = _TEMPLATE.format(
914
+ title="SVG Preview", body=body, extra_head="", extra_scripts="", **tv
915
+ )
916
+ self._load_html_string(full)
917
+
918
+ def clear(self, msg: str = "") -> None:
919
+ """Limpa o painel tkinterweb."""
920
+ tv = _theme_vars(self._tmgr)
921
+ body = f'<p style="color:{tv["muted"]}">{msg}</p>' if msg else ""
922
+ full = _TEMPLATE.format(
923
+ title="", body=body, extra_head="", extra_scripts="", **tv
924
+ )
925
+ self._frame.load_html(full)
926
+
927
+
928
+ def _render_to_browser(path: Path, tmgr=None) -> str | None:
929
+ suffix = path.suffix.lower()
930
+ if suffix not in (".html", ".htm", ".xhtml", ".md", ".markdown", ".svg"):
931
+ return _t("render.unsupported")
932
+
933
+ tv = _theme_vars(tmgr)
934
+ base_dir = path.parent
935
+ content = path.read_text(encoding="utf-8", errors="replace")
936
+
937
+ if suffix in (".md", ".markdown"):
938
+ try:
939
+ import markdown as mdlib # type: ignore
940
+
941
+ body = mdlib.markdown(
942
+ content,
943
+ extensions=["fenced_code", "tables",
944
+ "toc", "attr_list", "footnotes"],
945
+ )
946
+ except ImportError:
947
+ body = markdown_to_html(content)
948
+ tmp = base_dir / f"__codis_preview_{path.stem}.html"
949
+ tmp.write_text(
950
+ _TEMPLATE.format(
951
+ title=path.stem, body=body, extra_head="", extra_scripts="", **tv
952
+ ),
953
+ encoding="utf-8",
954
+ )
955
+ url = tmp.as_uri()
956
+ threading.Thread(
957
+ target=lambda: (time.sleep(120), tmp.unlink()
958
+ if tmp.exists() else None),
959
+ daemon=True,
960
+ ).start()
961
+ elif suffix == ".svg":
962
+ body = f'<div style="text-align:center;padding:2rem">{content}</div>'
963
+ tmp = base_dir / f"__codis_preview_{path.stem}.html"
964
+ tmp.write_text(
965
+ _TEMPLATE.format(
966
+ title=path.stem, body=body, extra_head="", extra_scripts="", **tv
967
+ ),
968
+ encoding="utf-8",
969
+ )
970
+ url = tmp.as_uri()
971
+ threading.Thread(
972
+ target=lambda: (time.sleep(120), tmp.unlink()
973
+ if tmp.exists() else None),
974
+ daemon=True,
975
+ ).start()
976
+ else:
977
+ port = _start_server(str(base_dir))
978
+ url = f"http://127.0.0.1:{port}/{path.name}"
979
+
980
+ try:
981
+ webbrowser.open(url)
982
+ return None
983
+ except OSError as exc:
984
+ return _t("render.browser_fail").format(err=exc)
985
+
986
+
987
+ class RenderPanel(tk.Frame):
988
+ """Painel de Preview nativo com suporte a HTML, Markdown e SVG."""
989
+
990
+ _SUPPORTED = {".html", ".htm", ".xhtml", ".md", ".markdown", ".svg"}
991
+
992
+ def __init__(self, parent: tk.Widget, tmgr, cfg) -> None:
993
+ t = tmgr.theme
994
+ super().__init__(parent, bg=t.panel_bg)
995
+ self._tmgr = tmgr
996
+ self._cfg = cfg
997
+ self._auto_var = tk.BooleanVar(value=False)
998
+ self._cur_path: Path | None = None
999
+ self._get_selection_cb: Callable | None = None
1000
+ self._renderer: _TextRenderer | _WebRenderer | None = None
1001
+ self._build()
1002
+
1003
+ def _build(self) -> None:
1004
+ t = self._tmgr.theme
1005
+
1006
+ for child in self.winfo_children():
1007
+ with contextlib.suppress(tk.TclError):
1008
+ child.destroy()
1009
+
1010
+ tb = tk.Frame(self, bg=t.panel_bg)
1011
+ tb.pack(fill="x", padx=6, pady=(6, 2))
1012
+
1013
+ engine = "tkinterweb" if _TKWEB else "Text"
1014
+ tk.Label(
1015
+ tb,
1016
+ text=f"🌐 {_t('render.title', 'Preview')}",
1017
+ bg=t.panel_bg,
1018
+ fg=t.fg,
1019
+ font=(FONT_UI, 10, "bold"),
1020
+ ).pack(side="left")
1021
+ tk.Label(
1022
+ tb, text=f"[{engine}]", bg=t.panel_bg, fg=t.fg_muted, font=(FONT_UI, 7)
1023
+ ).pack(side="left", padx=4)
1024
+
1025
+ self._refresh_btn = tk.Label(
1026
+ tb,
1027
+ text=_t("render.refresh", "↻ Atualizar"),
1028
+ bg=t.input_bg,
1029
+ fg=t.fg,
1030
+ font=(FONT_UI, 8),
1031
+ cursor="hand2",
1032
+ padx=6,
1033
+ pady=2,
1034
+ )
1035
+ self._refresh_btn.pack(side="right", padx=2)
1036
+ self._refresh_btn.bind("<Button-1>", lambda _: self._do_internal())
1037
+
1038
+ self._file_lbl = tk.Label(
1039
+ self,
1040
+ text=_t("render.no_file", "Nenhum arquivo"),
1041
+ bg=t.panel_bg,
1042
+ fg=t.fg_muted,
1043
+ font=(FONT_UI, 8),
1044
+ anchor="w",
1045
+ wraplength=230,
1046
+ justify="left",
1047
+ )
1048
+ self._file_lbl.pack(fill="x", padx=8, pady=(4, 2))
1049
+
1050
+ btn_row = tk.Frame(self, bg=t.panel_bg)
1051
+ btn_row.pack(fill="x", padx=8, pady=(0, 2))
1052
+
1053
+ def _btn(parent, text, cmd, primary=False):
1054
+ bg = t.accent if primary else t.input_bg
1055
+ fg_c = "#FFF" if primary else t.fg
1056
+ b = tk.Label(
1057
+ parent,
1058
+ text=text,
1059
+ bg=bg,
1060
+ fg=fg_c,
1061
+ font=(FONT_UI, 8, "bold" if primary else "normal"),
1062
+ cursor="hand2",
1063
+ padx=8,
1064
+ pady=4,
1065
+ )
1066
+ b.pack(side="left", padx=(0, 3), pady=2)
1067
+ b.bind("<Button-1>", lambda _, c=cmd: c())
1068
+ b.bind("<Enter>", lambda _, w=b, og=bg: w.config(bg=t.sel_bg))
1069
+ b.bind("<Leave>", lambda _, w=b, og=bg: w.config(bg=og))
1070
+ return b
1071
+
1072
+ _btn(
1073
+ btn_row,
1074
+ _t("render.open_internal", "Preview Interno"),
1075
+ self._do_internal,
1076
+ primary=True,
1077
+ )
1078
+ _btn(
1079
+ btn_row, _t("render.open_browser",
1080
+ "🌐 Abrir no Browser"), self._do_browser
1081
+ )
1082
+ _btn(
1083
+ btn_row, _t("webpreview.open_advanced", "🚀 Preview Web"),
1084
+ self._do_advanced, primary=True,
1085
+ )
1086
+
1087
+ sel_row = tk.Frame(self, bg=t.panel_bg)
1088
+ sel_row.pack(fill="x", padx=8, pady=(0, 2))
1089
+ _btn(
1090
+ sel_row,
1091
+ _t("render.preview_sel", "✂ Preview da Seleção"),
1092
+ self._preview_selection,
1093
+ )
1094
+
1095
+ tk.Checkbutton(
1096
+ self,
1097
+ text=_t("render.auto_preview", "Auto-preview ao salvar"),
1098
+ variable=self._auto_var,
1099
+ bg=t.panel_bg,
1100
+ fg=t.fg_muted,
1101
+ activebackground=t.panel_bg,
1102
+ selectcolor=t.sel_bg,
1103
+ font=(FONT_UI, 8),
1104
+ ).pack(anchor="w", padx=8, pady=(0, 4))
1105
+
1106
+ self._status_lbl = tk.Label(
1107
+ self,
1108
+ text="",
1109
+ bg=t.panel_bg,
1110
+ fg=t.fg_muted,
1111
+ font=(FONT_UI, 8),
1112
+ anchor="w",
1113
+ wraplength=230,
1114
+ justify="left",
1115
+ )
1116
+ self._status_lbl.pack(fill="x", padx=8)
1117
+
1118
+ tk.Frame(self, bg=t.border, height=1).pack(fill="x", padx=4, pady=2)
1119
+
1120
+ self._view_container = tk.Frame(self, bg=t.panel_bg)
1121
+ self._view_container.pack(fill="both", expand=True)
1122
+ self._placeholder_lbl = tk.Label(
1123
+ self._view_container,
1124
+ text=_t("render.no_file", "Nenhum arquivo\nsuportado aberto."),
1125
+ bg=t.panel_bg,
1126
+ fg=t.fg_muted,
1127
+ font=(FONT_UI, 9),
1128
+ wraplength=220,
1129
+ justify="center",
1130
+ )
1131
+ self._placeholder_lbl.pack(expand=True)
1132
+
1133
+ if _TKWEB:
1134
+ tk.Label(
1135
+ self,
1136
+ text=_t("render.tkweb_credit"),
1137
+ bg=t.panel_bg,
1138
+ fg=t.fg_muted,
1139
+ font=(FONT_UI, 7),
1140
+ ).pack(anchor="w", padx=8, pady=(0, 2))
1141
+ else:
1142
+ tk.Label(
1143
+ self,
1144
+ text="ℹ pip install tkinterweb - para preview HTML/CSS real",
1145
+ bg=t.panel_bg,
1146
+ fg=t.fg_muted,
1147
+ font=(FONT_UI, 7),
1148
+ ).pack(anchor="w", padx=8, pady=(0, 2))
1149
+
1150
+ def notify_active_file(self, path) -> None:
1151
+ """Notifica o painel sobre o arquivo atualmente ativo no editor."""
1152
+ if path is None:
1153
+ self._cur_path = None
1154
+ self._file_lbl.config(text=_t("render.no_file", "Nenhum arquivo"))
1155
+ return
1156
+ p = Path(path) if not isinstance(path, Path) else path
1157
+ self._cur_path = p
1158
+ sup = "+" if p.suffix.lower() in self._SUPPORTED else "-"
1159
+ self._file_lbl.config(text=f"{sup} {p.name}")
1160
+ if p.suffix.lower() in self._SUPPORTED and self._cfg.get(
1161
+ "render_internal", True
1162
+ ):
1163
+ self._do_internal()
1164
+
1165
+ def notify_file_saved(self, path) -> None:
1166
+ """Notifica o painel que o arquivo foi salvo (aciona re-render)."""
1167
+ if not self._auto_var.get():
1168
+ return
1169
+ p = Path(path) if not isinstance(path, Path) else path
1170
+ if p.suffix.lower() in self._SUPPORTED:
1171
+ self._do_internal()
1172
+
1173
+ def set_advanced_callback(self, cb: Callable[[Path | None], None] | None) -> None:
1174
+ """Registra o abridor do Preview Web (navegador embutido) do app."""
1175
+ self._advanced_cb = cb
1176
+
1177
+ def _do_advanced(self) -> None:
1178
+ cb = getattr(self, "_advanced_cb", None)
1179
+ if cb is None:
1180
+ self._status(_t("webpreview.unavailable", "Preview Web indisponível."), error=True)
1181
+ return
1182
+ cb(self._cur_path)
1183
+
1184
+ def set_selection_callback(self, cb) -> None:
1185
+ """Registra callback chamado quando o usuário seleciona texto no preview."""
1186
+ self._get_selection_cb = cb
1187
+
1188
+ def _do_internal(self) -> None:
1189
+ p = self._cur_path
1190
+ if p is None:
1191
+ self._status(_t("render.no_file", "Nenhum arquivo"))
1192
+ return
1193
+ suffix = p.suffix.lower()
1194
+ if suffix not in self._SUPPORTED:
1195
+ self._show_placeholder(
1196
+ _t("render.unsupported", "Tipo não suportado"))
1197
+ return
1198
+ self._status(_t("render.rendering", "Renderizando..."))
1199
+ self.update_idletasks()
1200
+ try:
1201
+ source = p.read_text(encoding="utf-8", errors="replace")
1202
+ except OSError as exc:
1203
+ self._status(str(exc), error=True)
1204
+ return
1205
+ view = self._get_renderer()
1206
+ if hasattr(view, "set_file_path"):
1207
+ view.set_file_path(p)
1208
+ if suffix in (".md", ".markdown"):
1209
+ view.render_markdown(source)
1210
+ elif suffix == ".svg":
1211
+ view.render_svg(source)
1212
+ else:
1213
+ if hasattr(view, "render_html"):
1214
+ import inspect
1215
+
1216
+ sig = inspect.signature(view.render_html)
1217
+ if "from_path" in sig.parameters:
1218
+ view.render_html(source, from_path=p)
1219
+ else:
1220
+ view.render_html(source)
1221
+ else:
1222
+ view.render_html(source)
1223
+ self._status(p.name)
1224
+
1225
+ def _do_browser(self) -> None:
1226
+ p = self._cur_path
1227
+ if p is None:
1228
+ self._status(_t("render.no_file", "Nenhum arquivo"), error=True)
1229
+ return
1230
+ if p.suffix.lower() not in self._SUPPORTED:
1231
+ self._status(
1232
+ _t("render.unsupported", "Tipo não suportado"), error=True)
1233
+ return
1234
+ try:
1235
+ err = _render_to_browser(p, self._tmgr)
1236
+ if err:
1237
+ self._status(err, error=True)
1238
+ else:
1239
+ self._status(_t("render.browser_ok", "Aberto no browser."))
1240
+ except OSError as exc:
1241
+ self._status(
1242
+ _t("render.browser_fail", "Erro: {err}").format(err=exc), error=True
1243
+ )
1244
+
1245
+ def _preview_selection(self) -> None:
1246
+ if not self._get_selection_cb:
1247
+ return
1248
+ sel = self._get_selection_cb()
1249
+ if not sel or not sel.strip():
1250
+ self._status(
1251
+ _t("msg.no_selection", "Nenhum texto selecionado."), error=True
1252
+ )
1253
+ return
1254
+ view = self._get_renderer()
1255
+ if sel.lstrip().startswith("#") or re.search(r"\*\*|__|\n#{", sel):
1256
+ view.render_markdown(sel)
1257
+ else:
1258
+ view.render_html(sel)
1259
+ self._status(_t("render.preview_sel", "Preview da seleção"))
1260
+
1261
+ def _get_renderer(self) -> _TextRenderer | _WebRenderer:
1262
+ if self._renderer is None:
1263
+ self._placeholder_lbl.pack_forget()
1264
+ try:
1265
+ if not _TKWEB:
1266
+ raise ImportError("tkinterweb ausente")
1267
+ self._renderer = _WebRenderer(self._view_container, self._tmgr)
1268
+ except Exception:
1269
+ self._renderer = _TextRenderer(
1270
+ self._view_container, self._tmgr)
1271
+ self._renderer.pack(fill="both", expand=True)
1272
+ return self._renderer
1273
+
1274
+ def _show_placeholder(self, msg: str) -> None:
1275
+ if self._renderer:
1276
+ self._renderer.pack_forget()
1277
+ self._renderer = None
1278
+ self._placeholder_lbl.config(text=msg)
1279
+ self._placeholder_lbl.pack(expand=True)
1280
+
1281
+ def _status(self, msg: str, error: bool = False) -> None:
1282
+ t = self._tmgr.theme
1283
+ fg = getattr(t, "err_fg", "#f38ba8") if error else t.fg_muted
1284
+ self._status_lbl.config(text=msg, fg=fg)
1285
+
1286
+ def apply_theme(self, tmgr) -> None:
1287
+ """Aplica o tema ``t`` ao painel de renderização."""
1288
+ self._tmgr = tmgr
1289
+ self._renderer = None
1290
+ for w in self.winfo_children():
1291
+ w.destroy()
1292
+ self.config(bg=tmgr.theme.panel_bg)
1293
+ self._build()