termux_gui/components/
checkbox.rs

1//! Checkbox component
2
3use serde_json::json;
4use crate::activity::Activity;
5use crate::view::View;
6use crate::error::Result;
7
8/// A Checkbox can be checked or unchecked
9pub struct Checkbox {
10    view: View,
11    aid: i64,
12}
13
14impl Checkbox {
15    /// Create a new Checkbox with optional initial checked state
16    pub fn new(activity: &mut Activity, text: &str, parent: Option<i64>) -> Result<Self> {
17        Self::new_with_checked(activity, text, parent, false)
18    }
19    
20    /// Create a new Checkbox with specified checked state
21    pub fn new_with_checked(activity: &mut Activity, text: &str, parent: Option<i64>, checked: bool) -> Result<Self> {
22        let mut params = json!({
23            "aid": activity.id(),
24            "text": text,
25            "checked": checked
26        });
27        
28        // Only set parent if explicitly provided
29        if let Some(parent_id) = parent {
30            params["parent"] = json!(parent_id);
31        }
32        
33        let response = activity.send_read(&json!({
34            "method": "createCheckbox",
35            "params": params
36        }))?;
37        
38        let id = response
39            .as_i64()
40            .ok_or_else(|| crate::error::GuiError::InvalidResponse("Invalid id".to_string()))?;
41        
42        Ok(Checkbox {
43            view: View::new(id),
44            aid: activity.id(),
45        })
46    }
47    
48    /// Get the view ID
49    pub fn id(&self) -> i64 {
50        self.view.id()
51    }
52    
53    /// Get the underlying View
54    pub fn view(&self) -> &View {
55        &self.view
56    }
57    
58    /// Set the checkbox text
59    pub fn set_text(&self, activity: &mut Activity, text: &str) -> Result<()> {
60        activity.send(&json!({
61            "method": "setText",
62            "params": {
63                "aid": self.aid,
64                "id": self.view.id(),
65                "text": text
66            }
67        }))?;
68        Ok(())
69    }
70    
71    /// Set checked state
72    pub fn set_checked(&self, activity: &mut Activity, checked: bool) -> Result<()> {
73        activity.send(&json!({
74            "method": "setChecked",
75            "params": {
76                "aid": self.aid,
77                "id": self.view.id(),
78                "checked": checked
79            }
80        }))?;
81        Ok(())
82    }
83}