termusiclib/
ueberzug.rs

1use crate::xywh::Xywh;
2use anyhow::Context;
3use anyhow::{bail, Result};
4use std::ffi::OsStr;
5use std::io::Read as _;
6use std::io::Write;
7use std::process::Child;
8use std::process::Command;
9use std::process::Stdio;
10
11#[derive(Debug)]
12pub enum UeInstanceState {
13    New,
14    Child(Child),
15    /// Permanent Error
16    Error,
17}
18
19impl PartialEq for UeInstanceState {
20    fn eq(&self, other: &Self) -> bool {
21        match (self, other) {
22            (Self::Child(_), Self::Child(_)) => true,
23            _ => core::mem::discriminant(self) == core::mem::discriminant(other),
24        }
25    }
26}
27
28impl UeInstanceState {
29    /// unwrap value in [`UeInstanceState::Child`], panicing if not that variant
30    fn unwrap_child_mut(&mut self) -> &mut Child {
31        if let Self::Child(v) = self {
32            return v;
33        }
34        unreachable!()
35    }
36}
37
38/// Run `ueberzug` commands
39///
40/// If there is a permanent error (like `ueberzug` not being installed), will silently ignore all commands after initial error
41#[derive(Debug)]
42pub struct UeInstance {
43    ueberzug: UeInstanceState,
44}
45
46impl Default for UeInstance {
47    fn default() -> Self {
48        info!("Potentially using ueberzug");
49
50        Self {
51            ueberzug: UeInstanceState::New,
52        }
53    }
54}
55
56impl UeInstance {
57    pub fn draw_cover_ueberzug(
58        &mut self,
59        url: &str,
60        draw_xywh: &Xywh,
61        use_sixel: bool,
62    ) -> Result<()> {
63        if draw_xywh.width <= 1 || draw_xywh.height <= 1 {
64            return Ok(());
65        }
66
67        // Ueberzug takes an area given in chars and fits the image to
68        // that area (from the top left).
69        //   draw_offset.y += (draw_size.y - size.y) - (draw_size.y - size.y) / 2;
70        let cmd = format!("{{\"action\":\"add\",\"scaler\":\"forced_cover\",\"identifier\":\"cover\",\"x\":{},\"y\":{},\"width\":{},\"height\":{},\"path\":\"{}\"}}\n",
71        // let cmd = format!("{{\"action\":\"add\",\"scaler\":\"fit_contain\",\"identifier\":\"cover\",\"x\":{},\"y\":{},\"width\":{},\"height\":{},\"path\":\"{}\"}}\n",
72        // TODO: right now the y position of ueberzug is not consistent, and could be a 0.5 difference
73                // draw_xywh.x, draw_xywh.y-1,
74                draw_xywh.x, draw_xywh.y,//-1 + (draw_xywh.width-draw_xywh.height) % 2,
75                draw_xywh.width,draw_xywh.height/2,//+ (draw_xywh.width-draw_xywh.height)%2,
76                url,
77            );
78
79        // debug!(
80        //     "draw_xywh.x = {}, draw_xywh.y = {}, draw_wyxh.width = {}, draw_wyxh.height = {}",
81        //     draw_xywh.x, draw_xywh.y, draw_xywh.width, draw_xywh.height,
82        // );
83        if use_sixel {
84            self.run_ueberzug_cmd_sixel(&cmd).map_err(map_err)?;
85        } else {
86            self.run_ueberzug_cmd(&cmd).map_err(map_err)?;
87        }
88
89        Ok(())
90    }
91
92    pub fn clear_cover_ueberzug(&mut self) -> Result<()> {
93        let cmd = "{\"action\": \"remove\", \"identifier\": \"cover\"}\n";
94        self.run_ueberzug_cmd(cmd)
95            .map_err(map_err)
96            .context("clear_cover")?;
97        Ok(())
98    }
99
100    fn run_ueberzug_cmd(&mut self, cmd: &str) -> Result<()> {
101        let Some(ueberzug) = self.try_wait_spawn(["layer", "--silent"])? else {
102            return Ok(());
103        };
104
105        let stdin = ueberzug.stdin.as_mut().unwrap();
106        stdin
107            .write_all(cmd.as_bytes())
108            .context("ueberzug command writing")?;
109
110        Ok(())
111    }
112
113    fn run_ueberzug_cmd_sixel(&mut self, cmd: &str) -> Result<()> {
114        // debug!("ueberzug forced sixel");
115
116        let Some(ueberzug) = self.try_wait_spawn(
117            ["layer", "--silent"],
118            // ["layer", "--silent", "--no-cache", "--output", "sixel"]
119            // ["layer", "--sixel"]
120            // ["--sixel"]
121        )?
122        else {
123            return Ok(());
124        };
125
126        let stdin = ueberzug.stdin.as_mut().unwrap();
127        stdin
128            .write_all(cmd.as_bytes())
129            .context("ueberzug command writing")?;
130
131        Ok(())
132    }
133
134    /// Spawn the given `cmd`, and set `self.ueberzug` and return a reference to the child for direct use
135    ///
136    /// On fail, also set `set.ueberzug` to [`UeInstanceState::Error`]
137    fn spawn_cmd<I, S>(&mut self, args: I) -> Result<&mut Child>
138    where
139        I: IntoIterator<Item = S>,
140        S: AsRef<OsStr>,
141    {
142        let mut cmd = Command::new("ueberzug");
143        cmd.args(args)
144            .stdin(Stdio::piped())
145            .stdout(Stdio::inherit()) // ueberzug may need this for chafa output
146            .stderr(Stdio::piped());
147
148        match cmd.spawn() {
149            Ok(child) => {
150                self.ueberzug = UeInstanceState::Child(child);
151                Ok(self.ueberzug.unwrap_child_mut())
152            }
153            Err(err) => {
154                if err.kind() == std::io::ErrorKind::NotFound {
155                    self.ueberzug = UeInstanceState::Error;
156                }
157                bail!(err)
158            }
159        }
160    }
161
162    /// If ueberzug instance does not exist, create it. Otherwise take the existing one
163    ///
164    /// Do a [`Child::try_wait`] on the existing instance and return a error if the instance has exited
165    fn try_wait_spawn<I, S>(&mut self, args: I) -> Result<Option<&mut Child>>
166    where
167        I: IntoIterator<Item = S>,
168        S: AsRef<OsStr>,
169    {
170        let child = match self.ueberzug {
171            UeInstanceState::New => self.spawn_cmd(args)?,
172            UeInstanceState::Child(ref mut v) => v,
173            UeInstanceState::Error => {
174                trace!("Not re-trying ueberzug, because it has a permanent error!");
175
176                return Ok(None);
177            }
178        };
179
180        if let Some(exit_status) = child.try_wait()? {
181            let mut stderr_buf = String::new();
182            child
183                .stderr
184                .as_mut()
185                .map(|v| v.read_to_string(&mut stderr_buf));
186
187            // using a permanent-Error because it is likely the error will happen again on restart (like being on wayland instead of x11)
188            self.ueberzug = UeInstanceState::Error;
189
190            if stderr_buf.is_empty() {
191                stderr_buf.push_str("<empty>");
192            }
193
194            // special handling for unix as that only contains the ".signal" extension, which is important there
195            #[cfg(not(target_family = "unix"))]
196            {
197                bail!(
198                    "ueberzug command closed unexpectedly, (code {:?}), stderr:\n{}",
199                    exit_status.code(),
200                    stderr_buf
201                );
202            }
203            #[cfg(target_family = "unix")]
204            {
205                use std::os::unix::process::ExitStatusExt as _;
206                bail!(
207                    "ueberzug command closed unexpectedly, (code {:?}, signal {:?}), stderr:\n{}",
208                    exit_status.code(),
209                    exit_status.signal(),
210                    stderr_buf
211                );
212            }
213        }
214
215        // out of some reason local variable "child" cannot be returned here because it is modified in the "try_wait" branch
216        // even though that branch never reaches here
217        Ok(Some(self.ueberzug.unwrap_child_mut()))
218    }
219}
220
221/// Map a given error to include extra context
222#[inline]
223fn map_err(err: anyhow::Error) -> anyhow::Error {
224    err.context("Failed to run Ueberzug")
225}