termux_gui/components/
toggle_button.rs1use serde_json::json;
4use crate::activity::Activity;
5use crate::view::View;
6use crate::error::Result;
7
8pub struct ToggleButton {
12 view: View,
13 aid: i64,
14}
15
16impl ToggleButton {
17 pub fn new(activity: &mut Activity, text: &str, parent: Option<i64>) -> Result<Self> {
19 Self::new_with_checked(activity, text, parent, false)
20 }
21
22 pub fn new_with_checked(activity: &mut Activity, text: &str, parent: Option<i64>, checked: bool) -> Result<Self> {
24 let mut params = json!({
25 "aid": activity.id(),
26 "text": text,
27 "checked": checked
28 });
29
30 if let Some(parent_id) = parent {
32 params["parent"] = json!(parent_id);
33 }
34
35 let response = activity.send_read(&json!({
36 "method": "createToggleButton",
37 "params": params
38 }))?;
39
40 let id = response
41 .as_i64()
42 .ok_or_else(|| crate::error::GuiError::InvalidResponse("Invalid id".to_string()))?;
43
44 Ok(ToggleButton {
45 view: View::new(id),
46 aid: activity.id(),
47 })
48 }
49
50 pub fn id(&self) -> i64 {
52 self.view.id()
53 }
54
55 pub fn view(&self) -> &View {
57 &self.view
58 }
59
60 pub fn set_text(&self, activity: &mut Activity, text: &str) -> Result<()> {
62 activity.send(&json!({
63 "method": "setText",
64 "params": {
65 "aid": self.aid,
66 "id": self.view.id(),
67 "text": text
68 }
69 }))?;
70 Ok(())
71 }
72
73 pub fn set_checked(&self, activity: &mut Activity, checked: bool) -> Result<()> {
75 activity.send(&json!({
76 "method": "setChecked",
77 "params": {
78 "aid": self.aid,
79 "id": self.view.id(),
80 "checked": checked
81 }
82 }))?;
83 Ok(())
84 }
85}