termux-gui 0.3.0

Rust bindings for Termux:GUI - Build Android GUI apps in Rust on Termux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Layout components

use serde_json::json;
use crate::activity::Activity;
use crate::view::View;
use crate::error::Result;

/// A LinearLayout arranges views linearly
pub struct LinearLayout {
    view: View,
    #[allow(dead_code)]
    aid: i64,
}

impl LinearLayout {
    /// Create a new vertical LinearLayout
    pub fn new(activity: &mut Activity, parent: Option<i64>) -> Result<Self> {
        Self::new_with_orientation(activity, parent, true)
    }
    
    /// Create a new LinearLayout with specified orientation
    /// 
    /// # Arguments
    /// * `vertical` - If true, arranges children vertically; if false, horizontally
    pub fn new_with_orientation(activity: &mut Activity, parent: Option<i64>, vertical: bool) -> Result<Self> {
        let mut params = json!({
            "aid": activity.id(),
            "vertical": vertical
        });
        
        // Only set parent if explicitly provided
        if let Some(parent_id) = parent {
            params["parent"] = json!(parent_id);
        }
        
        let response = activity.send_read(&json!({
            "method": "createLinearLayout",
            "params": params
        }))?;
        
        let id = response
            .as_i64()
            .ok_or_else(|| crate::error::GuiError::InvalidResponse("Invalid id".to_string()))?;
        
        Ok(LinearLayout {
            view: View::new(id),
            aid: activity.id(),
        })
    }
    
    /// Get the view ID
    pub fn id(&self) -> i64 {
        self.view.id()
    }
    
    /// Get the underlying View
    pub fn view(&self) -> &View {
        &self.view
    }
}

/// A NestedScrollView provides scrolling capability
pub struct NestedScrollView {
    view: View,
    #[allow(dead_code)]
    aid: i64,
}

impl NestedScrollView {
    /// Create a new NestedScrollView
    pub fn new(activity: &mut Activity, parent: Option<i64>) -> Result<Self> {
        let mut params = json!({
            "aid": activity.id(),
            "nobar": false,
            "snapping": false
        });
        
        // Only set parent if explicitly provided
        if let Some(parent_id) = parent {
            params["parent"] = json!(parent_id);
        }
        
        let response = activity.send_read(&json!({
            "method": "createNestedScrollView",
            "params": params
        }))?;
        
        let id = response
            .as_i64()
            .ok_or_else(|| crate::error::GuiError::InvalidResponse("Invalid id".to_string()))?;
        
        Ok(NestedScrollView {
            view: View::new(id),
            aid: activity.id(),
        })
    }
    
    /// Get the view ID
    pub fn id(&self) -> i64 {
        self.view.id()
    }
    
    /// Get the underlying View
    pub fn view(&self) -> &View {
        &self.view
    }
}

/// A FrameLayout is a simple layout that stacks children on top of each other
pub struct FrameLayout {
    view: View,
    #[allow(dead_code)]
    aid: i64,
}

impl FrameLayout {
    /// Create a new FrameLayout
    /// 
    /// Children are drawn in the order they are added, with the last child on top.
    /// FrameLayout is useful for overlaying views or creating simple stacked layouts.
    pub fn new(activity: &mut Activity, parent: Option<i64>) -> Result<Self> {
        let mut params = json!({
            "aid": activity.id()
        });
        
        // Only set parent if explicitly provided
        if let Some(parent_id) = parent {
            params["parent"] = json!(parent_id);
        }
        
        let response = activity.send_read(&json!({
            "method": "createFrameLayout",
            "params": params
        }))?;
        
        let id = response
            .as_i64()
            .ok_or_else(|| crate::error::GuiError::InvalidResponse("Invalid id".to_string()))?;
        
        Ok(FrameLayout {
            view: View::new(id),
            aid: activity.id(),
        })
    }
    
    /// Get the view ID
    pub fn id(&self) -> i64 {
        self.view.id()
    }
    
    /// Get the underlying View
    pub fn view(&self) -> &View {
        &self.view
    }
}

/// A GridLayout arranges children in a grid
pub struct GridLayout {
    view: View,
    #[allow(dead_code)]
    aid: i64,
    #[allow(dead_code)]
    rows: i32,
    #[allow(dead_code)]
    cols: i32,
}

impl GridLayout {
    /// Create a new GridLayout with specified rows and columns
    /// 
    /// # Arguments
    /// * `rows` - Number of rows in the grid
    /// * `cols` - Number of columns in the grid
    pub fn new(activity: &mut Activity, rows: i32, cols: i32, parent: Option<i64>) -> Result<Self> {
        let mut params = json!({
            "aid": activity.id(),
            "rows": rows,
            "cols": cols
        });
        
        // Only set parent if explicitly provided
        if let Some(parent_id) = parent {
            params["parent"] = json!(parent_id);
        }
        
        let response = activity.send_read(&json!({
            "method": "createGridLayout",
            "params": params
        }))?;
        
        let id = response
            .as_i64()
            .ok_or_else(|| crate::error::GuiError::InvalidResponse("Invalid id".to_string()))?;
        
        Ok(GridLayout {
            view: View::new(id),
            aid: activity.id(),
            rows,
            cols,
        })
    }
    
    /// Get the view ID
    pub fn id(&self) -> i64 {
        self.view.id()
    }
    
    /// Get the underlying View
    pub fn view(&self) -> &View {
        &self.view
    }
}

/// A HorizontalScrollView provides horizontal scrolling for content
///
/// ## Important Usage Notes for TabLayout
///
/// When using HorizontalScrollView with TabLayout for page switching:
///
/// 1. **Use pixel units**: Page widths must be set using `set_width_px()`, not `set_width()`
/// 2. **Match dimensions**: Use `get_dimensions()` to get screen width, then set each page width to match
/// 3. **Scroll position**: Calculate scroll position as `page_width * tab_index`
///
/// ### Example
///
/// ```rust,no_run
/// # use termux_gui::{Activity, Result};
/// # fn example(activity: &mut Activity, root_id: i64, content_id: i64) -> Result<()> {
/// // Create HorizontalScrollView with snapping and no scrollbar
/// let scroll = activity.create_horizontal_scroll_view_with_params(
///     Some(root_id), true, true, true
/// )?;
///
/// // Get width in pixels
/// let (page_width, _) = scroll.view().get_dimensions(activity)?;
///
/// // Create pages with pixel-based width
/// let page1 = activity.create_linear_layout(Some(content_id))?;
/// page1.view().set_width_px(activity, page_width)?;  // Use px, not dp!
///
/// // Scroll to page 2
/// scroll.set_scroll_position(activity, page_width * 2, 0, true)?;
/// # Ok(())
/// # }
/// ```
pub struct HorizontalScrollView {
    view: View,
    #[allow(dead_code)]
    aid: i64,
}

impl HorizontalScrollView {
    /// Create a new HorizontalScrollView
    pub fn new(activity: &mut Activity, parent: Option<i64>) -> Result<Self> {
        let mut params = json!({
            "aid": activity.id(),
            "nobar": false,
            "snapping": false,
            "fillviewport": true  // Set to true to allow child views to fill the viewport
        });
        
        // Only set parent if explicitly provided
        if let Some(parent_id) = parent {
            params["parent"] = json!(parent_id);
        }
        
        let response = activity.send_read(&json!({
            "method": "createHorizontalScrollView",
            "params": params
        }))?;
        
        let id = response
            .as_i64()
            .ok_or_else(|| crate::error::GuiError::InvalidResponse("Invalid id".to_string()))?;
        
        Ok(HorizontalScrollView {
            view: View::new(id),
            aid: activity.id(),
        })
    }
    
    /// Create a new HorizontalScrollView with custom parameters
    pub fn new_with_params(activity: &mut Activity, parent: Option<i64>, 
                          fillviewport: bool, snapping: bool, nobar: bool) -> Result<Self> {
        let mut params = json!({
            "aid": activity.id(),
            "nobar": nobar,
            "snapping": snapping,
            "fillviewport": fillviewport
        });
        
        if let Some(parent_id) = parent {
            params["parent"] = json!(parent_id);
        }
        
        let response = activity.send_read(&json!({
            "method": "createHorizontalScrollView",
            "params": params
        }))?;
        
        let id = response
            .as_i64()
            .ok_or_else(|| crate::error::GuiError::InvalidResponse("Invalid id".to_string()))?;
        
        Ok(HorizontalScrollView {
            view: View::new(id),
            aid: activity.id(),
        })
    }
    
    /// Get the view ID
    pub fn id(&self) -> i64 {
        self.view.id()
    }
    
    /// Get the underlying View
    pub fn view(&self) -> &View {
        &self.view
    }
    
    /// Get the scroll position (x, y) in pixels
    pub fn get_scroll_position(&self, activity: &mut Activity) -> Result<(i32, i32)> {
        let response = activity.send_read(&json!({
            "method": "getScrollPosition",
            "params": {
                "aid": self.aid,
                "id": self.view.id()
            }
        }))?;
        
        // Response is an array [x, y]
        if let Some(arr) = response.as_array() {
            let x = arr.get(0).and_then(|v| v.as_i64()).unwrap_or(0) as i32;
            let y = arr.get(1).and_then(|v| v.as_i64()).unwrap_or(0) as i32;
            Ok((x, y))
        } else {
            Ok((0, 0))
        }
    }
    
    /// Set the scroll position
    /// 
    /// # Arguments
    /// * `x` - Horizontal scroll position in pixels
    /// * `y` - Vertical scroll position in pixels (usually 0 for HorizontalScrollView)
    /// * `smooth` - Whether to scroll smoothly or jump immediately
    pub fn set_scroll_position(&self, activity: &mut Activity, x: i32, y: i32, smooth: bool) -> Result<()> {
        activity.send(&json!({
            "method": "setScrollPosition",
            "params": {
                "aid": self.aid,
                "id": self.view.id(),
                "x": x,
                "y": y,
                "soft": smooth
            }
        }))?;
        Ok(())
    }
}

/// A SwipeRefreshLayout provides pull-to-refresh functionality
pub struct SwipeRefreshLayout {
    view: View,
    aid: i64,
}

impl SwipeRefreshLayout {
    /// Create a new SwipeRefreshLayout
    pub fn new(activity: &mut Activity, parent: Option<i64>) -> Result<Self> {
        let mut params = json!({
            "aid": activity.id()
        });
        
        // Only set parent if explicitly provided
        if let Some(parent_id) = parent {
            params["parent"] = json!(parent_id);
        }
        
        let response = activity.send_read(&json!({
            "method": "createSwipeRefreshLayout",
            "params": params
        }))?;
        
        let id = response
            .as_i64()
            .ok_or_else(|| crate::error::GuiError::InvalidResponse("Invalid id".to_string()))?;
        
        Ok(SwipeRefreshLayout {
            view: View::new(id),
            aid: activity.id(),
        })
    }
    
    /// Get the view ID
    pub fn id(&self) -> i64 {
        self.view.id()
    }
    
    /// Get the underlying View
    pub fn view(&self) -> &View {
        &self.view
    }
    
    /// Set whether the refresh animation is showing
    /// 
    /// Call with false after refresh is complete to stop the animation
    pub fn set_refreshing(&self, activity: &mut Activity, refreshing: bool) -> Result<()> {
        activity.send(&json!({
            "method": "setRefreshing",
            "params": {
                "aid": self.aid,
                "id": self.view.id(),
                "refresh": refreshing
            }
        }))?;
        Ok(())
    }
}

/// A TabLayout displays a horizontal row of tabs
/// 
/// TabLayout is useful for creating tabbed interfaces. It emits 'itemselected' 
/// events when a tab is clicked, with the tab index as the value.
pub struct TabLayout {
    view: View,
    aid: i64,
}

impl TabLayout {
    /// Create a new TabLayout
    pub fn new(activity: &mut Activity, parent: Option<i64>) -> Result<Self> {
        let mut params = json!({
            "aid": activity.id()
        });
        
        // Only set parent if explicitly provided
        if let Some(parent_id) = parent {
            params["parent"] = json!(parent_id);
        }
        
        let response = activity.send_read(&json!({
            "method": "createTabLayout",
            "params": params
        }))?;
        
        let id = response
            .as_i64()
            .ok_or_else(|| crate::error::GuiError::InvalidResponse("Invalid id".to_string()))?;
        
        Ok(TabLayout {
            view: View::new(id),
            aid: activity.id(),
        })
    }
    
    /// Get the view ID
    pub fn id(&self) -> i64 {
        self.view.id()
    }
    
    /// Get the underlying View
    pub fn view(&self) -> &View {
        &self.view
    }
    
    /// Set the list of tab labels
    /// 
    /// # Arguments
    /// * `tabs` - A slice of strings representing the tab labels
    /// 
    /// # Example
    /// ```no_run
    /// tab_layout.set_list(activity, &["Page 1", "Page 2", "Page 3"])?;
    /// ```
    pub fn set_list(&self, activity: &mut Activity, tabs: &[&str]) -> Result<()> {
        activity.send(&json!({
            "method": "setList",
            "params": {
                "aid": self.aid,
                "id": self.view.id(),
                "list": tabs
            }
        }))?;
        Ok(())
    }
    
    /// Programmatically select a tab
    /// 
    /// # Arguments
    /// * `index` - The zero-based index of the tab to select
    /// 
    /// # Example
    /// ```no_run
    /// // Select the second tab (index 1)
    /// tab_layout.select_tab(activity, 1)?;
    /// ```
    pub fn select_tab(&self, activity: &mut Activity, index: usize) -> Result<()> {
        activity.send(&json!({
            "method": "selectTab",
            "params": {
                "aid": self.aid,
                "id": self.view.id(),
                "tab": index
            }
        }))?;
        Ok(())
    }
}