termux_api/api/
toast.rs

1use std::process::Command;
2
3use super::errors::TermuxError;
4
5pub enum ToastPosition {
6    Top,
7    Middle,
8    Bottom,
9}
10
11pub struct TermuxToast {
12    pub text: Option<String>,
13    pub background_color: Option<String>,
14    pub text_color: Option<String>,
15    pub position: ToastPosition,
16    pub short_duration: bool,
17}
18
19impl TermuxToast {
20    pub fn text(mut self, text: &str) -> Self {
21        self.text = Some(text.to_string());
22        self
23    }
24
25    pub fn background_color(mut self, color: &str) -> Self {
26        self.background_color = Some(color.to_string());
27        self
28    }
29
30    pub fn text_color(mut self, color: &str) -> Self {
31        self.text_color = Some(color.to_string());
32        self
33    }
34
35    pub fn position(mut self, position: ToastPosition) -> Self {
36        self.position = position;
37        self
38    }
39
40    pub fn short_duration(mut self, short: bool) -> Self {
41        self.short_duration = short;
42        self
43    }
44
45    pub fn new() -> Self {
46        Self {
47            text: None,
48            background_color: None,
49            text_color: None,
50            position: ToastPosition::Middle,
51            short_duration: false,
52        }
53    }
54
55    pub fn run(&mut self) -> Result<(), TermuxError> {
56        let mut command = Command::new("termux-toast");
57
58        if let Some(ref color) = self.background_color {
59            command.arg("-b").arg(color);
60        }
61        if let Some(ref color) = self.text_color {
62            command.arg("-c").arg(color);
63        }
64        command.arg("-g").arg(match self.position {
65            ToastPosition::Top => "top",
66            ToastPosition::Middle => "middle",
67            ToastPosition::Bottom => "bottom",
68        });
69
70        if self.short_duration {
71            command.arg("-s");
72        }
73
74        if let Some(ref text) = self.text {
75            command.arg(text);
76        }
77
78        let output = command.output();
79        match output {
80            Ok(output) => {
81                if output.status.success() {
82                    return Ok(());
83                }
84                Err(TermuxError::Output(output))
85            }
86            Err(e) => Err(TermuxError::IOError(e)),
87        }
88    }
89}