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
|
@@ -0,0 +1,763 @@
|
|
|
1
|
+
"""Host Python dos plugins do Sublime Text: um subconjunto das APIs ``sublime`` e ``sublime_plugin``.
|
|
2
|
+
|
|
3
|
+
Roda em um interpretador externo, falando com o Codis por JSON em linhas (stdin/stdout).
|
|
4
|
+
Uso: python -I py_host.py <pasta-do-pacote> <pasta-de-dados> [permissões separadas por vírgula]
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import heapq
|
|
11
|
+
import importlib.util
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import queue
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
import sysconfig
|
|
18
|
+
import threading
|
|
19
|
+
import time
|
|
20
|
+
import types
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
_PROTOCOL = sys.stdout
|
|
25
|
+
PACKAGE_DIR = Path(sys.argv[1]).resolve()
|
|
26
|
+
STORAGE_DIR = Path(sys.argv[2]).resolve()
|
|
27
|
+
GRANTED = frozenset(p for p in (sys.argv[3] if len(sys.argv) > 3 else "").split(",") if p)
|
|
28
|
+
_send_lock = threading.Lock()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _send(message: dict[str, Any]) -> None:
|
|
32
|
+
with _send_lock:
|
|
33
|
+
_PROTOCOL.write(json.dumps(message, ensure_ascii=False) + "\n")
|
|
34
|
+
_PROTOCOL.flush()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _LogStream:
|
|
38
|
+
def __init__(self, level: str) -> None:
|
|
39
|
+
self.level = level
|
|
40
|
+
|
|
41
|
+
def write(self, text: str) -> int:
|
|
42
|
+
if text.strip():
|
|
43
|
+
_send({"t": "evt", "op": "log", "level": self.level, "text": text[:4000]})
|
|
44
|
+
return len(text)
|
|
45
|
+
|
|
46
|
+
def flush(self) -> None:
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
sys.stdout, sys.stderr = _LogStream("stdout"), _LogStream("stderr") # type: ignore[assignment]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# --- restrições (reduzem estragos, não são um isolamento completo) -------------------------
|
|
54
|
+
# Cada grupo de eventos de auditoria depende de uma permissão; sem ela a operação é recusada.
|
|
55
|
+
|
|
56
|
+
_PROCESS_EVENTS = {
|
|
57
|
+
"subprocess.Popen", "os.system", "os.exec", "os.posix_spawn", "os.spawn", "os.fork", "os.forkpty",
|
|
58
|
+
}
|
|
59
|
+
_NATIVE_EVENTS = {"ctypes.dlopen", "ctypes.dlsym", "ctypes.call_function", "ctypes.cdata", "winreg.OpenKey"}
|
|
60
|
+
_NEEDS = {**dict.fromkeys(_PROCESS_EVENTS, ("process", "Processos")), **dict.fromkeys(_NATIVE_EVENTS, ("native", "Módulos nativos"))}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _can(perm: str) -> bool:
|
|
64
|
+
return "unrestricted" in GRANTED or perm in GRANTED
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _roots(*extra: Any) -> list[str]:
|
|
68
|
+
paths = {sys.prefix, sys.base_prefix, sys.exec_prefix, *(str(v) for v in sysconfig.get_paths().values())}
|
|
69
|
+
paths.update(str(p) for p in extra)
|
|
70
|
+
paths.update({"/usr/lib", "/usr/share", "/lib", "/etc/localtime", "/etc/ssl", "/dev", "/proc/self"})
|
|
71
|
+
return [os.path.normcase(os.path.realpath(p)) for p in paths if p]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
_READ_ROOTS = _roots(PACKAGE_DIR, STORAGE_DIR, Path(__file__).parent, os.environ.get("TEMP", ""), os.environ.get("SYSTEMROOT", ""))
|
|
75
|
+
_WRITE_ROOTS = [os.path.normcase(os.path.realpath(str(STORAGE_DIR)))]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
_DEVNULL = {os.path.normcase(os.devnull), os.path.normcase("\\\\.\\nul")}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _is_devnull(path: str) -> bool:
|
|
82
|
+
return os.path.normcase(path) in _DEVNULL
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _inside(path: str, roots: list[str]) -> bool:
|
|
86
|
+
real = os.path.normcase(os.path.realpath(path))
|
|
87
|
+
return any(real == r or real.startswith(r + os.sep) for r in roots)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _audit(event: str, args: tuple[Any, ...]) -> None:
|
|
91
|
+
need = _NEEDS.get(event)
|
|
92
|
+
if need is not None and not _can(need[0]):
|
|
93
|
+
raise PermissionError(f"operação bloqueada pelo Codis: {event} (exige a permissão \"{need[1]}\" desta extensão)")
|
|
94
|
+
if event == "open" and args and isinstance(args[0], (str, bytes, os.PathLike)) and not _can("files"):
|
|
95
|
+
path = os.fsdecode(args[0])
|
|
96
|
+
mode = str(args[1] or "r") if len(args) > 1 else "r"
|
|
97
|
+
writing = any(c in mode for c in "wax+")
|
|
98
|
+
if not path or path.isdigit() or _is_devnull(path):
|
|
99
|
+
return
|
|
100
|
+
if writing and not _inside(path, _WRITE_ROOTS):
|
|
101
|
+
raise PermissionError(f"escrita fora da pasta de dados da extensão: {path} (exige a permissão \"Arquivos\")")
|
|
102
|
+
if not writing and not _inside(path, _READ_ROOTS):
|
|
103
|
+
raise PermissionError(f"leitura fora da pasta da extensão: {path} (exige a permissão \"Arquivos\")")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# --- API do Sublime -----------------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
_unsupported: set[str] = set()
|
|
109
|
+
_pending: dict[int, dict[str, Any]] = {}
|
|
110
|
+
_pending_lock = threading.Lock()
|
|
111
|
+
_next_req = [1]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _note(name: str) -> None:
|
|
115
|
+
if name not in _unsupported:
|
|
116
|
+
_unsupported.add(name)
|
|
117
|
+
_send({"t": "evt", "op": "unsupported", "api": name})
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _request(op: str, **payload: Any) -> Any:
|
|
121
|
+
with _pending_lock:
|
|
122
|
+
req_id = _next_req[0]
|
|
123
|
+
_next_req[0] += 1
|
|
124
|
+
slot = {"event": threading.Event(), "reply": None}
|
|
125
|
+
_pending[req_id] = slot
|
|
126
|
+
_send({"t": "req", "id": req_id, "op": op, **payload})
|
|
127
|
+
slot["event"].wait()
|
|
128
|
+
reply = slot["reply"] or {}
|
|
129
|
+
if reply.get("ok") is False:
|
|
130
|
+
raise RuntimeError(reply.get("error") or "recusado")
|
|
131
|
+
return reply.get("value")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class Region:
|
|
135
|
+
def __init__(self, a: int, b: int | None = None) -> None:
|
|
136
|
+
self.a, self.b = a, a if b is None else b
|
|
137
|
+
|
|
138
|
+
def begin(self) -> int:
|
|
139
|
+
return min(self.a, self.b)
|
|
140
|
+
|
|
141
|
+
def end(self) -> int:
|
|
142
|
+
return max(self.a, self.b)
|
|
143
|
+
|
|
144
|
+
def size(self) -> int:
|
|
145
|
+
return self.end() - self.begin()
|
|
146
|
+
|
|
147
|
+
def empty(self) -> bool:
|
|
148
|
+
return self.a == self.b
|
|
149
|
+
|
|
150
|
+
def contains(self, x: Any) -> bool:
|
|
151
|
+
if isinstance(x, Region):
|
|
152
|
+
return self.begin() <= x.begin() and x.end() <= self.end()
|
|
153
|
+
return self.begin() <= x <= self.end()
|
|
154
|
+
|
|
155
|
+
def intersects(self, other: Region) -> bool:
|
|
156
|
+
return self.begin() < other.end() and other.begin() < self.end() or self == other
|
|
157
|
+
|
|
158
|
+
def cover(self, other: Region) -> Region:
|
|
159
|
+
return Region(min(self.begin(), other.begin()), max(self.end(), other.end()))
|
|
160
|
+
|
|
161
|
+
def __eq__(self, other: object) -> bool:
|
|
162
|
+
return isinstance(other, Region) and (self.a, self.b) == (other.a, other.b)
|
|
163
|
+
|
|
164
|
+
def __hash__(self) -> int:
|
|
165
|
+
return hash((self.a, self.b))
|
|
166
|
+
|
|
167
|
+
def __iter__(self):
|
|
168
|
+
return iter((self.a, self.b))
|
|
169
|
+
|
|
170
|
+
def __repr__(self) -> str:
|
|
171
|
+
return f"Region({self.a}, {self.b})"
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class Selection:
|
|
175
|
+
def __init__(self, regions: list[Region]) -> None:
|
|
176
|
+
self._r = regions
|
|
177
|
+
|
|
178
|
+
def __iter__(self):
|
|
179
|
+
return iter(list(self._r))
|
|
180
|
+
|
|
181
|
+
def __len__(self) -> int:
|
|
182
|
+
return len(self._r)
|
|
183
|
+
|
|
184
|
+
def __getitem__(self, i: int) -> Region:
|
|
185
|
+
return self._r[i]
|
|
186
|
+
|
|
187
|
+
def add(self, region: Any) -> None:
|
|
188
|
+
self._r.append(region if isinstance(region, Region) else Region(region))
|
|
189
|
+
|
|
190
|
+
def clear(self) -> None:
|
|
191
|
+
self._r.clear()
|
|
192
|
+
|
|
193
|
+
def add_all(self, regions: Any) -> None:
|
|
194
|
+
for r in regions:
|
|
195
|
+
self.add(r)
|
|
196
|
+
|
|
197
|
+
def subtract(self, region: Region) -> None:
|
|
198
|
+
self._r = [r for r in self._r if r != region]
|
|
199
|
+
|
|
200
|
+
def contains(self, region: Region) -> bool:
|
|
201
|
+
return any(r.contains(region) for r in self._r)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class Settings(dict):
|
|
205
|
+
def get(self, key: str, default: Any = None) -> Any:
|
|
206
|
+
return super().get(key, default)
|
|
207
|
+
|
|
208
|
+
def set(self, key: str, value: Any) -> None:
|
|
209
|
+
self[key] = value
|
|
210
|
+
|
|
211
|
+
def has(self, key: str) -> bool:
|
|
212
|
+
return key in self
|
|
213
|
+
|
|
214
|
+
def erase(self, key: str) -> None:
|
|
215
|
+
self.pop(key, None)
|
|
216
|
+
|
|
217
|
+
def add_on_change(self, *_: Any) -> None:
|
|
218
|
+
pass
|
|
219
|
+
|
|
220
|
+
def clear_on_change(self, *_: Any) -> None:
|
|
221
|
+
pass
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class Edit:
|
|
225
|
+
pass
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class View:
|
|
229
|
+
def __init__(self, snapshot: dict[str, Any] | None, window: Window) -> None:
|
|
230
|
+
snapshot = snapshot or {"text": "", "path": None, "lang": "text", "dirty": False}
|
|
231
|
+
self._text: str = snapshot["text"]
|
|
232
|
+
self._orig: str = snapshot["text"]
|
|
233
|
+
self._path: str | None = snapshot.get("path")
|
|
234
|
+
self._dirty: bool = bool(snapshot.get("dirty"))
|
|
235
|
+
self._window = window
|
|
236
|
+
self._settings = Settings({"tab_size": 4, "translate_tabs_to_spaces": False})
|
|
237
|
+
self._sel = Selection([])
|
|
238
|
+
|
|
239
|
+
# texto
|
|
240
|
+
def size(self) -> int:
|
|
241
|
+
return len(self._text)
|
|
242
|
+
|
|
243
|
+
def substr(self, x: Any) -> str:
|
|
244
|
+
if isinstance(x, Region):
|
|
245
|
+
return self._text[x.begin() : x.end()]
|
|
246
|
+
return self._text[x : x + 1]
|
|
247
|
+
|
|
248
|
+
def line(self, x: Any) -> Region:
|
|
249
|
+
pos = x.begin() if isinstance(x, Region) else x
|
|
250
|
+
start = self._text.rfind("\n", 0, pos) + 1
|
|
251
|
+
end = self._text.find("\n", pos)
|
|
252
|
+
return Region(start, len(self._text) if end == -1 else end)
|
|
253
|
+
|
|
254
|
+
def full_line(self, x: Any) -> Region:
|
|
255
|
+
r = self.line(x)
|
|
256
|
+
return Region(r.begin(), min(r.end() + 1, len(self._text)))
|
|
257
|
+
|
|
258
|
+
def lines(self, region: Region) -> list[Region]:
|
|
259
|
+
out, pos = [], region.begin()
|
|
260
|
+
while True:
|
|
261
|
+
ln = self.line(pos)
|
|
262
|
+
out.append(ln)
|
|
263
|
+
if ln.end() >= region.end() or ln.end() >= len(self._text):
|
|
264
|
+
return out
|
|
265
|
+
pos = ln.end() + 1
|
|
266
|
+
|
|
267
|
+
def word(self, x: Any) -> Region:
|
|
268
|
+
pos = x.begin() if isinstance(x, Region) else x
|
|
269
|
+
a = pos
|
|
270
|
+
while a > 0 and (self._text[a - 1].isalnum() or self._text[a - 1] == "_"):
|
|
271
|
+
a -= 1
|
|
272
|
+
b = pos
|
|
273
|
+
while b < len(self._text) and (self._text[b].isalnum() or self._text[b] == "_"):
|
|
274
|
+
b += 1
|
|
275
|
+
return Region(a, b)
|
|
276
|
+
|
|
277
|
+
def rowcol(self, pt: int) -> tuple[int, int]:
|
|
278
|
+
row = self._text.count("\n", 0, pt)
|
|
279
|
+
return row, pt - (self._text.rfind("\n", 0, pt) + 1)
|
|
280
|
+
|
|
281
|
+
def text_point(self, row: int, col: int) -> int:
|
|
282
|
+
pos = 0
|
|
283
|
+
for _ in range(row):
|
|
284
|
+
nxt = self._text.find("\n", pos)
|
|
285
|
+
if nxt == -1:
|
|
286
|
+
return len(self._text)
|
|
287
|
+
pos = nxt + 1
|
|
288
|
+
return min(pos + col, len(self._text))
|
|
289
|
+
|
|
290
|
+
# edição: altera o buffer local; o resultado vai ao Codis no fim do comando
|
|
291
|
+
def replace(self, edit: Edit, region: Region, text: str) -> None:
|
|
292
|
+
self._text = self._text[: region.begin()] + text + self._text[region.end() :]
|
|
293
|
+
self._shift_after(region.end(), len(text) - region.size())
|
|
294
|
+
|
|
295
|
+
def insert(self, edit: Edit, point: int, text: str) -> int:
|
|
296
|
+
self._text = self._text[:point] + text + self._text[point:]
|
|
297
|
+
self._shift_after(point, len(text))
|
|
298
|
+
return len(text)
|
|
299
|
+
|
|
300
|
+
def erase(self, edit: Edit, region: Region) -> None:
|
|
301
|
+
self.replace(edit, region, "")
|
|
302
|
+
|
|
303
|
+
def _shift_after(self, at: int, delta: int) -> None:
|
|
304
|
+
if not delta:
|
|
305
|
+
return
|
|
306
|
+
for r in self._sel._r:
|
|
307
|
+
if r.a >= at:
|
|
308
|
+
r.a += delta
|
|
309
|
+
if r.b >= at:
|
|
310
|
+
r.b += delta
|
|
311
|
+
|
|
312
|
+
# estado
|
|
313
|
+
def sel(self) -> Selection:
|
|
314
|
+
return self._sel
|
|
315
|
+
|
|
316
|
+
def file_name(self) -> str | None:
|
|
317
|
+
return self._path
|
|
318
|
+
|
|
319
|
+
def name(self) -> str:
|
|
320
|
+
return Path(self._path).name if self._path else ""
|
|
321
|
+
|
|
322
|
+
def is_dirty(self) -> bool:
|
|
323
|
+
return self._dirty
|
|
324
|
+
|
|
325
|
+
def is_read_only(self) -> bool:
|
|
326
|
+
return False
|
|
327
|
+
|
|
328
|
+
def id(self) -> int:
|
|
329
|
+
return 1
|
|
330
|
+
|
|
331
|
+
def buffer_id(self) -> int:
|
|
332
|
+
return 1
|
|
333
|
+
|
|
334
|
+
def window(self) -> Window:
|
|
335
|
+
return self._window
|
|
336
|
+
|
|
337
|
+
def settings(self) -> Settings:
|
|
338
|
+
return self._settings
|
|
339
|
+
|
|
340
|
+
def scope_name(self, _pt: int = 0) -> str:
|
|
341
|
+
return "text.plain "
|
|
342
|
+
|
|
343
|
+
def match_selector(self, *_: Any) -> bool:
|
|
344
|
+
return False
|
|
345
|
+
|
|
346
|
+
def set_status(self, key: str, text: str) -> None:
|
|
347
|
+
_send({"t": "evt", "op": "status", "text": text})
|
|
348
|
+
|
|
349
|
+
def erase_status(self, key: str) -> None:
|
|
350
|
+
_send({"t": "evt", "op": "status", "text": ""})
|
|
351
|
+
|
|
352
|
+
def show(self, *_: Any, **__: Any) -> None:
|
|
353
|
+
pass
|
|
354
|
+
|
|
355
|
+
def show_at_center(self, *_: Any) -> None:
|
|
356
|
+
pass
|
|
357
|
+
|
|
358
|
+
def set_name(self, *_: Any) -> None:
|
|
359
|
+
pass
|
|
360
|
+
|
|
361
|
+
def run_command(self, name: str, args: dict[str, Any] | None = None) -> None:
|
|
362
|
+
run_command(name, args or {}, view=self, window=self._window)
|
|
363
|
+
|
|
364
|
+
def find(self, pattern: str, start: int, flags: int = 0) -> Region:
|
|
365
|
+
m = re.compile(pattern if not flags & LITERAL else re.escape(pattern)).search(self._text, start)
|
|
366
|
+
return Region(m.start(), m.end()) if m else Region(-1, -1)
|
|
367
|
+
|
|
368
|
+
def find_all(self, pattern: str, flags: int = 0) -> list[Region]:
|
|
369
|
+
rx = re.compile(pattern if not flags & LITERAL else re.escape(pattern))
|
|
370
|
+
return [Region(m.start(), m.end()) for m in rx.finditer(self._text)]
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
class Window:
|
|
374
|
+
def __init__(self) -> None:
|
|
375
|
+
self._view: View | None = None
|
|
376
|
+
self._folders: list[str] = []
|
|
377
|
+
|
|
378
|
+
def active_view(self) -> View | None:
|
|
379
|
+
return self._view
|
|
380
|
+
|
|
381
|
+
def views(self) -> list[View]:
|
|
382
|
+
return [self._view] if self._view else []
|
|
383
|
+
|
|
384
|
+
def folders(self) -> list[str]:
|
|
385
|
+
return list(self._folders)
|
|
386
|
+
|
|
387
|
+
def id(self) -> int:
|
|
388
|
+
return 1
|
|
389
|
+
|
|
390
|
+
def status_message(self, text: str) -> None:
|
|
391
|
+
status_message(text)
|
|
392
|
+
|
|
393
|
+
def run_command(self, name: str, args: dict[str, Any] | None = None) -> None:
|
|
394
|
+
run_command(name, args or {}, view=self._view, window=self)
|
|
395
|
+
|
|
396
|
+
def show_input_panel(self, caption: str, initial: str, on_done: Any, on_change: Any, on_cancel: Any) -> None:
|
|
397
|
+
value = _request("input", prompt=caption, value=initial, password=False)
|
|
398
|
+
if isinstance(value, str):
|
|
399
|
+
if on_done:
|
|
400
|
+
on_done(value)
|
|
401
|
+
elif on_cancel:
|
|
402
|
+
on_cancel()
|
|
403
|
+
|
|
404
|
+
def show_quick_panel(self, items: list[Any], on_select: Any, flags: int = 0, selected_index: int = -1, *_: Any) -> None:
|
|
405
|
+
labels = [i if isinstance(i, str) else " — ".join(str(x) for x in i) for i in items]
|
|
406
|
+
picked = _request("pick", title="", items=labels, multi=False)
|
|
407
|
+
if on_select:
|
|
408
|
+
on_select(picked if isinstance(picked, int) else -1)
|
|
409
|
+
|
|
410
|
+
def new_file(self, *_: Any, **__: Any) -> View:
|
|
411
|
+
_note("Window.new_file")
|
|
412
|
+
return View(None, self)
|
|
413
|
+
|
|
414
|
+
def open_file(self, *_: Any, **__: Any) -> None:
|
|
415
|
+
_note("Window.open_file")
|
|
416
|
+
raise RuntimeError("Window.open_file não é suportado pelo Codis")
|
|
417
|
+
|
|
418
|
+
def create_output_panel(self, name: str) -> View:
|
|
419
|
+
return View(None, self)
|
|
420
|
+
|
|
421
|
+
def get_output_panel(self, name: str) -> View:
|
|
422
|
+
return View(None, self)
|
|
423
|
+
|
|
424
|
+
def project_data(self) -> None:
|
|
425
|
+
return None
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
class _Namespace(types.ModuleType):
|
|
429
|
+
def __getattr__(self, name: str) -> Any:
|
|
430
|
+
if name.startswith("__"):
|
|
431
|
+
raise AttributeError(name)
|
|
432
|
+
_note(f"sublime.{name}")
|
|
433
|
+
return lambda *a, **k: None
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
LITERAL, IGNORECASE = 1, 2
|
|
437
|
+
HIDDEN, DRAW_EMPTY, MONOSPACE_FONT = 4, 1, 1
|
|
438
|
+
_window = Window()
|
|
439
|
+
_timers: list[tuple[float, int, Any]] = []
|
|
440
|
+
_timer_ids = [0]
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def status_message(text: str) -> None:
|
|
444
|
+
_send({"t": "evt", "op": "status", "text": str(text)})
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def message_dialog(text: str) -> None:
|
|
448
|
+
_request("message", level="info", text=str(text), items=[])
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def error_message(text: str) -> None:
|
|
452
|
+
_request("message", level="error", text=str(text), items=[])
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def ok_cancel_dialog(text: str, ok_title: str = "OK", title: str = "") -> bool:
|
|
456
|
+
return _request("message", level="info", text=str(text), items=[ok_title or "OK", "Cancelar"]) == 0
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def yes_no_cancel_dialog(text: str, yes_title: str = "Sim", no_title: str = "Não") -> int:
|
|
460
|
+
choice = _request("message", level="info", text=str(text), items=[yes_title, no_title, "Cancelar"])
|
|
461
|
+
return {0: 1, 1: 2}.get(choice, 0) # DIALOG_YES = 1, DIALOG_NO = 2, DIALOG_CANCEL = 0
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def set_timeout(callback: Any, delay: int = 0) -> None:
|
|
465
|
+
_timer_ids[0] += 1
|
|
466
|
+
heapq.heappush(_timers, (time.monotonic() + delay / 1000, _timer_ids[0], callback))
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
set_timeout_async = set_timeout
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def load_settings(name: str) -> Settings:
|
|
473
|
+
settings = Settings()
|
|
474
|
+
target = PACKAGE_DIR / name
|
|
475
|
+
if target.is_file():
|
|
476
|
+
with contextlib.suppress(ValueError, OSError):
|
|
477
|
+
settings.update(json.loads(re.sub(r"^\s*//.*$", "", target.read_text("utf-8"), flags=re.MULTILINE)))
|
|
478
|
+
return settings
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def save_settings(name: str) -> None:
|
|
482
|
+
pass
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def active_window() -> Window:
|
|
486
|
+
return _window
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def windows() -> list[Window]:
|
|
490
|
+
return [_window]
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def version() -> str:
|
|
494
|
+
return "4126"
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def platform() -> str:
|
|
498
|
+
return {"win32": "windows", "darwin": "osx"}.get(sys.platform, "linux")
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def arch() -> str:
|
|
502
|
+
return "x64"
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def channel() -> str:
|
|
506
|
+
return "stable"
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def log_message(text: str) -> None:
|
|
510
|
+
print(text)
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def packages_path() -> str:
|
|
514
|
+
return str(PACKAGE_DIR.parent)
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def cache_path() -> str:
|
|
518
|
+
return str(STORAGE_DIR)
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def expand_variables(value: Any, variables: dict[str, str]) -> Any:
|
|
522
|
+
if isinstance(value, str):
|
|
523
|
+
return re.sub(r"\$\{(\w+)\}", lambda m: variables.get(m.group(1), m.group(0)), value)
|
|
524
|
+
return value
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def set_clipboard(text: str) -> None:
|
|
528
|
+
_request("clipboard", op="write", text=text)
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def get_clipboard(limit: int = 0) -> str:
|
|
532
|
+
return str(_request("clipboard", op="read") or "")
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
# --- sublime_plugin -----------------------------------------------------------------------
|
|
536
|
+
|
|
537
|
+
_commands: dict[str, type] = {}
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _command_name(cls_name: str) -> str:
|
|
541
|
+
base = cls_name[:-7] if cls_name.endswith("Command") else cls_name
|
|
542
|
+
return re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", base).lower()
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
class _Command:
|
|
546
|
+
def __init_subclass__(cls, **kw: Any) -> None:
|
|
547
|
+
super().__init_subclass__(**kw)
|
|
548
|
+
if cls.__module__ != __name__ and any(b in (TextCommand, WindowCommand, ApplicationCommand) for b in cls.__mro__):
|
|
549
|
+
_commands[_command_name(cls.__name__)] = cls
|
|
550
|
+
|
|
551
|
+
def is_enabled(self, *_: Any, **__: Any) -> bool:
|
|
552
|
+
return True
|
|
553
|
+
|
|
554
|
+
def is_visible(self, *_: Any, **__: Any) -> bool:
|
|
555
|
+
return True
|
|
556
|
+
|
|
557
|
+
def description(self, *_: Any, **__: Any) -> str:
|
|
558
|
+
return ""
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
class ApplicationCommand(_Command):
|
|
562
|
+
pass
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
class WindowCommand(_Command):
|
|
566
|
+
def __init__(self, window: Window) -> None:
|
|
567
|
+
self.window = window
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
class TextCommand(_Command):
|
|
571
|
+
def __init__(self, view: View) -> None:
|
|
572
|
+
self.view = view
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
class EventListener:
|
|
576
|
+
def __init_subclass__(cls, **kw: Any) -> None:
|
|
577
|
+
super().__init_subclass__(**kw)
|
|
578
|
+
for name in dir(cls):
|
|
579
|
+
if name.startswith("on_") and callable(getattr(cls, name)):
|
|
580
|
+
_note(f"EventListener.{name}")
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
class ViewEventListener(EventListener):
|
|
584
|
+
pass
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
class TextInputHandler:
|
|
588
|
+
pass
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
class ListInputHandler:
|
|
592
|
+
pass
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def run_command(name: str, args: dict[str, Any], *, view: View | None, window: Window | None) -> None:
|
|
596
|
+
cls = _commands.get(name)
|
|
597
|
+
if cls is None:
|
|
598
|
+
raise RuntimeError(f"comando '{name}' não existe nesta extensão")
|
|
599
|
+
window = window or _window
|
|
600
|
+
if issubclass(cls, TextCommand):
|
|
601
|
+
if view is None:
|
|
602
|
+
raise RuntimeError("não há arquivo aberto no editor")
|
|
603
|
+
inst = cls(view)
|
|
604
|
+
if not inst.is_enabled(**args):
|
|
605
|
+
raise RuntimeError(f"comando '{name}' está desabilitado agora")
|
|
606
|
+
inst.run(Edit(), **args)
|
|
607
|
+
elif issubclass(cls, WindowCommand):
|
|
608
|
+
inst = cls(window)
|
|
609
|
+
if not inst.is_enabled(**args):
|
|
610
|
+
raise RuntimeError(f"comando '{name}' está desabilitado agora")
|
|
611
|
+
inst.run(**args)
|
|
612
|
+
else:
|
|
613
|
+
inst = cls()
|
|
614
|
+
inst.run(**args)
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
def _install_modules() -> None:
|
|
618
|
+
sublime = _Namespace("sublime")
|
|
619
|
+
for name, value in list(globals().items()):
|
|
620
|
+
if name in ("Region", "Selection", "View", "Window", "Edit", "Settings", "LITERAL", "IGNORECASE", "HIDDEN", "DRAW_EMPTY",
|
|
621
|
+
"MONOSPACE_FONT", "status_message", "message_dialog", "error_message", "ok_cancel_dialog",
|
|
622
|
+
"yes_no_cancel_dialog", "set_timeout", "set_timeout_async", "load_settings", "save_settings",
|
|
623
|
+
"active_window", "windows", "version", "platform", "arch", "channel", "log_message", "packages_path",
|
|
624
|
+
"cache_path", "expand_variables", "set_clipboard", "get_clipboard"):
|
|
625
|
+
setattr(sublime, name, value)
|
|
626
|
+
sublime.DIALOG_CANCEL, sublime.DIALOG_YES, sublime.DIALOG_NO = 0, 1, 2
|
|
627
|
+
plugin = types.ModuleType("sublime_plugin")
|
|
628
|
+
for cls in (ApplicationCommand, WindowCommand, TextCommand, EventListener, ViewEventListener, TextInputHandler, ListInputHandler):
|
|
629
|
+
setattr(plugin, cls.__name__, cls)
|
|
630
|
+
sys.modules["sublime"], sys.modules["sublime_plugin"] = sublime, plugin
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
# --- carregamento e laço principal ---------------------------------------------------------
|
|
634
|
+
|
|
635
|
+
_inbox: queue.Queue[dict[str, Any]] = queue.Queue()
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def _reader() -> None:
|
|
639
|
+
for line in sys.__stdin__:
|
|
640
|
+
try:
|
|
641
|
+
msg = json.loads(line)
|
|
642
|
+
except ValueError:
|
|
643
|
+
continue
|
|
644
|
+
if msg.get("t") == "reply":
|
|
645
|
+
with _pending_lock:
|
|
646
|
+
slot = _pending.pop(msg.get("id"), None)
|
|
647
|
+
if slot:
|
|
648
|
+
slot["reply"] = msg
|
|
649
|
+
slot["event"].set()
|
|
650
|
+
else:
|
|
651
|
+
_inbox.put(msg)
|
|
652
|
+
_inbox.put({"t": "shutdown"})
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def _load_package() -> list[str]:
|
|
656
|
+
pkg_name = re.sub(r"\W", "_", PACKAGE_DIR.name) or "pkg"
|
|
657
|
+
package = types.ModuleType(pkg_name)
|
|
658
|
+
package.__path__ = [str(PACKAGE_DIR)] # type: ignore[attr-defined]
|
|
659
|
+
sys.modules[pkg_name] = package
|
|
660
|
+
sys.path.insert(0, str(PACKAGE_DIR))
|
|
661
|
+
loaded = []
|
|
662
|
+
for file in sorted(PACKAGE_DIR.glob("*.py")):
|
|
663
|
+
spec = importlib.util.spec_from_file_location(f"{pkg_name}.{file.stem}", file)
|
|
664
|
+
if spec is None or spec.loader is None:
|
|
665
|
+
continue
|
|
666
|
+
module = importlib.util.module_from_spec(spec)
|
|
667
|
+
sys.modules[spec.name] = module
|
|
668
|
+
spec.loader.exec_module(module)
|
|
669
|
+
loaded.append(file.name)
|
|
670
|
+
if hasattr(module, "plugin_loaded"):
|
|
671
|
+
module.plugin_loaded()
|
|
672
|
+
return loaded
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
def _prepare_window(ctx: dict[str, Any]) -> View | None:
|
|
676
|
+
_window._folders = list(ctx.get("workspace") or [])
|
|
677
|
+
doc = ctx.get("document")
|
|
678
|
+
if not doc:
|
|
679
|
+
_window._view = None
|
|
680
|
+
return None
|
|
681
|
+
view = View(doc, _window)
|
|
682
|
+
offsets = []
|
|
683
|
+
for sel in ctx.get("selections") or [{"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 0}}]:
|
|
684
|
+
a = view.text_point(sel["start"]["line"], sel["start"]["character"])
|
|
685
|
+
b = view.text_point(sel["end"]["line"], sel["end"]["character"])
|
|
686
|
+
offsets.append(Region(a, b))
|
|
687
|
+
view._sel = Selection(offsets)
|
|
688
|
+
_window._view = view
|
|
689
|
+
return view
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
def _diff_edit(old: str, new: str) -> dict[str, Any]:
|
|
693
|
+
"""Uma única edição que transforma ``old`` em ``new`` (prefixo e sufixo em comum ficam de fora)."""
|
|
694
|
+
start = 0
|
|
695
|
+
limit = min(len(old), len(new))
|
|
696
|
+
while start < limit and old[start] == new[start]:
|
|
697
|
+
start += 1
|
|
698
|
+
end_old, end_new = len(old), len(new)
|
|
699
|
+
while end_old > start and end_new > start and old[end_old - 1] == new[end_new - 1]:
|
|
700
|
+
end_old -= 1
|
|
701
|
+
end_new -= 1
|
|
702
|
+
|
|
703
|
+
def pos(offset: int) -> dict[str, int]:
|
|
704
|
+
line = old.count("\n", 0, offset)
|
|
705
|
+
return {"line": line, "character": offset - (old.rfind("\n", 0, offset) + 1)}
|
|
706
|
+
|
|
707
|
+
return {"range": {"start": pos(start), "end": pos(end_old)}, "newText": new[start:end_new]}
|
|
708
|
+
|
|
709
|
+
|
|
710
|
+
def _flush(view: View | None) -> None:
|
|
711
|
+
if view is not None and view._text != view._orig:
|
|
712
|
+
_request("edit", edits=[_diff_edit(view._orig, view._text)])
|
|
713
|
+
view._orig = view._text
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
def _run_due_timers(view: View | None) -> None:
|
|
717
|
+
while _timers and _timers[0][0] <= time.monotonic():
|
|
718
|
+
_, _, callback = heapq.heappop(_timers)
|
|
719
|
+
try:
|
|
720
|
+
callback()
|
|
721
|
+
_flush(view)
|
|
722
|
+
except Exception as exc:
|
|
723
|
+
print(f"erro em set_timeout: {exc!r}")
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
def main() -> None:
|
|
727
|
+
STORAGE_DIR.mkdir(parents=True, exist_ok=True)
|
|
728
|
+
threading.Thread(target=_reader, daemon=True).start()
|
|
729
|
+
_install_modules()
|
|
730
|
+
if "unrestricted" not in GRANTED:
|
|
731
|
+
sys.addaudithook(_audit)
|
|
732
|
+
current: View | None = None
|
|
733
|
+
while True:
|
|
734
|
+
wait = max(0.0, _timers[0][0] - time.monotonic()) if _timers else None
|
|
735
|
+
try:
|
|
736
|
+
msg = _inbox.get(timeout=wait)
|
|
737
|
+
except queue.Empty:
|
|
738
|
+
_run_due_timers(current)
|
|
739
|
+
continue
|
|
740
|
+
kind = msg.get("t")
|
|
741
|
+
if kind == "init":
|
|
742
|
+
try:
|
|
743
|
+
loaded = _load_package()
|
|
744
|
+
_send({"t": "ready", "commands": sorted(_commands), "unsupported": sorted(_unsupported), "files": loaded})
|
|
745
|
+
except BaseException as exc:
|
|
746
|
+
import traceback
|
|
747
|
+
_send({"t": "error", "where": "activate", "message": traceback.format_exc()[-4000:] or repr(exc)})
|
|
748
|
+
elif kind == "exec":
|
|
749
|
+
try:
|
|
750
|
+
current = _prepare_window(msg.get("ctx") or {})
|
|
751
|
+
run_command(msg["command"], (msg.get("args") or [{}])[0] if msg.get("args") else {}, view=current, window=_window)
|
|
752
|
+
_flush(current)
|
|
753
|
+
_send({"t": "result", "id": msg["id"], "ok": True, "value": None})
|
|
754
|
+
except BaseException as exc:
|
|
755
|
+
_send({"t": "result", "id": msg["id"], "ok": False, "error": f"{type(exc).__name__}: {exc}"[:2000]})
|
|
756
|
+
_run_due_timers(current)
|
|
757
|
+
elif kind == "shutdown":
|
|
758
|
+
break
|
|
759
|
+
os._exit(0)
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
if __name__ == "__main__":
|
|
763
|
+
main()
|