Skip to main content

tmux_client/
session.rs

1//! Session snapshots, hierarchy traversal, and mutations.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::ffi::OsString;
5use std::future::Future;
6
7use crate::{
8    AttachedClient, Client, Command, Error, NewWindow, ObjectKind, OptionMap, OptionScope,
9    OptionValue, Pane, Result, Server, SessionId, SessionName, SessionSnapshot, SparseOptionMap,
10    TmuxText, Window, WindowId, WindowTarget,
11};
12
13/// A tmux session handle with an owned snapshot.
14#[derive(Clone, Debug)]
15pub struct Session {
16    server: Server,
17    id: SessionId,
18    name: Option<SessionName>,
19    snapshot: SessionSnapshot,
20}
21
22impl Session {
23    pub(crate) fn from_row(server: Server, row: BTreeMap<&'static str, TmuxText>) -> Result<Self> {
24        let snapshot = SessionSnapshot::new(row);
25        let id = snapshot.id()?.ok_or_else(|| Error::Decode {
26            context: "session row",
27            message: "session_id was empty".to_owned(),
28        })?;
29        let name = snapshot.name()?;
30        Ok(Self {
31            server,
32            id,
33            name,
34            snapshot,
35        })
36    }
37
38    /// Resolves the session containing the pane named by `TMUX_PANE`.
39    pub async fn from_environment() -> Result<Self> {
40        Server::from_environment()?
41            .pane_from_environment()
42            .await?
43            .session()
44            .await
45    }
46
47    /// Returns the immutable tmux ID.
48    #[must_use]
49    pub const fn id(&self) -> SessionId {
50        self.id
51    }
52
53    /// Returns the name captured in the current snapshot.
54    #[must_use]
55    pub const fn name(&self) -> Option<&SessionName> {
56        self.name.as_ref()
57    }
58
59    /// Returns the owned snapshot.
60    #[must_use]
61    pub const fn snapshot(&self) -> &SessionSnapshot {
62        &self.snapshot
63    }
64
65    /// Returns the server handle used by this object.
66    #[must_use]
67    pub const fn server(&self) -> &Server {
68        &self.server
69    }
70
71    /// Replaces this object's state with a fresh snapshot.
72    pub async fn refresh(&mut self) -> Result<()> {
73        *self = self.server.session(self.id).await?;
74        Ok(())
75    }
76
77    /// Runs an arbitrary tmux command targeted at this session.
78    pub async fn cmd(&self, command: Command) -> Result<crate::CommandResult> {
79        self.server.cmd(command.target(self.id)).await
80    }
81
82    /// Lists window links owned by this session.
83    pub async fn windows(&self) -> Result<Vec<Window>> {
84        Ok(self
85            .server
86            .windows()
87            .await?
88            .into_iter()
89            .filter(|window| window.session_id() == self.id)
90            .collect())
91    }
92
93    /// Lists windows, returning an empty collection on failure.
94    pub async fn windows_or_empty(&self) -> Vec<Window> {
95        self.windows().await.unwrap_or_default()
96    }
97
98    /// Lists every pane belonging to this session.
99    pub async fn panes(&self) -> Result<Vec<Pane>> {
100        Ok(self
101            .server
102            .panes()
103            .await?
104            .into_iter()
105            .filter(|pane| pane.session_id() == self.id)
106            .collect())
107    }
108
109    /// Lists panes, returning an empty collection on failure.
110    pub async fn panes_or_empty(&self) -> Vec<Pane> {
111        self.panes().await.unwrap_or_default()
112    }
113
114    /// Returns the active pane in this session's active window.
115    pub async fn active_pane(&self) -> Result<Pane> {
116        self.active_window().await?.active_pane().await
117    }
118
119    /// Returns the active window link.
120    pub async fn active_window(&self) -> Result<Window> {
121        let mut active = Vec::new();
122        for window in self.windows().await? {
123            if window.snapshot().active()? == Some(true) {
124                active.push(window);
125            }
126        }
127        match active.len() {
128            0 => Err(Error::ObjectNotFound {
129                kind: ObjectKind::Window,
130                target: format!("active window in {}", self.id),
131            }),
132            1 => active.into_iter().next().ok_or_else(|| Error::Decode {
133                context: "active window",
134                message: "single result disappeared".to_owned(),
135            }),
136            count => Err(Error::MultipleObjects {
137                kind: ObjectKind::Window,
138                count,
139                query: format!("active windows in {}", self.id),
140            }),
141        }
142    }
143
144    /// Resolves one window ID within this session.
145    pub async fn window(&self, id: WindowId) -> Result<Window> {
146        self.windows()
147            .await?
148            .into_iter()
149            .find(|window| window.id() == id)
150            .ok_or_else(|| Error::ObjectNotFound {
151                kind: ObjectKind::Window,
152                target: format!("{id} in {}", self.id),
153            })
154    }
155
156    /// Lists clients currently attached to this session.
157    pub async fn clients(&self) -> Result<Vec<Client>> {
158        let name = self.name().map(ToString::to_string);
159        Ok(self
160            .server
161            .clients()
162            .await?
163            .into_iter()
164            .filter(|client| client.session_name().map(ToString::to_string) == name)
165            .collect())
166    }
167
168    /// Creates a window in this session.
169    pub async fn new_window(&self, options: NewWindow) -> Result<Window> {
170        Window::create(self, options).await
171    }
172
173    /// Creates a temporary window, runs an async operation, and attempts cleanup.
174    pub async fn with_window<F, Fut, T>(&self, options: NewWindow, operation: F) -> Result<T>
175    where
176        F: FnOnce(Window) -> Fut,
177        Fut: Future<Output = Result<T>>,
178    {
179        let window = self.new_window(options).await?;
180        let cleanup = window.clone();
181        let outcome = operation(window).await;
182        let cleanup_result = cleanup.kill().await;
183        match (outcome, cleanup_result) {
184            (Ok(value), Ok(())) => Ok(value),
185            (Ok(_), Err(source)) => Err(Error::Cleanup {
186                operation: "with_window",
187                source: Box::new(source),
188            }),
189            (Err(source), _) => Err(source),
190        }
191    }
192
193    /// Renames the session and refreshes the snapshot.
194    pub async fn rename(&mut self, name: impl Into<String>) -> Result<()> {
195        let name = SessionName::new(name)?;
196        self.server
197            .checked(
198                "rename session",
199                Command::new("rename-session")
200                    .target(self.id)
201                    .arg(name.to_string()),
202            )
203            .await?;
204        self.refresh().await
205    }
206
207    /// Selects this session for the invoking client.
208    pub async fn select(&self) -> Result<()> {
209        self.server
210            .checked(
211                "select session",
212                Command::new("switch-client").target(self.id),
213            )
214            .await
215            .map(|_| ())
216    }
217
218    /// Locks clients attached to this session.
219    pub async fn lock(&self) -> Result<()> {
220        self.server
221            .checked("lock session", Command::new("lock-session").target(self.id))
222            .await
223            .map(|_| ())
224    }
225
226    /// Kills one selected window in this session.
227    pub async fn kill_window(&self, target: impl Into<WindowTarget>) -> Result<()> {
228        self.server
229            .checked(
230                "kill session window",
231                Command::new("kill-window").target(target.into()),
232            )
233            .await
234            .map(|_| ())
235    }
236
237    /// Selects a window link in this session.
238    pub async fn select_window(&self, window: impl Into<WindowTarget>) -> Result<()> {
239        self.server
240            .checked(
241                "select window",
242                Command::new("select-window").target(window.into()),
243            )
244            .await
245            .map(|_| ())
246    }
247
248    /// Selects the next window.
249    pub async fn next_window(&self, alert: bool) -> Result<()> {
250        let command = if alert {
251            Command::new("next-window").arg("-a")
252        } else {
253            Command::new("next-window")
254        };
255        self.server
256            .checked("next window", command.target(self.id))
257            .await
258            .map(|_| ())
259    }
260
261    /// Selects the previous window.
262    pub async fn previous_window(&self, alert: bool) -> Result<()> {
263        let command = if alert {
264            Command::new("previous-window").arg("-a")
265        } else {
266            Command::new("previous-window")
267        };
268        self.server
269            .checked("previous window", command.target(self.id))
270            .await
271            .map(|_| ())
272    }
273
274    /// Selects the last active window.
275    pub async fn last_window(&self) -> Result<()> {
276        self.server
277            .checked("last window", Command::new("last-window").target(self.id))
278            .await
279            .map(|_| ())
280    }
281
282    /// Renumbers this session's window links.
283    pub async fn renumber_windows(&self) -> Result<()> {
284        self.server
285            .checked(
286                "renumber windows",
287                Command::new("move-window").arg("-r").target(self.id),
288            )
289            .await
290            .map(|_| ())
291    }
292
293    /// Detaches every client attached to this session.
294    pub async fn detach_clients(&self) -> Result<()> {
295        self.server
296            .checked(
297                "detach session clients",
298                Command::new("detach-client")
299                    .arg("-s")
300                    .arg(self.id.to_string()),
301            )
302            .await
303            .map(|_| ())
304    }
305
306    /// Detaches all clients and runs a shell command for each detached client.
307    pub async fn detach_clients_with_command(&self, shell_command: OsString) -> Result<()> {
308        self.server
309            .checked(
310                "detach session clients",
311                Command::new("detach-client")
312                    .arg("-s")
313                    .arg(self.id.to_string())
314                    .arg("-E")
315                    .sensitive_arg(shell_command),
316            )
317            .await
318            .map(|_| ())
319    }
320
321    /// Applies extended `kill-session` flags.
322    pub async fn kill_with(&self, all_except: bool, clear_alerts: bool, group: bool) -> Result<()> {
323        if group {
324            self.server
325                .version()
326                .await?
327                .require("kill session group", crate::ReleaseVersion::new(3, 7, None))?;
328        }
329        let mut command = Command::new("kill-session").target(self.id);
330        if all_except {
331            command = command.arg("-a");
332        }
333        if clear_alerts {
334            command = command.arg("-C");
335        }
336        if group {
337            command = command.arg("-g");
338        }
339        self.server
340            .checked("kill session", command)
341            .await
342            .map(|_| ())
343    }
344
345    /// Starts an interactive attachment.
346    pub fn attach(&self, read_only: bool) -> Result<AttachedClient> {
347        self.server.attach(self.id, read_only)
348    }
349
350    /// Destroys the session. Dropping the handle does not call this method.
351    pub async fn kill(&self) -> Result<()> {
352        self.server
353            .checked("kill session", Command::new("kill-session").target(self.id))
354            .await
355            .map(|_| ())
356    }
357
358    /// Shows options at session scope.
359    pub async fn options(&self) -> Result<OptionMap> {
360        self.server
361            .show_options(OptionScope::Session, Some(&self.id.to_string()))
362            .await
363    }
364
365    /// Shows sparse options and hooks at session scope.
366    pub async fn sparse_options(&self) -> Result<SparseOptionMap> {
367        self.server
368            .show_sparse_options(OptionScope::Session, Some(&self.id.to_string()))
369            .await
370    }
371
372    /// Sets a session option.
373    pub async fn set_option(&self, name: &str, value: &OptionValue, append: bool) -> Result<()> {
374        self.server
375            .set_option(
376                OptionScope::Session,
377                Some(&self.id.to_string()),
378                name,
379                value,
380                append,
381            )
382            .await
383    }
384
385    /// Unsets a session option.
386    pub async fn unset_option(&self, name: &str) -> Result<()> {
387        self.server
388            .unset_option(OptionScope::Session, Some(&self.id.to_string()), name)
389            .await
390    }
391
392    /// Shows this session's environment. Removed entries have a `None` value.
393    pub async fn environment(&self) -> Result<BTreeMap<String, Option<TmuxText>>> {
394        let result = self
395            .server
396            .checked(
397                "show session environment",
398                Command::new("show-environment").target(self.id),
399            )
400            .await?;
401        crate::server::parse_environment(result.stdout().as_bytes())
402    }
403
404    /// Returns one session environment entry.
405    ///
406    /// The outer option distinguishes an unknown name; the inner option is
407    /// `None` when tmux records the name as explicitly removed.
408    pub async fn environment_entry(&self, name: &str) -> Result<Option<Option<TmuxText>>> {
409        crate::server::validate_name("environment name", name)?;
410        Ok(self.environment().await?.remove(name))
411    }
412
413    /// Sets a session environment variable.
414    pub async fn set_environment(&self, name: &str, value: impl Into<OsString>) -> Result<()> {
415        self.set_environment_with(name, value, false, false).await
416    }
417
418    /// Sets a session environment variable with format expansion or hidden storage.
419    pub async fn set_environment_with(
420        &self,
421        name: &str,
422        value: impl Into<OsString>,
423        expand_formats: bool,
424        hidden: bool,
425    ) -> Result<()> {
426        crate::server::validate_name("environment name", name)?;
427        let mut command = Command::new("set-environment").target(self.id);
428        if expand_formats {
429            command = command.arg("-F");
430        }
431        if hidden {
432            command = command.arg("-h");
433        }
434        self.server
435            .checked(
436                "set session environment",
437                command.arg(name).sensitive_arg(value),
438            )
439            .await
440            .map(|_| ())
441    }
442
443    /// Unsets a session environment variable.
444    pub async fn unset_environment(&self, name: &str) -> Result<()> {
445        crate::server::validate_name("environment name", name)?;
446        self.server
447            .checked(
448                "unset session environment",
449                Command::new("set-environment")
450                    .arg("-u")
451                    .target(self.id)
452                    .arg(name),
453            )
454            .await
455            .map(|_| ())
456    }
457
458    /// Marks a session environment variable as removed for future child processes.
459    pub async fn remove_environment(&self, name: &str) -> Result<()> {
460        crate::server::validate_name("environment name", name)?;
461        self.server
462            .checked(
463                "remove session environment",
464                Command::new("set-environment")
465                    .arg("-r")
466                    .target(self.id)
467                    .arg(name),
468            )
469            .await
470            .map(|_| ())
471    }
472
473    /// Returns all distinct window IDs linked into this session.
474    pub async fn window_ids(&self) -> Result<BTreeSet<WindowId>> {
475        Ok(self
476            .windows()
477            .await?
478            .into_iter()
479            .map(|window| window.id())
480            .collect())
481    }
482}
483
484impl PartialEq for Session {
485    fn eq(&self, other: &Self) -> bool {
486        self.id == other.id && self.server.config() == other.server.config()
487    }
488}
489
490impl Eq for Session {}