termux_gui/components/
toggle_button.rs

1//! ToggleButton component
2
3use serde_json::json;
4use crate::activity::Activity;
5use crate::view::View;
6use crate::error::Result;
7
8/// A ToggleButton is a button that can be toggled on or off
9/// 
10/// Similar to Switch, but with a different visual style (button appearance).
11pub struct ToggleButton {
12    view: View,
13    aid: i64,
14}
15
16impl ToggleButton {
17    /// Create a new ToggleButton (unchecked by default)
18    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    /// Create a new ToggleButton with specified checked state
23    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        // Only set parent if explicitly provided
31        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    /// Get the view ID
51    pub fn id(&self) -> i64 {
52        self.view.id()
53    }
54    
55    /// Get the underlying View
56    pub fn view(&self) -> &View {
57        &self.view
58    }
59    
60    /// Set the toggle button text
61    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    /// Set checked state
74    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}