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/terminal/backends.py
ADDED
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
"""Backends de pseudo-terminal para o terminal integrado.
|
|
2
|
+
|
|
3
|
+
Cada backend expõe a mesma interface mínima (``read``, ``write``, ``resize``,
|
|
4
|
+
``interrupt``, ``terminate``, ``close``), de modo que a sessão do terminal não
|
|
5
|
+
precisa saber a plataforma:
|
|
6
|
+
|
|
7
|
+
- ``PosixPtyBackend``: ``pty.openpty`` com o PTY como terminal de controle, o
|
|
8
|
+
que habilita ``Ctrl+C``, controle de jobs e ``SIGWINCH`` do jeito do kernel.
|
|
9
|
+
- ``ConPtyBackend``: ConPTY do Windows 10 (1809+) via ``ctypes``.
|
|
10
|
+
- ``WinPtyBackend``: pacote opcional ``winpty``, usado se o ConPTY falhar.
|
|
11
|
+
- ``PipeBackend``: pipes comuns, sem TTY. Interativo só com eco local; é o
|
|
12
|
+
último recurso quando não há PTY disponível.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import contextlib
|
|
18
|
+
import logging
|
|
19
|
+
import os
|
|
20
|
+
import signal
|
|
21
|
+
import subprocess
|
|
22
|
+
import sys
|
|
23
|
+
import threading
|
|
24
|
+
import time
|
|
25
|
+
from abc import ABC, abstractmethod
|
|
26
|
+
from collections.abc import Mapping, Sequence
|
|
27
|
+
|
|
28
|
+
from src import proc_registry
|
|
29
|
+
|
|
30
|
+
logger = logging.getLogger("Codis.Terminal")
|
|
31
|
+
|
|
32
|
+
_NON_INTERACTIVE_FLAGS = frozenset({"-noninteractive"})
|
|
33
|
+
_NO_RC_FLAGS = frozenset({"--norc", "--no-rcs", "--no-config", "-noprofile"})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def interactive_command(cmd: Sequence[str], load_rc: bool = True) -> list[str]:
|
|
37
|
+
"""Ajusta a linha de comando de um shell para uso interativo em PTY.
|
|
38
|
+
|
|
39
|
+
Remove ``-NonInteractive`` (que desliga prompt e edição de linha no
|
|
40
|
+
PowerShell) e, se ``load_rc`` for verdadeiro, também as opções que impedem
|
|
41
|
+
o shell de ler os arquivos de configuração do usuário.
|
|
42
|
+
"""
|
|
43
|
+
blocked = _NON_INTERACTIVE_FLAGS | (_NO_RC_FLAGS if load_rc else frozenset())
|
|
44
|
+
out = [cmd[0]] + [arg for arg in cmd[1:] if arg.lower() not in blocked]
|
|
45
|
+
return out
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def child_process_env(base: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
49
|
+
"""Ambiente para programas externos lançados pelo Codis.
|
|
50
|
+
|
|
51
|
+
Num executável do PyInstaller o bootloader aponta ``LD_LIBRARY_PATH`` (ou
|
|
52
|
+
``DYLD_LIBRARY_PATH``) para as bibliotecas embutidas. Um ``bash`` ou um
|
|
53
|
+
servidor de linguagem lançado com isso carrega essas cópias em vez das do
|
|
54
|
+
sistema e pode falhar com segfault; o valor original é restaurado.
|
|
55
|
+
"""
|
|
56
|
+
env = dict(base if base is not None else os.environ)
|
|
57
|
+
for var in ("LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH", "LIBPATH"):
|
|
58
|
+
original = env.pop(f"{var}_ORIG", None)
|
|
59
|
+
if getattr(sys, "frozen", False) or original is not None:
|
|
60
|
+
if original:
|
|
61
|
+
env[var] = original
|
|
62
|
+
else:
|
|
63
|
+
env.pop(var, None)
|
|
64
|
+
from src.pyexec import strip_bundle_env
|
|
65
|
+
|
|
66
|
+
return strip_bundle_env(env)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def terminal_env(base: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
70
|
+
"""Ambiente do shell: ``TERM`` e cores verdadeiras, com UTF-8 garantido."""
|
|
71
|
+
env = child_process_env(base)
|
|
72
|
+
env["TERM"] = "xterm-256color"
|
|
73
|
+
env["COLORTERM"] = "truecolor"
|
|
74
|
+
env["TERM_PROGRAM"] = "Codis"
|
|
75
|
+
env.pop("LINES", None)
|
|
76
|
+
env.pop("COLUMNS", None)
|
|
77
|
+
if sys.platform != "win32" and not any(
|
|
78
|
+
"UTF-8" in env.get(k, "").upper() or "UTF8" in env.get(k, "").upper()
|
|
79
|
+
for k in ("LC_ALL", "LC_CTYPE", "LANG")
|
|
80
|
+
):
|
|
81
|
+
env["LANG"] = "en_US.UTF-8" if sys.platform == "darwin" else "C.UTF-8"
|
|
82
|
+
return env
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Backend(ABC):
|
|
86
|
+
"""Interface comum dos backends."""
|
|
87
|
+
|
|
88
|
+
pid: int | None = None
|
|
89
|
+
local_echo = False
|
|
90
|
+
|
|
91
|
+
@abstractmethod
|
|
92
|
+
def read(self, size: int = 65536) -> bytes:
|
|
93
|
+
"""Bloqueia até haver saída. Devolve ``b""`` no fim do fluxo."""
|
|
94
|
+
|
|
95
|
+
@abstractmethod
|
|
96
|
+
def write(self, data: bytes) -> None:
|
|
97
|
+
"""Escreve ``data`` na entrada do programa (pode bloquear)."""
|
|
98
|
+
|
|
99
|
+
@abstractmethod
|
|
100
|
+
def resize(self, rows: int, cols: int) -> None:
|
|
101
|
+
"""Informa o novo tamanho da janela ao programa."""
|
|
102
|
+
|
|
103
|
+
@abstractmethod
|
|
104
|
+
def terminate(self) -> None:
|
|
105
|
+
"""Encerra o programa e seus filhos, sem bloquear por muito tempo."""
|
|
106
|
+
|
|
107
|
+
@abstractmethod
|
|
108
|
+
def close(self) -> None:
|
|
109
|
+
"""Libera os recursos do sistema."""
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
@abstractmethod
|
|
113
|
+
def alive(self) -> bool:
|
|
114
|
+
"""``True`` enquanto o processo do shell estiver em execução."""
|
|
115
|
+
|
|
116
|
+
def interrupt(self) -> None:
|
|
117
|
+
"""Envia Ctrl+C ao programa em primeiro plano."""
|
|
118
|
+
with contextlib.suppress(OSError):
|
|
119
|
+
self.write(b"\x03")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _kill_tree_posix(pid: int, sig: int) -> None:
|
|
123
|
+
try:
|
|
124
|
+
os.killpg(os.getpgid(pid), sig)
|
|
125
|
+
except (ProcessLookupError, PermissionError, OSError):
|
|
126
|
+
with contextlib.suppress(ProcessLookupError, PermissionError, OSError):
|
|
127
|
+
os.kill(pid, sig)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _session_pids(sid: int) -> list[int]:
|
|
131
|
+
"""PIDs de todos os processos da sessão ``sid`` (inclui jobs em outros grupos).
|
|
132
|
+
|
|
133
|
+
Shells com controle de jobs colocam cada job em um grupo de processos
|
|
134
|
+
próprio, então ``killpg`` no grupo do shell não os alcança; todos, porém,
|
|
135
|
+
continuam na mesma sessão. Usa ``/proc`` quando existe e ``pgrep -s`` nos demais.
|
|
136
|
+
"""
|
|
137
|
+
pids: list[int] = []
|
|
138
|
+
try:
|
|
139
|
+
entries = os.listdir("/proc")
|
|
140
|
+
except OSError:
|
|
141
|
+
entries = None
|
|
142
|
+
if entries is not None:
|
|
143
|
+
for entry in entries:
|
|
144
|
+
if not entry.isdigit():
|
|
145
|
+
continue
|
|
146
|
+
try:
|
|
147
|
+
with open(f"/proc/{entry}/stat", encoding="utf-8", errors="replace") as handle:
|
|
148
|
+
data = handle.read()
|
|
149
|
+
fields = data[data.rindex(")") + 2:].split()
|
|
150
|
+
if int(fields[3]) == sid:
|
|
151
|
+
pids.append(int(entry))
|
|
152
|
+
except (OSError, ValueError, IndexError):
|
|
153
|
+
continue
|
|
154
|
+
return pids
|
|
155
|
+
try:
|
|
156
|
+
out = subprocess.run(
|
|
157
|
+
["pgrep", "-s", str(sid)], capture_output=True, text=True, timeout=2, check=False
|
|
158
|
+
).stdout
|
|
159
|
+
except (OSError, subprocess.SubprocessError):
|
|
160
|
+
return []
|
|
161
|
+
return [int(x) for x in out.split() if x.isdigit()]
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _signal_session(sid: int, sig: int) -> None:
|
|
165
|
+
_kill_tree_posix(sid, sig)
|
|
166
|
+
for pid in _session_pids(sid):
|
|
167
|
+
with contextlib.suppress(ProcessLookupError, PermissionError, OSError):
|
|
168
|
+
os.kill(pid, sig)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class PosixPtyBackend(Backend):
|
|
172
|
+
"""PTY nativo para Linux e macOS."""
|
|
173
|
+
|
|
174
|
+
def __init__(
|
|
175
|
+
self, cmd: Sequence[str], cwd: str, env: Mapping[str, str], rows: int, cols: int
|
|
176
|
+
) -> None:
|
|
177
|
+
import fcntl
|
|
178
|
+
import pty
|
|
179
|
+
import struct
|
|
180
|
+
import termios
|
|
181
|
+
|
|
182
|
+
self._fcntl, self._struct, self._termios = fcntl, struct, termios
|
|
183
|
+
master, slave = pty.openpty()
|
|
184
|
+
try:
|
|
185
|
+
self._set_winsize(master, rows, cols)
|
|
186
|
+
attrs = termios.tcgetattr(slave)
|
|
187
|
+
iutf8 = getattr(termios, "IUTF8", 0)
|
|
188
|
+
if iutf8:
|
|
189
|
+
attrs[0] |= iutf8
|
|
190
|
+
termios.tcsetattr(slave, termios.TCSANOW, attrs)
|
|
191
|
+
|
|
192
|
+
def _become_session_leader() -> None:
|
|
193
|
+
fcntl.ioctl(0, termios.TIOCSCTTY, 0)
|
|
194
|
+
|
|
195
|
+
self._proc = subprocess.Popen(
|
|
196
|
+
list(cmd),
|
|
197
|
+
stdin=slave,
|
|
198
|
+
stdout=slave,
|
|
199
|
+
stderr=slave,
|
|
200
|
+
cwd=cwd,
|
|
201
|
+
env=dict(env),
|
|
202
|
+
close_fds=True,
|
|
203
|
+
start_new_session=True,
|
|
204
|
+
preexec_fn=_become_session_leader,
|
|
205
|
+
)
|
|
206
|
+
proc_registry.track(self._proc, "terminal", "terminal (pty)")
|
|
207
|
+
except BaseException:
|
|
208
|
+
os.close(master)
|
|
209
|
+
raise
|
|
210
|
+
finally:
|
|
211
|
+
os.close(slave)
|
|
212
|
+
self._master = master
|
|
213
|
+
self._closed = False
|
|
214
|
+
self.pid = self._proc.pid
|
|
215
|
+
|
|
216
|
+
def _set_winsize(self, fd: int, rows: int, cols: int) -> None:
|
|
217
|
+
packed = self._struct.pack("HHHH", max(1, rows), max(1, cols), 0, 0)
|
|
218
|
+
self._fcntl.ioctl(fd, self._termios.TIOCSWINSZ, packed)
|
|
219
|
+
|
|
220
|
+
def read(self, size: int = 65536) -> bytes:
|
|
221
|
+
try:
|
|
222
|
+
return os.read(self._master, size)
|
|
223
|
+
except OSError:
|
|
224
|
+
return b""
|
|
225
|
+
|
|
226
|
+
def write(self, data: bytes) -> None:
|
|
227
|
+
view = memoryview(data)
|
|
228
|
+
while view:
|
|
229
|
+
written = os.write(self._master, view)
|
|
230
|
+
view = view[written:]
|
|
231
|
+
|
|
232
|
+
def resize(self, rows: int, cols: int) -> None:
|
|
233
|
+
with contextlib.suppress(OSError):
|
|
234
|
+
self._set_winsize(self._master, rows, cols)
|
|
235
|
+
|
|
236
|
+
@property
|
|
237
|
+
def alive(self) -> bool:
|
|
238
|
+
return self._proc.poll() is None
|
|
239
|
+
|
|
240
|
+
def interrupt(self) -> None:
|
|
241
|
+
with contextlib.suppress(OSError):
|
|
242
|
+
os.write(self._master, b"\x03")
|
|
243
|
+
|
|
244
|
+
def terminate(self) -> None:
|
|
245
|
+
"""Encerra o shell e todos os processos da sessão: HUP, depois TERM e KILL."""
|
|
246
|
+
sid = self._proc.pid
|
|
247
|
+
if self._proc.poll() is not None and not _session_pids(sid):
|
|
248
|
+
return
|
|
249
|
+
_signal_session(sid, signal.SIGHUP)
|
|
250
|
+
|
|
251
|
+
def _escalate() -> None:
|
|
252
|
+
for sig in (signal.SIGTERM, signal.SIGKILL):
|
|
253
|
+
time.sleep(0.6)
|
|
254
|
+
if self._proc.poll() is not None and not _session_pids(sid):
|
|
255
|
+
return
|
|
256
|
+
_signal_session(sid, sig)
|
|
257
|
+
with contextlib.suppress(Exception):
|
|
258
|
+
self._proc.wait(timeout=1.0)
|
|
259
|
+
|
|
260
|
+
threading.Thread(target=_escalate, daemon=True, name="pty-terminate").start()
|
|
261
|
+
|
|
262
|
+
def close(self) -> None:
|
|
263
|
+
if not self._closed:
|
|
264
|
+
self._closed = True
|
|
265
|
+
with contextlib.suppress(OSError):
|
|
266
|
+
os.close(self._master)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
class PipeBackend(Backend):
|
|
270
|
+
"""Pipes sem TTY; stderr é unido ao stdout. Requer eco local na interface."""
|
|
271
|
+
|
|
272
|
+
local_echo = True
|
|
273
|
+
|
|
274
|
+
def __init__(self, cmd: Sequence[str], cwd: str, env: Mapping[str, str]) -> None:
|
|
275
|
+
flags = 0
|
|
276
|
+
extra: dict = {}
|
|
277
|
+
if sys.platform == "win32":
|
|
278
|
+
flags = subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP
|
|
279
|
+
env = {**env, "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"}
|
|
280
|
+
else:
|
|
281
|
+
extra["start_new_session"] = True
|
|
282
|
+
self._proc = subprocess.Popen(
|
|
283
|
+
list(cmd),
|
|
284
|
+
stdin=subprocess.PIPE,
|
|
285
|
+
stdout=subprocess.PIPE,
|
|
286
|
+
stderr=subprocess.STDOUT,
|
|
287
|
+
cwd=cwd,
|
|
288
|
+
env=dict(env),
|
|
289
|
+
bufsize=0,
|
|
290
|
+
creationflags=flags,
|
|
291
|
+
**extra,
|
|
292
|
+
)
|
|
293
|
+
proc_registry.track(self._proc, "terminal", "terminal (pipe)")
|
|
294
|
+
self.pid = self._proc.pid
|
|
295
|
+
|
|
296
|
+
def read(self, size: int = 65536) -> bytes:
|
|
297
|
+
try:
|
|
298
|
+
return os.read(self._proc.stdout.fileno(), size)
|
|
299
|
+
except (OSError, ValueError):
|
|
300
|
+
return b""
|
|
301
|
+
|
|
302
|
+
def write(self, data: bytes) -> None:
|
|
303
|
+
stdin = self._proc.stdin
|
|
304
|
+
if stdin is None or stdin.closed:
|
|
305
|
+
raise OSError("stdin fechado")
|
|
306
|
+
stdin.write(data)
|
|
307
|
+
stdin.flush()
|
|
308
|
+
|
|
309
|
+
def resize(self, rows: int, cols: int) -> None:
|
|
310
|
+
return None
|
|
311
|
+
|
|
312
|
+
@property
|
|
313
|
+
def alive(self) -> bool:
|
|
314
|
+
return self._proc.poll() is None
|
|
315
|
+
|
|
316
|
+
def interrupt(self) -> None:
|
|
317
|
+
with contextlib.suppress(OSError, ValueError):
|
|
318
|
+
if sys.platform == "win32":
|
|
319
|
+
self._proc.send_signal(signal.CTRL_BREAK_EVENT)
|
|
320
|
+
else:
|
|
321
|
+
_kill_tree_posix(self._proc.pid, signal.SIGINT)
|
|
322
|
+
|
|
323
|
+
def terminate(self) -> None:
|
|
324
|
+
if self._proc.poll() is not None:
|
|
325
|
+
return
|
|
326
|
+
if sys.platform == "win32":
|
|
327
|
+
with contextlib.suppress(OSError, subprocess.SubprocessError):
|
|
328
|
+
subprocess.run(
|
|
329
|
+
["taskkill", "/F", "/T", "/PID", str(self._proc.pid)],
|
|
330
|
+
capture_output=True,
|
|
331
|
+
timeout=3,
|
|
332
|
+
check=False,
|
|
333
|
+
creationflags=subprocess.CREATE_NO_WINDOW,
|
|
334
|
+
)
|
|
335
|
+
else:
|
|
336
|
+
_kill_tree_posix(self._proc.pid, signal.SIGTERM)
|
|
337
|
+
|
|
338
|
+
def _escalate() -> None:
|
|
339
|
+
try:
|
|
340
|
+
self._proc.wait(timeout=1.5)
|
|
341
|
+
except subprocess.TimeoutExpired:
|
|
342
|
+
_kill_tree_posix(self._proc.pid, signal.SIGKILL)
|
|
343
|
+
|
|
344
|
+
threading.Thread(target=_escalate, daemon=True, name="pipe-terminate").start()
|
|
345
|
+
|
|
346
|
+
def close(self) -> None:
|
|
347
|
+
for stream in (self._proc.stdin, self._proc.stdout):
|
|
348
|
+
if stream is not None:
|
|
349
|
+
with contextlib.suppress(OSError, ValueError):
|
|
350
|
+
stream.close()
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
class WinPtyBackend(Backend):
|
|
354
|
+
"""Usa o pacote opcional ``winpty`` (pywinpty)."""
|
|
355
|
+
|
|
356
|
+
def __init__(self, cmd: Sequence[str], cwd: str, rows: int, cols: int) -> None:
|
|
357
|
+
import winpty
|
|
358
|
+
|
|
359
|
+
self._pty = winpty.PtyProcess.spawn(list(cmd), cwd=cwd, dimensions=(rows, cols))
|
|
360
|
+
self.pid = getattr(self._pty, "pid", None)
|
|
361
|
+
|
|
362
|
+
def read(self, size: int = 65536) -> bytes:
|
|
363
|
+
try:
|
|
364
|
+
data = self._pty.read(size)
|
|
365
|
+
except (EOFError, OSError):
|
|
366
|
+
return b""
|
|
367
|
+
return data.encode("utf-8", errors="replace") if isinstance(data, str) else data
|
|
368
|
+
|
|
369
|
+
def write(self, data: bytes) -> None:
|
|
370
|
+
self._pty.write(data.decode("utf-8", errors="replace"))
|
|
371
|
+
|
|
372
|
+
def resize(self, rows: int, cols: int) -> None:
|
|
373
|
+
with contextlib.suppress(Exception):
|
|
374
|
+
self._pty.setwinsize(rows, cols)
|
|
375
|
+
|
|
376
|
+
@property
|
|
377
|
+
def alive(self) -> bool:
|
|
378
|
+
try:
|
|
379
|
+
return bool(self._pty.isalive())
|
|
380
|
+
except Exception:
|
|
381
|
+
return False
|
|
382
|
+
|
|
383
|
+
def terminate(self) -> None:
|
|
384
|
+
with contextlib.suppress(Exception):
|
|
385
|
+
self._pty.terminate(force=True)
|
|
386
|
+
|
|
387
|
+
def close(self) -> None:
|
|
388
|
+
with contextlib.suppress(Exception):
|
|
389
|
+
self._pty.close()
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def conpty_supported() -> bool:
|
|
393
|
+
"""``True`` se este Windows tem a API de pseudo-console (10 build 17763+)."""
|
|
394
|
+
if sys.platform != "win32":
|
|
395
|
+
return False
|
|
396
|
+
try:
|
|
397
|
+
import ctypes
|
|
398
|
+
|
|
399
|
+
return hasattr(ctypes.WinDLL("kernel32"), "CreatePseudoConsole")
|
|
400
|
+
except (OSError, AttributeError):
|
|
401
|
+
return False
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
class ConPtyBackend(Backend):
|
|
405
|
+
"""Pseudo-console do Windows via ``ctypes``.
|
|
406
|
+
|
|
407
|
+
Todas as funções da API têm ``argtypes`` e ``restype`` declarados; sem isso
|
|
408
|
+
o ``ctypes`` trata ponteiros como ``int`` de 32 bits e corrompe a memória em
|
|
409
|
+
Python de 64 bits.
|
|
410
|
+
"""
|
|
411
|
+
|
|
412
|
+
def __init__(
|
|
413
|
+
self, cmd: Sequence[str], cwd: str, env: Mapping[str, str], rows: int, cols: int
|
|
414
|
+
) -> None:
|
|
415
|
+
import ctypes
|
|
416
|
+
from ctypes import wintypes
|
|
417
|
+
|
|
418
|
+
self._ct = ctypes
|
|
419
|
+
self._wt = wintypes
|
|
420
|
+
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
421
|
+
self._k32 = k32
|
|
422
|
+
self._declare(k32)
|
|
423
|
+
self._hpc = wintypes.HANDLE()
|
|
424
|
+
self._closed = False
|
|
425
|
+
self._lock = threading.Lock()
|
|
426
|
+
self._h_in_w = wintypes.HANDLE()
|
|
427
|
+
self._h_out_r = wintypes.HANDLE()
|
|
428
|
+
self._h_proc = wintypes.HANDLE()
|
|
429
|
+
self._h_thread = wintypes.HANDLE()
|
|
430
|
+
self._attr_buf = None
|
|
431
|
+
|
|
432
|
+
in_r, in_w = wintypes.HANDLE(), wintypes.HANDLE()
|
|
433
|
+
out_r, out_w = wintypes.HANDLE(), wintypes.HANDLE()
|
|
434
|
+
if not k32.CreatePipe(ctypes.byref(in_r), ctypes.byref(in_w), None, 0):
|
|
435
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
436
|
+
if not k32.CreatePipe(ctypes.byref(out_r), ctypes.byref(out_w), None, 0):
|
|
437
|
+
k32.CloseHandle(in_r)
|
|
438
|
+
k32.CloseHandle(in_w)
|
|
439
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
440
|
+
self._h_in_w, self._h_out_r = in_w, out_r
|
|
441
|
+
try:
|
|
442
|
+
hr = k32.CreatePseudoConsole(
|
|
443
|
+
self._coord(cols, rows), in_r, out_w, 0, ctypes.byref(self._hpc)
|
|
444
|
+
)
|
|
445
|
+
if hr != 0:
|
|
446
|
+
raise OSError(f"CreatePseudoConsole falhou: 0x{hr & 0xFFFFFFFF:08x}")
|
|
447
|
+
k32.CloseHandle(in_r)
|
|
448
|
+
k32.CloseHandle(out_w)
|
|
449
|
+
in_r = out_w = None
|
|
450
|
+
self._spawn(cmd, cwd, env)
|
|
451
|
+
except BaseException:
|
|
452
|
+
for handle in (in_r, out_w):
|
|
453
|
+
if handle is not None:
|
|
454
|
+
k32.CloseHandle(handle)
|
|
455
|
+
self._release()
|
|
456
|
+
raise
|
|
457
|
+
threading.Thread(target=self._watch_exit, daemon=True, name="conpty-watch").start()
|
|
458
|
+
|
|
459
|
+
def _declare(self, k32) -> None:
|
|
460
|
+
ct, wt = self._ct, self._wt
|
|
461
|
+
HANDLE, DWORD, BOOL, LPVOID = wt.HANDLE, wt.DWORD, wt.BOOL, ct.c_void_p
|
|
462
|
+
|
|
463
|
+
class COORD(ct.Structure):
|
|
464
|
+
_fields_ = [("X", ct.c_short), ("Y", ct.c_short)]
|
|
465
|
+
|
|
466
|
+
class STARTUPINFOW(ct.Structure):
|
|
467
|
+
_fields_ = [
|
|
468
|
+
("cb", DWORD), ("lpReserved", wt.LPWSTR), ("lpDesktop", wt.LPWSTR),
|
|
469
|
+
("lpTitle", wt.LPWSTR), ("dwX", DWORD), ("dwY", DWORD),
|
|
470
|
+
("dwXSize", DWORD), ("dwYSize", DWORD), ("dwXCountChars", DWORD),
|
|
471
|
+
("dwYCountChars", DWORD), ("dwFillAttribute", DWORD), ("dwFlags", DWORD),
|
|
472
|
+
("wShowWindow", wt.WORD), ("cbReserved2", wt.WORD), ("lpReserved2", LPVOID),
|
|
473
|
+
("hStdInput", HANDLE), ("hStdOutput", HANDLE), ("hStdError", HANDLE),
|
|
474
|
+
]
|
|
475
|
+
|
|
476
|
+
class STARTUPINFOEXW(ct.Structure):
|
|
477
|
+
_fields_ = [("StartupInfo", STARTUPINFOW), ("lpAttributeList", LPVOID)]
|
|
478
|
+
|
|
479
|
+
class PROCESS_INFORMATION(ct.Structure):
|
|
480
|
+
_fields_ = [
|
|
481
|
+
("hProcess", HANDLE), ("hThread", HANDLE),
|
|
482
|
+
("dwProcessId", DWORD), ("dwThreadId", DWORD),
|
|
483
|
+
]
|
|
484
|
+
|
|
485
|
+
self._COORD, self._SIEX, self._SI, self._PI = (
|
|
486
|
+
COORD, STARTUPINFOEXW, STARTUPINFOW, PROCESS_INFORMATION,
|
|
487
|
+
)
|
|
488
|
+
k32.CreatePipe.argtypes = [ct.POINTER(HANDLE), ct.POINTER(HANDLE), LPVOID, DWORD]
|
|
489
|
+
k32.CreatePipe.restype = BOOL
|
|
490
|
+
k32.CreatePseudoConsole.argtypes = [COORD, HANDLE, HANDLE, DWORD, ct.POINTER(HANDLE)]
|
|
491
|
+
k32.CreatePseudoConsole.restype = ct.c_long
|
|
492
|
+
k32.ResizePseudoConsole.argtypes = [HANDLE, COORD]
|
|
493
|
+
k32.ResizePseudoConsole.restype = ct.c_long
|
|
494
|
+
k32.ClosePseudoConsole.argtypes = [HANDLE]
|
|
495
|
+
k32.ClosePseudoConsole.restype = None
|
|
496
|
+
k32.InitializeProcThreadAttributeList.argtypes = [
|
|
497
|
+
LPVOID, DWORD, DWORD, ct.POINTER(ct.c_size_t),
|
|
498
|
+
]
|
|
499
|
+
k32.InitializeProcThreadAttributeList.restype = BOOL
|
|
500
|
+
k32.UpdateProcThreadAttribute.argtypes = [
|
|
501
|
+
LPVOID, DWORD, ct.c_size_t, LPVOID, ct.c_size_t, LPVOID, LPVOID,
|
|
502
|
+
]
|
|
503
|
+
k32.UpdateProcThreadAttribute.restype = BOOL
|
|
504
|
+
k32.DeleteProcThreadAttributeList.argtypes = [LPVOID]
|
|
505
|
+
k32.DeleteProcThreadAttributeList.restype = None
|
|
506
|
+
k32.CreateProcessW.argtypes = [
|
|
507
|
+
wt.LPCWSTR, wt.LPWSTR, LPVOID, LPVOID, BOOL, DWORD, LPVOID, wt.LPCWSTR,
|
|
508
|
+
LPVOID, ct.POINTER(PROCESS_INFORMATION),
|
|
509
|
+
]
|
|
510
|
+
k32.CreateProcessW.restype = BOOL
|
|
511
|
+
k32.ReadFile.argtypes = [HANDLE, LPVOID, DWORD, ct.POINTER(DWORD), LPVOID]
|
|
512
|
+
k32.ReadFile.restype = BOOL
|
|
513
|
+
k32.WriteFile.argtypes = [HANDLE, LPVOID, DWORD, ct.POINTER(DWORD), LPVOID]
|
|
514
|
+
k32.WriteFile.restype = BOOL
|
|
515
|
+
k32.CloseHandle.argtypes = [HANDLE]
|
|
516
|
+
k32.CloseHandle.restype = BOOL
|
|
517
|
+
k32.WaitForSingleObject.argtypes = [HANDLE, DWORD]
|
|
518
|
+
k32.WaitForSingleObject.restype = DWORD
|
|
519
|
+
|
|
520
|
+
def _coord(self, cols: int, rows: int):
|
|
521
|
+
return self._COORD(max(1, min(cols, 32767)), max(1, min(rows, 32767)))
|
|
522
|
+
|
|
523
|
+
def _spawn(self, cmd: Sequence[str], cwd: str, env: Mapping[str, str]) -> None:
|
|
524
|
+
ct, wt, k32 = self._ct, self._wt, self._k32
|
|
525
|
+
size = ct.c_size_t(0)
|
|
526
|
+
k32.InitializeProcThreadAttributeList(None, 1, 0, ct.byref(size))
|
|
527
|
+
self._attr_buf = ct.create_string_buffer(size.value)
|
|
528
|
+
attr_list = ct.cast(self._attr_buf, ct.c_void_p)
|
|
529
|
+
if not k32.InitializeProcThreadAttributeList(attr_list, 1, 0, ct.byref(size)):
|
|
530
|
+
raise ct.WinError(ct.get_last_error())
|
|
531
|
+
pseudoconsole_attr = 0x00020016
|
|
532
|
+
if not k32.UpdateProcThreadAttribute(
|
|
533
|
+
attr_list, 0, pseudoconsole_attr, self._hpc, ct.sizeof(wt.HANDLE), None, None
|
|
534
|
+
):
|
|
535
|
+
raise ct.WinError(ct.get_last_error())
|
|
536
|
+
|
|
537
|
+
siex = self._SIEX()
|
|
538
|
+
siex.StartupInfo.cb = ct.sizeof(self._SIEX)
|
|
539
|
+
siex.lpAttributeList = attr_list
|
|
540
|
+
# Sem isso o shell herda o stdin do processo pai; quando o Codis nasce com
|
|
541
|
+
# stdin em NUL (launcher), o PowerShell lê EOF e fecha logo após o prompt.
|
|
542
|
+
siex.StartupInfo.dwFlags |= 0x00000100 # STARTF_USESTDHANDLES, handles nulos
|
|
543
|
+
info = self._PI()
|
|
544
|
+
env_block = "".join(f"{k}={v}\0" for k, v in env.items()) + "\0"
|
|
545
|
+
env_buf = ct.create_unicode_buffer(env_block, len(env_block))
|
|
546
|
+
cmdline = ct.create_unicode_buffer(subprocess.list2cmdline(list(cmd)), 32768)
|
|
547
|
+
flags = 0x00080000 | 0x00000400
|
|
548
|
+
if not k32.CreateProcessW(
|
|
549
|
+
None, cmdline, None, None, False, flags, ct.cast(env_buf, ct.c_void_p),
|
|
550
|
+
cwd or None, ct.byref(siex), ct.byref(info),
|
|
551
|
+
):
|
|
552
|
+
raise ct.WinError(ct.get_last_error())
|
|
553
|
+
self._h_proc, self._h_thread = info.hProcess, info.hThread
|
|
554
|
+
self.pid = info.dwProcessId
|
|
555
|
+
|
|
556
|
+
def read(self, size: int = 65536) -> bytes:
|
|
557
|
+
ct = self._ct
|
|
558
|
+
buf = ct.create_string_buffer(size)
|
|
559
|
+
got = self._wt.DWORD(0)
|
|
560
|
+
ok = self._k32.ReadFile(self._h_out_r, buf, size, ct.byref(got), None)
|
|
561
|
+
if not ok or got.value == 0:
|
|
562
|
+
return b""
|
|
563
|
+
return buf.raw[: got.value]
|
|
564
|
+
|
|
565
|
+
def write(self, data: bytes) -> None:
|
|
566
|
+
ct = self._ct
|
|
567
|
+
view = memoryview(data)
|
|
568
|
+
while view:
|
|
569
|
+
chunk = bytes(view[:16384])
|
|
570
|
+
written = self._wt.DWORD(0)
|
|
571
|
+
ok = self._k32.WriteFile(
|
|
572
|
+
self._h_in_w, chunk, len(chunk), ct.byref(written), None
|
|
573
|
+
)
|
|
574
|
+
if not ok or written.value == 0:
|
|
575
|
+
raise OSError("falha ao escrever no ConPTY")
|
|
576
|
+
view = view[written.value:]
|
|
577
|
+
|
|
578
|
+
def resize(self, rows: int, cols: int) -> None:
|
|
579
|
+
if self._hpc and not self._closed:
|
|
580
|
+
self._k32.ResizePseudoConsole(self._hpc, self._coord(cols, rows))
|
|
581
|
+
|
|
582
|
+
@property
|
|
583
|
+
def alive(self) -> bool:
|
|
584
|
+
if not self._h_proc:
|
|
585
|
+
return False
|
|
586
|
+
return self._k32.WaitForSingleObject(self._h_proc, 0) == 0x102
|
|
587
|
+
|
|
588
|
+
def _watch_exit(self) -> None:
|
|
589
|
+
"""Ao sair o shell, fecha o pseudo-console para que a leitura termine."""
|
|
590
|
+
self._k32.WaitForSingleObject(self._h_proc, 0xFFFFFFFF)
|
|
591
|
+
with self._lock:
|
|
592
|
+
if self._closed or not self._hpc:
|
|
593
|
+
return
|
|
594
|
+
hpc, self._hpc = self._hpc, self._wt.HANDLE()
|
|
595
|
+
self._k32.ClosePseudoConsole(hpc)
|
|
596
|
+
|
|
597
|
+
def terminate(self) -> None:
|
|
598
|
+
if self.pid is None or not self.alive:
|
|
599
|
+
return
|
|
600
|
+
with contextlib.suppress(OSError, subprocess.SubprocessError):
|
|
601
|
+
subprocess.run(
|
|
602
|
+
["taskkill", "/F", "/T", "/PID", str(self.pid)],
|
|
603
|
+
capture_output=True,
|
|
604
|
+
timeout=3,
|
|
605
|
+
check=False,
|
|
606
|
+
creationflags=subprocess.CREATE_NO_WINDOW,
|
|
607
|
+
)
|
|
608
|
+
|
|
609
|
+
def _release(self) -> None:
|
|
610
|
+
k32 = self._k32
|
|
611
|
+
with self._lock:
|
|
612
|
+
hpc, self._hpc = self._hpc, self._wt.HANDLE()
|
|
613
|
+
self._closed = True
|
|
614
|
+
if hpc:
|
|
615
|
+
k32.ClosePseudoConsole(hpc)
|
|
616
|
+
for name in ("_h_in_w", "_h_out_r", "_h_thread", "_h_proc"):
|
|
617
|
+
handle = getattr(self, name, None)
|
|
618
|
+
if handle:
|
|
619
|
+
k32.CloseHandle(handle)
|
|
620
|
+
setattr(self, name, self._wt.HANDLE())
|
|
621
|
+
if self._attr_buf is not None:
|
|
622
|
+
k32.DeleteProcThreadAttributeList(self._ct.cast(self._attr_buf, self._ct.c_void_p))
|
|
623
|
+
self._attr_buf = None
|
|
624
|
+
|
|
625
|
+
def close(self) -> None:
|
|
626
|
+
if not self._closed:
|
|
627
|
+
self._release()
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def spawn_backend(
|
|
631
|
+
cmd: Sequence[str],
|
|
632
|
+
cwd: str,
|
|
633
|
+
rows: int,
|
|
634
|
+
cols: int,
|
|
635
|
+
*,
|
|
636
|
+
load_rc: bool = True,
|
|
637
|
+
prefer_conpty: bool = True,
|
|
638
|
+
) -> Backend:
|
|
639
|
+
"""Cria o melhor backend disponível para ``cmd``.
|
|
640
|
+
|
|
641
|
+
A ordem é: PTY nativo (POSIX), ConPTY, ``winpty`` e, por fim, pipes.
|
|
642
|
+
"""
|
|
643
|
+
argv = interactive_command(cmd, load_rc)
|
|
644
|
+
env = terminal_env()
|
|
645
|
+
if sys.platform != "win32":
|
|
646
|
+
try:
|
|
647
|
+
return PosixPtyBackend(argv, cwd, env, rows, cols)
|
|
648
|
+
except (OSError, ImportError, subprocess.SubprocessError) as exc:
|
|
649
|
+
logger.warning("PTY indisponível (%s); usando pipes.", exc)
|
|
650
|
+
else:
|
|
651
|
+
if prefer_conpty and conpty_supported():
|
|
652
|
+
try:
|
|
653
|
+
return ConPtyBackend(argv, cwd, env, rows, cols)
|
|
654
|
+
except (OSError, ImportError, AttributeError) as exc:
|
|
655
|
+
logger.warning("ConPTY falhou (%s); tentando alternativas.", exc)
|
|
656
|
+
with contextlib.suppress(ImportError, OSError, AttributeError):
|
|
657
|
+
return WinPtyBackend(argv, cwd, rows, cols)
|
|
658
|
+
return PipeBackend(cmd, cwd, env)
|