2026-08-24 01:18:40 +02:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
2026-08-24 16:10:59 +02:00
|
|
|
import os
|
2026-08-24 01:18:40 +02:00
|
|
|
import subprocess
|
2026-08-24 16:10:59 +02:00
|
|
|
from collections.abc import Sequence
|
2026-08-24 01:18:40 +02:00
|
|
|
from dataclasses import dataclass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ControlModeError(RuntimeError):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class ControlModeClient:
|
|
|
|
|
session: str
|
2026-08-24 16:10:59 +02:00
|
|
|
tmux_command: Sequence[str] | None = None
|
2026-08-24 01:18:40 +02:00
|
|
|
process: subprocess.Popen[str] | None = None
|
|
|
|
|
|
|
|
|
|
def start(self) -> None:
|
|
|
|
|
if self.process is not None:
|
|
|
|
|
return
|
2026-08-24 16:10:59 +02:00
|
|
|
socket_name = os.environ.get("TAMQ_TMUX_SOCKET")
|
|
|
|
|
command = tuple(
|
|
|
|
|
self.tmux_command
|
|
|
|
|
or (["tmux", "-L", socket_name] if socket_name else ["tmux"])
|
|
|
|
|
)
|
2026-08-24 01:18:40 +02:00
|
|
|
self.process = subprocess.Popen(
|
2026-08-24 16:10:59 +02:00
|
|
|
[*command, "-C", "attach-session", "-t", self.session],
|
2026-08-24 01:18:40 +02:00
|
|
|
stdin=subprocess.PIPE,
|
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
|
stderr=subprocess.PIPE,
|
|
|
|
|
text=True,
|
|
|
|
|
bufsize=1,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def command(self, value: str) -> None:
|
|
|
|
|
if self.process is None or self.process.stdin is None:
|
|
|
|
|
raise ControlModeError("control-mode client is not started")
|
|
|
|
|
self.process.stdin.write(value.rstrip("\n") + "\n")
|
|
|
|
|
self.process.stdin.flush()
|
|
|
|
|
|
|
|
|
|
def inject(self, window: str, text: str) -> None:
|
|
|
|
|
# send-keys -l preserves punctuation and whitespace in the message.
|
|
|
|
|
self.command(f"send-keys -t {window} -l -- {shell_quote(text)}")
|
|
|
|
|
|
|
|
|
|
def close(self) -> None:
|
|
|
|
|
if self.process is not None:
|
2026-08-24 16:10:59 +02:00
|
|
|
process = self.process
|
|
|
|
|
process.terminate()
|
|
|
|
|
try:
|
|
|
|
|
process.wait(timeout=1)
|
|
|
|
|
except subprocess.TimeoutExpired:
|
|
|
|
|
process.kill()
|
|
|
|
|
process.wait(timeout=1)
|
2026-08-24 01:18:40 +02:00
|
|
|
self.process = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def shell_quote(value: str) -> str:
|
|
|
|
|
return "'" + value.replace("'", "'\\''") + "'"
|