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/plugins/loader.py ADDED
@@ -0,0 +1,571 @@
1
+ """Codis - PluginLoader.
2
+
3
+ Descobre, valida, carrega e descarrega plugins (``.py``, ``.zip`` ou pasta com
4
+ ``plugin.py``). Cada plugin recebe a sua própria instância de :class:`PluginAPI`,
5
+ que é desfeita por completo quando o plugin é desativado.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import importlib.util
12
+ import logging
13
+ import shutil
14
+ import sys
15
+ import traceback
16
+ import types
17
+ import zipfile
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ from src.constants import APP_VERSION, PLUGINS_DIR
22
+ from src.i18n import _t
23
+ from src.plugins.api import (
24
+ PluginAPI,
25
+ PluginManifest,
26
+ _get_plugin_readme,
27
+ _get_plugin_source,
28
+ _load_trusted_plugins,
29
+ _normalize_manifest,
30
+ _save_trusted_plugins,
31
+ )
32
+ from src.plugins.safety import (
33
+ UnsafeArchiveError,
34
+ compat_problem,
35
+ extract_zip,
36
+ fingerprint,
37
+ read_manifest_static,
38
+ scan_plugin,
39
+ )
40
+
41
+ logger = logging.getLogger("Codis")
42
+
43
+ PLUGIN_API_VERSION = "4.0"
44
+
45
+
46
+ def _is_inside(path: Path, root: Path) -> bool:
47
+ """Indica se ``path``, já resolvido, está dentro de ``root`` (ou é o próprio ``root``)."""
48
+ return path == root or root in path.parents
49
+
50
+
51
+ def plugin_id_of(path: Path) -> str:
52
+ """Id do plugin: nome da pasta, ou o nome do arquivo sem extensão."""
53
+ return path.name if path.is_dir() else path.stem
54
+
55
+
56
+ class PluginLoader:
57
+ """Carrega plugins e mantém o estado de cada um.
58
+
59
+ Interface do plugin::
60
+
61
+ MANIFEST = PluginManifest(name="...", version="...", ...)
62
+ def activate(api: PluginAPI) -> None: ...
63
+ def deactivate() -> None: ...
64
+
65
+ Antes de executar qualquer código, o loader lê o manifesto sem importar o módulo,
66
+ confere a compatibilidade e analisa todos os arquivos Python do plugin. A confiança
67
+ fica ligada ao hash do plugin inteiro: mudou qualquer arquivo, a análise é refeita.
68
+ """
69
+
70
+ def __init__(self, app_api: PluginAPI) -> None:
71
+ self._app_api = app_api
72
+ self._t = _t
73
+ self._loaded: dict[str, Any] = {}
74
+ self._apis: dict[str, PluginAPI] = {}
75
+ self._errors: dict[str, str] = {}
76
+ self._active: set[str] = set()
77
+ self._disabled: set[str] = set()
78
+ self._paths: dict[str, Path] = {}
79
+ self._trusted: dict[str, str] = _load_trusted_plugins()
80
+ self._proc_mgr: Any | None = None
81
+ self._loading: list[str] = []
82
+
83
+ # Descoberta
84
+
85
+ def _discover(self) -> list[Path]:
86
+ """Plugins instalados: pastas com ``plugin.py`` primeiro, depois ``.zip`` e ``.py``."""
87
+ PLUGINS_DIR.mkdir(parents=True, exist_ok=True)
88
+ found: list[Path] = []
89
+ seen: set[str] = set()
90
+ for entry in sorted(PLUGINS_DIR.iterdir(), key=lambda p: (not p.is_dir(), p.name)):
91
+ if entry.name.startswith(("_", ".")):
92
+ continue
93
+ pid = plugin_id_of(entry)
94
+ if pid in seen:
95
+ continue
96
+ if (entry.is_dir() and (entry / "plugin.py").exists()) or entry.suffix in (".zip", ".py"):
97
+ found.append(entry)
98
+ seen.add(pid)
99
+ return found
100
+
101
+ def load_all(self) -> None:
102
+ """Carrega todos os plugins instalados, respeitando as dependências entre eles."""
103
+ for path in self._discover():
104
+ if plugin_id_of(path) not in self._loaded:
105
+ self._load_one(path)
106
+
107
+ def _static_manifest(self, path: Path) -> PluginManifest:
108
+ """Manifesto lido da fonte, sem executar o plugin."""
109
+ data = read_manifest_static(_get_plugin_source(path))
110
+ manifest = _normalize_manifest(data) if data else PluginManifest(name="")
111
+ if not manifest.name:
112
+ manifest.name = plugin_id_of(path)
113
+ return manifest
114
+
115
+ # Carga
116
+
117
+ def _fail(self, plugin_id: str, message: str) -> bool:
118
+ self._errors[plugin_id] = message
119
+ logger.warning("Plugin %s: %s", plugin_id, message)
120
+ return False
121
+
122
+ def _load_one(self, path: Path) -> bool:
123
+ """Valida, carrega e ativa o plugin em ``path``. Retorna ``True`` se ficou ativo."""
124
+ plugin_id = plugin_id_of(path)
125
+ if plugin_id in self._loaded:
126
+ return True
127
+ if plugin_id in self._disabled:
128
+ return False
129
+ if plugin_id in self._loading:
130
+ return self._fail(plugin_id, "Dependência circular: " + " -> ".join([*self._loading, plugin_id]))
131
+
132
+ self._loading.append(plugin_id)
133
+ try:
134
+ return self._load_checked(path, plugin_id)
135
+ finally:
136
+ self._loading.remove(plugin_id)
137
+
138
+ def _load_checked(self, path: Path, plugin_id: str) -> bool:
139
+ manifest = self._static_manifest(path)
140
+
141
+ problem = compat_problem(manifest, APP_VERSION, PLUGIN_API_VERSION)
142
+ if problem:
143
+ return self._fail(plugin_id, f"Plugin '{plugin_id}' {problem}.")
144
+
145
+ for dep in manifest.dependencies:
146
+ dep_id = str(dep).strip()
147
+ if not dep_id or dep_id in self._loaded:
148
+ continue
149
+ dep_path = self._descobrir_caminho(dep_id)
150
+ if dep_path is None or not self._load_one(dep_path):
151
+ return self._fail(plugin_id, f"Depende do plugin '{dep_id}', que não pôde ser carregado.")
152
+
153
+ digest = fingerprint(path)
154
+ if digest is None or self._trusted.get(plugin_id) != digest:
155
+ findings = scan_plugin(path)
156
+ if findings.flagged:
157
+ return self._fail(
158
+ plugin_id,
159
+ f"Plugin '{plugin_id}' recusado: {', '.join(findings.flagged)}. "
160
+ "Instale-o pelo painel de Plugins para revisar e aceitar.",
161
+ )
162
+
163
+ app = getattr(self._app_api, "_app", None)
164
+ if app is None:
165
+ # Gerenciador de plugins aberto fora do editor (tela inicial): não há app para
166
+ # o plugin usar, então ele fica instalado e é ativado quando o editor abrir.
167
+ return True
168
+ cfg = getattr(app, "_cfg", None)
169
+ isolate = bool(manifest.isolated and (cfg.get("plugin_isolation", True) if cfg else True))
170
+
171
+ plugin_api: PluginAPI | None = None
172
+ try:
173
+ entry, search = self._resolve_entry(path, plugin_id)
174
+ if isolate:
175
+ mod: Any = types.SimpleNamespace(MANIFEST=manifest, _isolated_process=True, _entry=entry)
176
+ if not self._start_isolated(plugin_id, entry):
177
+ return self._fail(plugin_id, "Não foi possível iniciar o processo isolado do plugin.")
178
+ else:
179
+ mod = self._exec_module(entry, search, plugin_id)
180
+ plugin_api = PluginAPI(app, plugin_id)
181
+ if hasattr(mod, "activate"):
182
+ mod.activate(plugin_api)
183
+ mod._enabled = True
184
+ mod._plugin_path = path
185
+ if plugin_api is not None:
186
+ mod._plugin_api = plugin_api
187
+ self._apis[plugin_id] = plugin_api
188
+ except Exception:
189
+ err = traceback.format_exc()
190
+ if plugin_api is not None:
191
+ with contextlib.suppress(Exception):
192
+ plugin_api._teardown()
193
+ self._drop_modules(plugin_id)
194
+ self._apis.pop(plugin_id, None)
195
+ return self._fail(plugin_id, err)
196
+
197
+ self._loaded[plugin_id] = mod
198
+ self._paths[plugin_id] = path
199
+ self._active.add(plugin_id)
200
+ self._errors.pop(plugin_id, None)
201
+ if digest is not None and self._trusted.get(plugin_id) != digest:
202
+ self._trusted[plugin_id] = digest
203
+ _save_trusted_plugins(self._trusted)
204
+ logger.info("Plugin carregado: %s", manifest.name or plugin_id)
205
+ self._emit_event("plugin_loaded", plugin_id)
206
+ return True
207
+
208
+ def _emit_event(self, event: str, *args: Any) -> None:
209
+ """Avisa os handlers de ``event``; erro de um handler não afeta o plugin nem os outros."""
210
+ try:
211
+ hooks = self._app_api._app._plugin_hooks
212
+ fire = getattr(hooks, "fire", None)
213
+ if fire is not None:
214
+ fire(event, *args)
215
+ else:
216
+ for handler in list(hooks.get(event, [])):
217
+ handler(*args)
218
+ except Exception as exc:
219
+ logger.warning("Handler de '%s' falhou: %s", event, exc)
220
+
221
+ def _start_isolated(self, plugin_id: str, entry: Path) -> bool:
222
+ from src.plugins.process_runner import IsolatedPluginManager
223
+
224
+ if self._proc_mgr is None:
225
+ app = self._app_api._app
226
+ self._proc_mgr = IsolatedPluginManager(app, cfg=getattr(app, "_cfg", None))
227
+ if not self._proc_mgr.launch(plugin_id, entry):
228
+ return False
229
+ self._forward_events(plugin_id)
230
+ return True
231
+
232
+ def _forward_events(self, plugin_id: str) -> None:
233
+ """Entrega os eventos do núcleo ao plugin isolado como ``on_<evento>(dados)``."""
234
+ hooks = self._app_api._app._plugin_hooks
235
+ manager = self._proc_mgr
236
+
237
+ def make(event: str) -> Any:
238
+ def forward(*args: Any) -> None:
239
+ manager.send_event(plugin_id, event, {"args": [str(a) for a in args]})
240
+
241
+ return forward
242
+
243
+ for event in sorted(PluginAPI.CORE_EVENTS):
244
+ hooks.add(event, make(event), owner=plugin_id)
245
+
246
+ def _stop_isolated(self, plugin_id: str) -> None:
247
+ with contextlib.suppress(Exception):
248
+ self._app_api._app._plugin_hooks.remove_owner(plugin_id)
249
+ if self._proc_mgr is not None:
250
+ with contextlib.suppress(Exception):
251
+ self._proc_mgr.shutdown(plugin_id)
252
+
253
+ def _resolve_entry(self, path: Path, plugin_id: str) -> tuple[Path, list[str] | None]:
254
+ """Arquivo de entrada e pasta de busca de submódulos. ZIPs são extraídos antes."""
255
+ if path.suffix == ".py" and path.is_file():
256
+ return path, None
257
+ folder = path
258
+ if path.suffix == ".zip":
259
+ folder = self._extract(path)
260
+ entry = folder / "plugin.py"
261
+ if not entry.exists():
262
+ raise ImportError(f"plugin.py não encontrado em {path.name}")
263
+ return entry, [str(folder)]
264
+
265
+ @staticmethod
266
+ def _extract(path: Path) -> Path:
267
+ """Extrai o ZIP ao lado dele, substituindo a extração anterior só se a nova der certo."""
268
+ if not zipfile.is_zipfile(path):
269
+ raise ImportError(f"Arquivo inválido ou corrompido: {path.name}")
270
+ dest = path.parent / path.stem
271
+ staging = path.parent / f"_{path.stem}.novo"
272
+ shutil.rmtree(staging, ignore_errors=True)
273
+ try:
274
+ with zipfile.ZipFile(path) as zf:
275
+ extract_zip(zf, staging)
276
+ if not (staging / "plugin.py").exists():
277
+ raise ImportError(f"plugin.py não encontrado em {path.name}")
278
+ except (OSError, zipfile.BadZipFile, UnsafeArchiveError) as exc:
279
+ shutil.rmtree(staging, ignore_errors=True)
280
+ raise ImportError(f"Erro ao extrair {path.name}: {exc}") from exc
281
+ except ImportError:
282
+ shutil.rmtree(staging, ignore_errors=True)
283
+ raise
284
+ shutil.rmtree(dest, ignore_errors=True)
285
+ staging.replace(dest)
286
+ return dest
287
+
288
+ @staticmethod
289
+ def _module_name(plugin_id: str) -> str:
290
+ return f"codis_plugin_{plugin_id.replace('.', '_').replace('-', '_')}"
291
+
292
+ def _exec_module(self, entry: Path, search: list[str] | None, plugin_id: str) -> Any:
293
+ """Importa o módulo do plugin; imports relativos entre arquivos do plugin funcionam."""
294
+ name = self._module_name(plugin_id)
295
+ spec = importlib.util.spec_from_file_location(name, entry, submodule_search_locations=search)
296
+ if spec is None or spec.loader is None:
297
+ raise ImportError(f"Não foi possível carregar {entry}")
298
+ mod = importlib.util.module_from_spec(spec)
299
+ sys.modules[name] = mod
300
+ try:
301
+ spec.loader.exec_module(mod)
302
+ except BaseException:
303
+ self._drop_modules(plugin_id)
304
+ raise
305
+ return mod
306
+
307
+ def _drop_modules(self, plugin_id: str) -> None:
308
+ name = self._module_name(plugin_id)
309
+ for key in [k for k in sys.modules if k == name or k.startswith(name + ".")]:
310
+ sys.modules.pop(key, None)
311
+
312
+ # Instalação
313
+
314
+ def load_file(self, path: Path, confirm_cb: Any | None = None) -> bool:
315
+ """Carrega um plugin de fora da pasta de plugins (instalação manual).
316
+
317
+ ``confirm_cb(plugin_id, bloqueados, avisos) -> bool`` pergunta ao usuário se aceita
318
+ um plugin com pontos de atenção. Sem ``confirm_cb``, nada que esteja bloqueado entra.
319
+ """
320
+ plugin_id = plugin_id_of(path)
321
+ digest = fingerprint(path)
322
+ trusted = digest is not None and self._trusted.get(plugin_id) == digest
323
+ if not trusted:
324
+ findings = scan_plugin(path)
325
+ if findings.flagged and confirm_cb is None:
326
+ return self._fail(plugin_id, f"Plugin '{plugin_id}' recusado: {', '.join(findings.flagged)}.")
327
+ if (findings.flagged or findings.warned) and confirm_cb is not None:
328
+ if not confirm_cb(plugin_id, findings.flagged, findings.warned):
329
+ return False
330
+ if digest is not None:
331
+ self._trusted[plugin_id] = digest
332
+ _save_trusted_plugins(self._trusted)
333
+ return self._load_one(path)
334
+
335
+ def install_from_path(
336
+ self,
337
+ src_path: Path,
338
+ confirm_cb: Any | None = None,
339
+ plugin_id: str | None = None,
340
+ ) -> bool:
341
+ """Instala um plugin em ``PLUGINS_DIR`` e o ativa.
342
+
343
+ O conteúdo novo é preparado ao lado e só troca o antigo quando está íntegro; se
344
+ algo falhar, a versão instalada continua como estava.
345
+
346
+ Args:
347
+ src_path: Arquivo ``.py``, ``.zip`` ou pasta do plugin.
348
+ confirm_cb: Pergunta ao usuário se os pontos de atenção devem ser aceitos.
349
+ plugin_id: Id de instalação. Sem ele vale o nome do arquivo (sem extensão);
350
+ quem baixa para um arquivo temporário (a loja) precisa informá-lo.
351
+
352
+ Raises:
353
+ RuntimeError: id inválido, ZIP inseguro ou falha ao copiar os arquivos.
354
+ """
355
+ plugin_id = plugin_id if plugin_id is not None else src_path.stem
356
+ if plugin_id in ("", ".", "..") or Path(plugin_id).name != plugin_id or "\\" in plugin_id:
357
+ raise RuntimeError(f"Nome de plugin inválido: {plugin_id!r}")
358
+
359
+ PLUGINS_DIR.mkdir(parents=True, exist_ok=True)
360
+ staging = PLUGINS_DIR / f"_{plugin_id}.novo"
361
+ shutil.rmtree(staging, ignore_errors=True)
362
+ staging.unlink(missing_ok=True)
363
+ single_file = not (src_path.is_dir() or (src_path.suffix == ".zip" and zipfile.is_zipfile(src_path)))
364
+ dest = PLUGINS_DIR / (f"{plugin_id}.py" if single_file else plugin_id)
365
+
366
+ try:
367
+ if single_file:
368
+ shutil.copy2(src_path, staging)
369
+ elif src_path.is_dir():
370
+ shutil.copytree(src_path, staging)
371
+ else:
372
+ with zipfile.ZipFile(src_path) as zf:
373
+ extract_zip(zf, staging)
374
+ if not single_file and not (staging / "plugin.py").exists():
375
+ raise RuntimeError("plugin.py não encontrado no pacote.")
376
+ except (OSError, shutil.Error, zipfile.BadZipFile, UnsafeArchiveError, RuntimeError) as exc:
377
+ shutil.rmtree(staging, ignore_errors=True)
378
+ staging.unlink(missing_ok=True)
379
+ raise RuntimeError(f"Falha ao instalar plugin: {exc}") from exc
380
+
381
+ self._desativar_plugin(plugin_id)
382
+ self._errors.pop(plugin_id, None)
383
+ for old in (PLUGINS_DIR / plugin_id, PLUGINS_DIR / f"{plugin_id}.py", PLUGINS_DIR / f"{plugin_id}.zip"):
384
+ if old == dest:
385
+ continue
386
+ if old.is_dir():
387
+ shutil.rmtree(old, ignore_errors=True)
388
+ else:
389
+ old.unlink(missing_ok=True)
390
+ if dest.is_dir():
391
+ shutil.rmtree(dest, ignore_errors=True)
392
+ staging.replace(dest)
393
+ return self.load_file(dest, confirm_cb)
394
+
395
+ # Ciclo de vida
396
+
397
+ def _deactivate(self, plugin_id: str, mod: Any, api: PluginAPI | None) -> None:
398
+ """Chama ``deactivate()``, desfaz tudo o que o plugin registrou e para o processo isolado."""
399
+ if hasattr(mod, "deactivate"):
400
+ try:
401
+ mod.deactivate()
402
+ except Exception as exc:
403
+ logger.warning("deactivate() de '%s' falhou: %s", plugin_id, exc)
404
+ if api is not None:
405
+ try:
406
+ api._teardown()
407
+ except Exception as exc:
408
+ logger.warning("Limpeza de '%s' falhou: %s", plugin_id, exc)
409
+ if getattr(mod, "_isolated_process", False):
410
+ self._stop_isolated(plugin_id)
411
+
412
+ def _desativar_plugin(self, plugin_id: str) -> None:
413
+ """Desativa e remove um plugin da memória sem apagar do disco."""
414
+ mod = self._loaded.pop(plugin_id, None)
415
+ api = self._apis.pop(plugin_id, None)
416
+ if mod is not None:
417
+ self._deactivate(plugin_id, mod, api)
418
+ self._drop_modules(plugin_id)
419
+ self._active.discard(plugin_id)
420
+ self._emit_event("plugin_unloaded", plugin_id)
421
+
422
+ def unload(self, plugin_id: str) -> bool:
423
+ """Descarrega um plugin da memória (não apaga do disco)."""
424
+ if plugin_id not in self._loaded:
425
+ return False
426
+ self._desativar_plugin(plugin_id)
427
+ return True
428
+
429
+ def uninstall(self, plugin_id: str) -> bool:
430
+ """Desativa o plugin e apaga os arquivos, os dados e a confiança dele."""
431
+ self.unload(plugin_id)
432
+ path = self._paths.pop(plugin_id, None) or self._descobrir_caminho(plugin_id)
433
+ if path is None or not path.exists():
434
+ return False
435
+ try:
436
+ if path.is_dir():
437
+ shutil.rmtree(path)
438
+ else:
439
+ path.unlink()
440
+ if path.suffix == ".zip":
441
+ shutil.rmtree(path.parent / path.stem, ignore_errors=True)
442
+ except OSError as exc:
443
+ logger.warning("Erro ao desinstalar plugin %s: %s", plugin_id, exc)
444
+ return False
445
+ cache = PLUGINS_DIR / "__pycache__"
446
+ if cache.exists():
447
+ for f in cache.glob(f"codis_plugin_{plugin_id}*"):
448
+ with contextlib.suppress(OSError):
449
+ f.unlink()
450
+ if self._trusted.pop(plugin_id, None) is not None:
451
+ _save_trusted_plugins(self._trusted)
452
+ self._errors.pop(plugin_id, None)
453
+ self._disabled.discard(plugin_id)
454
+ return True
455
+
456
+ def toggle(self, plugin_id: str) -> bool:
457
+ """Ativa ou desativa um plugin. Retorna o novo estado (``True`` = ativo)."""
458
+ mod = self._loaded.get(plugin_id)
459
+ if mod is None:
460
+ path = self._paths.get(plugin_id) or self._descobrir_caminho(plugin_id)
461
+ if path and path.exists():
462
+ self._disabled.discard(plugin_id)
463
+ return self._load_one(path)
464
+ return False
465
+
466
+ if getattr(mod, "_enabled", True):
467
+ self._deactivate(plugin_id, mod, self._apis.pop(plugin_id, None))
468
+ mod._enabled = False
469
+ self._disabled.add(plugin_id)
470
+ self._active.discard(plugin_id)
471
+ return False
472
+
473
+ self._disabled.discard(plugin_id)
474
+ path = self._paths.get(plugin_id)
475
+ if getattr(mod, "_isolated_process", False):
476
+ ok = bool(path) and self._start_isolated(plugin_id, mod._entry)
477
+ mod._enabled = ok
478
+ if ok:
479
+ self._active.add(plugin_id)
480
+ return ok
481
+ plugin_api = PluginAPI(self._app_api._app, plugin_id)
482
+ try:
483
+ if hasattr(mod, "activate"):
484
+ mod.activate(plugin_api)
485
+ except Exception:
486
+ self._fail(plugin_id, traceback.format_exc())
487
+ with contextlib.suppress(Exception):
488
+ plugin_api._teardown()
489
+ self._disabled.add(plugin_id)
490
+ return False
491
+ mod._enabled = True
492
+ mod._plugin_api = plugin_api
493
+ self._apis[plugin_id] = plugin_api
494
+ self._active.add(plugin_id)
495
+ self._errors.pop(plugin_id, None)
496
+ return True
497
+
498
+ def reload(self, plugin_id: str) -> bool:
499
+ """Recarrega um plugin do disco."""
500
+ path = self._paths.get(plugin_id) or self._descobrir_caminho(plugin_id)
501
+ if path is None:
502
+ return False
503
+ self.unload(plugin_id)
504
+ self._disabled.discard(plugin_id)
505
+ return self._load_one(path)
506
+
507
+ # Consulta
508
+
509
+ def get_readme(self, plugin_id: str) -> str:
510
+ """Retorna o README do plugin em Markdown."""
511
+ mod = self._loaded.get(plugin_id)
512
+ path = self._paths.get(plugin_id) or self._descobrir_caminho(plugin_id)
513
+ return _get_plugin_readme(path, mod) if path else "*(Plugin não encontrado)*"
514
+
515
+ def get_security_info(self, plugin_id: str) -> tuple[list[str], list[str]]:
516
+ """Retorna (pontos_bloqueados, imports_com_aviso) de todos os arquivos do plugin."""
517
+ path = self._paths.get(plugin_id) or self._descobrir_caminho(plugin_id)
518
+ if path:
519
+ found = scan_plugin(path)
520
+ return found.flagged, found.warned
521
+ return [], []
522
+
523
+ @staticmethod
524
+ def _descobrir_caminho(plugin_id: str) -> Path | None:
525
+ """Localiza o plugin no disco pelo id."""
526
+ for candidate in (PLUGINS_DIR / plugin_id, PLUGINS_DIR / f"{plugin_id}.py", PLUGINS_DIR / f"{plugin_id}.zip"):
527
+ if candidate.is_dir() and (candidate / "plugin.py").exists():
528
+ return candidate
529
+ if candidate.is_file():
530
+ return candidate
531
+ return None
532
+
533
+ def all_plugin_ids(self) -> list[str]:
534
+ """Ids de todos os plugins conhecidos: carregados, com erro ou apenas instalados."""
535
+ ids = set(self._loaded) | set(self._errors)
536
+ if PLUGINS_DIR.exists():
537
+ ids.update(plugin_id_of(e) for e in self._discover())
538
+ return sorted(ids)
539
+
540
+ def get_plugin_weight(self, plugin_id: str) -> int:
541
+ """Tamanho aproximado do plugin em disco, em KB."""
542
+ path = self._paths.get(plugin_id) or self._descobrir_caminho(plugin_id)
543
+ if path is None:
544
+ return 0
545
+ try:
546
+ if path.is_dir():
547
+ return sum(f.stat().st_size for f in path.rglob("*") if f.is_file()) // 1024
548
+ return path.stat().st_size // 1024
549
+ except OSError:
550
+ return 0
551
+
552
+ @property
553
+ def plugins(self) -> dict[str, Any]:
554
+ """Plugins carregados, indexados por id."""
555
+ return dict(self._loaded)
556
+
557
+ @property
558
+ def errors(self) -> dict[str, str]:
559
+ """Erros de carregamento, indexados por id."""
560
+ return dict(self._errors)
561
+
562
+ def get_manifest(self, plugin_id: str) -> PluginManifest:
563
+ """Manifesto do plugin; para plugins não carregados, o que dá para ler da fonte."""
564
+ mod = self._loaded.get(plugin_id)
565
+ if mod:
566
+ return _normalize_manifest(getattr(mod, "MANIFEST", None))
567
+ path = self._descobrir_caminho(plugin_id)
568
+ return self._static_manifest(path) if path else PluginManifest(name=plugin_id)
569
+
570
+
571
+ __all__ = ["PluginLoader", "plugin_id_of"]