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 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 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#[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 let cmd = format!("{{\"action\":\"add\",\"scaler\":\"forced_cover\",\"identifier\":\"cover\",\"x\":{},\"y\":{},\"width\":{},\"height\":{},\"path\":\"{}\"}}\n",
71 draw_xywh.x, draw_xywh.y,draw_xywh.width,draw_xywh.height/2,url,
77 );
78
79 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 let Some(ueberzug) = self.try_wait_spawn(
117 ["layer", "--silent"],
118 )?
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 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()) .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 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 self.ueberzug = UeInstanceState::Error;
189
190 if stderr_buf.is_empty() {
191 stderr_buf.push_str("<empty>");
192 }
193
194 #[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 Ok(Some(self.ueberzug.unwrap_child_mut()))
218 }
219}
220
221#[inline]
223fn map_err(err: anyhow::Error) -> anyhow::Error {
224 err.context("Failed to run Ueberzug")
225}