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.
- codis-1.1.1.dist-info/METADATA +194 -0
- codis-1.1.1.dist-info/RECORD +329 -0
- codis-1.1.1.dist-info/WHEEL +5 -0
- codis-1.1.1.dist-info/entry_points.txt +5 -0
- codis-1.1.1.dist-info/licenses/LICENSE +21 -0
- codis-1.1.1.dist-info/top_level.txt +2 -0
- run.py +190 -0
- src/__init__.py +1 -0
- src/__main__.py +81 -0
- src/_app_build.py +1507 -0
- src/_app_editor.py +1274 -0
- src/_app_kui.py +825 -0
- src/_app_lsp.py +625 -0
- src/_app_recovery.py +189 -0
- src/_app_settings.py +1385 -0
- src/_app_tools.py +2471 -0
- src/_app_webpreview.py +126 -0
- src/_font_safety.py +127 -0
- src/_shells.py +172 -0
- src/app.py +1488 -0
- src/chat/__init__.py +1 -0
- src/chat/adapters/__init__.py +33 -0
- src/chat/adapters/base.py +209 -0
- src/chat/adapters/discord.py +190 -0
- src/chat/adapters/http.py +78 -0
- src/chat/adapters/irc.py +360 -0
- src/chat/adapters/matrix.py +219 -0
- src/chat/adapters/mattermost.py +178 -0
- src/chat/adapters/mqtt.py +165 -0
- src/chat/adapters/slack.py +204 -0
- src/chat/adapters/telegram.py +117 -0
- src/chat/adapters/ws.py +154 -0
- src/chat/adapters/xmpp.py +337 -0
- src/chat/history.py +76 -0
- src/chat/models.py +207 -0
- src/chat/probe.py +79 -0
- src/chat/session.py +446 -0
- src/chat/util.py +125 -0
- src/collab/__init__.py +1 -0
- src/collab/net.py +411 -0
- src/collab/ot.py +311 -0
- src/collab/session.py +141 -0
- src/collab/tk_adapter.py +134 -0
- src/config.py +335 -0
- src/constants.py +2552 -0
- src/dep_catalog.py +446 -0
- src/diff/__init__.py +1 -0
- src/diff/engine.py +247 -0
- src/dpi.py +30 -0
- src/editor/__init__.py +1 -0
- src/editor/_pane_lsp.py +2937 -0
- src/editor/_pane_utils.py +171 -0
- src/editor/autocomplete.py +607 -0
- src/editor/code_folding.py +836 -0
- src/editor/color_preview.py +382 -0
- src/editor/complexity_lens.py +281 -0
- src/editor/diff_pane.py +623 -0
- src/editor/file_watcher.py +144 -0
- src/editor/focus_block.py +236 -0
- src/editor/heatmap.py +141 -0
- src/editor/inlay_hints.py +366 -0
- src/editor/inline_blame.py +429 -0
- src/editor/kdocs.py +3376 -0
- src/editor/large_file.py +488 -0
- src/editor/ligatures.py +180 -0
- src/editor/line_numbers.py +598 -0
- src/editor/minimap.py +691 -0
- src/editor/multi_cursor.py +269 -0
- src/editor/pane.py +2082 -0
- src/editor/rhythm.py +206 -0
- src/editor/save_hooks.py +43 -0
- src/editor/smart_selection.py +425 -0
- src/editor/smart_tips.py +719 -0
- src/editor/snippets.py +411 -0
- src/editor/sticky_note_gutter.py +410 -0
- src/editor/sticky_scroll.py +385 -0
- src/editor/suggest.py +464 -0
- src/editor/text_transforms.py +310 -0
- src/editor/vim_mode.py +1074 -0
- src/events/__init__.py +84 -0
- src/events/bus.py +427 -0
- src/events/correlator.py +244 -0
- src/events/kinds.py +125 -0
- src/events/pipeline.py +264 -0
- src/events/stream.py +416 -0
- src/events/window.py +204 -0
- src/extcompat/__init__.py +19 -0
- src/extcompat/code/__init__.py +13 -0
- src/extcompat/code/consent.py +162 -0
- src/extcompat/code/host.py +353 -0
- src/extcompat/code/hosts/py_host.py +763 -0
- src/extcompat/code/locate.py +105 -0
- src/extcompat/code/manager.py +325 -0
- src/extcompat/code/permissions.py +154 -0
- src/extcompat/code/sandbox.py +60 -0
- src/extcompat/colors.py +131 -0
- src/extcompat/common.py +184 -0
- src/extcompat/cson.py +269 -0
- src/extcompat/formats/__init__.py +22 -0
- src/extcompat/formats/_tm.py +189 -0
- src/extcompat/formats/_util.py +31 -0
- src/extcompat/formats/base16.py +66 -0
- src/extcompat/formats/brackets.py +172 -0
- src/extcompat/formats/eclipse.py +193 -0
- src/extcompat/formats/emacs.py +361 -0
- src/extcompat/formats/geany.py +147 -0
- src/extcompat/formats/generic.py +184 -0
- src/extcompat/formats/gtksource.py +117 -0
- src/extcompat/formats/helix.py +91 -0
- src/extcompat/formats/jetbrains.py +343 -0
- src/extcompat/formats/kate.py +130 -0
- src/extcompat/formats/micro.py +131 -0
- src/extcompat/formats/nano.py +111 -0
- src/extcompat/formats/notepadpp.py +140 -0
- src/extcompat/formats/pulsar.py +165 -0
- src/extcompat/formats/pyides.py +163 -0
- src/extcompat/formats/sublime.py +340 -0
- src/extcompat/jsonc.py +65 -0
- src/extcompat/lessish.py +128 -0
- src/extcompat/manager.py +122 -0
- src/extcompat/market/__init__.py +63 -0
- src/extcompat/market/sources.py +211 -0
- src/extcompat/model.py +88 -0
- src/extcompat/net.py +228 -0
- src/extcompat/openvsx.py +63 -0
- src/extcompat/readers.py +362 -0
- src/extcompat/registry.py +73 -0
- src/extcompat/safexml.py +63 -0
- src/extcompat/sexp.py +187 -0
- src/extcompat/sources.py +105 -0
- src/extcompat/store.py +276 -0
- src/extcompat/textmate.py +214 -0
- src/extcompat/themes.py +487 -0
- src/extcompat/yamlite.py +294 -0
- src/fileio.py +94 -0
- src/fs_ops.py +106 -0
- src/i18n.py +233 -0
- src/ia/__init__.py +1 -0
- src/ia/actions.py +295 -0
- src/ia/approval_gate.py +672 -0
- src/ia/checkpoints.py +308 -0
- src/ia/context_builder.py +921 -0
- src/ia/dialdiff.py +408 -0
- src/ia/iaspace.py +2078 -0
- src/ia/pair.py +296 -0
- src/ia/providers.py +954 -0
- src/ia/session.py +335 -0
- src/ia/toolbox.py +2524 -0
- src/launcher_actions.py +204 -0
- src/lint/__init__.py +1 -0
- src/lint/manager.py +1058 -0
- src/locales/.translate_manifest.json +64170 -0
- src/locales/de.json +4936 -0
- src/locales/en.json +4936 -0
- src/locales/es.json +4936 -0
- src/locales/fr.json +4936 -0
- src/locales/it.json +4936 -0
- src/locales/ja.json +4936 -0
- src/locales/ko.json +4936 -0
- src/locales/nl.json +4936 -0
- src/locales/pl.json +4936 -0
- src/locales/pt-BR.json +4936 -0
- src/locales/ru.json +4936 -0
- src/locales/tr.json +4936 -0
- src/locales/uk.json +4936 -0
- src/locales/zh-CN.json +4936 -0
- src/lsp/__init__.py +26 -0
- src/lsp/client.py +2300 -0
- src/lsp/dap_client.py +480 -0
- src/lsp/edits.py +84 -0
- src/lsp/framing.py +73 -0
- src/lsp/protocol.py +931 -0
- src/main.py +260 -0
- src/memtrim.py +91 -0
- src/plugins/__init__.py +1 -0
- src/plugins/api.py +1761 -0
- src/plugins/loader.py +571 -0
- src/plugins/process_runner.py +519 -0
- src/plugins/registry.py +342 -0
- src/plugins/safety.py +367 -0
- src/plugins/startup.py +195 -0
- src/plugins/store.py +1178 -0
- src/proc_registry.py +278 -0
- src/pyexec.py +394 -0
- src/recovery.py +259 -0
- src/stall_trace.py +92 -0
- src/standalone.py +1070 -0
- src/startup_profile.py +35 -0
- src/syntax/__init__.py +1 -0
- src/syntax/highlighter.py +776 -0
- src/syntax/patterns.py +584 -0
- src/system_profile.py +430 -0
- src/terminal/backends.py +658 -0
- src/terminal/internal.py +346 -0
- src/terminal/keys.py +138 -0
- src/terminal/palette.py +67 -0
- src/terminal/session.py +283 -0
- src/terminal/shells.py +79 -0
- src/terminal/view.py +489 -0
- src/terminal/vt.py +870 -0
- src/textfmt.py +22 -0
- src/theme/__init__.py +1 -0
- src/theme/base.py +1281 -0
- src/theme/colors.py +49 -0
- src/theme/manager.py +602 -0
- src/theme/utils.py +312 -0
- src/toolbox.py +329 -0
- src/trash_core.py +531 -0
- src/ui/__init__.py +1 -0
- src/ui/_perf_utils.py +285 -0
- src/ui/_persistence_utils.py +93 -0
- src/ui/accessibility.py +843 -0
- src/ui/activity_bar.py +860 -0
- src/ui/app_embed.py +434 -0
- src/ui/archive_panel.py +608 -0
- src/ui/bookmarks.py +314 -0
- src/ui/breadcrumb.py +383 -0
- src/ui/calculator_panel.py +982 -0
- src/ui/calendar_panel.py +1218 -0
- src/ui/chat_panel.py +1271 -0
- src/ui/chat_profile_dialog.py +278 -0
- src/ui/chat_render.py +128 -0
- src/ui/clock_panel.py +810 -0
- src/ui/code_outline.py +364 -0
- src/ui/code_runner.py +729 -0
- src/ui/code_stats.py +546 -0
- src/ui/collab_panel.py +1009 -0
- src/ui/color_picker.py +547 -0
- src/ui/command_palette.py +452 -0
- src/ui/cursor_manager.py +750 -0
- src/ui/custom_keywords_panel.py +413 -0
- src/ui/debug_panel.py +1037 -0
- src/ui/dependency_graph.py +692 -0
- src/ui/diff_panel.py +381 -0
- src/ui/docs_panel.py +514 -0
- src/ui/doom_embed.py +349 -0
- src/ui/dropdown.py +321 -0
- src/ui/easter_eggs.py +979 -0
- src/ui/env_manager.py +666 -0
- src/ui/extcode_bridge.py +215 -0
- src/ui/extcode_dialogs.py +412 -0
- src/ui/extcompat_dialog.py +583 -0
- src/ui/file_timeline.py +319 -0
- src/ui/file_tree.py +1208 -0
- src/ui/find_in_files.py +1355 -0
- src/ui/flowchart_panel.py +727 -0
- src/ui/formatter_panel.py +490 -0
- src/ui/git_auth.py +763 -0
- src/ui/git_clone_dialog.py +487 -0
- src/ui/git_panel.py +1483 -0
- src/ui/grab_safe.py +84 -0
- src/ui/internal_python_dialog.py +98 -0
- src/ui/k_ui/__init__.py +1305 -0
- src/ui/k_ui/_bgrenderer.py +317 -0
- src/ui/k_ui/_colors.py +213 -0
- src/ui/k_ui/_dock.py +545 -0
- src/ui/k_ui/_easter.py +290 -0
- src/ui/k_ui/_engine.py +5448 -0
- src/ui/k_ui/_perf.py +333 -0
- src/ui/k_ui/_tkutil.py +7 -0
- src/ui/k_ui/_tooltip.py +365 -0
- src/ui/k_ui/_widgets.py +1204 -0
- src/ui/k_ui/_world.py +837 -0
- src/ui/key_remapper.py +856 -0
- src/ui/launcher.py +1252 -0
- src/ui/lazy_panel.py +73 -0
- src/ui/macro_recorder.py +610 -0
- src/ui/menu_bar.py +898 -0
- src/ui/output_panel.py +321 -0
- src/ui/paint_canvas.py +1000 -0
- src/ui/paint_engine.py +535 -0
- src/ui/paint_panel.py +888 -0
- src/ui/panel_detach.py +112 -0
- src/ui/performance_panel.py +861 -0
- src/ui/pip_manager.py +1758 -0
- src/ui/plugin_panel.py +1586 -0
- src/ui/pomodoro_panel.py +447 -0
- src/ui/problems.py +566 -0
- src/ui/process_manager.py +1657 -0
- src/ui/project_templates.py +775 -0
- src/ui/recovery_dialog.py +122 -0
- src/ui/regex_playground.py +304 -0
- src/ui/remote_adapters.py +1398 -0
- src/ui/remote_browser.py +1224 -0
- src/ui/remote_profile_dialog.py +342 -0
- src/ui/render_panel.py +1293 -0
- src/ui/rest_client.py +549 -0
- src/ui/scratchpad.py +548 -0
- src/ui/search_bar.py +1274 -0
- src/ui/settings_editor.py +3349 -0
- src/ui/settings_window.py +1554 -0
- src/ui/snippets_panel.py +597 -0
- src/ui/sql_studio.py +1815 -0
- src/ui/status_bar.py +438 -0
- src/ui/tab_bar.py +654 -0
- src/ui/task_manager.py +1773 -0
- src/ui/terminal.py +525 -0
- src/ui/theme_preview_panel.py +851 -0
- src/ui/thread_safe_tk.py +152 -0
- src/ui/time_tracker.py +574 -0
- src/ui/tkbind.py +43 -0
- src/ui/todo_panel.py +358 -0
- src/ui/toolbox_panels.py +658 -0
- src/ui/trash_manager.py +657 -0
- src/ui/ui_scale.py +294 -0
- src/ui/ux_enhancements.py +41 -0
- src/ui/web_preview.py +397 -0
- src/ui/webdev.py +630 -0
- src/ui/welcome.py +567 -0
- src/ui/window_embed.py +1500 -0
- src/ui/wizard.py +1550 -0
- src/ui/workspace_switcher.py +418 -0
- src/ui/workspace_trust.py +370 -0
- src/ui/zen_audio.py +354 -0
- src/ui/zen_media.py +2271 -0
- src/ui/zen_media_client.py +303 -0
- src/ui/zen_media_host.py +329 -0
- src/ui/zen_player.py +907 -0
- src/ui/zen_player_widgets.py +700 -0
- src/updater/__init__.py +11 -0
- src/updater/assets.py +145 -0
- src/updater/backup.py +101 -0
- src/updater/channel.py +221 -0
- src/updater/dialog.py +492 -0
- src/updater/integrity.py +111 -0
- src/updater/manager.py +727 -0
- src/updater/result.py +114 -0
- src/venv_runtime.py +531 -0
- src/workspace_state.py +25 -0
src/plugins/api.py
ADDED
|
@@ -0,0 +1,1761 @@
|
|
|
1
|
+
"""Codis - API pública de plugins: PluginManifest, PluginAPI e utilitários de suporte.
|
|
2
|
+
|
|
3
|
+
Fornece os tipos e classes usados por plugins para interagir com o editor:
|
|
4
|
+
:class:`OutputChannel`, :class:`PluginStorage`, :class:`ProgressHandle`,
|
|
5
|
+
:class:`PluginLogger` e a classe principal :class:`PluginAPI`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import contextlib
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import re
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
import tkinter as tk
|
|
17
|
+
import zipfile
|
|
18
|
+
from dataclasses import dataclass, field, fields
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from tkinter import filedialog, messagebox, simpledialog
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from src.constants import (
|
|
24
|
+
CONFIG_DIR,
|
|
25
|
+
EXT_LANG,
|
|
26
|
+
LANG_COMMENT,
|
|
27
|
+
LANG_KEYWORDS,
|
|
28
|
+
LANG_LABEL,
|
|
29
|
+
LANG_META,
|
|
30
|
+
)
|
|
31
|
+
from src.i18n import I18n, _t
|
|
32
|
+
from src.plugins.registry import CommandInfo, Extension, call_flexible
|
|
33
|
+
from src.plugins.safety import (
|
|
34
|
+
plugin_sources,
|
|
35
|
+
scan_source,
|
|
36
|
+
)
|
|
37
|
+
from src.syntax.patterns import LANG_RE, _pat
|
|
38
|
+
from src.theme.base import THEME_ORDER, THEMES
|
|
39
|
+
from src.theme.manager import _patch_theme
|
|
40
|
+
|
|
41
|
+
logger = logging.getLogger("Codis")
|
|
42
|
+
_MISSING = object()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class PluginManifest:
|
|
47
|
+
"""Metadados completos de um plugin Codis."""
|
|
48
|
+
|
|
49
|
+
name: str
|
|
50
|
+
version: str = "1.0.0"
|
|
51
|
+
author: str = ""
|
|
52
|
+
description: str = ""
|
|
53
|
+
homepage: str = ""
|
|
54
|
+
repository: str = ""
|
|
55
|
+
icon: str = "🔌"
|
|
56
|
+
api_version: str = "4.0"
|
|
57
|
+
tags: list[str] = field(default_factory=list)
|
|
58
|
+
license: str = ""
|
|
59
|
+
category: str = "Geral"
|
|
60
|
+
min_codis: str = "1.0.0"
|
|
61
|
+
trusted: bool = False
|
|
62
|
+
readme: str = ""
|
|
63
|
+
keywords: list[str] = field(default_factory=list)
|
|
64
|
+
capabilities: list[str] = field(default_factory=list)
|
|
65
|
+
dependencies: list[str] = field(default_factory=list)
|
|
66
|
+
engines: dict[str, str] = field(default_factory=dict)
|
|
67
|
+
changelog: str = ""
|
|
68
|
+
funding: str = ""
|
|
69
|
+
preview: bool = False
|
|
70
|
+
isolated: bool = False
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
_PRIVATE_KEY = re.compile(r"(token|secret|password|passwd|api[_-]?key|credential|private[_-]?key)", re.I)
|
|
74
|
+
_PROTECTED_KEYS = frozenset({"updater_url"})
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _is_private_key(key: str) -> bool:
|
|
78
|
+
"""Chaves que guardam credenciais não são visíveis para plugins."""
|
|
79
|
+
return bool(_PRIVATE_KEY.search(key))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _is_protected_key(key: str) -> bool:
|
|
83
|
+
"""Chaves que definem a política de segurança de plugins e atualizações."""
|
|
84
|
+
return key in _PROTECTED_KEYS or key.startswith("plugin_")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _glob_match(posix_path: str, pattern: str) -> bool:
|
|
88
|
+
"""Casa ``posix_path`` com um glob em que ``**`` atravessa pastas."""
|
|
89
|
+
regex = ""
|
|
90
|
+
i = 0
|
|
91
|
+
while i < len(pattern):
|
|
92
|
+
ch = pattern[i]
|
|
93
|
+
if pattern.startswith("**/", i):
|
|
94
|
+
regex += "(?:.*/)?"
|
|
95
|
+
i += 3
|
|
96
|
+
continue
|
|
97
|
+
if pattern.startswith("**", i):
|
|
98
|
+
regex += ".*"
|
|
99
|
+
i += 2
|
|
100
|
+
continue
|
|
101
|
+
if ch == "*":
|
|
102
|
+
regex += "[^/]*"
|
|
103
|
+
elif ch == "?":
|
|
104
|
+
regex += "[^/]"
|
|
105
|
+
else:
|
|
106
|
+
regex += re.escape(ch)
|
|
107
|
+
i += 1
|
|
108
|
+
return re.fullmatch(regex, posix_path) is not None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def run_on_ui(app: Any, fn: Any) -> None:
|
|
112
|
+
"""Executa ``fn`` na thread da interface; se já estiver nela, chama direto."""
|
|
113
|
+
if threading.current_thread() is threading.main_thread():
|
|
114
|
+
fn()
|
|
115
|
+
return
|
|
116
|
+
root = getattr(app, "_root", None)
|
|
117
|
+
if root is not None:
|
|
118
|
+
with contextlib.suppress(tk.TclError, RuntimeError):
|
|
119
|
+
root.after(0, fn)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class OutputChannel:
|
|
123
|
+
"""Canal de saída com buffer, visível no painel Output do Codis."""
|
|
124
|
+
|
|
125
|
+
def __init__(self, name: str, app: Any) -> None:
|
|
126
|
+
"""Cria um canal de saída nomeado.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
name: Nome do canal no seletor do painel Output.
|
|
130
|
+
app: Instância de ``CodisApp``.
|
|
131
|
+
"""
|
|
132
|
+
self._nome = name
|
|
133
|
+
self._app = app
|
|
134
|
+
self._linhas: list[str] = []
|
|
135
|
+
self._lock = threading.Lock()
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
def name(self) -> str:
|
|
139
|
+
"""Nome do canal."""
|
|
140
|
+
return self._nome
|
|
141
|
+
|
|
142
|
+
def _panel(self) -> Any | None:
|
|
143
|
+
return getattr(self._app, "_output_panel", None)
|
|
144
|
+
|
|
145
|
+
def append(self, text: str, level: str = "info") -> None:
|
|
146
|
+
"""Adiciona texto ao canal; cada linha vira uma entrada."""
|
|
147
|
+
lines = text.splitlines() or [""]
|
|
148
|
+
with self._lock:
|
|
149
|
+
self._linhas.extend(lines)
|
|
150
|
+
level = "warn" if level == "warning" else level
|
|
151
|
+
|
|
152
|
+
def _write() -> None:
|
|
153
|
+
panel = self._panel()
|
|
154
|
+
if panel is not None and hasattr(panel, "write"):
|
|
155
|
+
for line in lines:
|
|
156
|
+
panel.write(line, channel=self._nome, level=level)
|
|
157
|
+
|
|
158
|
+
run_on_ui(self._app, _write)
|
|
159
|
+
|
|
160
|
+
def appendLine(self, text: str) -> None:
|
|
161
|
+
"""Adiciona exatamente uma linha."""
|
|
162
|
+
self.append(text)
|
|
163
|
+
|
|
164
|
+
def clear(self) -> None:
|
|
165
|
+
"""Limpa o canal."""
|
|
166
|
+
with self._lock:
|
|
167
|
+
self._linhas.clear()
|
|
168
|
+
|
|
169
|
+
def _clear() -> None:
|
|
170
|
+
panel = self._panel()
|
|
171
|
+
if panel is not None and hasattr(panel, "clear_channel"):
|
|
172
|
+
panel.clear_channel(self._nome)
|
|
173
|
+
|
|
174
|
+
run_on_ui(self._app, _clear)
|
|
175
|
+
|
|
176
|
+
def show(self) -> None:
|
|
177
|
+
"""Mostra este canal no painel Output."""
|
|
178
|
+
|
|
179
|
+
def _show() -> None:
|
|
180
|
+
panel = self._panel()
|
|
181
|
+
if panel is not None and hasattr(panel, "show_channel"):
|
|
182
|
+
panel.show_channel(self._nome)
|
|
183
|
+
show_panel = getattr(self._app, "_show_panel", None)
|
|
184
|
+
if callable(show_panel):
|
|
185
|
+
show_panel("output")
|
|
186
|
+
|
|
187
|
+
run_on_ui(self._app, _show)
|
|
188
|
+
|
|
189
|
+
def get_all(self) -> str:
|
|
190
|
+
"""Todo o texto do canal."""
|
|
191
|
+
with self._lock:
|
|
192
|
+
return "\n".join(self._linhas)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
_SAFE_ID = re.compile(r"[^\w.\-]+")
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class PluginStorage:
|
|
199
|
+
"""Armazenamento chave-valor persistente por plugin.
|
|
200
|
+
|
|
201
|
+
Fica em ``CONFIG_DIR/plugin_data/<plugin_id>.json``. As gravações são agrupadas
|
|
202
|
+
(500 ms) e feitas em arquivo temporário, para não deixar JSON pela metade.
|
|
203
|
+
"""
|
|
204
|
+
|
|
205
|
+
def __init__(self, plugin_id: str) -> None:
|
|
206
|
+
"""Carrega os dados do plugin.
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
plugin_id: Id do plugin; define o nome do arquivo.
|
|
210
|
+
"""
|
|
211
|
+
self._plugin_id = plugin_id
|
|
212
|
+
safe = _SAFE_ID.sub("_", plugin_id) or "plugin"
|
|
213
|
+
self._caminho = CONFIG_DIR / "plugin_data" / f"{safe}.json"
|
|
214
|
+
self._dados: dict[str, Any] = self._carregar()
|
|
215
|
+
self._sujo = False
|
|
216
|
+
self._lock = threading.Lock()
|
|
217
|
+
self._timer: threading.Timer | None = None
|
|
218
|
+
|
|
219
|
+
def get(self, key: str, default: Any = None) -> Any:
|
|
220
|
+
"""Valor guardado em ``key``, ou ``default`` se não existir."""
|
|
221
|
+
with self._lock:
|
|
222
|
+
return self._dados.get(key, default)
|
|
223
|
+
|
|
224
|
+
def set(self, key: str, value: Any) -> None:
|
|
225
|
+
"""Guarda ``value`` em ``key`` e agenda a gravação."""
|
|
226
|
+
with self._lock:
|
|
227
|
+
self._dados[key] = value
|
|
228
|
+
self._sujo = True
|
|
229
|
+
self._agendar_flush()
|
|
230
|
+
|
|
231
|
+
def delete(self, key: str) -> None:
|
|
232
|
+
"""Remove ``key``."""
|
|
233
|
+
with self._lock:
|
|
234
|
+
self._dados.pop(key, None)
|
|
235
|
+
self._sujo = True
|
|
236
|
+
self._agendar_flush()
|
|
237
|
+
|
|
238
|
+
def keys(self) -> list[str]:
|
|
239
|
+
"""Chaves guardadas."""
|
|
240
|
+
with self._lock:
|
|
241
|
+
return list(self._dados.keys())
|
|
242
|
+
|
|
243
|
+
def clear(self) -> None:
|
|
244
|
+
"""Remove tudo e agenda a gravação."""
|
|
245
|
+
with self._lock:
|
|
246
|
+
self._dados.clear()
|
|
247
|
+
self._sujo = True
|
|
248
|
+
self._agendar_flush()
|
|
249
|
+
|
|
250
|
+
def flush(self) -> None:
|
|
251
|
+
"""Grava no disco agora, sem esperar o intervalo."""
|
|
252
|
+
with self._lock:
|
|
253
|
+
if self._timer is not None:
|
|
254
|
+
self._timer.cancel()
|
|
255
|
+
self._timer = None
|
|
256
|
+
if not self._sujo:
|
|
257
|
+
return
|
|
258
|
+
try:
|
|
259
|
+
self._caminho.parent.mkdir(parents=True, exist_ok=True)
|
|
260
|
+
tmp = self._caminho.with_suffix(".tmp")
|
|
261
|
+
tmp.write_text(json.dumps(self._dados, indent=2, ensure_ascii=False), "utf-8")
|
|
262
|
+
tmp.replace(self._caminho)
|
|
263
|
+
self._sujo = False
|
|
264
|
+
except (OSError, ValueError, TypeError) as exc:
|
|
265
|
+
logger.warning("PluginStorage[%s]: flush falhou: %s", self._plugin_id, exc)
|
|
266
|
+
|
|
267
|
+
def _carregar(self) -> dict[str, Any]:
|
|
268
|
+
"""Dados do arquivo; ``{}`` se ele não existir ou estiver inválido."""
|
|
269
|
+
try:
|
|
270
|
+
if self._caminho.exists():
|
|
271
|
+
data = json.loads(self._caminho.read_text("utf-8"))
|
|
272
|
+
if isinstance(data, dict):
|
|
273
|
+
return data
|
|
274
|
+
except (OSError, ValueError) as exc:
|
|
275
|
+
logger.warning("PluginStorage[%s]: falha ao carregar: %s", self._plugin_id, exc)
|
|
276
|
+
return {}
|
|
277
|
+
|
|
278
|
+
def _agendar_flush(self) -> None:
|
|
279
|
+
"""Reinicia o intervalo de 500 ms para a próxima gravação."""
|
|
280
|
+
with self._lock:
|
|
281
|
+
if self._timer is not None:
|
|
282
|
+
self._timer.cancel()
|
|
283
|
+
self._timer = threading.Timer(0.5, self.flush)
|
|
284
|
+
self._timer.daemon = True
|
|
285
|
+
self._timer.start()
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class ProgressHandle:
|
|
289
|
+
"""Gerenciador de contexto para reportar progresso longo na status bar."""
|
|
290
|
+
|
|
291
|
+
def __init__(self, title: str, app: Any, cancelavel: bool = False) -> None:
|
|
292
|
+
"""Cria um handle de progresso vinculado à status bar do app.
|
|
293
|
+
|
|
294
|
+
Args:
|
|
295
|
+
title: Texto exibido na status bar durante a operação.
|
|
296
|
+
app: Instância de ``CodisApp`` com acesso à ``_status`` bar.
|
|
297
|
+
cancelavel: Se ``True``, sinaliza que a operação pode ser cancelada.
|
|
298
|
+
"""
|
|
299
|
+
self._titulo = title
|
|
300
|
+
self._app = app
|
|
301
|
+
self._cancelado = False
|
|
302
|
+
self._ativo = False
|
|
303
|
+
|
|
304
|
+
def __enter__(self) -> ProgressHandle:
|
|
305
|
+
"""Inicia o indicador de progresso na status bar."""
|
|
306
|
+
self._ativo = True
|
|
307
|
+
self._reportar(0, self._titulo)
|
|
308
|
+
return self
|
|
309
|
+
|
|
310
|
+
def __exit__(self, *_: Any) -> None:
|
|
311
|
+
"""Encerra o indicador e limpa a status bar."""
|
|
312
|
+
self._ativo = False
|
|
313
|
+
self._ocultar()
|
|
314
|
+
|
|
315
|
+
def report(self, porcentagem: int, message: str = "") -> None:
|
|
316
|
+
"""Atualiza a status bar com a porcentagem e mensagem de progresso.
|
|
317
|
+
|
|
318
|
+
Args:
|
|
319
|
+
porcentagem: Valor de 0 a 100 indicando o progresso.
|
|
320
|
+
message: Texto descritivo; usa o título do handle se omitido.
|
|
321
|
+
"""
|
|
322
|
+
if self._ativo:
|
|
323
|
+
self._reportar(porcentagem, message or self._titulo)
|
|
324
|
+
|
|
325
|
+
@property
|
|
326
|
+
def is_cancelled(self) -> bool:
|
|
327
|
+
"""Retorna ``True`` se :meth:`cancel` foi chamado."""
|
|
328
|
+
return self._cancelado
|
|
329
|
+
|
|
330
|
+
def cancel(self) -> None:
|
|
331
|
+
"""Sinaliza que a operação foi cancelada (consultável via :attr:`is_cancelled`)."""
|
|
332
|
+
self._cancelado = True
|
|
333
|
+
|
|
334
|
+
def _reportar(self, pct: int, msg: str) -> None:
|
|
335
|
+
with contextlib.suppress(tk.TclError):
|
|
336
|
+
status = getattr(self._app, "_status", None)
|
|
337
|
+
if status:
|
|
338
|
+
status.notify(f"⏳ {msg} ({pct}%)", duration=0, level="info")
|
|
339
|
+
|
|
340
|
+
def _ocultar(self) -> None:
|
|
341
|
+
with contextlib.suppress(tk.TclError):
|
|
342
|
+
status = getattr(self._app, "_status", None)
|
|
343
|
+
if status:
|
|
344
|
+
status.notify("", duration=1, level="info")
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
class PluginLogger:
|
|
348
|
+
"""Logger estruturado com escopo por plugin, espelhado no OutputChannel."""
|
|
349
|
+
|
|
350
|
+
def __init__(self, plugin_id: str, canal: OutputChannel | None = None) -> None:
|
|
351
|
+
"""Cria um logger com namespace ``Codis.plugin.<plugin_id>``.
|
|
352
|
+
|
|
353
|
+
Args:
|
|
354
|
+
plugin_id: ID do plugin; define o namespace do logger.
|
|
355
|
+
canal: Canal de output opcional para espelhar as mensagens.
|
|
356
|
+
"""
|
|
357
|
+
self._log = logging.getLogger(f"Codis.plugin.{plugin_id}")
|
|
358
|
+
self._canal = canal
|
|
359
|
+
|
|
360
|
+
def debug(self, msg: str, *args: Any) -> None:
|
|
361
|
+
"""Registra mensagem de nível DEBUG no logger do plugin."""
|
|
362
|
+
self._log.debug(msg, *args)
|
|
363
|
+
|
|
364
|
+
def info(self, msg: str, *args: Any) -> None:
|
|
365
|
+
"""Registra mensagem de nível INFO e espelha no OutputChannel, se configurado."""
|
|
366
|
+
self._log.info(msg, *args)
|
|
367
|
+
if self._canal:
|
|
368
|
+
self._canal.appendLine(f"[INFO] {msg % args if args else msg}")
|
|
369
|
+
|
|
370
|
+
def warning(self, msg: str, *args: Any) -> None:
|
|
371
|
+
"""Registra mensagem de nível WARNING e espelha no OutputChannel, se configurado."""
|
|
372
|
+
self._log.warning(msg, *args)
|
|
373
|
+
if self._canal:
|
|
374
|
+
self._canal.appendLine(f"[AVISO] {msg % args if args else msg}")
|
|
375
|
+
|
|
376
|
+
def error(self, msg: str, *args: Any) -> None:
|
|
377
|
+
"""Registra mensagem de nível ERROR e espelha no OutputChannel, se configurado."""
|
|
378
|
+
self._log.error(msg, *args)
|
|
379
|
+
if self._canal:
|
|
380
|
+
self._canal.appendLine(f"[ERRO] {msg % args if args else msg}")
|
|
381
|
+
|
|
382
|
+
def exception(self, msg: str, *args: Any) -> None:
|
|
383
|
+
"""Registra exceção com traceback e espelha no OutputChannel, se configurado."""
|
|
384
|
+
self._log.exception(msg, *args)
|
|
385
|
+
if self._canal:
|
|
386
|
+
self._canal.appendLine(f"[EXCEÇÃO] {msg % args if args else msg}")
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
class PluginAPI:
|
|
390
|
+
"""Interface entre um plugin e o Codis.
|
|
391
|
+
|
|
392
|
+
Cada plugin recebe a sua instância em ``activate(api)``. Tudo o que registrar por ela
|
|
393
|
+
é desfeito na desativação (``_teardown``), sem deixar nada para trás.
|
|
394
|
+
|
|
395
|
+
Início rápido
|
|
396
|
+
-------------
|
|
397
|
+
::
|
|
398
|
+
|
|
399
|
+
# ~/.codis/plugins/meu_plugin/plugin.py
|
|
400
|
+
from src.plugins.api import PluginManifest
|
|
401
|
+
|
|
402
|
+
MANIFEST = PluginManifest(
|
|
403
|
+
name="Meu Plugin",
|
|
404
|
+
version="1.0.0",
|
|
405
|
+
author="Você",
|
|
406
|
+
description="Faz algo incrível.",
|
|
407
|
+
icon="",
|
|
408
|
+
tags=["produtividade"],
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
def activate(api):
|
|
412
|
+
api.register_command("meu_plugin.ola", "Dizer Olá",
|
|
413
|
+
lambda: api.show_message("Olá!"))
|
|
414
|
+
api.add_keybinding("<Control-shift-h>", "meu_plugin.ola")
|
|
415
|
+
|
|
416
|
+
def deactivate():
|
|
417
|
+
pass # limpeza feita automaticamente pela API
|
|
418
|
+
|
|
419
|
+
Superfície da API
|
|
420
|
+
-----------------
|
|
421
|
+
Temas register_theme
|
|
422
|
+
Comandos register_command, run_command, wrap_command, list_commands,
|
|
423
|
+
describe_command, register_toggle, is_toggle_on
|
|
424
|
+
Linguagens register_language, register_formatter,
|
|
425
|
+
register_code_action_provider, register_symbol_provider
|
|
426
|
+
Sidebar add_sidebar_panel
|
|
427
|
+
Status bar add_status_item, update_status_item, remove_status_item
|
|
428
|
+
Atalhos add_keybinding / bind_key
|
|
429
|
+
Menus add_menu_item, add_context_menu_item
|
|
430
|
+
Calha e hints add_gutter_icon, add_inlay_hint
|
|
431
|
+
Realces add_highlight, remove_highlight
|
|
432
|
+
Eventos on, on_lang, once, off, emit
|
|
433
|
+
Editor get_active_editor, get_all_editors, get_text, set_text,
|
|
434
|
+
insert_at_cursor, get_selection, replace_selection,
|
|
435
|
+
get_cursor_position, set_cursor_position, get_line,
|
|
436
|
+
get_line_count, get_active_file, get_active_lang,
|
|
437
|
+
open_file, save_file, get_visible_range, scroll_to_line
|
|
438
|
+
UI show_message, show_error, show_info, show_warning,
|
|
439
|
+
ask_input, ask_yesno, ask_choice, open_file_dialog,
|
|
440
|
+
open_files_dialog, save_file_dialog, ask_directory,
|
|
441
|
+
with_progress
|
|
442
|
+
i18n extend_i18n, t
|
|
443
|
+
Config get_config, set_config, watch_config, migrate_config,
|
|
444
|
+
add_settings_section
|
|
445
|
+
Workspace get_workspace_folder, get_workspace_files, find_files
|
|
446
|
+
Storage get_storage
|
|
447
|
+
Output create_output_channel
|
|
448
|
+
Logger get_logger
|
|
449
|
+
IPC get_plugin, require, call_plugin
|
|
450
|
+
Clipboard read_clipboard, write_clipboard
|
|
451
|
+
Timers set_timeout, set_interval, clear_timer, debounce, throttle
|
|
452
|
+
"""
|
|
453
|
+
|
|
454
|
+
CORE_EVENTS: frozenset[str] = frozenset(
|
|
455
|
+
{
|
|
456
|
+
"file_open",
|
|
457
|
+
"file_save",
|
|
458
|
+
"file_close",
|
|
459
|
+
"text_change",
|
|
460
|
+
"cursor_move",
|
|
461
|
+
"theme_change",
|
|
462
|
+
"lang_change",
|
|
463
|
+
"app_ready",
|
|
464
|
+
"app_exit",
|
|
465
|
+
"before_save",
|
|
466
|
+
"after_save",
|
|
467
|
+
"before_format",
|
|
468
|
+
"after_format",
|
|
469
|
+
"lint_complete",
|
|
470
|
+
"git_commit",
|
|
471
|
+
"tab_change",
|
|
472
|
+
"workspace_set",
|
|
473
|
+
"workspace_close",
|
|
474
|
+
"plugin_loaded",
|
|
475
|
+
"plugin_unloaded",
|
|
476
|
+
}
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
def __init__(self, app: Any, plugin_id: str = "") -> None:
|
|
480
|
+
"""Cria a API de um plugin.
|
|
481
|
+
|
|
482
|
+
Args:
|
|
483
|
+
app: Instância do ``CodisApp``.
|
|
484
|
+
plugin_id: Id do plugin dono desta API. Tudo o que for registrado por ela é
|
|
485
|
+
desfeito em ``_teardown``.
|
|
486
|
+
"""
|
|
487
|
+
self._app = app
|
|
488
|
+
self._plugin_id = plugin_id
|
|
489
|
+
self._t = _t
|
|
490
|
+
|
|
491
|
+
self._undo: list[Any] = []
|
|
492
|
+
self._timers: dict[int, threading.Timer] = {}
|
|
493
|
+
self._interval_stops: dict[int, threading.Event] = {}
|
|
494
|
+
self._timer_counter: int = 0
|
|
495
|
+
self._key_counter: int = 0
|
|
496
|
+
self._lock = threading.Lock()
|
|
497
|
+
self._cleanup_hooks: list[Any] = []
|
|
498
|
+
self._output_channels: dict[str, OutputChannel] = {}
|
|
499
|
+
self._storage: PluginStorage | None = None
|
|
500
|
+
self._config_watchers: list[tuple[str, Any]] = []
|
|
501
|
+
|
|
502
|
+
# Infra
|
|
503
|
+
|
|
504
|
+
def _register_cleanup(self, fn: Any) -> None:
|
|
505
|
+
self._cleanup_hooks.append(fn)
|
|
506
|
+
|
|
507
|
+
def _remember(self, undo: Any) -> None:
|
|
508
|
+
"""Guarda como desfazer um registro; ``_teardown`` executa na ordem inversa."""
|
|
509
|
+
self._undo.append(undo)
|
|
510
|
+
|
|
511
|
+
def _hooks_table(self) -> Any:
|
|
512
|
+
return self._app._plugin_hooks
|
|
513
|
+
|
|
514
|
+
def _commands_table(self) -> Any:
|
|
515
|
+
return self._app._commands
|
|
516
|
+
|
|
517
|
+
def _extensions_table(self) -> Any:
|
|
518
|
+
return self._app._extensions
|
|
519
|
+
|
|
520
|
+
def _teardown(self) -> None:
|
|
521
|
+
"""Desfaz tudo o que este plugin registrou. Chamado pelo loader ao desativar."""
|
|
522
|
+
with self._lock:
|
|
523
|
+
for timer in self._timers.values():
|
|
524
|
+
timer.cancel()
|
|
525
|
+
for stop in self._interval_stops.values():
|
|
526
|
+
stop.set()
|
|
527
|
+
self._timers.clear()
|
|
528
|
+
self._interval_stops.clear()
|
|
529
|
+
for fn in reversed(self._undo):
|
|
530
|
+
try:
|
|
531
|
+
fn()
|
|
532
|
+
except Exception as exc:
|
|
533
|
+
logger.warning("Plugin %s: não foi possível desfazer um registro: %s", self._plugin_id, exc)
|
|
534
|
+
self._undo.clear()
|
|
535
|
+
for table, method in (
|
|
536
|
+
("_plugin_hooks", "remove_owner"),
|
|
537
|
+
("_commands", "remove_owner"),
|
|
538
|
+
("_extensions", "remove_owner"),
|
|
539
|
+
):
|
|
540
|
+
with contextlib.suppress(Exception):
|
|
541
|
+
getattr(getattr(self._app, table), method)(self._plugin_id)
|
|
542
|
+
for fn in self._cleanup_hooks:
|
|
543
|
+
try:
|
|
544
|
+
fn()
|
|
545
|
+
except Exception as exc:
|
|
546
|
+
logger.warning("Plugin %s: limpeza falhou: %s", self._plugin_id, exc)
|
|
547
|
+
self._cleanup_hooks.clear()
|
|
548
|
+
if self._storage is not None:
|
|
549
|
+
with contextlib.suppress(Exception):
|
|
550
|
+
self._storage.flush()
|
|
551
|
+
|
|
552
|
+
# Temas
|
|
553
|
+
|
|
554
|
+
def register_theme(self, theme_id: Any, theme: Any = None) -> None:
|
|
555
|
+
"""Registra um tema de cores.
|
|
556
|
+
|
|
557
|
+
Aceita ``register_theme("id", Theme(...))`` ou ``register_theme(Theme(...))``
|
|
558
|
+
(o id é então ``theme.name``). Registrar de novo o mesmo id atualiza o tema.
|
|
559
|
+
"""
|
|
560
|
+
if theme is None:
|
|
561
|
+
theme, theme_id = theme_id, getattr(theme_id, "name", "")
|
|
562
|
+
if not theme_id:
|
|
563
|
+
raise ValueError("register_theme: informe um id para o tema")
|
|
564
|
+
_patch_theme(theme)
|
|
565
|
+
previous = THEMES.get(theme_id)
|
|
566
|
+
was_listed = theme_id in THEME_ORDER
|
|
567
|
+
THEMES[theme_id] = theme
|
|
568
|
+
if not was_listed:
|
|
569
|
+
THEME_ORDER.append(theme_id)
|
|
570
|
+
|
|
571
|
+
def undo() -> None:
|
|
572
|
+
if THEMES.get(theme_id) is theme:
|
|
573
|
+
if previous is not None:
|
|
574
|
+
THEMES[theme_id] = previous
|
|
575
|
+
else:
|
|
576
|
+
THEMES.pop(theme_id, None)
|
|
577
|
+
if not was_listed and theme_id in THEME_ORDER:
|
|
578
|
+
THEME_ORDER.remove(theme_id)
|
|
579
|
+
|
|
580
|
+
self._remember(undo)
|
|
581
|
+
|
|
582
|
+
# Comandos
|
|
583
|
+
|
|
584
|
+
def register_command(
|
|
585
|
+
self,
|
|
586
|
+
cmd_id: str,
|
|
587
|
+
label: str,
|
|
588
|
+
handler: Any,
|
|
589
|
+
category: str = "Plugin",
|
|
590
|
+
*,
|
|
591
|
+
when: Any | None = None,
|
|
592
|
+
doc: str = "",
|
|
593
|
+
) -> None:
|
|
594
|
+
"""Registra um comando na paleta de comandos.
|
|
595
|
+
|
|
596
|
+
``cmd_id`` : id único com ponto (``meu_plugin.rodar``).
|
|
597
|
+
``label`` : texto da paleta.
|
|
598
|
+
``handler`` : função chamada ao executar; pode declarar os argumentos que quiser
|
|
599
|
+
receber de ``run_command``.
|
|
600
|
+
``category`` : prefixo na paleta.
|
|
601
|
+
``when`` : predicado; com ele falso, o comando some da paleta e não executa.
|
|
602
|
+
``doc`` : descrição exibida por ``describe_command``.
|
|
603
|
+
"""
|
|
604
|
+
table = self._commands_table()
|
|
605
|
+
table.register(
|
|
606
|
+
CommandInfo(
|
|
607
|
+
id=cmd_id,
|
|
608
|
+
label=label,
|
|
609
|
+
handler=handler,
|
|
610
|
+
owner=self._plugin_id,
|
|
611
|
+
doc=doc or (getattr(handler, "__doc__", "") or "").strip(),
|
|
612
|
+
category=category,
|
|
613
|
+
when=when,
|
|
614
|
+
)
|
|
615
|
+
)
|
|
616
|
+
self._remember(lambda: table.unregister(cmd_id, self._plugin_id))
|
|
617
|
+
|
|
618
|
+
def run_command(self, cmd_id: str, *args: Any, **kwargs: Any) -> Any:
|
|
619
|
+
"""Executa um comando (do núcleo ou de outro plugin) passando pelos ``wrap_command``."""
|
|
620
|
+
return self._commands_table().run(cmd_id, *args, **kwargs)
|
|
621
|
+
|
|
622
|
+
def wrap_command(self, cmd_id: str, *, before: Any = None, after: Any = None,
|
|
623
|
+
around: Any = None, priority: int = 0) -> None:
|
|
624
|
+
"""Acopla comportamento a um comando existente sem alterá-lo.
|
|
625
|
+
|
|
626
|
+
``before(*args)`` : roda antes; devolver ``False`` cancela o comando.
|
|
627
|
+
``after(resultado, *args)``: roda depois, com o resultado.
|
|
628
|
+
``around(proximo, *args)``: recebe ``proximo`` para chamar (ou não) o original.
|
|
629
|
+
|
|
630
|
+
Vale para comandos executados por ``run_command``, pela paleta e por atalhos de
|
|
631
|
+
plugin. O acoplamento é desfeito quando o plugin é desativado.
|
|
632
|
+
"""
|
|
633
|
+
table = self._commands_table()
|
|
634
|
+
for kind, fn in (("before", before), ("around", around), ("after", after)):
|
|
635
|
+
if fn is not None:
|
|
636
|
+
self._remember(table.wrap(cmd_id, kind, fn, owner=self._plugin_id, priority=priority))
|
|
637
|
+
|
|
638
|
+
def list_commands(self) -> list[dict[str, Any]]:
|
|
639
|
+
"""Comandos disponíveis agora, com rótulo, dono, atalhos e documentação."""
|
|
640
|
+
table = self._commands_table()
|
|
641
|
+
return [d for c in table.all(only_available=True) if (d := table.describe(c.id))]
|
|
642
|
+
|
|
643
|
+
def describe_command(self, cmd_id: str) -> dict[str, Any] | None:
|
|
644
|
+
"""Informações de um comando (rótulo, dono, atalhos, documentação), ou ``None``."""
|
|
645
|
+
return self._commands_table().describe(cmd_id)
|
|
646
|
+
|
|
647
|
+
def register_toggle(
|
|
648
|
+
self,
|
|
649
|
+
toggle_id: str,
|
|
650
|
+
label: str,
|
|
651
|
+
on_enable: Any,
|
|
652
|
+
on_disable: Any = None,
|
|
653
|
+
*,
|
|
654
|
+
default: bool = False,
|
|
655
|
+
doc: str = "",
|
|
656
|
+
) -> None:
|
|
657
|
+
"""Registra um recurso que o usuário liga e desliga, com o estado guardado entre sessões.
|
|
658
|
+
|
|
659
|
+
Cria o comando ``<plugin>.<toggle_id>.toggle`` na paleta. ``on_enable`` roda ao
|
|
660
|
+
ligar (e na ativação do plugin, se o estado salvo for ligado); ``on_disable``, ao
|
|
661
|
+
desligar. Use ``is_toggle_on`` para consultar.
|
|
662
|
+
"""
|
|
663
|
+
storage = self.get_storage()
|
|
664
|
+
key = f"__toggle__{toggle_id}"
|
|
665
|
+
state = {"on": bool(storage.get(key, default))}
|
|
666
|
+
|
|
667
|
+
def _apply(value: bool) -> None:
|
|
668
|
+
state["on"] = value
|
|
669
|
+
storage.set(key, value)
|
|
670
|
+
fn = on_enable if value else on_disable
|
|
671
|
+
if fn is not None:
|
|
672
|
+
call_flexible(fn)
|
|
673
|
+
|
|
674
|
+
def _toggle() -> None:
|
|
675
|
+
_apply(not state["on"])
|
|
676
|
+
self.show_message(f"{label}: {'ligado' if state['on'] else 'desligado'}")
|
|
677
|
+
|
|
678
|
+
self._toggles = getattr(self, "_toggles", {})
|
|
679
|
+
self._toggles[toggle_id] = state
|
|
680
|
+
self.register_command(
|
|
681
|
+
f"{self._plugin_id or 'plugin'}.{toggle_id}.toggle",
|
|
682
|
+
label,
|
|
683
|
+
_toggle,
|
|
684
|
+
doc=doc,
|
|
685
|
+
)
|
|
686
|
+
if state["on"] and on_enable is not None:
|
|
687
|
+
call_flexible(on_enable)
|
|
688
|
+
if on_disable is not None:
|
|
689
|
+
self._register_cleanup(lambda: state["on"] and call_flexible(on_disable))
|
|
690
|
+
|
|
691
|
+
def is_toggle_on(self, toggle_id: str) -> bool:
|
|
692
|
+
"""``True`` se o recurso registrado com ``register_toggle`` está ligado."""
|
|
693
|
+
return bool(getattr(self, "_toggles", {}).get(toggle_id, {}).get("on", False))
|
|
694
|
+
|
|
695
|
+
# Linguagens
|
|
696
|
+
|
|
697
|
+
def register_language(
|
|
698
|
+
self,
|
|
699
|
+
lang_id: str,
|
|
700
|
+
patterns: list[tuple[str, str]] | None = None,
|
|
701
|
+
keywords: list[str] | None = None,
|
|
702
|
+
label: str | None = None,
|
|
703
|
+
extensions: list[str] | None = None,
|
|
704
|
+
comment: str | None = None,
|
|
705
|
+
comment_block: tuple[str, str] | None = None,
|
|
706
|
+
*,
|
|
707
|
+
indent_rules: dict[str, Any] | None = None,
|
|
708
|
+
bracket_pairs: list[tuple[str, str]] | None = None,
|
|
709
|
+
lsp_command: str | None = None,
|
|
710
|
+
) -> None:
|
|
711
|
+
"""Registra uma linguagem.
|
|
712
|
+
|
|
713
|
+
``lang_id`` : identificador único.
|
|
714
|
+
``patterns`` : lista de ``(tag, regex)`` para o realce.
|
|
715
|
+
``keywords`` : palavras reservadas.
|
|
716
|
+
``label`` : nome no seletor de linguagem.
|
|
717
|
+
``extensions`` : extensões (com ponto) para detecção automática.
|
|
718
|
+
``comment`` : prefixo de comentário de linha.
|
|
719
|
+
``comment_block``, ``indent_rules``, ``bracket_pairs``, ``lsp_command``: metadados
|
|
720
|
+
guardados em ``LANG_META`` e consultáveis com ``get_language_meta``.
|
|
721
|
+
"""
|
|
722
|
+
saved: list[tuple[dict, str, Any]] = []
|
|
723
|
+
|
|
724
|
+
def _set(table: dict, key: str, value: Any) -> None:
|
|
725
|
+
saved.append((table, key, table.get(key, _MISSING)))
|
|
726
|
+
table[key] = value
|
|
727
|
+
|
|
728
|
+
if patterns:
|
|
729
|
+
_set(LANG_RE, lang_id, _pat(patterns))
|
|
730
|
+
if keywords:
|
|
731
|
+
_set(LANG_KEYWORDS, lang_id, keywords)
|
|
732
|
+
if label:
|
|
733
|
+
_set(LANG_LABEL, lang_id, label)
|
|
734
|
+
for ext in extensions or []:
|
|
735
|
+
_set(EXT_LANG, ext.lower(), lang_id)
|
|
736
|
+
if comment:
|
|
737
|
+
_set(LANG_COMMENT, lang_id, comment)
|
|
738
|
+
meta = {
|
|
739
|
+
k: v
|
|
740
|
+
for k, v in (
|
|
741
|
+
("comment_block", comment_block),
|
|
742
|
+
("indent_rules", indent_rules),
|
|
743
|
+
("bracket_pairs", bracket_pairs),
|
|
744
|
+
("lsp_command", lsp_command),
|
|
745
|
+
)
|
|
746
|
+
if v
|
|
747
|
+
}
|
|
748
|
+
if meta:
|
|
749
|
+
_set(LANG_META, lang_id, meta)
|
|
750
|
+
|
|
751
|
+
def undo() -> None:
|
|
752
|
+
for table, key, old in reversed(saved):
|
|
753
|
+
if old is _MISSING:
|
|
754
|
+
table.pop(key, None)
|
|
755
|
+
else:
|
|
756
|
+
table[key] = old
|
|
757
|
+
|
|
758
|
+
self._remember(undo)
|
|
759
|
+
|
|
760
|
+
@staticmethod
|
|
761
|
+
def get_language_meta(lang_id: str) -> dict[str, Any]:
|
|
762
|
+
"""Metadados registrados para ``lang_id`` (cópia; vazio se não houver)."""
|
|
763
|
+
return dict(LANG_META.get(lang_id, {}))
|
|
764
|
+
|
|
765
|
+
def _add_extension(self, kind: str, key: str, fn: Any, **extra: Any) -> None:
|
|
766
|
+
table = self._extensions_table()
|
|
767
|
+
ext = Extension(kind=kind, key=key, fn=fn, owner=self._plugin_id, **extra)
|
|
768
|
+
table.add(ext)
|
|
769
|
+
self._remember(lambda: table.remove(ext))
|
|
770
|
+
|
|
771
|
+
def register_formatter(self, lang_id: str, formatter: Any, *, priority: int = 0) -> None:
|
|
772
|
+
"""Registra um formatador: ``formatter(texto) -> texto`` (levante exceção se falhar).
|
|
773
|
+
|
|
774
|
+
Entre vários formatadores da mesma linguagem, o de maior ``priority`` é tentado
|
|
775
|
+
primeiro; se falhar, o próximo.
|
|
776
|
+
"""
|
|
777
|
+
self._add_extension("formatter", lang_id, formatter, priority=priority)
|
|
778
|
+
|
|
779
|
+
def register_code_action_provider(self, lang_id: str, provider: Any) -> None:
|
|
780
|
+
"""Registra um provedor de correções rápidas.
|
|
781
|
+
|
|
782
|
+
``provider(texto, linha, col) -> list[dict]``, cada dict com ``title`` e
|
|
783
|
+
``command`` (id de comando) e, opcionalmente, ``arguments``.
|
|
784
|
+
"""
|
|
785
|
+
self._add_extension("code_action", lang_id, provider)
|
|
786
|
+
|
|
787
|
+
def register_symbol_provider(self, lang_id: str, provider: Any) -> None:
|
|
788
|
+
"""Registra um provedor de símbolos para o esboço.
|
|
789
|
+
|
|
790
|
+
``provider(texto) -> list[dict]`` com ``name``, ``kind``, ``line`` e ``children``.
|
|
791
|
+
"""
|
|
792
|
+
self._add_extension("symbols", lang_id, provider)
|
|
793
|
+
|
|
794
|
+
# Interface
|
|
795
|
+
|
|
796
|
+
def add_sidebar_panel(
|
|
797
|
+
self,
|
|
798
|
+
panel_id: str,
|
|
799
|
+
icon: str,
|
|
800
|
+
factory: Any,
|
|
801
|
+
tooltip: str = "",
|
|
802
|
+
*,
|
|
803
|
+
title: str = "",
|
|
804
|
+
position: str = "bottom",
|
|
805
|
+
) -> None:
|
|
806
|
+
"""Adiciona um painel à barra de atividades.
|
|
807
|
+
|
|
808
|
+
``factory(parent) -> tk.Widget`` constrói o widget. ``title`` serve de dica quando
|
|
809
|
+
``tooltip`` está vazio; ``position`` é aceito por compatibilidade e não muda nada.
|
|
810
|
+
"""
|
|
811
|
+
del position
|
|
812
|
+
app = self._app
|
|
813
|
+
if hasattr(app, "_register_plugin_panel"):
|
|
814
|
+
app._register_plugin_panel(panel_id, icon, factory, tooltip or title)
|
|
815
|
+
self._remember(lambda: app._unregister_plugin_panel(panel_id))
|
|
816
|
+
|
|
817
|
+
def add_status_item(
|
|
818
|
+
self,
|
|
819
|
+
item_id: str,
|
|
820
|
+
text_fn: Any,
|
|
821
|
+
click_fn: Any | None = None,
|
|
822
|
+
side: str = "right",
|
|
823
|
+
*,
|
|
824
|
+
tooltip: str = "",
|
|
825
|
+
priority: int = 0,
|
|
826
|
+
) -> None:
|
|
827
|
+
"""Adiciona um item à barra de status.
|
|
828
|
+
|
|
829
|
+
``text_fn()`` devolve o texto (reavaliado periodicamente e em ``update_status_item``).
|
|
830
|
+
``click_fn()`` roda ao clicar. ``side``: ``"left"`` ou ``"right"``. ``priority``:
|
|
831
|
+
maior fica mais perto da borda.
|
|
832
|
+
"""
|
|
833
|
+
status = self._status_bar()
|
|
834
|
+
if status is not None and hasattr(status, "add_plugin_item"):
|
|
835
|
+
status.add_plugin_item(item_id, text_fn, click_fn, side, tooltip=tooltip, priority=priority)
|
|
836
|
+
self._remember(lambda: self.remove_status_item(item_id))
|
|
837
|
+
|
|
838
|
+
def _status_bar(self) -> Any | None:
|
|
839
|
+
return getattr(self._app, "_status", None)
|
|
840
|
+
|
|
841
|
+
def update_status_item(self, item_id: str) -> None:
|
|
842
|
+
"""Reavalia o texto de um item da barra de status."""
|
|
843
|
+
status = self._status_bar()
|
|
844
|
+
if status is not None and hasattr(status, "refresh_item"):
|
|
845
|
+
status.refresh_item(item_id)
|
|
846
|
+
|
|
847
|
+
def remove_status_item(self, item_id: str) -> None:
|
|
848
|
+
"""Remove um item da barra de status."""
|
|
849
|
+
status = self._status_bar()
|
|
850
|
+
if status is not None and hasattr(status, "remove_plugin_item"):
|
|
851
|
+
status.remove_plugin_item(item_id)
|
|
852
|
+
|
|
853
|
+
def add_keybinding(
|
|
854
|
+
self,
|
|
855
|
+
key_combo: str,
|
|
856
|
+
cmd_id_or_fn: str | Any,
|
|
857
|
+
*,
|
|
858
|
+
when: Any | None = None,
|
|
859
|
+
) -> None:
|
|
860
|
+
"""Vincula um atalho a um id de comando ou a uma função.
|
|
861
|
+
|
|
862
|
+
``key_combo``: sequência do Tkinter, ex. ``"<Control-Shift-H>"``.
|
|
863
|
+
``when`` : predicado; com ele falso, o atalho passa adiante para outros vínculos.
|
|
864
|
+
"""
|
|
865
|
+
if isinstance(cmd_id_or_fn, str):
|
|
866
|
+
cmd_id = cmd_id_or_fn
|
|
867
|
+
else:
|
|
868
|
+
self._key_counter += 1
|
|
869
|
+
cmd_id = f"{self._plugin_id or 'plugin'}.__atalho{self._key_counter}"
|
|
870
|
+
table = self._commands_table()
|
|
871
|
+
table.register(
|
|
872
|
+
CommandInfo(id=cmd_id, label=cmd_id, handler=cmd_id_or_fn, owner=self._plugin_id, category="")
|
|
873
|
+
)
|
|
874
|
+
self._remember(lambda: table.unregister(cmd_id, self._plugin_id))
|
|
875
|
+
app = self._app
|
|
876
|
+
if hasattr(app, "_bind_key"):
|
|
877
|
+
app._bind_key(key_combo, cmd_id, when)
|
|
878
|
+
self._commands_table().add_key(cmd_id, key_combo)
|
|
879
|
+
self._remember(lambda: app._unbind_key(key_combo, cmd_id))
|
|
880
|
+
|
|
881
|
+
bind_key = add_keybinding
|
|
882
|
+
|
|
883
|
+
def add_menu_item(
|
|
884
|
+
self,
|
|
885
|
+
menu_path: str,
|
|
886
|
+
label: str,
|
|
887
|
+
handler: Any,
|
|
888
|
+
*,
|
|
889
|
+
accelerator: str = "",
|
|
890
|
+
before: str = "",
|
|
891
|
+
after: str = "",
|
|
892
|
+
) -> None:
|
|
893
|
+
"""Adiciona um item ao menu Plugins (ou a um submenu dele: ``"Plugins/Meu Plugin"``).
|
|
894
|
+
|
|
895
|
+
``accelerator``: texto de atalho exibido ao lado do item. ``before`` e ``after``
|
|
896
|
+
são aceitos por compatibilidade; o item entra no fim do menu.
|
|
897
|
+
"""
|
|
898
|
+
del before, after
|
|
899
|
+
app = self._app
|
|
900
|
+
if hasattr(app, "_add_plugin_menu_item"):
|
|
901
|
+
app._add_plugin_menu_item(menu_path, label, handler, accelerator)
|
|
902
|
+
self._remember(lambda: app._remove_plugin_menu_item(menu_path, label))
|
|
903
|
+
|
|
904
|
+
def add_context_menu_item(
|
|
905
|
+
self,
|
|
906
|
+
context: str,
|
|
907
|
+
label: str,
|
|
908
|
+
handler: Any,
|
|
909
|
+
*,
|
|
910
|
+
when: Any | None = None,
|
|
911
|
+
) -> None:
|
|
912
|
+
"""Adiciona um item a um menu de contexto.
|
|
913
|
+
|
|
914
|
+
``context``: ``"editor"`` ou ``"file_tree"``. ``handler`` recebe o alvo do clique
|
|
915
|
+
(o caminho, na árvore); no editor não recebe nada.
|
|
916
|
+
``when`` é avaliado a cada abertura do menu.
|
|
917
|
+
"""
|
|
918
|
+
self._add_extension("context_menu", context, handler, label=label, when=when)
|
|
919
|
+
|
|
920
|
+
def register_decorator(self, name: str, factory: Any) -> None:
|
|
921
|
+
"""Obsoleto: nunca teve efeito. Use ``add_highlight`` ou ``add_inlay_hint``."""
|
|
922
|
+
del factory
|
|
923
|
+
logger.warning("Plugin %s: register_decorator('%s') é obsoleto e não faz nada.", self._plugin_id, name)
|
|
924
|
+
|
|
925
|
+
def add_gutter_icon(
|
|
926
|
+
self,
|
|
927
|
+
line: int,
|
|
928
|
+
icon: str,
|
|
929
|
+
tooltip: str = "",
|
|
930
|
+
on_click: Any | None = None,
|
|
931
|
+
) -> None:
|
|
932
|
+
"""Adiciona um ícone na calha do editor ativo (linha base 1).
|
|
933
|
+
|
|
934
|
+
Depende de suporte do editor, que ainda não existe: por ora a chamada não tem efeito.
|
|
935
|
+
"""
|
|
936
|
+
pane = self.get_active_editor()
|
|
937
|
+
if pane is not None and hasattr(pane, "add_gutter_icon"):
|
|
938
|
+
pane.add_gutter_icon(line, icon, tooltip, on_click, owner=self._plugin_id)
|
|
939
|
+
self._remember(lambda: pane.remove_plugin_marks(self._plugin_id))
|
|
940
|
+
|
|
941
|
+
def add_inlay_hint(
|
|
942
|
+
self,
|
|
943
|
+
line: int,
|
|
944
|
+
col: int,
|
|
945
|
+
text: str,
|
|
946
|
+
*,
|
|
947
|
+
fg: str = "#888888",
|
|
948
|
+
) -> None:
|
|
949
|
+
"""Adiciona um texto fantasma após ``(line, col)`` do editor ativo.
|
|
950
|
+
|
|
951
|
+
Depende de suporte do editor, que ainda não existe: por ora a chamada não tem efeito.
|
|
952
|
+
"""
|
|
953
|
+
pane = self.get_active_editor()
|
|
954
|
+
if pane is not None and hasattr(pane, "add_inlay_hint"):
|
|
955
|
+
pane.add_inlay_hint(line, col, text, fg=fg, owner=self._plugin_id)
|
|
956
|
+
self._remember(lambda: pane.remove_plugin_marks(self._plugin_id))
|
|
957
|
+
|
|
958
|
+
def add_highlight(
|
|
959
|
+
self,
|
|
960
|
+
line_start: int,
|
|
961
|
+
col_start: int,
|
|
962
|
+
line_end: int,
|
|
963
|
+
col_end: int,
|
|
964
|
+
tag: str = "plugin_highlight",
|
|
965
|
+
*,
|
|
966
|
+
bg: str = "#ffff00",
|
|
967
|
+
fg: str = "",
|
|
968
|
+
) -> None:
|
|
969
|
+
"""Realça uma região do editor ativo."""
|
|
970
|
+
pane = self.get_active_editor()
|
|
971
|
+
if pane:
|
|
972
|
+
with contextlib.suppress(tk.TclError):
|
|
973
|
+
kw: dict[str, str] = {"background": bg}
|
|
974
|
+
if fg:
|
|
975
|
+
kw["foreground"] = fg
|
|
976
|
+
pane.text.tag_configure(tag, **kw)
|
|
977
|
+
pane.text.tag_add(tag, f"{line_start}.{col_start}", f"{line_end}.{col_end}")
|
|
978
|
+
|
|
979
|
+
def remove_highlight(self, tag: str = "plugin_highlight") -> None:
|
|
980
|
+
"""Remove o realce de ``tag`` no editor ativo."""
|
|
981
|
+
pane = self.get_active_editor()
|
|
982
|
+
if pane:
|
|
983
|
+
with contextlib.suppress(tk.TclError):
|
|
984
|
+
pane.text.tag_remove(tag, "1.0", "end")
|
|
985
|
+
|
|
986
|
+
# Eventos
|
|
987
|
+
|
|
988
|
+
def on(self, event: str, handler: Any, *, priority: int = 0, lang: str = "") -> None:
|
|
989
|
+
"""Assina um evento do editor ou de outro plugin.
|
|
990
|
+
|
|
991
|
+
Eventos do núcleo: ``CORE_EVENTS``. Eventos de plugins usam nomes com namespace
|
|
992
|
+
(``"meu_plugin.pronto"``). Maior ``priority`` roda primeiro. O handler declara só
|
|
993
|
+
os argumentos que quer receber. Em ``before_save`` e ``before_format``, devolver
|
|
994
|
+
``False`` cancela a ação. Com ``lang``, só roda para essa linguagem.
|
|
995
|
+
"""
|
|
996
|
+
table = self._hooks_table()
|
|
997
|
+
table.add(event, handler, priority=priority, owner=self._plugin_id, lang=lang)
|
|
998
|
+
self._remember(lambda: table.remove(event, handler))
|
|
999
|
+
|
|
1000
|
+
def on_lang(self, lang: str, handler: Any, *, event: str = "file_open") -> None:
|
|
1001
|
+
"""Roda ``handler`` quando um arquivo de ``lang`` é aberto (ou, com ``event``, no evento dado)."""
|
|
1002
|
+
self.on(event, handler, lang=lang)
|
|
1003
|
+
if event == "file_open":
|
|
1004
|
+
self.on("lang_change", handler, lang=lang)
|
|
1005
|
+
|
|
1006
|
+
def once(self, event: str, handler: Any) -> None:
|
|
1007
|
+
"""Assina um evento exatamente uma vez."""
|
|
1008
|
+
fired = [False]
|
|
1009
|
+
|
|
1010
|
+
def _wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
1011
|
+
if fired[0]:
|
|
1012
|
+
return None
|
|
1013
|
+
fired[0] = True
|
|
1014
|
+
self.off(event, _wrapper)
|
|
1015
|
+
return call_flexible(handler, *args, **kwargs)
|
|
1016
|
+
|
|
1017
|
+
self.on(event, _wrapper)
|
|
1018
|
+
|
|
1019
|
+
def off(self, event: str, handler: Any) -> None:
|
|
1020
|
+
"""Cancela a assinatura de ``handler`` em ``event``."""
|
|
1021
|
+
self._hooks_table().remove(event, handler)
|
|
1022
|
+
|
|
1023
|
+
def emit(self, event: str, *args: Any, **kwargs: Any) -> None:
|
|
1024
|
+
"""Dispara um evento próprio. Use nomes com namespace: ``"meu_plugin.dados_prontos"``."""
|
|
1025
|
+
self._hooks_table().fire(event, *args, **kwargs)
|
|
1026
|
+
|
|
1027
|
+
def require(self, plugin_id: str) -> Any:
|
|
1028
|
+
"""Devolve o módulo de outro plugin ativo, ou levanta ``LookupError`` se não houver."""
|
|
1029
|
+
mod = self.get_plugin(plugin_id)
|
|
1030
|
+
if mod is None:
|
|
1031
|
+
raise LookupError(f"O plugin '{plugin_id}' não está ativo.")
|
|
1032
|
+
return mod
|
|
1033
|
+
|
|
1034
|
+
|
|
1035
|
+
def get_active_editor(self) -> Any | None:
|
|
1036
|
+
"""Retorna o EditorPane ativo, ou None."""
|
|
1037
|
+
with contextlib.suppress(tk.TclError):
|
|
1038
|
+
if hasattr(self._app, "_e"):
|
|
1039
|
+
return self._app._e()
|
|
1040
|
+
return getattr(self._app, "_active_pane", None)
|
|
1041
|
+
|
|
1042
|
+
def get_all_editors(self) -> list[Any]:
|
|
1043
|
+
"""Retorna a lista de todos os painéis de editor abertos."""
|
|
1044
|
+
return list(getattr(self._app, "_editors", []))
|
|
1045
|
+
|
|
1046
|
+
def get_text(self) -> str:
|
|
1047
|
+
"""Retorna o texto completo do editor ativo."""
|
|
1048
|
+
pane = self.get_active_editor()
|
|
1049
|
+
if pane:
|
|
1050
|
+
with contextlib.suppress(tk.TclError):
|
|
1051
|
+
return pane.text.get("1.0", "end-1c")
|
|
1052
|
+
return ""
|
|
1053
|
+
|
|
1054
|
+
def set_text(self, text: str) -> None:
|
|
1055
|
+
"""Substitui todo o conteúdo do editor ativo pelo texto fornecido."""
|
|
1056
|
+
pane = self.get_active_editor()
|
|
1057
|
+
if pane:
|
|
1058
|
+
with contextlib.suppress(tk.TclError):
|
|
1059
|
+
pane.text.delete("1.0", "end")
|
|
1060
|
+
pane.text.insert("1.0", text)
|
|
1061
|
+
|
|
1062
|
+
def insert_at_cursor(self, text: str) -> None:
|
|
1063
|
+
"""Insere texto na posição atual do cursor."""
|
|
1064
|
+
pane = self.get_active_editor()
|
|
1065
|
+
if pane:
|
|
1066
|
+
with contextlib.suppress(tk.TclError):
|
|
1067
|
+
pane.text.insert(tk.INSERT, text)
|
|
1068
|
+
|
|
1069
|
+
def get_selection(self) -> str:
|
|
1070
|
+
"""Retorna o texto selecionado (string vazia se não houver seleção)."""
|
|
1071
|
+
pane = self.get_active_editor()
|
|
1072
|
+
if pane:
|
|
1073
|
+
with contextlib.suppress(tk.TclError):
|
|
1074
|
+
return pane.text.get(tk.SEL_FIRST, tk.SEL_LAST)
|
|
1075
|
+
return ""
|
|
1076
|
+
|
|
1077
|
+
def replace_selection(self, text: str) -> None:
|
|
1078
|
+
"""Substitui a seleção atual pelo texto informado."""
|
|
1079
|
+
pane = self.get_active_editor()
|
|
1080
|
+
if pane:
|
|
1081
|
+
with contextlib.suppress(tk.TclError, Exception):
|
|
1082
|
+
pane.text.delete(tk.SEL_FIRST, tk.SEL_LAST)
|
|
1083
|
+
pane.text.insert(tk.INSERT, text)
|
|
1084
|
+
|
|
1085
|
+
def get_cursor_position(self) -> tuple[int, int]:
|
|
1086
|
+
"""Retorna (linha, coluna) do cursor (linha base 1, coluna base 0)."""
|
|
1087
|
+
pane = self.get_active_editor()
|
|
1088
|
+
if pane:
|
|
1089
|
+
with contextlib.suppress(tk.TclError):
|
|
1090
|
+
idx = pane.text.index(tk.INSERT)
|
|
1091
|
+
ln, col = map(int, idx.split("."))
|
|
1092
|
+
return ln, col
|
|
1093
|
+
return (1, 0)
|
|
1094
|
+
|
|
1095
|
+
def set_cursor_position(self, line: int, col: int = 0) -> None:
|
|
1096
|
+
"""Move o cursor para (linha, coluna)."""
|
|
1097
|
+
pane = self.get_active_editor()
|
|
1098
|
+
if pane:
|
|
1099
|
+
with contextlib.suppress(tk.TclError):
|
|
1100
|
+
pane.text.mark_set(tk.INSERT, f"{line}.{col}")
|
|
1101
|
+
pane.text.see(tk.INSERT)
|
|
1102
|
+
|
|
1103
|
+
def get_line(self, line: int) -> str:
|
|
1104
|
+
"""Retorna o texto da linha ``line`` (base 1) no editor ativo."""
|
|
1105
|
+
pane = self.get_active_editor()
|
|
1106
|
+
if pane:
|
|
1107
|
+
with contextlib.suppress(tk.TclError):
|
|
1108
|
+
return pane.text.get(f"{line}.0", f"{line}.end")
|
|
1109
|
+
return ""
|
|
1110
|
+
|
|
1111
|
+
def get_line_count(self) -> int:
|
|
1112
|
+
"""Retorna o total de linhas do editor ativo."""
|
|
1113
|
+
pane = self.get_active_editor()
|
|
1114
|
+
if pane:
|
|
1115
|
+
with contextlib.suppress(tk.TclError):
|
|
1116
|
+
return int(pane.text.index("end-1c").split(".")[0])
|
|
1117
|
+
return 0
|
|
1118
|
+
|
|
1119
|
+
def get_active_file(self) -> Path | None:
|
|
1120
|
+
"""Retorna o Path do arquivo ativo, ou None."""
|
|
1121
|
+
pane = self.get_active_editor()
|
|
1122
|
+
return getattr(pane, "path", None) if pane else None
|
|
1123
|
+
|
|
1124
|
+
def get_active_lang(self) -> str:
|
|
1125
|
+
"""Retorna o ID de linguagem do editor ativo (ex: ``"python"``)."""
|
|
1126
|
+
pane = self.get_active_editor()
|
|
1127
|
+
return getattr(pane, "lang", "text") if pane else "text"
|
|
1128
|
+
|
|
1129
|
+
def open_file(self, path: str | Path) -> None:
|
|
1130
|
+
"""Solicita ao Codis que abra um arquivo em nova aba."""
|
|
1131
|
+
with contextlib.suppress(tk.TclError):
|
|
1132
|
+
if hasattr(self._app, "_open_file"):
|
|
1133
|
+
self._app._open_file(Path(path))
|
|
1134
|
+
|
|
1135
|
+
def save_file(self) -> None:
|
|
1136
|
+
"""Salva o arquivo ativo."""
|
|
1137
|
+
with contextlib.suppress(tk.TclError):
|
|
1138
|
+
if hasattr(self._app, "_save"):
|
|
1139
|
+
self._app._save()
|
|
1140
|
+
|
|
1141
|
+
def get_visible_range(self) -> tuple[int, int]:
|
|
1142
|
+
"""Retorna (primeira_linha_visível, última_linha_visível) no editor ativo."""
|
|
1143
|
+
pane = self.get_active_editor()
|
|
1144
|
+
if pane:
|
|
1145
|
+
with contextlib.suppress(tk.TclError):
|
|
1146
|
+
top = pane.text.index("@0,0")
|
|
1147
|
+
base = pane.text.index(f"@0,{pane.text.winfo_height()}")
|
|
1148
|
+
return int(top.split(".")[0]), int(base.split(".")[0])
|
|
1149
|
+
return (1, 1)
|
|
1150
|
+
|
|
1151
|
+
def scroll_to_line(self, line: int) -> None:
|
|
1152
|
+
"""Rola o editor ativo até a linha ``line`` ficar visível."""
|
|
1153
|
+
pane = self.get_active_editor()
|
|
1154
|
+
if pane:
|
|
1155
|
+
with contextlib.suppress(tk.TclError):
|
|
1156
|
+
pane.text.see(f"{line}.0")
|
|
1157
|
+
|
|
1158
|
+
def show_message(
|
|
1159
|
+
self,
|
|
1160
|
+
message: str,
|
|
1161
|
+
duration: int = 3000,
|
|
1162
|
+
*,
|
|
1163
|
+
level: str = "info",
|
|
1164
|
+
) -> None:
|
|
1165
|
+
"""
|
|
1166
|
+
Exibe notificação transitória na status bar.
|
|
1167
|
+
|
|
1168
|
+
``duration``: tempo em ms antes de desaparecer (0 = permanente).
|
|
1169
|
+
``level`` : ``"info"`` | ``"warning"`` | ``"error"``.
|
|
1170
|
+
"""
|
|
1171
|
+
status = getattr(self._app, "_status", None)
|
|
1172
|
+
if status:
|
|
1173
|
+
with contextlib.suppress(tk.TclError):
|
|
1174
|
+
status.notify(message, duration=duration, level=level)
|
|
1175
|
+
|
|
1176
|
+
@staticmethod
|
|
1177
|
+
def show_error(title: str, message: str) -> None:
|
|
1178
|
+
"""Exibe diálogo modal de erro."""
|
|
1179
|
+
messagebox.showerror(title, message)
|
|
1180
|
+
|
|
1181
|
+
@staticmethod
|
|
1182
|
+
def show_info(title: str, message: str) -> None:
|
|
1183
|
+
"""Exibe diálogo modal informativo."""
|
|
1184
|
+
messagebox.showinfo(title, message)
|
|
1185
|
+
|
|
1186
|
+
@staticmethod
|
|
1187
|
+
def show_warning(title: str, message: str) -> None:
|
|
1188
|
+
"""Exibe diálogo modal de aviso."""
|
|
1189
|
+
messagebox.showwarning(title, message)
|
|
1190
|
+
|
|
1191
|
+
def ask_input(
|
|
1192
|
+
self,
|
|
1193
|
+
prompt: str,
|
|
1194
|
+
title: str = "Input",
|
|
1195
|
+
*,
|
|
1196
|
+
initial: str = "",
|
|
1197
|
+
) -> str | None:
|
|
1198
|
+
"""Diálogo de entrada de texto. Retorna string ou None."""
|
|
1199
|
+
return simpledialog.askstring(title, prompt, initialvalue=initial)
|
|
1200
|
+
|
|
1201
|
+
@staticmethod
|
|
1202
|
+
def ask_yesno(question: str, title: str = "Confirmar") -> bool:
|
|
1203
|
+
"""Diálogo sim/não. Retorna True se o usuário clicou Sim."""
|
|
1204
|
+
return bool(messagebox.askyesno(title, question))
|
|
1205
|
+
|
|
1206
|
+
def ask_choice(
|
|
1207
|
+
self,
|
|
1208
|
+
title: str,
|
|
1209
|
+
prompt: str,
|
|
1210
|
+
choices: list[str],
|
|
1211
|
+
) -> str | None:
|
|
1212
|
+
"""
|
|
1213
|
+
Diálogo de escolha. Retorna o item selecionado ou None.
|
|
1214
|
+
|
|
1215
|
+
Usa seletor nativo da aplicação quando disponível;
|
|
1216
|
+
caso contrário faz fallback para entrada de texto.
|
|
1217
|
+
"""
|
|
1218
|
+
with contextlib.suppress(tk.TclError):
|
|
1219
|
+
if hasattr(self._app, "_show_choice_dialog"):
|
|
1220
|
+
return self._app._show_choice_dialog(title, prompt, choices)
|
|
1221
|
+
options = "\n".join(f"{i + 1}. {c}" for i, c in enumerate(choices))
|
|
1222
|
+
raw = simpledialog.askstring(
|
|
1223
|
+
title, f"{prompt}\n\n{options}\n\nDigite o número ou name:"
|
|
1224
|
+
)
|
|
1225
|
+
if raw is None:
|
|
1226
|
+
return None
|
|
1227
|
+
raw = raw.strip()
|
|
1228
|
+
if raw.isdigit():
|
|
1229
|
+
idx = int(raw) - 1
|
|
1230
|
+
return choices[idx] if 0 <= idx < len(choices) else None
|
|
1231
|
+
return raw if raw in choices else None
|
|
1232
|
+
|
|
1233
|
+
@staticmethod
|
|
1234
|
+
def open_file_dialog(**kwargs: Any) -> Path | None:
|
|
1235
|
+
"""Diálogo de abrir arquivo. Retorna Path ou None."""
|
|
1236
|
+
p = filedialog.askopenfilename(**kwargs)
|
|
1237
|
+
return Path(p) if p else None
|
|
1238
|
+
|
|
1239
|
+
@staticmethod
|
|
1240
|
+
def open_files_dialog(**kwargs: Any) -> list[Path]:
|
|
1241
|
+
"""Diálogo de abrir múltiplos arquivos. Retorna lista de Path."""
|
|
1242
|
+
paths = filedialog.askopenfilenames(**kwargs)
|
|
1243
|
+
return [Path(p) for p in paths] if paths else []
|
|
1244
|
+
|
|
1245
|
+
@staticmethod
|
|
1246
|
+
def save_file_dialog(**kwargs: Any) -> Path | None:
|
|
1247
|
+
"""Diálogo de salvar arquivo. Retorna Path ou None."""
|
|
1248
|
+
p = filedialog.asksaveasfilename(**kwargs)
|
|
1249
|
+
return Path(p) if p else None
|
|
1250
|
+
|
|
1251
|
+
@staticmethod
|
|
1252
|
+
def ask_directory(**kwargs: Any) -> Path | None:
|
|
1253
|
+
"""Diálogo de selecionar pasta. Retorna Path ou None."""
|
|
1254
|
+
p = filedialog.askdirectory(**kwargs)
|
|
1255
|
+
return Path(p) if p else None
|
|
1256
|
+
|
|
1257
|
+
def with_progress(self, title: str, cancelavel: bool = False) -> ProgressHandle:
|
|
1258
|
+
"""Retorna gerenciador de contexto que exibe indicador de progresso."""
|
|
1259
|
+
return ProgressHandle(title, self._app, cancelavel=cancelavel)
|
|
1260
|
+
|
|
1261
|
+
@staticmethod
|
|
1262
|
+
def extend_i18n(locale: str, translations: dict[str, str], label: str = "") -> None:
|
|
1263
|
+
"""
|
|
1264
|
+
Adiciona traduções para um locale.
|
|
1265
|
+
|
|
1266
|
+
``locale`` : tag BCP-47 (ex: ``"pt-BR"``, ``"tl"``, ``"ja"``).
|
|
1267
|
+
``translations``: ``{chave: string_traduzida}``.
|
|
1268
|
+
``label`` : nome legível exibido no seletor de idioma da UI
|
|
1269
|
+
(ex: ``"Tagalog (Filipino)"``). Quando omitido, usa
|
|
1270
|
+
o valor da chave ``"lang.name"`` nas translations,
|
|
1271
|
+
ou o próprio código do locale.
|
|
1272
|
+
|
|
1273
|
+
Se o locale ainda não existir, ele é automaticamente adicionado
|
|
1274
|
+
à lista de idiomas disponíveis no Settings.
|
|
1275
|
+
"""
|
|
1276
|
+
I18n.get_instance().extend(locale, translations, label=label)
|
|
1277
|
+
|
|
1278
|
+
@staticmethod
|
|
1279
|
+
def t(key: str, **kwargs: Any) -> str:
|
|
1280
|
+
"""Traduz ``key`` no locale atual."""
|
|
1281
|
+
return _t(key, **kwargs)
|
|
1282
|
+
|
|
1283
|
+
def get_config(self, key: str, default: Any = None) -> Any:
|
|
1284
|
+
"""Lê um valor de configuração. Chaves com credenciais não são expostas a plugins."""
|
|
1285
|
+
if _is_private_key(key):
|
|
1286
|
+
return default
|
|
1287
|
+
return self._app._cfg.get(key, default)
|
|
1288
|
+
|
|
1289
|
+
def set_config(self, key: str, value: Any) -> None:
|
|
1290
|
+
"""Grava um valor de configuração e persiste no disco.
|
|
1291
|
+
|
|
1292
|
+
Raises:
|
|
1293
|
+
PermissionError: a chave guarda credenciais ou controla a segurança dos plugins.
|
|
1294
|
+
"""
|
|
1295
|
+
if _is_private_key(key) or _is_protected_key(key):
|
|
1296
|
+
raise PermissionError(f"Plugins não podem alterar a configuração '{key}'.")
|
|
1297
|
+
self._app._cfg.set(key, value)
|
|
1298
|
+
self._app._cfg.save()
|
|
1299
|
+
|
|
1300
|
+
def watch_config(self, key: str, callback: Any) -> None:
|
|
1301
|
+
"""Chama ``callback(novo_valor)`` quando ``key`` mudar. Cancelado ao desativar o plugin."""
|
|
1302
|
+
if _is_private_key(key):
|
|
1303
|
+
return
|
|
1304
|
+
cfg = self._app._cfg
|
|
1305
|
+
cfg.on_change(key, callback)
|
|
1306
|
+
self._config_watchers.append((key, callback))
|
|
1307
|
+
self._remember(lambda: cfg.off_change(key, callback))
|
|
1308
|
+
|
|
1309
|
+
def migrate_config(self, migrations: dict[str, str]) -> None:
|
|
1310
|
+
"""
|
|
1311
|
+
Renomeia chaves de configuração.
|
|
1312
|
+
|
|
1313
|
+
``migrations``: ``{chave_antiga: chave_nova}``.
|
|
1314
|
+
Útil quando o plugin é atualizado e suas chaves de config mudam.
|
|
1315
|
+
"""
|
|
1316
|
+
for chave_antiga, chave_nova in migrations.items():
|
|
1317
|
+
_AUSENTE = object()
|
|
1318
|
+
value = self._app._cfg.get(chave_antiga, _AUSENTE)
|
|
1319
|
+
if value is not _AUSENTE:
|
|
1320
|
+
self._app._cfg.set(chave_nova, value)
|
|
1321
|
+
with contextlib.suppress(tk.TclError):
|
|
1322
|
+
self._app._cfg._data.pop(chave_antiga, None)
|
|
1323
|
+
self._app._cfg.save()
|
|
1324
|
+
|
|
1325
|
+
def add_settings_section(
|
|
1326
|
+
self,
|
|
1327
|
+
category: str,
|
|
1328
|
+
settings: list[Any],
|
|
1329
|
+
) -> None:
|
|
1330
|
+
"""
|
|
1331
|
+
Adiciona seção de configurações do plugin no painel de Settings.
|
|
1332
|
+
|
|
1333
|
+
Cada entrada pode ser dict ou tupla de 8 campos:
|
|
1334
|
+
``(key, label, desc, kind, default, opts, type_hint, example)``
|
|
1335
|
+
|
|
1336
|
+
``kind``: ``toggle`` | ``combo`` | ``slider`` | ``text`` | ``number`` | ``path``
|
|
1337
|
+
|
|
1338
|
+
Forma dict (recomendada)::
|
|
1339
|
+
|
|
1340
|
+
api.add_settings_section("Meu Plugin", [
|
|
1341
|
+
{
|
|
1342
|
+
"key": "meu_plugin.timeout",
|
|
1343
|
+
"label": "Timeout (segundos)",
|
|
1344
|
+
"description": "Tempo máximo de espera.",
|
|
1345
|
+
"kind": "number",
|
|
1346
|
+
"default": 30,
|
|
1347
|
+
},
|
|
1348
|
+
])
|
|
1349
|
+
"""
|
|
1350
|
+
from src.ui.settings_editor import SettingsEditor
|
|
1351
|
+
|
|
1352
|
+
schema = SettingsEditor._EXTRA_SCHEMA
|
|
1353
|
+
added: list[tuple] = []
|
|
1354
|
+
for raw in settings:
|
|
1355
|
+
if isinstance(raw, dict):
|
|
1356
|
+
entry: tuple = (
|
|
1357
|
+
raw.get("key", ""),
|
|
1358
|
+
f"{category} \u203a " + raw.get("label", ""),
|
|
1359
|
+
raw.get("description", raw.get("desc", "")),
|
|
1360
|
+
raw.get("kind", raw.get("type", "text")),
|
|
1361
|
+
raw.get("default"),
|
|
1362
|
+
raw.get("opts", raw.get("choices")),
|
|
1363
|
+
raw.get("type_hint"),
|
|
1364
|
+
raw.get("example"),
|
|
1365
|
+
)
|
|
1366
|
+
else:
|
|
1367
|
+
entry = tuple(raw)
|
|
1368
|
+
if len(entry) < 4:
|
|
1369
|
+
continue
|
|
1370
|
+
padded = entry + (None,) * (8 - len(entry))
|
|
1371
|
+
if any(item[0] == padded[0] for item in schema):
|
|
1372
|
+
schema[:] = [item for item in schema if item[0] != padded[0]]
|
|
1373
|
+
schema.append(padded)
|
|
1374
|
+
added.append(padded)
|
|
1375
|
+
key, default = padded[0], padded[4]
|
|
1376
|
+
if key and default is not None and self._app._cfg.get(key, _MISSING) is _MISSING:
|
|
1377
|
+
self._app._cfg._data.setdefault(key, default)
|
|
1378
|
+
|
|
1379
|
+
def undo() -> None:
|
|
1380
|
+
schema[:] = [item for item in schema if item not in added]
|
|
1381
|
+
|
|
1382
|
+
self._remember(undo)
|
|
1383
|
+
|
|
1384
|
+
def get_workspace_folder(self) -> Path | None:
|
|
1385
|
+
"""Retorna a pasta raiz do workspace atual, ou None."""
|
|
1386
|
+
return getattr(self._app, "_workspace", None)
|
|
1387
|
+
|
|
1388
|
+
_SKIP_DIRS = frozenset({".git", "node_modules", "__pycache__", ".venv", "venv", ".mypy_cache", ".idea"})
|
|
1389
|
+
|
|
1390
|
+
def get_workspace_files(
|
|
1391
|
+
self,
|
|
1392
|
+
pattern: str = "**/*",
|
|
1393
|
+
*,
|
|
1394
|
+
exclude: list[str] | None = None,
|
|
1395
|
+
max_results: int = 5000,
|
|
1396
|
+
) -> list[Path]:
|
|
1397
|
+
"""Arquivos do workspace que casam com o glob ``pattern``.
|
|
1398
|
+
|
|
1399
|
+
``exclude``: globs a ignorar (``["**/dist/**"]``). Pastas como ``.git`` e
|
|
1400
|
+
``node_modules`` são sempre puladas, a menos que o próprio ``pattern`` as cite.
|
|
1401
|
+
"""
|
|
1402
|
+
root = self.get_workspace_folder()
|
|
1403
|
+
if root is None:
|
|
1404
|
+
return []
|
|
1405
|
+
return self._glob_files(Path(root), pattern, exclude or [], max_results)
|
|
1406
|
+
|
|
1407
|
+
def _glob_files(self, root: Path, pattern: str, exclude: list[str], limit: int) -> list[Path]:
|
|
1408
|
+
if Path(pattern).is_absolute() or ".." in Path(pattern).parts:
|
|
1409
|
+
raise ValueError("O padrão deve ficar dentro da pasta de busca.")
|
|
1410
|
+
explicit = any(part in self._SKIP_DIRS for part in Path(pattern).parts)
|
|
1411
|
+
out: list[Path] = []
|
|
1412
|
+
for p in root.glob(pattern):
|
|
1413
|
+
rel = p.relative_to(root)
|
|
1414
|
+
if not explicit and any(part in self._SKIP_DIRS for part in rel.parts[:-1]):
|
|
1415
|
+
continue
|
|
1416
|
+
if not p.is_file():
|
|
1417
|
+
continue
|
|
1418
|
+
posix = rel.as_posix()
|
|
1419
|
+
if any(_glob_match(posix, ex) for ex in exclude):
|
|
1420
|
+
continue
|
|
1421
|
+
out.append(p)
|
|
1422
|
+
if len(out) >= limit:
|
|
1423
|
+
break
|
|
1424
|
+
return out
|
|
1425
|
+
|
|
1426
|
+
def find_files(
|
|
1427
|
+
self,
|
|
1428
|
+
pattern: str,
|
|
1429
|
+
*,
|
|
1430
|
+
root: Path | None = None,
|
|
1431
|
+
max_results: int = 1000,
|
|
1432
|
+
) -> list[Path]:
|
|
1433
|
+
"""Encontra arquivos por glob sob ``root`` (padrão: o workspace)."""
|
|
1434
|
+
base = root or self.get_workspace_folder()
|
|
1435
|
+
if base is None:
|
|
1436
|
+
return []
|
|
1437
|
+
return self._glob_files(Path(base), pattern, [], max_results)
|
|
1438
|
+
|
|
1439
|
+
def get_storage(self) -> PluginStorage:
|
|
1440
|
+
"""
|
|
1441
|
+
Retorna armazenamento persistente chave-valor para este plugin.
|
|
1442
|
+
|
|
1443
|
+
Criado sob demanda; descarregado automaticamente na desativação.
|
|
1444
|
+
"""
|
|
1445
|
+
if self._storage is None:
|
|
1446
|
+
self._storage = PluginStorage(self._plugin_id or "unknown")
|
|
1447
|
+
return self._storage
|
|
1448
|
+
|
|
1449
|
+
def create_output_channel(self, name: str) -> OutputChannel:
|
|
1450
|
+
"""Cria (ou recupera) um canal de saída nomeado, visível no painel Output."""
|
|
1451
|
+
if name not in self._output_channels:
|
|
1452
|
+
self._output_channels[name] = OutputChannel(name, self._app)
|
|
1453
|
+
panel = getattr(self._app, "_output_panel", None)
|
|
1454
|
+
if panel is not None and hasattr(panel, "add_channel"):
|
|
1455
|
+
run_on_ui(self._app, lambda: panel.add_channel(name))
|
|
1456
|
+
return self._output_channels[name]
|
|
1457
|
+
|
|
1458
|
+
def get_logger(self, *, with_channel: bool = True) -> PluginLogger:
|
|
1459
|
+
"""Logger do plugin; com ``with_channel`` (padrão) também escreve no canal do plugin."""
|
|
1460
|
+
canal: OutputChannel | None = None
|
|
1461
|
+
if with_channel and self._plugin_id:
|
|
1462
|
+
canal = self.create_output_channel(self._plugin_id)
|
|
1463
|
+
return PluginLogger(self._plugin_id or "plugin", canal)
|
|
1464
|
+
|
|
1465
|
+
def get_plugin(self, plugin_id: str) -> Any | None:
|
|
1466
|
+
"""
|
|
1467
|
+
Retorna o módulo de outro plugin carregado, ou None.
|
|
1468
|
+
|
|
1469
|
+
Use para comunicação entre plugins. Prefira ``call_plugin``
|
|
1470
|
+
para uma fronteira de API mais segura.
|
|
1471
|
+
"""
|
|
1472
|
+
loader = getattr(self._app, "_plugin_loader", None)
|
|
1473
|
+
if loader:
|
|
1474
|
+
with contextlib.suppress(tk.TclError):
|
|
1475
|
+
return loader.plugins.get(plugin_id)
|
|
1476
|
+
return None
|
|
1477
|
+
|
|
1478
|
+
def call_plugin(
|
|
1479
|
+
self,
|
|
1480
|
+
plugin_id: str,
|
|
1481
|
+
method: str,
|
|
1482
|
+
*args: Any,
|
|
1483
|
+
**kwargs: Any,
|
|
1484
|
+
) -> Any:
|
|
1485
|
+
"""Chama ``method`` de outro plugin ativo; ``None`` se o plugin ou o método não existir."""
|
|
1486
|
+
mod = self.get_plugin(plugin_id)
|
|
1487
|
+
if mod is None:
|
|
1488
|
+
return None
|
|
1489
|
+
fn = getattr(mod, method, None)
|
|
1490
|
+
if callable(fn):
|
|
1491
|
+
return fn(*args, **kwargs)
|
|
1492
|
+
return None
|
|
1493
|
+
|
|
1494
|
+
def _clipboard_root(self) -> Any:
|
|
1495
|
+
return getattr(self._app, "_root", None) or self._app
|
|
1496
|
+
|
|
1497
|
+
def read_clipboard(self) -> str:
|
|
1498
|
+
"""Texto atual da área de transferência (vazio se não houver texto)."""
|
|
1499
|
+
try:
|
|
1500
|
+
return self._clipboard_root().clipboard_get()
|
|
1501
|
+
except (tk.TclError, AttributeError):
|
|
1502
|
+
return ""
|
|
1503
|
+
|
|
1504
|
+
def write_clipboard(self, text: str) -> None:
|
|
1505
|
+
"""Define o texto da área de transferência."""
|
|
1506
|
+
root = self._clipboard_root()
|
|
1507
|
+
with contextlib.suppress(tk.TclError, AttributeError):
|
|
1508
|
+
root.clipboard_clear()
|
|
1509
|
+
root.clipboard_append(text)
|
|
1510
|
+
|
|
1511
|
+
def _call_on_ui(self, fn: Any) -> None:
|
|
1512
|
+
"""Roda ``fn`` na thread da interface; o erro de um plugin é registrado, não propagado."""
|
|
1513
|
+
|
|
1514
|
+
def _run() -> None:
|
|
1515
|
+
try:
|
|
1516
|
+
fn()
|
|
1517
|
+
except Exception as exc:
|
|
1518
|
+
logger.warning("Plugin %s: erro em timer: %s", self._plugin_id, exc)
|
|
1519
|
+
|
|
1520
|
+
run_on_ui(self._app, _run)
|
|
1521
|
+
|
|
1522
|
+
def set_timeout(self, delay_ms: int, fn: Any) -> int:
|
|
1523
|
+
"""
|
|
1524
|
+
Chama ``fn()`` uma vez após ``delay_ms`` milissegundos.
|
|
1525
|
+
|
|
1526
|
+
Retorna um handle para uso em ``clear_timer()``.
|
|
1527
|
+
"""
|
|
1528
|
+
with self._lock:
|
|
1529
|
+
self._timer_counter += 1
|
|
1530
|
+
handle = self._timer_counter
|
|
1531
|
+
|
|
1532
|
+
def _disparar() -> None:
|
|
1533
|
+
with self._lock:
|
|
1534
|
+
self._timers.pop(handle, None)
|
|
1535
|
+
self._call_on_ui(fn)
|
|
1536
|
+
|
|
1537
|
+
timer = threading.Timer(delay_ms / 1000.0, _disparar)
|
|
1538
|
+
timer.daemon = True
|
|
1539
|
+
with self._lock:
|
|
1540
|
+
self._timers[handle] = timer
|
|
1541
|
+
timer.start()
|
|
1542
|
+
return handle
|
|
1543
|
+
|
|
1544
|
+
def set_interval(self, interval_ms: int, fn: Any) -> int:
|
|
1545
|
+
"""
|
|
1546
|
+
Chama ``fn()`` repetidamente a cada ``interval_ms`` milissegundos.
|
|
1547
|
+
|
|
1548
|
+
Retorna um handle para uso em ``clear_timer()``.
|
|
1549
|
+
Para automaticamente quando o plugin é desativado.
|
|
1550
|
+
"""
|
|
1551
|
+
with self._lock:
|
|
1552
|
+
self._timer_counter += 1
|
|
1553
|
+
handle = self._timer_counter
|
|
1554
|
+
parado = threading.Event()
|
|
1555
|
+
with self._lock:
|
|
1556
|
+
self._interval_stops[handle] = parado
|
|
1557
|
+
|
|
1558
|
+
def _loop() -> None:
|
|
1559
|
+
if parado.is_set():
|
|
1560
|
+
return
|
|
1561
|
+
self._call_on_ui(fn)
|
|
1562
|
+
if not parado.is_set():
|
|
1563
|
+
t = threading.Timer(interval_ms / 1000.0, _loop)
|
|
1564
|
+
t.daemon = True
|
|
1565
|
+
with self._lock:
|
|
1566
|
+
self._timers[handle] = t
|
|
1567
|
+
t.start()
|
|
1568
|
+
|
|
1569
|
+
timer = threading.Timer(interval_ms / 1000.0, _loop)
|
|
1570
|
+
timer.daemon = True
|
|
1571
|
+
with self._lock:
|
|
1572
|
+
self._timers[handle] = timer
|
|
1573
|
+
self._register_cleanup(parado.set)
|
|
1574
|
+
timer.start()
|
|
1575
|
+
return handle
|
|
1576
|
+
|
|
1577
|
+
def clear_timer(self, handle: int) -> None:
|
|
1578
|
+
"""Cancela um timer criado com ``set_timeout`` ou ``set_interval``."""
|
|
1579
|
+
with self._lock:
|
|
1580
|
+
timer = self._timers.pop(handle, None)
|
|
1581
|
+
stop = self._interval_stops.pop(handle, None)
|
|
1582
|
+
if stop is not None:
|
|
1583
|
+
stop.set() # vale também quando chamado de dentro do próprio callback do intervalo
|
|
1584
|
+
if timer is not None:
|
|
1585
|
+
timer.cancel()
|
|
1586
|
+
|
|
1587
|
+
def debounce(self, delay_ms: int, fn: Any) -> Any:
|
|
1588
|
+
"""
|
|
1589
|
+
Retorna versão debounced de ``fn``.
|
|
1590
|
+
|
|
1591
|
+
Chamadas repetidas dentro de ``delay_ms`` ms reiniciam o timer;
|
|
1592
|
+
``fn`` só é chamada uma vez após a última chamada.
|
|
1593
|
+
"""
|
|
1594
|
+
state: dict[str, Any] = {"handle": None}
|
|
1595
|
+
lock = threading.Lock()
|
|
1596
|
+
|
|
1597
|
+
def _debounced(*args: Any, **kwargs: Any) -> None:
|
|
1598
|
+
with lock:
|
|
1599
|
+
if state["handle"] is not None:
|
|
1600
|
+
self.clear_timer(state["handle"])
|
|
1601
|
+
|
|
1602
|
+
def _disparar() -> None:
|
|
1603
|
+
with lock:
|
|
1604
|
+
state["handle"] = None
|
|
1605
|
+
fn(*args, **kwargs)
|
|
1606
|
+
|
|
1607
|
+
state["handle"] = self.set_timeout(delay_ms, _disparar)
|
|
1608
|
+
|
|
1609
|
+
return _debounced
|
|
1610
|
+
|
|
1611
|
+
@staticmethod
|
|
1612
|
+
def throttle(interval_ms: int, fn: Any) -> Any:
|
|
1613
|
+
"""
|
|
1614
|
+
Retorna versão throttled de ``fn``.
|
|
1615
|
+
|
|
1616
|
+
``fn`` é chamada no máximo uma vez a cada ``interval_ms`` ms,
|
|
1617
|
+
com os argumentos mais recentes.
|
|
1618
|
+
"""
|
|
1619
|
+
ultima: dict[str, float] = {"t": 0.0}
|
|
1620
|
+
|
|
1621
|
+
def _throttled(*args: Any, **kwargs: Any) -> None:
|
|
1622
|
+
agora = time.monotonic()
|
|
1623
|
+
if agora - ultima["t"] >= interval_ms / 1000.0:
|
|
1624
|
+
ultima["t"] = agora
|
|
1625
|
+
fn(*args, **kwargs)
|
|
1626
|
+
|
|
1627
|
+
return _throttled
|
|
1628
|
+
|
|
1629
|
+
|
|
1630
|
+
_TRUSTED_PLUGINS_FILE: Path = CONFIG_DIR / "trusted_plugins.json"
|
|
1631
|
+
|
|
1632
|
+
|
|
1633
|
+
def _load_trusted_plugins() -> dict[str, str]:
|
|
1634
|
+
"""Carrega o mapa de plugins confiáveis (plugin_id -> sha256 do código-fonte).
|
|
1635
|
+
|
|
1636
|
+
Formato: ``{"trusted": {"meu_plugin": "<sha256>", ...}}``.
|
|
1637
|
+
"""
|
|
1638
|
+
with contextlib.suppress(OSError, ValueError):
|
|
1639
|
+
if _TRUSTED_PLUGINS_FILE.exists():
|
|
1640
|
+
data = json.loads(_TRUSTED_PLUGINS_FILE.read_text("utf-8"))
|
|
1641
|
+
raw = data.get("trusted", {})
|
|
1642
|
+
if isinstance(raw, dict):
|
|
1643
|
+
return dict(raw)
|
|
1644
|
+
return {}
|
|
1645
|
+
|
|
1646
|
+
|
|
1647
|
+
def _save_trusted_plugins(trusted: dict[str, str]) -> None:
|
|
1648
|
+
"""Grava o mapa de plugins confiáveis (plugin_id -> sha256) sem deixar arquivo pela metade."""
|
|
1649
|
+
with contextlib.suppress(OSError):
|
|
1650
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
1651
|
+
tmp = _TRUSTED_PLUGINS_FILE.with_suffix(".tmp")
|
|
1652
|
+
tmp.write_text(json.dumps({"trusted": dict(sorted(trusted.items()))}, indent=2), "utf-8")
|
|
1653
|
+
tmp.replace(_TRUSTED_PLUGINS_FILE)
|
|
1654
|
+
|
|
1655
|
+
|
|
1656
|
+
def _sandbox_check_imports(source: str) -> tuple[list[str], list[str]]:
|
|
1657
|
+
"""Analisa o código de um plugin.
|
|
1658
|
+
|
|
1659
|
+
Retorna ``(bloqueados, avisos)``. Em ``bloqueados`` entram imports proibidos e
|
|
1660
|
+
chamadas dinâmicas (``eval``, ``exec``, ``__import__``...); em ``avisos``, imports
|
|
1661
|
+
que só merecem atenção. É uma verificação estática, não uma sandbox.
|
|
1662
|
+
"""
|
|
1663
|
+
found = scan_source(source)
|
|
1664
|
+
return found.flagged, found.warned
|
|
1665
|
+
|
|
1666
|
+
|
|
1667
|
+
def _get_plugin_source(path: Path) -> str:
|
|
1668
|
+
"""Código do ponto de entrada do plugin (``plugin.py``, ``__init__.py`` ou o próprio ``.py``)."""
|
|
1669
|
+
files = plugin_sources(path)
|
|
1670
|
+
if not files:
|
|
1671
|
+
return ""
|
|
1672
|
+
if path.suffix == ".py" and path.is_file():
|
|
1673
|
+
return next(iter(files.values()))
|
|
1674
|
+
for wanted in ("plugin.py", "__init__.py"):
|
|
1675
|
+
for name in sorted(files, key=len):
|
|
1676
|
+
if name == wanted or name.endswith("/" + wanted):
|
|
1677
|
+
return files[name]
|
|
1678
|
+
return ""
|
|
1679
|
+
|
|
1680
|
+
|
|
1681
|
+
def _normalize_manifest(manifest: Any) -> PluginManifest:
|
|
1682
|
+
"""
|
|
1683
|
+
Converte qualquer representação de manifesto para PluginManifest.
|
|
1684
|
+
|
|
1685
|
+
Aceita: None, PluginManifest, dict, SimpleNamespace ou objeto com __dict__.
|
|
1686
|
+
"""
|
|
1687
|
+
if manifest is None:
|
|
1688
|
+
return PluginManifest(name="")
|
|
1689
|
+
if isinstance(manifest, PluginManifest):
|
|
1690
|
+
return manifest
|
|
1691
|
+
chaves_validas = {f.name for f in fields(PluginManifest)}
|
|
1692
|
+
if isinstance(manifest, dict):
|
|
1693
|
+
filtrado = {k: v for k, v in manifest.items() if k in chaves_validas}
|
|
1694
|
+
return PluginManifest(**filtrado)
|
|
1695
|
+
if hasattr(manifest, "__dict__"):
|
|
1696
|
+
filtrado = {k: v for k, v in vars(
|
|
1697
|
+
manifest).items() if k in chaves_validas}
|
|
1698
|
+
return PluginManifest(**filtrado)
|
|
1699
|
+
return PluginManifest(name=str(manifest))
|
|
1700
|
+
|
|
1701
|
+
|
|
1702
|
+
def _get_plugin_readme(path: Path | None, mod: Any = None) -> str:
|
|
1703
|
+
"""
|
|
1704
|
+
Retorna o README do plugin em Markdown.
|
|
1705
|
+
|
|
1706
|
+
Prioridade:
|
|
1707
|
+
1. ``MANIFEST.readme`` inline
|
|
1708
|
+
2. README.md / README.rst ao lado do arquivo ou dentro do ZIP
|
|
1709
|
+
3. Gerado a partir dos campos do MANIFEST (fallback)
|
|
1710
|
+
"""
|
|
1711
|
+
if mod is not None:
|
|
1712
|
+
manifest = getattr(mod, "MANIFEST", None)
|
|
1713
|
+
if manifest and getattr(manifest, "readme", ""):
|
|
1714
|
+
return manifest.readme
|
|
1715
|
+
|
|
1716
|
+
nomes_readme = [
|
|
1717
|
+
"README.md",
|
|
1718
|
+
"readme.md",
|
|
1719
|
+
"README.rst",
|
|
1720
|
+
"README.txt",
|
|
1721
|
+
"readme.txt",
|
|
1722
|
+
"README",
|
|
1723
|
+
]
|
|
1724
|
+
|
|
1725
|
+
if path is not None:
|
|
1726
|
+
if path.is_dir():
|
|
1727
|
+
for name in nomes_readme:
|
|
1728
|
+
f = path / name
|
|
1729
|
+
if f.exists():
|
|
1730
|
+
with contextlib.suppress(OSError):
|
|
1731
|
+
return f.read_text("utf-8", errors="replace")
|
|
1732
|
+
elif path.suffix == ".zip":
|
|
1733
|
+
with contextlib.suppress(tk.TclError), zipfile.ZipFile(path) as zf:
|
|
1734
|
+
for name in nomes_readme:
|
|
1735
|
+
if name in zf.namelist():
|
|
1736
|
+
return zf.read(name).decode("utf-8", errors="replace")
|
|
1737
|
+
elif path.suffix == ".py":
|
|
1738
|
+
for name in nomes_readme:
|
|
1739
|
+
f = path.parent / name
|
|
1740
|
+
if f.exists():
|
|
1741
|
+
with contextlib.suppress(OSError):
|
|
1742
|
+
return f.read_text("utf-8", errors="replace")
|
|
1743
|
+
|
|
1744
|
+
if mod is not None:
|
|
1745
|
+
manifest = _normalize_manifest(getattr(mod, "MANIFEST", None))
|
|
1746
|
+
if manifest:
|
|
1747
|
+
lines = [f"# {manifest.name}"]
|
|
1748
|
+
if manifest.version:
|
|
1749
|
+
lines.append(f"**Versão:** {manifest.version}")
|
|
1750
|
+
if manifest.author:
|
|
1751
|
+
lines.append(f"**Autor:** {manifest.author}")
|
|
1752
|
+
if manifest.description:
|
|
1753
|
+
lines.append(f"\n{manifest.description}")
|
|
1754
|
+
if manifest.tags:
|
|
1755
|
+
lines.append("\n**Tags:** " + ", ".join(manifest.tags))
|
|
1756
|
+
if manifest.homepage:
|
|
1757
|
+
lines.append(f"\n[Homepage]({manifest.homepage})")
|
|
1758
|
+
if manifest.changelog:
|
|
1759
|
+
lines.append(f"\n---\n\n## Changelog\n\n{manifest.changelog}")
|
|
1760
|
+
return "\n\n".join(lines)
|
|
1761
|
+
return "*(Sem documentação disponível)*"
|