termux_api/api/dialog/
confirm.rs

1use serde::{Deserialize, Deserializer};
2use std::process::Command;
3
4use crate::api::errors::TermuxError;
5
6#[derive(Debug, Deserialize)]
7pub struct TermuxDialogConfirmResult {
8    pub code: i32,
9
10    #[serde(rename = "text", deserialize_with = "deserialize_yes_no")]
11    pub confirmed: bool,
12}
13
14fn deserialize_yes_no<'de, D>(deserializer: D) -> Result<bool, D::Error>
15where
16    D: Deserializer<'de>,
17{
18    let opt = Option::<String>::deserialize(deserializer)?;
19    match opt.as_deref() {
20        Some("yes") => Ok(true),
21        Some("no") => Ok(false),
22        _ => Err(serde::de::Error::custom("Unexpected value")),
23    }
24}
25
26pub struct TermuxConfirmDialog {
27    pub title: Option<String>,
28    pub hint: Option<String>,
29}
30
31impl TermuxConfirmDialog {
32    pub fn new() -> Self {
33        Self {
34            title: None,
35            hint: None,
36        }
37    }
38
39    pub fn title(mut self, title: &str) -> Self {
40        self.title = Some(title.to_string());
41        self
42    }
43
44    pub fn hint(mut self, hint: &str) -> Self {
45        self.hint = Some(hint.to_string());
46        self
47    }
48
49    pub fn run(&self) -> Result<TermuxDialogConfirmResult, TermuxError> {
50        let mut command = Command::new("termux-dialog");
51        command.arg("confirm");
52
53        if let Some(ref title) = self.title {
54            command.arg("-t").arg(title);
55        }
56
57        if let Some(ref hint) = self.hint {
58            command.arg("-i").arg(hint);
59        }
60
61        let output = command.output();
62        match output {
63            Ok(output) => {
64                if output.status.success() {
65                    let result: TermuxDialogConfirmResult =
66                        serde_json::from_slice(&output.stdout).unwrap();
67                    Ok(result)
68                } else {
69                    Err(TermuxError::Output(output))
70                }
71            }
72            Err(e) => Err(TermuxError::IOError(e)),
73        }
74    }
75}