# crates/libtmux/src/client.rs

libtmux/libtmux-rs@6a256a08d97d

````rust
//! 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 std::time::SystemTime;

use crate::formats::TmuxText;
use crate::internal::core::Core;
use crate::internal::listing;
#[cfg(feature = "query")]
use crate::query::{FilterSchema, Filterable, ReadField};
#[cfg(feature = "query")]
use crate::snapshot::{Availability, ClientFields, FieldRef};
use crate::snapshot::{ClientInfo, stored_time};
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.
    ///
    /// tmux keeps whole seconds. `ClientFields::client_created` filters and
    /// reads the same field as the `i64` of Unix seconds tmux reports, because
    /// the query grammar compares integers.
    #[must_use]
    pub fn created(&self) -> SystemTime {
        stored_time(*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()
    }

    /// Report whether this process opened this client itself.
    ///
    /// tmux counts a control connection as an attached client, and this crate
    /// opens them: [`crate::Pane::stream_output`],
    /// [`crate::control::ControlMode::attach`] and the waits built on them all
    /// show up in a client listing beside a human's terminal. A caller asking
    /// "is anybody watching this session" means anybody *else*, so this is the
    /// question to ask before counting.
    ///
    /// `false` for every client once this process ends, since the answer is
    /// about connections this `Server` is still holding open.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn watchers(server: &libtmux::Server) -> Result<(), libtmux::Error> {
    /// let others = server
    ///     .clients()
    ///     .await?
    ///     .into_iter()
    ///     .filter(|client| !client.is_own())
    ///     .count();
    /// # let _ = others;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "control-mode")]
    #[must_use]
    pub fn is_own(&self) -> bool {
        self.core.owns_control_client(self.pid())
    }

    /// 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. If tmux
    /// omits a stopped client from the listing, a probe can distinguish it as
    /// [`Error::ClientSuspended`]. Releases that keep it listed can refresh
    /// successfully instead. Keep the handle when the client is suspended.
    /// 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.
    ///
    /// Some releases leave out the dead, the exiting and the suspended
    /// alike, so absence from the listing does not say which happened. A
    /// suspended client still resolves 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 the same errors as [`Self::refresh`], including
    /// [`Error::ClientSuspended`] when an omitted client is found stopped.
    /// A stopped client that remains listed can refresh successfully instead.
    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 version = server.capabilities().await?.tmux_version().clone();
    /// # let eligible = version.has_behavior(&libtmux::since::CONTROL_ACQUISITION);
    /// # if eligible {
    /// 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. Some tmux releases omit a
    /// suspended client from [`Server::clients`]; others keep it listed.
    /// The client resumes when its process continues with `SIGCONT`.
    ///
    /// [`Server::clients`]: crate::Server::clients
    ///
    /// # Errors
    ///
    /// Returns an error when tmux refuses the command. A later
    /// [`Self::refresh`] can return [`Error::ClientSuspended`] or succeed,
    /// depending on whether that tmux release omits the stopped client.
    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 can leave [`crate::Server::clients`] the same way and
    /// returns to normal 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. A later
    /// [`Self::refresh`] can return [`Error::ClientSuspended`] or succeed,
    /// depending on whether that tmux release omits the locked client.
    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()
    }
}

#[cfg(feature = "query")]
impl Client {
    /// Read one field of this client's snapshot, named by the handle that
    /// filters it.
    ///
    /// Every field in [`ClientFields`] reads this way, including those with no
    /// getter of their own. Nothing is sent to tmux, so the value is as old as
    /// the snapshot. The result says why a field holds no value: see
    /// [`Availability`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example(server: &libtmux::Server) -> Result<(), libtmux::Error> {
    /// use libtmux::Client;
    /// use libtmux::query::Filterable as _;
    ///
    /// let fields = Client::filter_fields();
    /// for client in server.clients().await? {
    ///     // The key table a client is in: `prefix` right after the prefix key.
    ///     if let Some(table) = client.get(fields.client_key_table).available() {
    ///         println!("{client}: {}", table.to_string_lossy());
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn get<F: ReadField<Self>>(&self, field: F) -> Availability<F::Value<'_>> {
        field.__read(self).unwrap_or(Availability::Absent)
    }

    /// Return the stored field tmux names `name`.
    pub(crate) fn stored(&self, name: &str) -> Option<Availability<FieldRef<'_>>> {
        self.info.stored(name)
    }
}

/// 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())
    }
}
````
