Debian Codegraph @

src/libtmux/client.py

raw symbols SCIP
1 """Pythonization of the :term:`tmux(1)` client.
2
3 libtmux.client
4 ~~~~~~~~~~~~~~
5
6 """
7
8 from __future__ import annotations
9
10 import dataclasses
11 import logging
12 import typing as t
13
14 from libtmux import exc
15 from libtmux.neo import Obj, fetch_obj
16
17 if t.TYPE_CHECKING:
18 from libtmux.pane import Pane
19 from libtmux.server import Server
20 from libtmux.session import Session
21 from libtmux.window import Window
22
23
24 logger = logging.getLogger(__name__)
25
26
27 @dataclasses.dataclass()
28 class Client(Obj):
29 """:term:`tmux(1)` :term:`Client` [client_manual]_.
30
31 A tmux client is an attached terminal. The same tmux server can have
32 multiple clients attached simultaneously (e.g. ``$ tmux attach`` from
33 several terminals) and each receives its own view of the active
34 session, window, and pane.
35
36 .. warning::
37
38 ``client_session``, ``session_id``, ``window_id`` and
39 ``pane_id`` are snapshots of the client's *currently attached
40 view* at the moment this object was read — not stable identity
41 for the client. When the client switches sessions via
42 ``switch-client``, moves focus via ``select-window`` /
43 ``select-pane``, or detaches, these fields go stale until
44 :meth:`refresh` re-reads them from ``list-clients``. The
45 ``client_name`` (tty path on Unix) is the client's stable
46 identity.
47
48 Prefer :meth:`attached_session`, :meth:`attached_window`, and
49 :meth:`attached_pane` when you need the client's current
50 attachment. Each property re-reads tmux before returning, so
51 the :class:`Session` / :class:`Window` / :class:`Pane` you get
52 back reflects where the client is attached *now*, not where it
53 was when this :class:`Client` was constructed. If tmux no longer
54 reports this ``client_name`` through ``list-clients``, these
55 properties return ``None``.
56
57 :meth:`attached_pane` follows the attached session's current
58 window. That can differ from the per-client active pane set by
59 ``select-pane -P``; see :meth:`attached_pane` for the exact
60 behavior. Each property re-reads tmux on every access.
61
62 Parameters
63 ----------
64 server : :class:`Server`
65
66 Examples
67 --------
68 >>> with control_mode() as ctl:
69 ... attached = [
70 ... c
71 ... for c in server.clients
72 ... if c.client_name == ctl.client_name
73 ... ]
74 >>> bool(attached)
75 True
76
77 >>> with control_mode() as ctl:
78 ... client = server.clients.get(client_name=ctl.client_name)
79 ... client.client_readonly in {"0", "1"}
80 True
81
82 References
83 ----------
84 .. [client_manual] tmux client. openbsd manpage for TMUX(1).
85 "tmux supports multiple attached clients. Each client has its
86 own keymap, view of the session, and message log."
87
88 https://man.openbsd.org/tmux.1#DESCRIPTION. Accessed 2026.
89 """
90
91 server: Server
92
93 def refresh(self) -> None:
94 """Refresh client attributes from tmux.
95
96 Raises
97 ------
98 ValueError
99 When ``client_name`` is unset. Surfaces a clear error under
100 ``python -O``, where an ``assert`` would be stripped.
101 """
102 if self.client_name is None:
103 msg = "Client must have a client_name to refresh"
104 raise ValueError(msg)
105 return super()._refresh(
106 obj_key="client_name",
107 obj_id=self.client_name,
108 list_cmd="list-clients",
109 )
110
111 @classmethod
112 def from_client_name(cls, server: Server, client_name: str) -> Client:
113 """Create Client from an existing client_name."""
114 client = fetch_obj(
115 obj_key="client_name",
116 obj_id=client_name,
117 list_cmd="list-clients",
118 server=server,
119 )
120 return cls(server=server, **client)
121
122 #
123 # Computed properties
124 #
125 @property
126 def attached_session(self) -> Session | None:
127 """Return the :class:`Session` this client is currently attached to.
128
129 Re-reads the client from ``list-clients`` before resolving, so the
130 returned :class:`Session` reflects the client's *live* attachment
131 rather than the snapshot captured when this :class:`Client` was
132 read. Returns ``None`` when tmux no longer reports this
133 ``client_name`` through ``list-clients``, when the client is not
134 attached to any session, or when the snapshot ``session_id`` no
135 longer names a live session.
136
137 Examples
138 --------
139 >>> with control_mode() as ctl:
140 ... client = server.clients.get(client_name=ctl.client_name)
141 ... attached = client.attached_session
142 >>> attached is not None
143 True
144 """
145 try:
146 self.refresh()
147 except exc.TmuxObjectDoesNotExist:
148 return None
149 if self.session_id is None:
150 return None
151 return self.server.sessions.get(
152 session_id=self.session_id,
153 default=None,
154 )
155
156 @property
157 def attached_window(self) -> Window | None:
158 """Return the :class:`Window` this client is currently viewing.
159
160 Re-reads the client from ``list-clients``, looks up its attached
161 session, and returns that session's :attr:`~libtmux.Session.active_window`.
162 Returns ``None`` when no live attached session can be resolved.
163 """
164 session = self.attached_session
165 if session is None:
166 return None
167 return session.active_window
168
169 @property
170 def attached_pane(self) -> Pane | None:
171 """Return the :class:`Pane` this client is currently viewing.
172
173 Re-reads the client from ``list-clients``, looks up its attached
174 session's current window, and returns that window's
175 :attr:`~libtmux.Window.active_pane`. Returns ``None`` when no
176 live attached session or active pane can be resolved.
177
178 This follows the attached session's current window and active
179 pane. When a client has used ``select-pane -P`` to set its own
180 active pane, this property returns the *session's* current
181 active pane, not the client's per-client focus.
182 """
183 window = self.attached_window
184 if window is None:
185 return None
186 return window.active_pane
187
188 def _resolve_attached(
189 self,
190 ) -> tuple[Session | None, Window | None, Pane | None]:
191 """Resolve live attachment with a single ``list-clients`` refresh.
192
193 The three :attr:`attached_session` / :attr:`attached_window` /
194 :attr:`attached_pane` properties each trigger their own
195 ``list-clients`` refresh — calling them in sequence performs three
196 tmux reads for one conceptual "where is this client attached *now*"
197 read. ``_resolve_attached`` shares a single refresh across the
198 triple and returns the three values together.
199
200 Returns
201 -------
202 tuple[Session | None, Window | None, Pane | None]
203 * ``(None, None, None)`` when tmux no longer reports this
204 ``client_name`` through ``list-clients``, when the client
205 snapshot has no ``session_id``, or when the snapshot
206 ``session_id`` no longer names a live session.
207 * ``(session, None, None)`` when the attached session has no
208 active window.
209 * ``(session, window, pane)`` for a fully-resolved live
210 attachment. ``pane`` is ``None`` only when the active
211 window has no active pane.
212
213 :exc:`~libtmux.exc.MultipleActiveWindows` propagates rather than
214 collapsing to ``(session, None, None)`` — multiple active windows
215 in one session indicates inconsistent tmux state that callers
216 should see, not absent attachment.
217 """
218 try:
219 self.refresh()
220 except exc.TmuxObjectDoesNotExist:
221 return None, None, None
222 if self.session_id is None:
223 return None, None, None
224 session = self.server.sessions.get(
225 session_id=self.session_id,
226 default=None,
227 )
228 if session is None:
229 return None, None, None
230 try:
231 window = session.active_window
232 except exc.NoActiveWindow:
233 return session, None, None
234 return session, window, window.active_pane