1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Client handles and their snapshot getters.
use std::ffi::OsString;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::os::unix::ffi::OsStringExt as _;
use std::sync::Arc;
use crate::formats::TmuxText;
use crate::internal::core::Core;
use crate::internal::listing;
#[cfg(feature = "query")]
use crate::query::{FilterSchema, Filterable};
#[cfg(feature = "query")]
use crate::snapshot::ClientFields;
use crate::snapshot::ClientInfo;
use crate::target::ServerIdentity;
use crate::{Command, Error, ObjectKind};
/// One client attached to the tmux server.
///
/// Clients have no `$`-style id. tmux identifies them by the terminal they
/// occupy, so [`Client::name`] is the identity and is always present.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
/// # runtime.block_on(async {
/// let guard = libtmux::test::TestServer::new().await?;
/// guard.server().new_session("work").await?;
///
/// // A session created without attaching has no client, which is the usual
/// // shape under test and under automation.
/// assert!(guard.server().clients().await?.is_empty());
///
/// guard.shutdown().await?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct Client {
core: Arc<Core>,
info: ClientInfo,
}
impl Client {
/// Build a handle from a hydrated snapshot.
pub(crate) const fn new(core: Arc<Core>, info: ClientInfo) -> Self {
Self { core, info }
}
/// Return the client name, which is its terminal path.
#[must_use]
pub const fn name(&self) -> &TmuxText {
self.info.client_name()
}
/// Return the client's controlling terminal.
#[must_use]
pub fn tty(&self) -> &TmuxText {
self.info.client_tty()
}
/// Return the terminal type the client reports.
#[must_use]
pub fn term_name(&self) -> &TmuxText {
self.info.client_termname()
}
/// Return the client process id.
#[must_use]
pub fn pid(&self) -> u32 {
*self.info.client_pid()
}
/// Return the client width in cells.
#[must_use]
pub fn width(&self) -> u32 {
*self.info.client_width()
}
/// Return the client height in cells.
#[must_use]
pub fn height(&self) -> Option<u32> {
self.info.client_height().copied().available()
}
/// Return when the client connected, as a Unix timestamp.
#[must_use]
pub fn created(&self) -> i64 {
*self.info.client_created()
}
/// Report whether the client is attached read-only.
#[must_use]
pub fn is_readonly(&self) -> bool {
*self.info.client_readonly()
}
/// Report whether the client is a control-mode client.
///
/// Control-mode clients speak tmux's machine protocol rather than drawing
/// a terminal, so they are usually other programs rather than people.
#[must_use]
pub fn is_control_mode(&self) -> bool {
*self.info.client_control_mode()
}
/// Return the identity of the server this client is attached to.
pub(crate) fn server_identity(&self) -> &ServerIdentity {
self.core.configuration().identity()
}
/// Replace this handle's snapshot with the client's current state.
///
/// # Errors
///
/// Returns [`Error::ObjectGone`] when the client has detached, and
/// [`Error::ClientSuspended`] when it is stopped rather than gone --
/// suspended or locked, which tmux leaves out of the same listing. Keep
/// the handle for the second: the client is listed again once it resumes.
/// Returns a listing error when tmux could not be read.
pub async fn refresh(&mut self) -> Result<&mut Self, Error> {
let listed = listing::clients(&self.core, None)
.await?
.into_iter()
.find(|info| info.client_name() == self.name());
let Some(info) = listed else {
return Err(self.why_unlisted().await);
};
self.info = info;
Ok(self)
}
/// Say why this client is not in the listing.
///
/// `list-clients` leaves out the dead, the exiting and the suspended
/// alike, so absence from it does not say which happened. A suspended
/// client is still resolvable as a command target and reports itself,
/// which is what tells the temporary case from the permanent one.
///
/// Only the miss path pays for this, and only tmux's own answer is
/// trusted: anything that does not resolve to this client by name, or
/// resolves without saying it is suspended, is reported gone exactly as
/// before. The probe cannot turn a gone client into a live one, only a
/// suspended one into something other than gone.
async fn why_unlisted(&self) -> Error {
let gone = || Error::ObjectGone {
kind: ObjectKind::Client,
id: self.name().to_string_lossy().into_owned(),
};
// Flags first: they are a comma-separated list of known words and so
// never hold the separator, while a client name is a terminal path
// and is not this crate's to constrain. Splitting once puts every
// ambiguous byte on the far side.
let Ok(result) = self
.core
.execute(
Command::new("display-message")
.arg("-p")
.arg("-t")
.arg(OsString::from_vec(self.name().as_bytes().to_vec()))
.arg(OsString::from("#{client_flags}|#{client_name}")),
)
.await
else {
return gone();
};
if !result.success() {
return gone();
}
let stdout = result.stdout();
let answer = stdout.strip_suffix(b"\n").unwrap_or(stdout);
let Some(separator) = answer.iter().position(|byte| *byte == b'|') else {
return gone();
};
let (flags, separated) = answer.split_at(separator);
// Past the separator itself. `split_at` puts it at the head of the
// second half, so this is never out of range; asking rather than
// indexing keeps that true if the split ever moves.
let Some(name) = separated.get(1..) else {
return gone();
};
if name != self.name().as_bytes() {
return gone();
}
// `display-message` is allowed to fail its target, so an absent client
// expands every format empty rather than erroring. That makes the flag
// the whole signal: no flag, no claim.
if flags
.split(|byte| *byte == b',')
.any(|flag| flag == b"suspended")
{
return Error::ClientSuspended {
name: self.name().to_string_lossy().into_owned(),
};
}
gone()
}
/// Return a new handle holding the client's current state.
///
/// # Errors
///
/// Returns [`Error::ObjectGone`] when the client has detached, and
/// [`Error::ClientSuspended`] when it is stopped rather than gone. The
/// two are worth telling apart: [`Error::is_object_gone`] answers false
/// for the second, because the same handle works again once the client
/// resumes. Returns a listing error when tmux could not be read.
pub async fn refreshed(&self) -> Result<Self, Error> {
let mut refreshed = self.clone();
refreshed.refresh().await?;
Ok(refreshed)
}
/// The session this client is attached to.
///
/// `None` when the client is attached to nothing, which is an ordinary
/// state rather than a failure.
///
/// Resolved through `#{session_id}` rather than `#{client_session}`. The
/// latter is what tmux calls the attachment, but it is a *name*, and a
/// name is not a handle: tmux will create a session called `a:b` and then
/// refuse to address it, because `:` separates a session from a window in
/// a target. The ID is unambiguous by construction.
///
/// Costs one tmux command. tmux fills a client's session into the same
/// format tree it fills the client's own fields into, so the whole session
/// snapshot comes back with the id rather than needing a listing after it.
///
/// ```console
/// $ cargo test --package libtmux --all-features --test command_budget \
/// asking_a_client
/// ```
///
/// # Errors
///
/// Returns an error when tmux cannot be reached, or answers with an ID
/// this crate cannot parse.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
/// # runtime.block_on(async {
/// let guard = libtmux::test::TestServer::new().await?;
/// let server = guard.server();
/// let session = server.new_session("work").await?;
///
/// // A control-mode connection is a client, so the server has one to find.
/// # #[cfg(feature = "control-mode")]
/// # {
/// let control = libtmux::control::ControlMode::attach(server, session.id()).await?;
/// let client = server.clients().await?.into_iter().next().expect("one client");
///
/// let attached = client.attached_session().await?.expect("it is attached");
/// assert_eq!(attached.id(), session.id());
/// control.shutdown().await?;
/// # }
///
/// guard.shutdown().await?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// # })?;
/// # Ok(())
/// # }
/// ```
pub async fn attached_session(&self) -> Result<Option<crate::Session>, Error> {
let name = OsString::from_vec(self.name().as_bytes().to_vec());
Ok(listing::client_session(&self.core, &name)
.await?
.map(|info| crate::Session::new(Arc::clone(&self.core), info)))
}
/// The current window of the session this client is attached to.
///
/// Not this client's own view. tmux keeps the current window on the
/// session -- `curw` is a member of `struct session`, not of
/// `struct client` -- so every client attached to one session reports the
/// same window, and one client changing it changes it for all of them.
///
/// `None` when the client is attached to nothing.
///
/// Costs one tmux command, as [`Self::attached_session`] describes.
///
/// # Errors
///
/// Returns an error when tmux cannot be reached, or answers with an ID
/// this crate cannot parse.
pub async fn attached_window(&self) -> Result<Option<crate::Window>, Error> {
let name = OsString::from_vec(self.name().as_bytes().to_vec());
Ok(listing::client_window(&self.core, &name)
.await?
.map(|projection| crate::Window::new(Arc::clone(&self.core), projection)))
}
/// The active pane of the current window of this client's session.
///
/// Shares the caveat on [`Self::attached_window`], and adds one: this is
/// the window's active pane, not a per-client focus, because tmux does
/// not keep one. Two clients on the same session always report the same
/// pane.
///
/// `None` when the client is attached to nothing.
///
/// Costs one tmux command, as [`Self::attached_session`] describes.
///
/// # Errors
///
/// Returns an error when tmux cannot be reached, or answers with an ID
/// this crate cannot parse.
pub async fn attached_pane(&self) -> Result<Option<crate::Pane>, Error> {
let name = OsString::from_vec(self.name().as_bytes().to_vec());
Ok(listing::client_pane(&self.core, &name)
.await?
.map(|projection| crate::Pane::new(Arc::clone(&self.core), projection)))
}
/// Detach this client from its server.
///
/// This consumes the handle: the client is gone once it detaches.
///
/// # Errors
///
/// Returns an error when tmux refuses the command.
pub async fn detach(self) -> Result<(), Error> {
listing::mutate(
&self.core,
"detach-client",
Command::new("detach-client")
.arg("-t")
.arg(self.name().to_string_lossy().into_owned()),
)
.await
}
/// Suspend this client, as if its user pressed the suspend key.
///
/// The handle survives, and deliberately: unlike [`Self::detach`], this
/// stops the client rather than ending it. tmux stops listing a suspended
/// client, so [`Server::clients`] will not show it and the session stops
/// counting it as attached, but it is still there. It returns when its
/// process continues, which for a suspended client is `SIGCONT`.
///
/// [`Server::clients`]: crate::Server::clients
///
/// # Errors
///
/// Returns an error when tmux refuses the command. Reading through the
/// handle afterwards gives [`Error::ClientSuspended`] rather than
/// [`Error::ObjectGone`], so a caller can tell this from a client that
/// left.
pub async fn suspend(&self) -> Result<(), Error> {
listing::mutate(
&self.core,
"suspend-client",
Command::new("suspend-client")
.arg("-t")
.arg(self.name().to_string_lossy().into_owned()),
)
.await
}
/// Lock this client's terminal.
///
/// Runs the `lock-command` option, which is `lock -np` unless the server
/// was told otherwise. [`crate::Session::lock`] locks every client
/// attached to one session and [`crate::Server::lock_all`] locks every
/// client on the server; this locks exactly one.
///
/// tmux marks a locked client with the flag it uses for a suspended one,
/// so a locked client leaves [`crate::Server::clients`] the same way and
/// comes back when its `lock-command` exits. A server with
/// `lock-after-time` set reaches that state with nobody asking.
///
/// # Errors
///
/// Returns an error when tmux refuses the command. Reading through the
/// handle while the client is locked gives [`Error::ClientSuspended`],
/// not [`Error::ObjectGone`].
pub async fn lock(&self) -> Result<(), Error> {
listing::mutate(
&self.core,
"lock-client",
Command::new("lock-client")
.arg("-t")
.arg(self.name().to_string_lossy().into_owned()),
)
.await
}
/// Redraw this client's terminal.
///
/// This is tmux's `refresh-client`. It is named `redraw` because
/// `refresh` means "re-read the snapshot" on every handle in this crate,
/// and these do different things.
///
/// # Errors
///
/// Returns an error when tmux refuses the command.
pub async fn redraw(&self) -> Result<(), Error> {
listing::mutate(
&self.core,
"refresh-client",
Command::new("refresh-client")
.arg("-t")
.arg(self.name().to_string_lossy().into_owned()),
)
.await
}
/// Point this client at another session.
///
/// # Errors
///
/// Returns [`Error::ServerMismatch`] when the session belongs to another
/// server, or an error when the session does not exist or tmux refuses.
pub async fn switch_to(&self, session: &crate::Session) -> Result<(), Error> {
self.core
.require_same_server(session.server_identity(), "switch-client")?;
listing::mutate(
&self.core,
"switch-client",
Command::new("switch-client")
.arg("-c")
.arg(self.name().to_string_lossy().into_owned())
.arg("-t")
.arg(session.id().to_string()),
)
.await
}
}
/// Clients compare by server endpoint and client name.
impl PartialEq for Client {
fn eq(&self, other: &Self) -> bool {
self.server_identity() == other.server_identity() && self.name() == other.name()
}
}
impl Eq for Client {}
impl Hash for Client {
fn hash<H: Hasher>(&self, state: &mut H) {
self.server_identity().hash(state);
self.name().hash(state);
}
}
/// Renders nothing but the type.
///
/// A client name is a terminal path, which identifies the user's machine, so
/// it stays out of diagnostics like every other snapshot value.
impl fmt::Debug for Client {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.debug_struct("Client").finish_non_exhaustive()
}
}
/// Filtering a client uses the same handles as the snapshot beneath it.
///
/// Matching and validation delegate to that snapshot, so an expression can
/// only name fields the catalog knows. The companion is re-parameterized to
/// [`Client`] so the type a listing returns is the type an expression
/// filters.
#[cfg(feature = "query")]
impl Filterable for Client {
type Fields = ClientFields<Self>;
const FILTER_TARGET: &'static str = <ClientInfo as Filterable>::FILTER_TARGET;
fn filter_fields() -> Self::Fields {
Self::Fields::for_target(Self::FILTER_TARGET)
}
fn __filter_matches(&self, predicate: &crate::query::__private::Predicate) -> bool {
self.info.__filter_matches(predicate)
}
fn __filter_validate(
predicate: &crate::query::__private::Predicate,
) -> Result<(), crate::query::FilterExpressionError> {
<ClientInfo as Filterable>::__filter_validate(predicate)
}
}
#[cfg(feature = "query")]
impl FilterSchema for Client {
fn __filter_schema() -> crate::query::__private::FilterSchemaDescriptor {
<ClientInfo as FilterSchema>::__filter_schema()
}
}
/// Renders the client name, which is its terminal path.
impl fmt::Display for Client {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.name().to_string_lossy())
}
}