summaryrefslogtreecommitdiff
path: root/src/widgets/prompt.rs
blob: 31c863030d5a4a3062ee52c1a9239a162b45d689 (plain)
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
//! A box for getting a line of text input.
//!
//! To create a prompt widget, make a `PromptBuilder`, optionally modify
//! properties, and then use its `create` method to create a `Prompt` object.

use std::ptr;

use crate::bindings;
use crate::core::Screen;
use crate::util;

pub struct Prompt {
    ptr: *mut bindings::Promptwidget,
}

pub struct PromptBuilder<'a, 'b> {
    _screen: &'a Screen<'b>,
    lefttop: (u32, u32),
    width: u32,
    title: Option<&'a str>,
}

impl<'a, 'b> PromptBuilder<'a, 'b> {
    pub fn new(screen: &'a Screen<'b>, lefttop: (u32, u32), width: u32) -> Self {
        PromptBuilder {
            _screen: screen,
            lefttop, width,
            title: None,
        }
    }

    pub fn add_title<'s: 'a>(&mut self, title: &'s str)
                -> &mut Self {
        self.title = Some(title);
        self
    }

    pub fn create(&self) -> Prompt {
        Prompt {
            ptr: unsafe {
                bindings::prw_make(
                    self.lefttop.0 as i32, self.lefttop.1 as i32,
                    self.width as i32,
                    match self.title {
                        None => ptr::null(),
                        Some(s) => s.as_ptr() as *const i8,
                    })
            }
        }
    }
}

impl Prompt {
    /// Called automatically; should only be needed if something else overwrote
    /// the widget.
    pub fn redraw(&self) {
        unsafe { bindings::prw_redraw(self.ptr); }
    }

    /// Input string if <enter>, None otherwise.
    ///
    /// The key should be a return value from `Keyboard::get_key()`.
    pub fn handle_key(&mut self, key: i32) -> Option<String> {
        let ptr = unsafe { bindings::prw_handlekey(self.ptr, key) };
        if ptr.is_null() {
            None
        } else {
            unsafe { Some(util::string_from_utf8_charp(ptr)) }
        }
    }

    pub fn change_title(&mut self, title: &str) {
        unsafe { bindings::prw_changetitle(self.ptr, title.as_ptr() as *const i8); }
    }
}

impl Drop for Prompt {
    fn drop(&mut self) {
        unsafe { bindings::prw_destroy(self.ptr); }
    }
}