Skip to main content

tmux_client/
client.rs

1//! Attached-client snapshots and interactive attachment handles.
2
3use std::collections::BTreeMap;
4use std::process::ExitStatus;
5
6use tokio::process::Child;
7
8use crate::{
9    ClientName, ClientSnapshot, Command, CommandSummary, Error, ObjectKind, Pane, PaneId, Result,
10    Server, Session, SessionName, SessionTarget, TmuxText, Window, WindowId,
11};
12
13/// A tmux client discovered with `list-clients`.
14#[derive(Clone, Debug)]
15pub struct Client {
16    server: Server,
17    name: ClientName,
18    session_name: Option<SessionName>,
19    snapshot: ClientSnapshot,
20}
21
22impl Client {
23    pub(crate) fn from_row(server: Server, row: BTreeMap<&'static str, TmuxText>) -> Result<Self> {
24        let snapshot = ClientSnapshot::new(row);
25        let name = snapshot.name()?.ok_or_else(|| Error::Decode {
26            context: "client row",
27            message: "client_name was empty".to_owned(),
28        })?;
29        let session_name = snapshot.session_name()?;
30        Ok(Self {
31            server,
32            name,
33            session_name,
34            snapshot,
35        })
36    }
37
38    /// Returns the byte-preserving tmux client name.
39    #[must_use]
40    pub const fn name(&self) -> &ClientName {
41        &self.name
42    }
43
44    /// Returns the attached session name captured by this snapshot.
45    #[must_use]
46    pub const fn session_name(&self) -> Option<&SessionName> {
47        self.session_name.as_ref()
48    }
49
50    /// Returns the owned client snapshot.
51    #[must_use]
52    pub const fn snapshot(&self) -> &ClientSnapshot {
53        &self.snapshot
54    }
55
56    /// Returns the server handle.
57    #[must_use]
58    pub const fn server(&self) -> &Server {
59        &self.server
60    }
61
62    /// Replaces this object's state with a fresh client snapshot.
63    pub async fn refresh(&mut self) -> Result<()> {
64        let name = self.name.clone();
65        *self = self
66            .server
67            .clients()
68            .await?
69            .into_iter()
70            .find(|client| client.name == name)
71            .ok_or_else(|| Error::ObjectNotFound {
72                kind: ObjectKind::Client,
73                target: name.to_string(),
74            })?;
75        Ok(())
76    }
77
78    /// Resolves the currently attached session, if any.
79    pub async fn session(&self) -> Result<Option<Session>> {
80        let Some(name) = self.session_name() else {
81            return Ok(None);
82        };
83        self.server.session_by_name(name).await.map(Some)
84    }
85
86    /// Resolves the active window attached to this client.
87    pub async fn window(&self) -> Result<Option<Window>> {
88        let Some(id) = snapshot_id::<WindowId>(&self.snapshot, "window_id", "client window ID")?
89        else {
90            return Ok(None);
91        };
92        let Some(session) = self.session().await? else {
93            return Ok(None);
94        };
95        session.window(id).await.map(Some)
96    }
97
98    /// Resolves the active pane attached to this client.
99    pub async fn pane(&self) -> Result<Option<Pane>> {
100        let Some(id) = snapshot_id::<PaneId>(&self.snapshot, "pane_id", "client pane ID")? else {
101            return Ok(None);
102        };
103        self.server.pane(id).await.map(Some)
104    }
105
106    /// Runs an arbitrary tmux command targeted at this client.
107    pub async fn cmd(&self, command: Command) -> Result<crate::CommandResult> {
108        self.server
109            .cmd(command.arg("-t").arg(self.name.to_os_string()))
110            .await
111    }
112
113    /// Detaches this client.
114    pub async fn detach(&self, hangup: bool) -> Result<()> {
115        let mut command = Command::new("detach-client");
116        if hangup {
117            command = command.arg("-P");
118        }
119        self.server
120            .checked(
121                "detach client",
122                command.arg("-t").arg(self.name.to_os_string()),
123            )
124            .await
125            .map(|_| ())
126    }
127
128    /// Switches this client to another session.
129    pub async fn switch_session(&self, target: impl Into<SessionTarget>) -> Result<()> {
130        self.server
131            .checked(
132                "switch client session",
133                Command::new("switch-client")
134                    .arg("-c")
135                    .arg(self.name.to_os_string())
136                    .arg("-t")
137                    .arg(target.into().to_string()),
138            )
139            .await
140            .map(|_| ())
141    }
142
143    /// Suspends this client process.
144    pub async fn suspend(&self) -> Result<()> {
145        self.server
146            .checked(
147                "suspend client",
148                Command::new("suspend-client")
149                    .arg("-t")
150                    .arg(self.name.to_os_string()),
151            )
152            .await
153            .map(|_| ())
154    }
155
156    /// Locks this client.
157    pub async fn lock(&self) -> Result<()> {
158        self.server
159            .checked(
160                "lock client",
161                Command::new("lock-client")
162                    .arg("-t")
163                    .arg(self.name.to_os_string()),
164            )
165            .await
166            .map(|_| ())
167    }
168
169    /// Reports an updated terminal size for a control-mode client.
170    pub async fn resize(&self, width: u32, height: u32) -> Result<()> {
171        if width == 0 || height == 0 {
172            return Err(Error::InvalidArgument {
173                argument: "client size",
174                message: "width and height must be non-zero".to_owned(),
175            });
176        }
177        self.server
178            .checked(
179                "resize client",
180                Command::new("refresh-client")
181                    .arg("-C")
182                    .arg(format!("{width},{height}"))
183                    .arg("-t")
184                    .arg(self.name.to_os_string()),
185            )
186            .await
187            .map(|_| ())
188    }
189}
190
191impl PartialEq for Client {
192    fn eq(&self, other: &Self) -> bool {
193        self.name == other.name && self.server.config() == other.server.config()
194    }
195}
196
197impl Eq for Client {}
198
199fn snapshot_id<T>(
200    snapshot: &ClientSnapshot,
201    token: &'static str,
202    context: &'static str,
203) -> Result<Option<T>>
204where
205    T: std::str::FromStr,
206    T::Err: std::fmt::Display,
207{
208    let Some(value) = snapshot.get(token) else {
209        return Ok(None);
210    };
211    if value.is_empty() {
212        return Ok(None);
213    }
214    let value = value.to_str().map_err(|source| Error::Decode {
215        context,
216        message: source.to_string(),
217    })?;
218    value
219        .parse::<T>()
220        .map(Some)
221        .map_err(|source| Error::Decode {
222            context,
223            message: source.to_string(),
224        })
225}
226
227/// A running, interactive `attach-session` child process.
228///
229/// Dropping the handle terminates the spawned tmux client process because the
230/// underlying Tokio child is configured with `kill_on_drop`. It never destroys
231/// the attached session.
232#[derive(Debug)]
233pub struct AttachedClient {
234    child: Child,
235    summary: CommandSummary,
236}
237
238impl AttachedClient {
239    pub(crate) const fn new(child: Child, summary: CommandSummary) -> Self {
240        Self { child, summary }
241    }
242
243    /// Returns the child process ID when it is still available.
244    #[must_use]
245    pub fn id(&self) -> Option<u32> {
246        self.child.id()
247    }
248
249    /// Returns the redacted attachment command.
250    #[must_use]
251    pub const fn summary(&self) -> &CommandSummary {
252        &self.summary
253    }
254
255    /// Waits for the interactive client to exit.
256    pub async fn wait(mut self) -> Result<ExitStatus> {
257        self.child.wait().await.map_err(|source| Error::Io {
258            operation: "wait for attached client",
259            source,
260        })
261    }
262
263    /// Requests termination and waits for the client process.
264    pub async fn terminate(&mut self) -> Result<ExitStatus> {
265        self.child.kill().await.map_err(|source| Error::Io {
266            operation: "terminate attached client",
267            source,
268        })?;
269        self.child.wait().await.map_err(|source| Error::Io {
270            operation: "wait for terminated attached client",
271            source,
272        })
273    }
274}