Struct MenuItem

Source
pub struct MenuItem { /* private fields */ }
Expand description

Creates a menu item

Implementations§

Source§

impl MenuItem

Source

pub unsafe fn from_ptr(ptr: *mut Fl_Menu_Item) -> MenuItem

Initializes a MenuItem from a pointer

§Safety

The pointer must be valid

Source

pub unsafe fn as_ptr(&self) -> *mut Fl_Menu_Item

Returns the inner pointer from a MenuItem

§Safety

Can return multiple mutable pointers to the same item

Source

pub fn new(choices: &[&'static str]) -> MenuItem

Initializes a new menu item. This will allocate a static MenuItem, that is expected to live for the entirety of the program.

Examples found in repository?
examples/popup_browser.rs (line 26)
5fn main() {
6    let app = app::App::default().with_scheme(app::Scheme::Gtk);
7    app::background(211, 211, 211);
8
9    let mut win = window::Window::default().with_size(900, 300);
10    let mut b = browser::HoldBrowser::default()
11        .with_size(900 - 10, 300 - 10)
12        .center_of(&win);
13    let widths = &[50, 50, 50, 70, 70, 40, 40, 70, 70, 50];
14
15    b.set_column_widths(widths);
16    b.set_column_char('\t');
17    b.add("USER\tPID\t%CPU\t%MEM\tVSZ\tRSS\tTTY\tSTAT\tSTART\tTIME\tCOMMAND");
18    b.add("root\t2888\t0.0\t0.0\t1352\t0\ttty3\tSW\tAug15\t0:00\t@b@f/sbin/mingetty tty3");
19    b.add("erco\t2889\t0.0\t13.0\t221352\t0\ttty3\tR\tAug15\t1:34\t@b@f/usr/local/bin/render a35 0004");
20    b.add("uucp\t2892\t0.0\t0.0\t1352\t0\tttyS0\tSW\tAug15\t0:00\t@b@f/sbin/agetty -h 19200 ttyS0 vt100");
21    b.add("root\t13115\t0.0\t0.0\t1352\t0\ttty2\tSW\tAug30\t0:00\t@b@f/sbin/mingetty tty2");
22    b.add(
23        "root\t13464\t0.0\t0.0\t1352\t0\ttty1\tSW\tAug30\t0:00\t@b@f/sbin/mingetty tty1 --noclear",
24    );
25
26    let menu = menu::MenuItem::new(&["1st menu item\t", "2nd menu item\t", "3rd menu item\t"]);
27    b.select(2);
28
29    b.set_callback(move |_| {
30        if app::event_mouse_button() == app::MouseButton::Right {
31            // or app::event_button() == 3
32            let coords = app::event_coords();
33            match menu.popup(coords.0, coords.1) {
34                None => println!("No value was chosen!"),
35                Some(val) => println!("{}", val.label().unwrap()),
36            }
37        }
38    });
39
40    win.make_resizable(true);
41    win.end();
42    win.show();
43    app.run().unwrap();
44}
Source

pub fn popup(&self, x: i32, y: i32) -> Option<MenuItem>

Creates a popup menu at the specified coordinates and returns its choice

Examples found in repository?
examples/popup_browser.rs (line 33)
5fn main() {
6    let app = app::App::default().with_scheme(app::Scheme::Gtk);
7    app::background(211, 211, 211);
8
9    let mut win = window::Window::default().with_size(900, 300);
10    let mut b = browser::HoldBrowser::default()
11        .with_size(900 - 10, 300 - 10)
12        .center_of(&win);
13    let widths = &[50, 50, 50, 70, 70, 40, 40, 70, 70, 50];
14
15    b.set_column_widths(widths);
16    b.set_column_char('\t');
17    b.add("USER\tPID\t%CPU\t%MEM\tVSZ\tRSS\tTTY\tSTAT\tSTART\tTIME\tCOMMAND");
18    b.add("root\t2888\t0.0\t0.0\t1352\t0\ttty3\tSW\tAug15\t0:00\t@b@f/sbin/mingetty tty3");
19    b.add("erco\t2889\t0.0\t13.0\t221352\t0\ttty3\tR\tAug15\t1:34\t@b@f/usr/local/bin/render a35 0004");
20    b.add("uucp\t2892\t0.0\t0.0\t1352\t0\tttyS0\tSW\tAug15\t0:00\t@b@f/sbin/agetty -h 19200 ttyS0 vt100");
21    b.add("root\t13115\t0.0\t0.0\t1352\t0\ttty2\tSW\tAug30\t0:00\t@b@f/sbin/mingetty tty2");
22    b.add(
23        "root\t13464\t0.0\t0.0\t1352\t0\ttty1\tSW\tAug30\t0:00\t@b@f/sbin/mingetty tty1 --noclear",
24    );
25
26    let menu = menu::MenuItem::new(&["1st menu item\t", "2nd menu item\t", "3rd menu item\t"]);
27    b.select(2);
28
29    b.set_callback(move |_| {
30        if app::event_mouse_button() == app::MouseButton::Right {
31            // or app::event_button() == 3
32            let coords = app::event_coords();
33            match menu.popup(coords.0, coords.1) {
34                None => println!("No value was chosen!"),
35                Some(val) => println!("{}", val.label().unwrap()),
36            }
37        }
38    });
39
40    win.make_resizable(true);
41    win.end();
42    win.show();
43    app.run().unwrap();
44}
Source

pub fn pulldown( &self, x: i32, y: i32, w: i32, h: i32, picked: Option<MenuItem>, menu: Option<&impl MenuExt>, ) -> Option<MenuItem>

Creates a pulldown menu at the specified coordinates and returns its choice

Source

pub fn label(&self) -> Option<String>

Returns the label of the menu item

Examples found in repository?
examples/popup_browser.rs (line 35)
5fn main() {
6    let app = app::App::default().with_scheme(app::Scheme::Gtk);
7    app::background(211, 211, 211);
8
9    let mut win = window::Window::default().with_size(900, 300);
10    let mut b = browser::HoldBrowser::default()
11        .with_size(900 - 10, 300 - 10)
12        .center_of(&win);
13    let widths = &[50, 50, 50, 70, 70, 40, 40, 70, 70, 50];
14
15    b.set_column_widths(widths);
16    b.set_column_char('\t');
17    b.add("USER\tPID\t%CPU\t%MEM\tVSZ\tRSS\tTTY\tSTAT\tSTART\tTIME\tCOMMAND");
18    b.add("root\t2888\t0.0\t0.0\t1352\t0\ttty3\tSW\tAug15\t0:00\t@b@f/sbin/mingetty tty3");
19    b.add("erco\t2889\t0.0\t13.0\t221352\t0\ttty3\tR\tAug15\t1:34\t@b@f/usr/local/bin/render a35 0004");
20    b.add("uucp\t2892\t0.0\t0.0\t1352\t0\tttyS0\tSW\tAug15\t0:00\t@b@f/sbin/agetty -h 19200 ttyS0 vt100");
21    b.add("root\t13115\t0.0\t0.0\t1352\t0\ttty2\tSW\tAug30\t0:00\t@b@f/sbin/mingetty tty2");
22    b.add(
23        "root\t13464\t0.0\t0.0\t1352\t0\ttty1\tSW\tAug30\t0:00\t@b@f/sbin/mingetty tty1 --noclear",
24    );
25
26    let menu = menu::MenuItem::new(&["1st menu item\t", "2nd menu item\t", "3rd menu item\t"]);
27    b.select(2);
28
29    b.set_callback(move |_| {
30        if app::event_mouse_button() == app::MouseButton::Right {
31            // or app::event_button() == 3
32            let coords = app::event_coords();
33            match menu.popup(coords.0, coords.1) {
34                None => println!("No value was chosen!"),
35                Some(val) => println!("{}", val.label().unwrap()),
36            }
37        }
38    });
39
40    win.make_resizable(true);
41    win.end();
42    win.show();
43    app.run().unwrap();
44}
More examples
Hide additional examples
examples/format_text.rs (line 171)
122fn main() {
123    let style = Rc::from(RefCell::from(Style::new()));
124
125    let app = App::default().with_scheme(Scheme::Gleam);
126    let mut wind = Window::default()
127        .with_size(500, 200)
128        .with_label("Highlight");
129    let mut vpack = Pack::new(4, 4, 492, 192, "");
130    vpack.set_spacing(4);
131    let mut text_editor = TextEditor::default().with_size(492, 163);
132
133    let mut hpack = Pack::new(4, 4, 492, 25, "").with_type(PackType::Horizontal);
134    hpack.set_spacing(8);
135    let mut font = Choice::default().with_size(130, 25);
136    let mut choice = Choice::default().with_size(130, 25);
137    let mut size = Spinner::default().with_size(60, 25);
138
139    let mut color = Choice::default().with_size(100, 25);
140    let mut btn_clear = Button::default().with_size(40, 25).with_label("X");
141    hpack.end();
142
143    vpack.end();
144    wind.end();
145    wind.show();
146
147    text_editor.wrap_mode(fltk::text::WrapMode::AtBounds, 0);
148    text_editor.set_buffer(TextBuffer::default());
149
150    font.add_choice("Courier|Helvetica|Times");
151    font.set_value(0);
152    font.set_tooltip("Font");
153
154    choice.add_choice("Normal|Underline|Strike");
155    choice.set_value(0);
156
157    size.set_value(18.0);
158    size.set_step(1.0);
159    size.set_range(12.0, 28.0);
160    size.set_tooltip("Size");
161
162    color.set_tooltip("Color");
163    color.add_choice("#000000|#ff0000|#00ff00|#0000ff|#ffff00|#00ffff");
164    color.set_value(0);
165
166    btn_clear.set_label_color(Color::Red);
167    btn_clear.set_tooltip("Clear style");
168
169    // set colors
170    for mut item in color.clone() {
171        if let Some(lbl) = item.label() {
172            item.set_label_color(Color::from_u32(
173                u32::from_str_radix(lbl.trim().strip_prefix('#').unwrap(), 16)
174                    .ok()
175                    .unwrap(),
176            ));
177        }
178    }
179
180    let style_rc1 = Rc::clone(&style);
181
182    text_editor.buffer().unwrap().add_modify_callback({
183        let mut text_editor1 = text_editor.clone();
184        let font1 = font.clone();
185        let size1 = size.clone();
186        let color1 = color.clone();
187        let choice1 = choice.clone();
188        move |_buf, pos: i32, ins_items: i32, del_items: i32, _: i32, _: Option<&str>| {
189            let attr = if choice1.value() == 1 {
190                TextAttr::Underline
191            } else if choice1.value() == 2 {
192                TextAttr::StrikeThrough
193            } else {
194                TextAttr::None
195            };
196            if ins_items > 0 || del_items > 0 {
197                let mut style = style_rc1.borrow_mut();
198                let color = Color::from_u32(
199                    u32::from_str_radix(
200                        color1
201                            .text(color1.value())
202                            .unwrap()
203                            .trim()
204                            .strip_prefix('#')
205                            .unwrap(),
206                        16,
207                    )
208                    .ok()
209                    .unwrap(),
210                );
211                style.apply_style(
212                    Some(pos),
213                    Some(ins_items),
214                    Some(del_items),
215                    None,
216                    None,
217                    Font::by_name(font1.text(font1.value()).unwrap().trim()),
218                    size1.value() as i32,
219                    color,
220                    attr,
221                    &mut text_editor1,
222                );
223            }
224        }
225    });
226
227    color.set_callback({
228        let size = size.clone();
229        let font = font.clone();
230        let choice = choice.clone();
231        let mut text_editor = text_editor.clone();
232        let style_rc1 = Rc::clone(&style);
233        move |color| {
234            let attr = match choice.value() {
235                0 => TextAttr::None,
236                1 => TextAttr::Underline,
237                2 => TextAttr::StrikeThrough,
238                _ => unreachable!(),
239            };
240            if let Some(buf) = text_editor.buffer() {
241                if let Some((s, e)) = buf.selection_position() {
242                    let mut style = style_rc1.borrow_mut();
243                    let color = Color::from_u32(
244                        u32::from_str_radix(
245                            color
246                                .text(color.value())
247                                .unwrap()
248                                .trim()
249                                .strip_prefix('#')
250                                .unwrap(),
251                            16,
252                        )
253                        .ok()
254                        .unwrap(),
255                    );
256                    style.apply_style(
257                        None,
258                        None,
259                        None,
260                        Some(s),
261                        Some(e),
262                        Font::by_name(font.text(font.value()).unwrap().trim()),
263                        size.value() as i32,
264                        color,
265                        attr,
266                        &mut text_editor,
267                    );
268                }
269            }
270        }
271    });
272
273    // get the style from the current cursor position
274    text_editor.handle({
275        let style_rc1 = Rc::clone(&style);
276        let mut font1 = font.clone();
277        let mut size1 = size.clone();
278        let mut color1 = color.clone();
279        move |te, e| match e {
280            Event::KeyUp | Event::Released => {
281                if let Some(buff) = te.style_buffer() {
282                    let i = te.insert_position();
283                    if let Some(t) = buff.text_range(i, i + 1) {
284                        if !t.is_empty() {
285                            let style = style_rc1.borrow_mut();
286                            if let Some(i) = t.chars().next().map(|c| (c as usize - 65)) {
287                                if let Some(style) = style.style_table.get(i) {
288                                    if let Some(mn) = font1.find_item(&format!("{:?}", style.font))
289                                    {
290                                        font1.set_item(&mn);
291                                    }
292                                    size1.set_value(style.size as f64);
293                                    let (r, g, b) = style.color.to_rgb();
294                                    if let Some(mn) =
295                                        color1.find_item(format!("{r:02x}{g:02x}{b:02x}").as_str())
296                                    {
297                                        color1.set_item(&mn);
298                                    }
299                                }
300                            }
301                        }
302                    }
303                }
304                true
305            }
306            _ => false,
307        }
308    });
309
310    choice.set_callback({
311        let mut color1 = color.clone();
312        move |_| color1.do_callback()
313    });
314
315    font.set_callback({
316        let mut color1 = color.clone();
317        move |_| color1.do_callback()
318    });
319
320    size.set_callback({
321        let mut color1 = color.clone();
322        move |_| color1.do_callback()
323    });
324
325    // clear style of the current selection or, if no text is selected, clear all text style
326    btn_clear.set_callback({
327        let style_rc1 = Rc::clone(&style);
328        let text_editor1 = text_editor.clone();
329        move |_| {
330            match text_editor1.buffer().unwrap().selection_position() {
331                Some((_, _)) => {
332                    font.set_value(0);
333                    size.set_value(18.0);
334                    color.set_value(0);
335                    choice.set_value(0);
336                    color.do_callback();
337                }
338                None => {
339                    font.set_value(0);
340                    size.set_value(18.0);
341                    color.set_value(0);
342                    style_rc1.borrow_mut().apply_style(
343                        None,
344                        None,
345                        None,
346                        Some(0),
347                        Some(text_editor1.buffer().unwrap().length()),
348                        Font::Courier,
349                        16,
350                        Color::Black,
351                        TextAttr::None,
352                        &mut text_editor,
353                    );
354                }
355            };
356        }
357    });
358
359    app.run().unwrap();
360}
Source

pub fn set_label(&mut self, txt: &str)

Sets the label of the menu item

Source

pub fn label_type(&self) -> LabelType

Returns the label type of the menu item

Source

pub fn set_label_type(&mut self, typ: LabelType)

Sets the label type of the menu item

Source

pub fn label_color(&self) -> Color

Returns the label color of the menu item

Source

pub fn set_label_color(&mut self, color: Color)

Sets the label color of the menu item

Examples found in repository?
examples/editor2.rs (line 325)
311    pub fn save_file(&mut self) -> Result<bool, Box<dyn error::Error>> {
312        match &self.filename {
313            Some(f) => {
314                self.buf.save_file(f)?;
315                self.modified = false;
316                self.menu
317                    .menu
318                    .find_item("&File/&Save\t")
319                    .unwrap()
320                    .deactivate();
321                self.menu
322                    .menu
323                    .find_item("&File/&Quit\t")
324                    .unwrap()
325                    .set_label_color(Color::Black);
326                let name = match &self.filename {
327                    Some(f) => f.to_string_lossy().to_string(),
328                    None => "(Untitled)".to_string(),
329                };
330                self.main_win.set_label(&format!("{name} - RustyEd"));
331                Ok(true)
332            }
333            None => self.save_file_as(),
334        }
335    }
336
337    /** Called by "Save As..." or by "Save" in case no file was set yet.
338     * Returns true if the file was succesfully saved. */
339    pub fn save_file_as(&mut self) -> Result<bool, Box<dyn error::Error>> {
340        if let Some(c) = nfc_get_file(dialog::NativeFileChooserType::BrowseSaveFile) {
341            self.buf.save_file(&c)?;
342            self.modified = false;
343            self.menu
344                .menu
345                .find_item("&File/&Save\t")
346                .unwrap()
347                .deactivate();
348            self.menu
349                .menu
350                .find_item("&File/&Quit\t")
351                .unwrap()
352                .set_label_color(Color::Black);
353            self.filename = Some(c);
354            self.main_win
355                .set_label(&format!("{:?} - RustyEd", self.filename.as_ref().unwrap()));
356            Ok(true)
357        } else {
358            Ok(false)
359        }
360    }
361
362    pub fn launch(&mut self) {
363        while self.app.wait() {
364            use Message::*;
365            if let Some(msg) = self.r.recv() {
366                match msg {
367                    Changed => {
368                        if !self.modified {
369                            self.modified = true;
370                            self.menu
371                                .menu
372                                .find_item("&File/&Save\t")
373                                .unwrap()
374                                .activate();
375                            self.menu
376                                .menu
377                                .find_item("&File/&Quit\t")
378                                .unwrap()
379                                .set_label_color(Color::Red);
380                            let name = match &self.filename {
381                                Some(f) => f.to_string_lossy().to_string(),
382                                None => "(Untitled)".to_string(),
383                            };
384                            self.main_win.set_label(&format!("* {name} - RustyEd"));
385                        }
386                    }
387                    New => {
388                        if self.buf.text() != "" {
389                            let clear = if let Some(x) = dialog::choice(
390                                "File unsaved, Do you wish to continue?",
391                                "&Yes",
392                                "&No!",
393                                "",
394                            ) {
395                                x == 0
396                            } else {
397                                false
398                            };
399                            if clear {
400                                self.buf.set_text("");
401                            }
402                        }
403                    }
404                    Open => {
405                        if let Some(c) = nfc_get_file(dialog::NativeFileChooserType::BrowseFile) {
406                            if c.exists() {
407                                match self.buf.load_file(&c) {
408                                    Ok(_) => self.filename = Some(c),
409                                    Err(e) => dialog::alert(&format!(
410                                        "An issue occured while loading the file: {e}"
411                                    )),
412                                }
413                            } else {
414                                dialog::alert("File does not exist!")
415                            }
416                        }
417                    }
418                    Save => {
419                        self.save_file().unwrap();
420                    }
421                    SaveAs => {
422                        self.save_file_as().unwrap();
423                    }
424                    Print => {
425                        let mut printer = printer::Printer::default();
426                        if printer.begin_job(0).is_ok() {
427                            let (w, h) = printer.printable_rect();
428                            self.printable.resize(
429                                self.printable.x(),
430                                self.printable.y(),
431                                w - 40,
432                                h - 40,
433                            );
434                            // Needs cleanup
435                            let line_count = self.printable.count_lines(
436                                0,
437                                self.printable.buffer().unwrap().length(),
438                                true,
439                            ) / 45;
440                            for i in 0..=line_count {
441                                self.printable.scroll(45 * i, 0);
442                                printer.begin_page().ok();
443                                printer.print_widget(&self.printable, 20, 20);
444                                printer.end_page().ok();
445                            }
446                            printer.end_job();
447                        }
448                    }
449                    Quit => {
450                        if self.modified {
451                            match dialog::choice(
452                                "Would you like to save your work?",
453                                "&Yes",
454                                "&No",
455                                "",
456                            ) {
457                                Some(0) => {
458                                    if self.save_file().unwrap() {
459                                        self.app.quit();
460                                    }
461                                }
462                                Some(1) => self.app.quit(),
463                                Some(_) | None => (),
464                            }
465                        } else {
466                            self.app.quit();
467                        }
468                    }
469                    Cut => self.editor.cut(),
470                    Copy => self.editor.copy(),
471                    Paste => self.editor.paste(),
472                    About => dialog::message(
473                        "This is an example application written in Rust and using the FLTK Gui library.",
474                    ),
475                }
476            }
477        }
478    }
More examples
Hide additional examples
examples/editor.rs (line 56)
25fn init_menu(m: &mut menu::SysMenuBar) {
26    m.add(
27        "&File/&New...\t",
28        Shortcut::Ctrl | 'n',
29        menu::MenuFlag::Normal,
30        menu_cb,
31    );
32    m.add(
33        "&File/&Open...\t",
34        Shortcut::Ctrl | 'o',
35        menu::MenuFlag::Normal,
36        menu_cb,
37    );
38    m.add(
39        "&File/&Save\t",
40        Shortcut::Ctrl | 's',
41        menu::MenuFlag::Normal,
42        menu_cb,
43    );
44    m.add(
45        "&File/Save &as...\t",
46        Shortcut::Ctrl | 'w',
47        menu::MenuFlag::MenuDivider,
48        menu_cb,
49    );
50    let idx = m.add(
51        "&File/&Quit\t",
52        Shortcut::Ctrl | 'q',
53        menu::MenuFlag::Normal,
54        menu_cb,
55    );
56    m.at(idx).unwrap().set_label_color(Color::Red);
57    m.add(
58        "&Edit/Cu&t\t",
59        Shortcut::Ctrl | 'x',
60        menu::MenuFlag::Normal,
61        menu_cb,
62    );
63    m.add(
64        "&Edit/&Copy\t",
65        Shortcut::Ctrl | 'c',
66        menu::MenuFlag::Normal,
67        menu_cb,
68    );
69    m.add(
70        "&Edit/&Paste\t",
71        Shortcut::Ctrl | 'v',
72        menu::MenuFlag::Normal,
73        menu_cb,
74    );
75    m.add(
76        "&Help/&About\t",
77        Shortcut::None,
78        menu::MenuFlag::Normal,
79        menu_cb,
80    );
81}
examples/format_text.rs (lines 172-176)
122fn main() {
123    let style = Rc::from(RefCell::from(Style::new()));
124
125    let app = App::default().with_scheme(Scheme::Gleam);
126    let mut wind = Window::default()
127        .with_size(500, 200)
128        .with_label("Highlight");
129    let mut vpack = Pack::new(4, 4, 492, 192, "");
130    vpack.set_spacing(4);
131    let mut text_editor = TextEditor::default().with_size(492, 163);
132
133    let mut hpack = Pack::new(4, 4, 492, 25, "").with_type(PackType::Horizontal);
134    hpack.set_spacing(8);
135    let mut font = Choice::default().with_size(130, 25);
136    let mut choice = Choice::default().with_size(130, 25);
137    let mut size = Spinner::default().with_size(60, 25);
138
139    let mut color = Choice::default().with_size(100, 25);
140    let mut btn_clear = Button::default().with_size(40, 25).with_label("X");
141    hpack.end();
142
143    vpack.end();
144    wind.end();
145    wind.show();
146
147    text_editor.wrap_mode(fltk::text::WrapMode::AtBounds, 0);
148    text_editor.set_buffer(TextBuffer::default());
149
150    font.add_choice("Courier|Helvetica|Times");
151    font.set_value(0);
152    font.set_tooltip("Font");
153
154    choice.add_choice("Normal|Underline|Strike");
155    choice.set_value(0);
156
157    size.set_value(18.0);
158    size.set_step(1.0);
159    size.set_range(12.0, 28.0);
160    size.set_tooltip("Size");
161
162    color.set_tooltip("Color");
163    color.add_choice("#000000|#ff0000|#00ff00|#0000ff|#ffff00|#00ffff");
164    color.set_value(0);
165
166    btn_clear.set_label_color(Color::Red);
167    btn_clear.set_tooltip("Clear style");
168
169    // set colors
170    for mut item in color.clone() {
171        if let Some(lbl) = item.label() {
172            item.set_label_color(Color::from_u32(
173                u32::from_str_radix(lbl.trim().strip_prefix('#').unwrap(), 16)
174                    .ok()
175                    .unwrap(),
176            ));
177        }
178    }
179
180    let style_rc1 = Rc::clone(&style);
181
182    text_editor.buffer().unwrap().add_modify_callback({
183        let mut text_editor1 = text_editor.clone();
184        let font1 = font.clone();
185        let size1 = size.clone();
186        let color1 = color.clone();
187        let choice1 = choice.clone();
188        move |_buf, pos: i32, ins_items: i32, del_items: i32, _: i32, _: Option<&str>| {
189            let attr = if choice1.value() == 1 {
190                TextAttr::Underline
191            } else if choice1.value() == 2 {
192                TextAttr::StrikeThrough
193            } else {
194                TextAttr::None
195            };
196            if ins_items > 0 || del_items > 0 {
197                let mut style = style_rc1.borrow_mut();
198                let color = Color::from_u32(
199                    u32::from_str_radix(
200                        color1
201                            .text(color1.value())
202                            .unwrap()
203                            .trim()
204                            .strip_prefix('#')
205                            .unwrap(),
206                        16,
207                    )
208                    .ok()
209                    .unwrap(),
210                );
211                style.apply_style(
212                    Some(pos),
213                    Some(ins_items),
214                    Some(del_items),
215                    None,
216                    None,
217                    Font::by_name(font1.text(font1.value()).unwrap().trim()),
218                    size1.value() as i32,
219                    color,
220                    attr,
221                    &mut text_editor1,
222                );
223            }
224        }
225    });
226
227    color.set_callback({
228        let size = size.clone();
229        let font = font.clone();
230        let choice = choice.clone();
231        let mut text_editor = text_editor.clone();
232        let style_rc1 = Rc::clone(&style);
233        move |color| {
234            let attr = match choice.value() {
235                0 => TextAttr::None,
236                1 => TextAttr::Underline,
237                2 => TextAttr::StrikeThrough,
238                _ => unreachable!(),
239            };
240            if let Some(buf) = text_editor.buffer() {
241                if let Some((s, e)) = buf.selection_position() {
242                    let mut style = style_rc1.borrow_mut();
243                    let color = Color::from_u32(
244                        u32::from_str_radix(
245                            color
246                                .text(color.value())
247                                .unwrap()
248                                .trim()
249                                .strip_prefix('#')
250                                .unwrap(),
251                            16,
252                        )
253                        .ok()
254                        .unwrap(),
255                    );
256                    style.apply_style(
257                        None,
258                        None,
259                        None,
260                        Some(s),
261                        Some(e),
262                        Font::by_name(font.text(font.value()).unwrap().trim()),
263                        size.value() as i32,
264                        color,
265                        attr,
266                        &mut text_editor,
267                    );
268                }
269            }
270        }
271    });
272
273    // get the style from the current cursor position
274    text_editor.handle({
275        let style_rc1 = Rc::clone(&style);
276        let mut font1 = font.clone();
277        let mut size1 = size.clone();
278        let mut color1 = color.clone();
279        move |te, e| match e {
280            Event::KeyUp | Event::Released => {
281                if let Some(buff) = te.style_buffer() {
282                    let i = te.insert_position();
283                    if let Some(t) = buff.text_range(i, i + 1) {
284                        if !t.is_empty() {
285                            let style = style_rc1.borrow_mut();
286                            if let Some(i) = t.chars().next().map(|c| (c as usize - 65)) {
287                                if let Some(style) = style.style_table.get(i) {
288                                    if let Some(mn) = font1.find_item(&format!("{:?}", style.font))
289                                    {
290                                        font1.set_item(&mn);
291                                    }
292                                    size1.set_value(style.size as f64);
293                                    let (r, g, b) = style.color.to_rgb();
294                                    if let Some(mn) =
295                                        color1.find_item(format!("{r:02x}{g:02x}{b:02x}").as_str())
296                                    {
297                                        color1.set_item(&mn);
298                                    }
299                                }
300                            }
301                        }
302                    }
303                }
304                true
305            }
306            _ => false,
307        }
308    });
309
310    choice.set_callback({
311        let mut color1 = color.clone();
312        move |_| color1.do_callback()
313    });
314
315    font.set_callback({
316        let mut color1 = color.clone();
317        move |_| color1.do_callback()
318    });
319
320    size.set_callback({
321        let mut color1 = color.clone();
322        move |_| color1.do_callback()
323    });
324
325    // clear style of the current selection or, if no text is selected, clear all text style
326    btn_clear.set_callback({
327        let style_rc1 = Rc::clone(&style);
328        let text_editor1 = text_editor.clone();
329        move |_| {
330            match text_editor1.buffer().unwrap().selection_position() {
331                Some((_, _)) => {
332                    font.set_value(0);
333                    size.set_value(18.0);
334                    color.set_value(0);
335                    choice.set_value(0);
336                    color.do_callback();
337                }
338                None => {
339                    font.set_value(0);
340                    size.set_value(18.0);
341                    color.set_value(0);
342                    style_rc1.borrow_mut().apply_style(
343                        None,
344                        None,
345                        None,
346                        Some(0),
347                        Some(text_editor1.buffer().unwrap().length()),
348                        Font::Courier,
349                        16,
350                        Color::Black,
351                        TextAttr::None,
352                        &mut text_editor,
353                    );
354                }
355            };
356        }
357    });
358
359    app.run().unwrap();
360}
Source

pub fn label_font(&self) -> Font

Returns the label font of the menu item

Source

pub fn set_label_font(&mut self, font: Font)

Sets the label font of the menu item

Source

pub fn label_size(&self) -> i32

Returns the label size of the menu item

Source

pub fn set_label_size(&mut self, sz: i32)

Sets the label size of the menu item

Source

pub fn value(&self) -> bool

Returns the value of the menu item

Source

pub fn set(&mut self)

Sets the menu item

Source

pub fn clear(&mut self)

Turns the check or radio item “off” for the menu item

Source

pub fn visible(&self) -> bool

Returns whether the menu item is visible or not

Source

pub fn active(&self) -> bool

Returns whether the menu item is active

Source

pub fn activate(&mut self)

Activates the menu item

Examples found in repository?
examples/editor2.rs (line 374)
362    pub fn launch(&mut self) {
363        while self.app.wait() {
364            use Message::*;
365            if let Some(msg) = self.r.recv() {
366                match msg {
367                    Changed => {
368                        if !self.modified {
369                            self.modified = true;
370                            self.menu
371                                .menu
372                                .find_item("&File/&Save\t")
373                                .unwrap()
374                                .activate();
375                            self.menu
376                                .menu
377                                .find_item("&File/&Quit\t")
378                                .unwrap()
379                                .set_label_color(Color::Red);
380                            let name = match &self.filename {
381                                Some(f) => f.to_string_lossy().to_string(),
382                                None => "(Untitled)".to_string(),
383                            };
384                            self.main_win.set_label(&format!("* {name} - RustyEd"));
385                        }
386                    }
387                    New => {
388                        if self.buf.text() != "" {
389                            let clear = if let Some(x) = dialog::choice(
390                                "File unsaved, Do you wish to continue?",
391                                "&Yes",
392                                "&No!",
393                                "",
394                            ) {
395                                x == 0
396                            } else {
397                                false
398                            };
399                            if clear {
400                                self.buf.set_text("");
401                            }
402                        }
403                    }
404                    Open => {
405                        if let Some(c) = nfc_get_file(dialog::NativeFileChooserType::BrowseFile) {
406                            if c.exists() {
407                                match self.buf.load_file(&c) {
408                                    Ok(_) => self.filename = Some(c),
409                                    Err(e) => dialog::alert(&format!(
410                                        "An issue occured while loading the file: {e}"
411                                    )),
412                                }
413                            } else {
414                                dialog::alert("File does not exist!")
415                            }
416                        }
417                    }
418                    Save => {
419                        self.save_file().unwrap();
420                    }
421                    SaveAs => {
422                        self.save_file_as().unwrap();
423                    }
424                    Print => {
425                        let mut printer = printer::Printer::default();
426                        if printer.begin_job(0).is_ok() {
427                            let (w, h) = printer.printable_rect();
428                            self.printable.resize(
429                                self.printable.x(),
430                                self.printable.y(),
431                                w - 40,
432                                h - 40,
433                            );
434                            // Needs cleanup
435                            let line_count = self.printable.count_lines(
436                                0,
437                                self.printable.buffer().unwrap().length(),
438                                true,
439                            ) / 45;
440                            for i in 0..=line_count {
441                                self.printable.scroll(45 * i, 0);
442                                printer.begin_page().ok();
443                                printer.print_widget(&self.printable, 20, 20);
444                                printer.end_page().ok();
445                            }
446                            printer.end_job();
447                        }
448                    }
449                    Quit => {
450                        if self.modified {
451                            match dialog::choice(
452                                "Would you like to save your work?",
453                                "&Yes",
454                                "&No",
455                                "",
456                            ) {
457                                Some(0) => {
458                                    if self.save_file().unwrap() {
459                                        self.app.quit();
460                                    }
461                                }
462                                Some(1) => self.app.quit(),
463                                Some(_) | None => (),
464                            }
465                        } else {
466                            self.app.quit();
467                        }
468                    }
469                    Cut => self.editor.cut(),
470                    Copy => self.editor.copy(),
471                    Paste => self.editor.paste(),
472                    About => dialog::message(
473                        "This is an example application written in Rust and using the FLTK Gui library.",
474                    ),
475                }
476            }
477        }
478    }
Source

pub fn deactivate(&mut self)

Deactivates the menu item

Examples found in repository?
examples/editor2.rs (line 211)
199    pub fn new(args: Vec<String>) -> Self {
200        let app = app::App::default().with_scheme(app::Scheme::Gtk);
201        app::background(211, 211, 211);
202        let (s, r) = app::channel::<Message>();
203        let mut buf = text::TextBuffer::default();
204        buf.set_tab_distance(4);
205        let mut main_win = window::Window::default()
206            .with_size(800, 600)
207            .with_label("RustyEd");
208        main_win.set_center_screen();
209        let menu = MyMenu::new(&s);
210        let modified = false;
211        menu.menu.find_item("&File/&Save\t").unwrap().deactivate();
212        let mut editor = MyEditor::new(buf.clone());
213        editor.emit(s, Message::Changed);
214        main_win.make_resizable(true);
215        // only resize editor, not the menu bar
216        main_win.resizable(&*editor);
217        main_win.end();
218        main_win.show();
219        main_win.set_callback(move |_| {
220            if app::event() == Event::Close {
221                s.send(Message::Quit);
222            }
223        });
224        let filename = if args.len() > 1 {
225            let file = path::Path::new(&args[1]);
226            assert!(
227                file.exists() && file.is_file(),
228                "An error occurred while opening the file!"
229            );
230            match buf.load_file(&args[1]) {
231                Ok(_) => Some(PathBuf::from(args[1].clone())),
232                Err(e) => {
233                    dialog::alert(&format!("An issue occured while loading the file: {e}"));
234                    None
235                }
236            }
237        } else {
238            None
239        };
240
241        // Handle drag and drop
242        editor.handle({
243            let mut dnd = false;
244            let mut released = false;
245            let buf = buf.clone();
246            move |_, ev| match ev {
247                Event::DndEnter => {
248                    dnd = true;
249                    true
250                }
251                Event::DndDrag => true,
252                Event::DndRelease => {
253                    released = true;
254                    true
255                }
256                Event::Paste => {
257                    if dnd && released {
258                        let path = app::event_text().unwrap();
259                        let path = path.trim();
260                        let path = path.replace("file://", "");
261                        let path = std::path::PathBuf::from(&path);
262                        if path.exists() {
263                            // we use a timeout to avoid pasting the path into the buffer
264                            app::add_timeout(0.0, {
265                                let mut buf = buf.clone();
266                                move |_| match buf.load_file(&path) {
267                                    Ok(_) => (),
268                                    Err(e) => dialog::alert(&format!(
269                                        "An issue occured while loading the file: {e}"
270                                    )),
271                                }
272                            });
273                        }
274                        dnd = false;
275                        released = false;
276                        true
277                    } else {
278                        false
279                    }
280                }
281                Event::DndLeave => {
282                    dnd = false;
283                    released = false;
284                    true
285                }
286                _ => false,
287            }
288        });
289
290        // What shows when we attempt to print
291        let mut printable = text::TextDisplay::default();
292        printable.set_frame(FrameType::NoBox);
293        printable.set_scrollbar_size(0);
294        printable.set_buffer(Some(buf.clone()));
295
296        Self {
297            app,
298            modified,
299            filename,
300            r,
301            main_win,
302            menu,
303            buf,
304            editor,
305            printable,
306        }
307    }
308
309    /** Called by "Save", test if file can be written, otherwise call save_file_as()
310     * afterwards. Will return true if the file is succesfully saved. */
311    pub fn save_file(&mut self) -> Result<bool, Box<dyn error::Error>> {
312        match &self.filename {
313            Some(f) => {
314                self.buf.save_file(f)?;
315                self.modified = false;
316                self.menu
317                    .menu
318                    .find_item("&File/&Save\t")
319                    .unwrap()
320                    .deactivate();
321                self.menu
322                    .menu
323                    .find_item("&File/&Quit\t")
324                    .unwrap()
325                    .set_label_color(Color::Black);
326                let name = match &self.filename {
327                    Some(f) => f.to_string_lossy().to_string(),
328                    None => "(Untitled)".to_string(),
329                };
330                self.main_win.set_label(&format!("{name} - RustyEd"));
331                Ok(true)
332            }
333            None => self.save_file_as(),
334        }
335    }
336
337    /** Called by "Save As..." or by "Save" in case no file was set yet.
338     * Returns true if the file was succesfully saved. */
339    pub fn save_file_as(&mut self) -> Result<bool, Box<dyn error::Error>> {
340        if let Some(c) = nfc_get_file(dialog::NativeFileChooserType::BrowseSaveFile) {
341            self.buf.save_file(&c)?;
342            self.modified = false;
343            self.menu
344                .menu
345                .find_item("&File/&Save\t")
346                .unwrap()
347                .deactivate();
348            self.menu
349                .menu
350                .find_item("&File/&Quit\t")
351                .unwrap()
352                .set_label_color(Color::Black);
353            self.filename = Some(c);
354            self.main_win
355                .set_label(&format!("{:?} - RustyEd", self.filename.as_ref().unwrap()));
356            Ok(true)
357        } else {
358            Ok(false)
359        }
360    }
Source

pub fn is_submenu(&self) -> bool

Returns whether a menu item is a submenu

Source

pub fn is_checkbox(&self) -> bool

Returns whether a menu item is a checkbox

Source

pub fn is_radio(&self) -> bool

Returns whether a menu item is a radio item

Source

pub fn show(&mut self)

Shows the menu item

Source

pub fn hide(&mut self)

Hides the menu item

Source

pub fn next(&self, idx: i32) -> Option<MenuItem>

Get the next menu item skipping submenus

Source

pub fn children(&self) -> i32

Get children of MenuItem

Source

pub fn submenus(&self) -> i32

Get the submenu count

Source

pub fn size(&self) -> i32

Get the size of the MenuItem

Source

pub fn at(&self, idx: i32) -> Option<MenuItem>

Get the menu item at idx

Source

pub unsafe fn user_data(&self) -> Option<Box<dyn FnMut()>>

Get the user data

§Safety

Can return multiple mutable instances of the user data, which has a different lifetime than the object

Source

pub fn set_callback<F: FnMut(&mut Choice) + 'static>(&mut self, cb: F)

Set a callback for the menu item

Examples found in repository?
examples/terminal.rs (lines 50-53)
20fn main() {
21    let app = fltk::app::App::default();
22
23    // Set panic handler for main thread (will become UI thread)
24    std::panic::set_hook(Box::new({
25        |e| {
26            eprintln!("!!!!PANIC!!!!{:#?}", e);
27            error_box(e.to_string()); // Only works from the UI thread
28            std::process::exit(2);
29        }
30    }));
31
32    let mut main_win = Window::new(
33        2285,
34        180,
35        WIN_WIDTH,
36        WIN_HEIGHT,
37        "FLTK/Terminal Rust wrapper test",
38    );
39    main_win.set_type(WindowType::Double);
40    main_win.make_resizable(true);
41
42    let mut menu_bar = MenuBar::new(0, 0, WIN_WIDTH, 30, None);
43
44    let mut term = Terminal::new(0, 30, WIN_WIDTH, WIN_HEIGHT - 30, None);
45    term.set_label("term");
46    main_win.resizable(&term);
47    term.set_label_type(LabelType::None);
48
49    let idx = menu_bar.add_choice("Test&1");
50    menu_bar.at(idx).unwrap().set_callback({
51        let mut term1 = term.clone();
52        move |c| mb_test1_cb(c, &mut term1)
53    });
54    menu_bar
55        .at(idx)
56        .unwrap()
57        .set_shortcut(unsafe { std::mem::transmute(0x80031) }); // Alt-1
58
59    let idx = menu_bar.add_choice("Test&2");
60    menu_bar.at(idx).unwrap().set_callback({
61        let mut term1 = term.clone();
62        move |c| mb_test2_cb(c, &mut term1)
63    });
64    menu_bar
65        .at(idx)
66        .unwrap()
67        .set_shortcut(unsafe { std::mem::transmute(0x80032) }); // Alt-2
68
69    let idx = menu_bar.add_choice("Test&3");
70    menu_bar.at(idx).unwrap().set_callback({
71        let mut term1 = term.clone();
72        move |c| mb_test3_cb(c, &mut term1)
73    });
74    menu_bar
75        .at(idx)
76        .unwrap()
77        .set_shortcut(unsafe { std::mem::transmute(0x80033) }); // Alt-3
78
79    let idx = menu_bar.add_choice("Test&4");
80    menu_bar.at(idx).unwrap().set_callback({
81        let mut term1 = term.clone();
82        move |c| mb_test4_cb(c, &mut term1)
83    });
84    menu_bar
85        .at(idx)
86        .unwrap()
87        .set_shortcut(unsafe { std::mem::transmute(0x80034) }); // Alt-4
88
89    let idx = menu_bar.add_choice("Test&5");
90    menu_bar.at(idx).unwrap().set_callback({
91        let mut term1 = term.clone();
92        move |c| mb_test5_cb(c, &mut term1)
93    });
94    menu_bar
95        .at(idx)
96        .unwrap()
97        .set_shortcut(unsafe { std::mem::transmute(0x80035) }); // Alt-5
98
99    menu_bar.end();
100
101    main_win.end();
102    main_win.show();
103
104    // Worker thread that drives the startup tests
105    let _worker_thread: std::thread::JoinHandle<_> = std::thread::spawn({
106        let mut term = term.clone();
107        move || {
108            println!("Startup tests\n");
109            term.append("Startup tests\n\n");
110            term.append("<tmp>\n"); // This line will be overwritten later
111
112            term.cursor_up(2, false);
113            assert_eq!(term.text(false), "Startup tests\n\n"); // Ignores lines below cursor
114            assert_eq!(
115                term.text(true),
116                "Startup tests\n\n<tmp>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
117            );
118
119            // Testing ansi() and set_ansi() methods
120            assert!(term.ansi(), "Default ANSI mode should be ON at startup");
121            term.append("ANSI mode is \x1b[4mON\x1b[0m\n");
122            term.set_ansi(false);
123            assert!(!term.ansi());
124            term.append("ANSI mode is \x1b[4mOFF\x1b[0m\n");
125            // append() method is already being used/tested. Test the u8, ascii, and utf8 variants
126            term.append_u8(b"Appending u8 array\n");
127            term.append_ascii("Appending ASCII array ↑ (up-arrow is dropped)\n");
128            term.set_ansi(true); // Restore ANSI state
129
130            // Play with the horizontal scrollbar
131            assert_eq!(term.hscrollbar_style(), ScrollbarStyle::AUTO);
132            term.set_hscrollbar_style(ScrollbarStyle::ON);
133            assert_eq!(term.hscrollbar_style(), ScrollbarStyle::ON);
134
135            // Test show_unknown() as incidental part of testing append methods
136            term.set_show_unknown(true);
137            assert!(term.show_unknown());
138            term.append_ascii(
139                "Appending ASCII array with show_unknown() ↑ (up-arrow is three unknown bytes)\n",
140            );
141            term.set_show_unknown(false);
142            assert!(!term.show_unknown());
143
144            term.append_utf8("Appending UTF8 array ↑ (up-arrow is visible)\n");
145            term.append_utf8_u8(b"Appending UTF8 array as u8 \xe2\x86\x91 (up-arrow is visible)\n");
146
147            let r = term.cursor_row();
148            assert_eq!(term.cursor_col(), 0);
149            term.append(&format!("Testing cursor row/col {r}"));
150            assert_eq!(term.cursor_col(), 24);
151            assert_eq!(term.cursor_row(), r);
152
153            // Test cursor color methods
154            assert_eq!(
155                term.cursor_bg_color(),
156                Color::XtermGreen,
157                "Default cursor bg at startup"
158            );
159            term.set_cursor_bg_color(Color::Red);
160            assert_eq!(term.cursor_bg_color(), Color::Red);
161            term.set_cursor_fg_color(Color::Blue);
162            assert_eq!(term.cursor_bg_color(), Color::Red);
163            assert_eq!(term.cursor_fg_color(), Color::Blue);
164            term.set_cursor_bg_color(Color::XtermGreen); // Restore the defaults
165            term.set_cursor_fg_color(Color::from_hex(0xff_ff_f0));
166            assert_eq!(term.cursor_bg_color(), Color::XtermGreen);
167            assert_eq!(term.cursor_fg_color(), Color::from_hex(0xff_ff_f0));
168
169            // The default display_rows() will derive from the window size
170            let dr = term.display_rows();
171            let height = term.h();
172            assert_eq!(height, term.h());
173            assert!(dr > 20, "Default display_rows at startup");
174            term.resize(term.x(), term.y(), term.w(), height * 2);
175            assert_eq!(term.h(), height * 2);
176            assert_eq!(height * 2, term.h());
177            assert!(term.display_rows() > dr);
178            term.resize(term.x(), term.y(), term.w(), height);
179
180            // The default display_columns() will derive from the window size
181            let dc = term.display_columns();
182            assert!(dc > 80, "Default display_rows at startup");
183            term.set_display_columns(200);
184            assert_eq!(term.display_columns(), 200);
185            term.append("\n         1         2         3         4         5         6         7         8         9");
186            term.append("\n123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890");
187            term.append("[This text should be truncated by display_columns() call below.]\n"); // We shouldn't see this on screen
188            term.set_display_columns(90);
189            assert_eq!(term.display_columns(), 90);
190            term.set_display_columns(dc); // Set back to default
191            assert_eq!(term.display_columns(), dc);
192
193            assert_eq!(term.history_rows(), 100, "Default history_rows at startup");
194            term.set_history_rows(50);
195            assert_eq!(term.history_rows(), 50);
196            term.set_history_rows(100); // Set back to default
197            assert_eq!(term.history_rows(), 100);
198
199            let hu = term.history_use();
200            term.append(&format!(
201                "history_use = {hu} (it's not clear what this means)\n"
202            ));
203            // assert_eq!(term.history_use(), hu+1);
204
205            term.append(&format!(
206                "margins = b:{} l:{} r:{} t{}\n",
207                term.margin_bottom(),
208                term.margin_left(),
209                term.margin_right(),
210                term.margin_top()
211            ));
212            assert_eq!(term.margin_bottom(), 3);
213            assert_eq!(term.margin_left(), 3);
214            assert_eq!(term.margin_right(), 3);
215            assert_eq!(term.margin_top(), 3);
216
217            term.set_margin_bottom(5);
218            term.set_margin_left(10);
219            term.set_margin_right(15);
220            term.set_margin_top(20);
221            assert_eq!(term.margin_bottom(), 5);
222            assert_eq!(term.margin_left(), 10);
223            assert_eq!(term.margin_right(), 15);
224            assert_eq!(term.margin_top(), 20);
225
226            term.append("Single character: '");
227            term.print_char('X');
228            term.append("', single UTF-8 character: '");
229            term.print_char_utf8('↑');
230            term.append("'\n");
231
232            let rr = term.redraw_rate();
233            assert_eq!(rr, 0.1, "Default redraw rate at startup");
234            term.append(&format!("Redraw rate {rr}\n"));
235            term.set_redraw_rate(1.0);
236            assert_eq!(term.redraw_rate(), 1.0);
237            term.set_redraw_rate(rr);
238            assert_eq!(term.redraw_rate(), rr);
239
240            let rs = term.redraw_style();
241            term.append(&format!("Redraw style {rs:?}\n"));
242            assert_eq!(
243                rs,
244                RedrawStyle::RateLimited,
245                "Default redraw style at startup"
246            );
247            term.set_redraw_style(RedrawStyle::NoRedraw);
248            assert_eq!(term.redraw_style(), RedrawStyle::NoRedraw);
249            term.set_redraw_style(rs);
250            assert_eq!(term.redraw_style(), rs);
251
252            // Sanity checks: enum values are implicitly assigned in the C++ code so could change unexpectedly
253            assert_eq!(
254                RedrawStyle::NoRedraw.bits(),
255                0x0000,
256                "RedrawStyle enum values have been reassigned"
257            );
258            assert_eq!(
259                RedrawStyle::RateLimited.bits(),
260                0x0001,
261                "RedrawStyle enum values have been reassigned"
262            );
263            assert_eq!(
264                RedrawStyle::PerWrite.bits(),
265                0x0002,
266                "RedrawStyle enum values have been reassigned"
267            );
268
269            let sb = term.scrollbar();
270            let hsb = term.hscrollbar();
271            // Both vertical and horizontal scrollbars are at zero
272            assert_eq!(sb.value(), 0.0);
273            assert_eq!(hsb.value(), 0.0);
274            term.set_hscrollbar_style(ScrollbarStyle::AUTO);
275
276            term.append(&format!(
277                "Scrollbar actual size {}\n",
278                term.scrollbar_actual_size()
279            ));
280            assert_eq!(term.scrollbar_actual_size(), 16);
281            term.append(&format!("Scrollbar size {}\n", term.scrollbar_size()));
282            assert_eq!(
283                term.scrollbar_size(),
284                0,
285                "Default scrollbar size at startup"
286            );
287            term.set_scrollbar_size(40);
288            assert_eq!(term.scrollbar_size(), 40);
289            assert_eq!(term.scrollbar_actual_size(), 40);
290            term.append(&format!(
291                "Scrollbar actual size {}\n",
292                term.scrollbar_actual_size()
293            ));
294            term.set_scrollbar_size(0); // Restore default
295            assert_eq!(term.scrollbar_size(), 0);
296            assert_eq!(term.scrollbar_actual_size(), 16);
297
298            let sfc = term.selection_fg_color();
299            let sbc = term.selection_bg_color();
300            assert_eq!(sfc, Color::Black);
301            assert_eq!(sbc, Color::White);
302            term.append(&format!("Selection colors: {sfc} {sbc}\n"));
303            term.set_selection_fg_color(Color::Green);
304            term.set_selection_bg_color(Color::DarkBlue);
305            assert_eq!(term.selection_fg_color(), Color::Green);
306            assert_eq!(term.selection_bg_color(), Color::DarkBlue);
307            term.set_selection_fg_color(sfc);
308            term.set_selection_bg_color(sbc);
309            assert_eq!(term.selection_fg_color(), Color::Black);
310            assert_eq!(term.selection_bg_color(), Color::White);
311
312            let tfcd = term.text_fg_color_default();
313            let tbcd = term.text_bg_color_default();
314            assert_eq!(tfcd, Color::XtermWhite);
315            assert_eq!(tbcd, Color::TransparentBg);
316            term.append(&format!("Default text colors: {sfc} {sbc}\n"));
317            term.set_text_fg_color_default(Color::Green);
318            term.set_text_bg_color_default(Color::DarkBlue);
319            assert_eq!(term.text_fg_color_default(), Color::Green);
320            assert_eq!(term.text_bg_color_default(), Color::DarkBlue);
321            term.set_text_fg_color_default(tfcd);
322            term.set_text_bg_color_default(tbcd);
323            assert_eq!(term.text_fg_color_default(), Color::XtermWhite);
324            assert_eq!(term.text_bg_color_default(), Color::TransparentBg);
325
326            let tfc = term.text_fg_color();
327            let tbc = term.text_bg_color();
328            assert_eq!(tfc, Color::XtermWhite);
329            assert_eq!(tbc, Color::TransparentBg);
330            term.append(&format!("Text colors: {sfc} {sbc}\n"));
331            term.set_text_fg_color(Color::Green);
332            term.set_text_bg_color(Color::DarkBlue);
333            assert_eq!(term.text_fg_color(), Color::Green);
334            assert_eq!(term.text_bg_color(), Color::DarkBlue);
335            term.set_text_fg_color(tfc);
336            term.set_text_bg_color(tbc);
337            assert_eq!(term.text_fg_color(), Color::XtermWhite);
338            assert_eq!(term.text_bg_color(), Color::TransparentBg);
339
340            let tf = term.text_font();
341            term.append(&format!("Text font: {tf:?}\n"));
342            assert_eq!(tf, Font::Courier);
343            term.set_text_font(Font::Screen);
344            assert_eq!(term.text_font(), Font::Screen);
345            term.set_text_font(tf);
346            assert_eq!(term.text_font(), Font::Courier);
347
348            let ts = term.text_size();
349            let r = term.h_to_row(100);
350            let c = term.w_to_col(100);
351            term.append(&format!(
352                "Text size: {ts}, h_to_row(100): {r}, w_to_col(100): {c}\n"
353            ));
354            assert_eq!(ts, 14);
355            term.set_text_size(30);
356            assert_eq!(term.text_size(), 30);
357            term.append(&format!(
358                "Text size: {}, h_to_row(100): {}, w_to_col(100): {}\n",
359                term.text_size(),
360                term.h_to_row(100),
361                term.w_to_col(100)
362            ));
363            term.set_text_size(ts);
364            assert_eq!(term.text_size(), ts);
365            term.append(&format!(
366                "Text size: {}, h_to_row(100): {}, w_to_col(100): {}\n",
367                term.text_size(),
368                term.h_to_row(100),
369                term.w_to_col(100)
370            ));
371
372            // Keyboard handler
373            term.handle({
374                move |term, e| {
375                    match e {
376                        fltk::enums::Event::KeyDown
377                            if fltk::app::event_key() == fltk::enums::Key::Escape =>
378                        {
379                            // false to let FLTK handle ESC. true to hide ESC
380                            false
381                        }
382
383                        fltk::enums::Event::KeyDown
384                            if fltk::app::event_length() == 1 && fltk::app::is_event_ctrl() =>
385                        {
386                            // We handle control keystroke
387                            let k = fltk::app::event_text().unwrap();
388                            term.append_utf8(&k);
389                            true
390                        }
391
392                        fltk::enums::Event::KeyDown
393                            if fltk::app::event_length() == 1 && !fltk::app::is_event_alt() =>
394                        {
395                            // We handle normal printable keystroke
396                            let k = fltk::app::event_text().unwrap();
397                            term.take_focus().unwrap();
398                            term.append(&k);
399                            true
400                        }
401
402                        // fltk docs say that keyboard handler should always claim Focus and Unfocus events
403                        // We can do this, or else ignore them (return false)
404                        // fltk::enums::Event::Focus | fltk::enums::Event::Unfocus => {
405                        //     term.redraw();
406                        //     true
407                        // }
408                        _ => false, // Let FLTK handle everything else
409                    }
410                }
411            });
412
413            let attr_save = term.text_attrib();
414            term.set_text_attrib(Attrib::Inverse | Attrib::Italic);
415            term.append("\nStartup tests complete. Keyboard is live.\n");
416            assert_eq!(term.text_attrib(), Attrib::Inverse | Attrib::Italic);
417            term.set_text_attrib(attr_save);
418            assert_eq!(term.text_attrib(), attr_save);
419            term.redraw();
420        }
421    });
422
423    app.run().unwrap();
424}
Source

pub fn do_callback<W: MenuExt>(&mut self, w: &W)

Run the menu item’s callback

Source

pub fn emit<T: 'static + Clone + Send + Sync>( &mut self, sender: Sender<T>, msg: T, )

Use a sender to send a message during callback

Source

pub fn was_deleted(&self) -> bool

Check if a menu item was deleted

Source

pub fn draw<M: MenuExt>( &self, x: i32, y: i32, w: i32, h: i32, menu: &M, selected: bool, )

Draw a box around the menu item. Requires the call to be made inside a MenuExt-implementing widget’s own draw method

Source

pub fn measure(&self) -> (i32, i32)

Measure the width and height of a menu item

Source

pub fn add_image<I: ImageExt>(&mut self, image: Option<I>, on_left: bool)

Add an image to a menu item

use fltk::{prelude::*, *};
const PXM: &[&str] = &[
    "13 11 3 1",
    "   c None",
    "x  c #d8d833",
    "@  c #808011",
    "             ",
    "     @@@@    ",
    "    @xxxx@   ",
    "@@@@@xxxx@@  ",
    "@xxxxxxxxx@  ",
    "@xxxxxxxxx@  ",
    "@xxxxxxxxx@  ",
    "@xxxxxxxxx@  ",
    "@xxxxxxxxx@  ",
    "@xxxxxxxxx@  ",
    "@@@@@@@@@@@  "
];
let image = image::Pixmap::new(PXM).unwrap();
let mut menu = menu::MenuBar::default();
menu.add(
    "&File/Open...\t",
    enums::Shortcut::Ctrl | 'o',
    menu::MenuFlag::Normal,
    |_| println!("Opened file!"),
);
if let Some(mut item) = menu.find_item("&File/Open...\t") {
    item.add_image(Some(image), true);
}
Source

pub fn add<F: FnMut(&mut Choice) + 'static>( &mut self, name: &str, shortcut: Shortcut, flag: MenuFlag, cb: F, ) -> i32

Add a menu item

Source

pub fn insert<F: FnMut(&mut Choice) + 'static>( &mut self, idx: i32, name: &str, shortcut: Shortcut, flag: MenuFlag, cb: F, ) -> i32

Insert a menu item

Source

pub fn add_emit<T: 'static + Clone + Send + Sync>( &mut self, label: &str, shortcut: Shortcut, flag: MenuFlag, sender: Sender<T>, msg: T, ) -> i32

Add a menu item along with an emit (sender and message).

Source

pub fn insert_emit<T: 'static + Clone + Send + Sync>( &mut self, idx: i32, label: &str, shortcut: Shortcut, flag: MenuFlag, sender: Sender<T>, msg: T, ) -> i32

Insert a menu item along with an emit (sender and message).

Source

pub fn set_shortcut(&mut self, shortcut: Shortcut)

Set the menu item’s shortcut

Examples found in repository?
examples/terminal.rs (line 57)
20fn main() {
21    let app = fltk::app::App::default();
22
23    // Set panic handler for main thread (will become UI thread)
24    std::panic::set_hook(Box::new({
25        |e| {
26            eprintln!("!!!!PANIC!!!!{:#?}", e);
27            error_box(e.to_string()); // Only works from the UI thread
28            std::process::exit(2);
29        }
30    }));
31
32    let mut main_win = Window::new(
33        2285,
34        180,
35        WIN_WIDTH,
36        WIN_HEIGHT,
37        "FLTK/Terminal Rust wrapper test",
38    );
39    main_win.set_type(WindowType::Double);
40    main_win.make_resizable(true);
41
42    let mut menu_bar = MenuBar::new(0, 0, WIN_WIDTH, 30, None);
43
44    let mut term = Terminal::new(0, 30, WIN_WIDTH, WIN_HEIGHT - 30, None);
45    term.set_label("term");
46    main_win.resizable(&term);
47    term.set_label_type(LabelType::None);
48
49    let idx = menu_bar.add_choice("Test&1");
50    menu_bar.at(idx).unwrap().set_callback({
51        let mut term1 = term.clone();
52        move |c| mb_test1_cb(c, &mut term1)
53    });
54    menu_bar
55        .at(idx)
56        .unwrap()
57        .set_shortcut(unsafe { std::mem::transmute(0x80031) }); // Alt-1
58
59    let idx = menu_bar.add_choice("Test&2");
60    menu_bar.at(idx).unwrap().set_callback({
61        let mut term1 = term.clone();
62        move |c| mb_test2_cb(c, &mut term1)
63    });
64    menu_bar
65        .at(idx)
66        .unwrap()
67        .set_shortcut(unsafe { std::mem::transmute(0x80032) }); // Alt-2
68
69    let idx = menu_bar.add_choice("Test&3");
70    menu_bar.at(idx).unwrap().set_callback({
71        let mut term1 = term.clone();
72        move |c| mb_test3_cb(c, &mut term1)
73    });
74    menu_bar
75        .at(idx)
76        .unwrap()
77        .set_shortcut(unsafe { std::mem::transmute(0x80033) }); // Alt-3
78
79    let idx = menu_bar.add_choice("Test&4");
80    menu_bar.at(idx).unwrap().set_callback({
81        let mut term1 = term.clone();
82        move |c| mb_test4_cb(c, &mut term1)
83    });
84    menu_bar
85        .at(idx)
86        .unwrap()
87        .set_shortcut(unsafe { std::mem::transmute(0x80034) }); // Alt-4
88
89    let idx = menu_bar.add_choice("Test&5");
90    menu_bar.at(idx).unwrap().set_callback({
91        let mut term1 = term.clone();
92        move |c| mb_test5_cb(c, &mut term1)
93    });
94    menu_bar
95        .at(idx)
96        .unwrap()
97        .set_shortcut(unsafe { std::mem::transmute(0x80035) }); // Alt-5
98
99    menu_bar.end();
100
101    main_win.end();
102    main_win.show();
103
104    // Worker thread that drives the startup tests
105    let _worker_thread: std::thread::JoinHandle<_> = std::thread::spawn({
106        let mut term = term.clone();
107        move || {
108            println!("Startup tests\n");
109            term.append("Startup tests\n\n");
110            term.append("<tmp>\n"); // This line will be overwritten later
111
112            term.cursor_up(2, false);
113            assert_eq!(term.text(false), "Startup tests\n\n"); // Ignores lines below cursor
114            assert_eq!(
115                term.text(true),
116                "Startup tests\n\n<tmp>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
117            );
118
119            // Testing ansi() and set_ansi() methods
120            assert!(term.ansi(), "Default ANSI mode should be ON at startup");
121            term.append("ANSI mode is \x1b[4mON\x1b[0m\n");
122            term.set_ansi(false);
123            assert!(!term.ansi());
124            term.append("ANSI mode is \x1b[4mOFF\x1b[0m\n");
125            // append() method is already being used/tested. Test the u8, ascii, and utf8 variants
126            term.append_u8(b"Appending u8 array\n");
127            term.append_ascii("Appending ASCII array ↑ (up-arrow is dropped)\n");
128            term.set_ansi(true); // Restore ANSI state
129
130            // Play with the horizontal scrollbar
131            assert_eq!(term.hscrollbar_style(), ScrollbarStyle::AUTO);
132            term.set_hscrollbar_style(ScrollbarStyle::ON);
133            assert_eq!(term.hscrollbar_style(), ScrollbarStyle::ON);
134
135            // Test show_unknown() as incidental part of testing append methods
136            term.set_show_unknown(true);
137            assert!(term.show_unknown());
138            term.append_ascii(
139                "Appending ASCII array with show_unknown() ↑ (up-arrow is three unknown bytes)\n",
140            );
141            term.set_show_unknown(false);
142            assert!(!term.show_unknown());
143
144            term.append_utf8("Appending UTF8 array ↑ (up-arrow is visible)\n");
145            term.append_utf8_u8(b"Appending UTF8 array as u8 \xe2\x86\x91 (up-arrow is visible)\n");
146
147            let r = term.cursor_row();
148            assert_eq!(term.cursor_col(), 0);
149            term.append(&format!("Testing cursor row/col {r}"));
150            assert_eq!(term.cursor_col(), 24);
151            assert_eq!(term.cursor_row(), r);
152
153            // Test cursor color methods
154            assert_eq!(
155                term.cursor_bg_color(),
156                Color::XtermGreen,
157                "Default cursor bg at startup"
158            );
159            term.set_cursor_bg_color(Color::Red);
160            assert_eq!(term.cursor_bg_color(), Color::Red);
161            term.set_cursor_fg_color(Color::Blue);
162            assert_eq!(term.cursor_bg_color(), Color::Red);
163            assert_eq!(term.cursor_fg_color(), Color::Blue);
164            term.set_cursor_bg_color(Color::XtermGreen); // Restore the defaults
165            term.set_cursor_fg_color(Color::from_hex(0xff_ff_f0));
166            assert_eq!(term.cursor_bg_color(), Color::XtermGreen);
167            assert_eq!(term.cursor_fg_color(), Color::from_hex(0xff_ff_f0));
168
169            // The default display_rows() will derive from the window size
170            let dr = term.display_rows();
171            let height = term.h();
172            assert_eq!(height, term.h());
173            assert!(dr > 20, "Default display_rows at startup");
174            term.resize(term.x(), term.y(), term.w(), height * 2);
175            assert_eq!(term.h(), height * 2);
176            assert_eq!(height * 2, term.h());
177            assert!(term.display_rows() > dr);
178            term.resize(term.x(), term.y(), term.w(), height);
179
180            // The default display_columns() will derive from the window size
181            let dc = term.display_columns();
182            assert!(dc > 80, "Default display_rows at startup");
183            term.set_display_columns(200);
184            assert_eq!(term.display_columns(), 200);
185            term.append("\n         1         2         3         4         5         6         7         8         9");
186            term.append("\n123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890");
187            term.append("[This text should be truncated by display_columns() call below.]\n"); // We shouldn't see this on screen
188            term.set_display_columns(90);
189            assert_eq!(term.display_columns(), 90);
190            term.set_display_columns(dc); // Set back to default
191            assert_eq!(term.display_columns(), dc);
192
193            assert_eq!(term.history_rows(), 100, "Default history_rows at startup");
194            term.set_history_rows(50);
195            assert_eq!(term.history_rows(), 50);
196            term.set_history_rows(100); // Set back to default
197            assert_eq!(term.history_rows(), 100);
198
199            let hu = term.history_use();
200            term.append(&format!(
201                "history_use = {hu} (it's not clear what this means)\n"
202            ));
203            // assert_eq!(term.history_use(), hu+1);
204
205            term.append(&format!(
206                "margins = b:{} l:{} r:{} t{}\n",
207                term.margin_bottom(),
208                term.margin_left(),
209                term.margin_right(),
210                term.margin_top()
211            ));
212            assert_eq!(term.margin_bottom(), 3);
213            assert_eq!(term.margin_left(), 3);
214            assert_eq!(term.margin_right(), 3);
215            assert_eq!(term.margin_top(), 3);
216
217            term.set_margin_bottom(5);
218            term.set_margin_left(10);
219            term.set_margin_right(15);
220            term.set_margin_top(20);
221            assert_eq!(term.margin_bottom(), 5);
222            assert_eq!(term.margin_left(), 10);
223            assert_eq!(term.margin_right(), 15);
224            assert_eq!(term.margin_top(), 20);
225
226            term.append("Single character: '");
227            term.print_char('X');
228            term.append("', single UTF-8 character: '");
229            term.print_char_utf8('↑');
230            term.append("'\n");
231
232            let rr = term.redraw_rate();
233            assert_eq!(rr, 0.1, "Default redraw rate at startup");
234            term.append(&format!("Redraw rate {rr}\n"));
235            term.set_redraw_rate(1.0);
236            assert_eq!(term.redraw_rate(), 1.0);
237            term.set_redraw_rate(rr);
238            assert_eq!(term.redraw_rate(), rr);
239
240            let rs = term.redraw_style();
241            term.append(&format!("Redraw style {rs:?}\n"));
242            assert_eq!(
243                rs,
244                RedrawStyle::RateLimited,
245                "Default redraw style at startup"
246            );
247            term.set_redraw_style(RedrawStyle::NoRedraw);
248            assert_eq!(term.redraw_style(), RedrawStyle::NoRedraw);
249            term.set_redraw_style(rs);
250            assert_eq!(term.redraw_style(), rs);
251
252            // Sanity checks: enum values are implicitly assigned in the C++ code so could change unexpectedly
253            assert_eq!(
254                RedrawStyle::NoRedraw.bits(),
255                0x0000,
256                "RedrawStyle enum values have been reassigned"
257            );
258            assert_eq!(
259                RedrawStyle::RateLimited.bits(),
260                0x0001,
261                "RedrawStyle enum values have been reassigned"
262            );
263            assert_eq!(
264                RedrawStyle::PerWrite.bits(),
265                0x0002,
266                "RedrawStyle enum values have been reassigned"
267            );
268
269            let sb = term.scrollbar();
270            let hsb = term.hscrollbar();
271            // Both vertical and horizontal scrollbars are at zero
272            assert_eq!(sb.value(), 0.0);
273            assert_eq!(hsb.value(), 0.0);
274            term.set_hscrollbar_style(ScrollbarStyle::AUTO);
275
276            term.append(&format!(
277                "Scrollbar actual size {}\n",
278                term.scrollbar_actual_size()
279            ));
280            assert_eq!(term.scrollbar_actual_size(), 16);
281            term.append(&format!("Scrollbar size {}\n", term.scrollbar_size()));
282            assert_eq!(
283                term.scrollbar_size(),
284                0,
285                "Default scrollbar size at startup"
286            );
287            term.set_scrollbar_size(40);
288            assert_eq!(term.scrollbar_size(), 40);
289            assert_eq!(term.scrollbar_actual_size(), 40);
290            term.append(&format!(
291                "Scrollbar actual size {}\n",
292                term.scrollbar_actual_size()
293            ));
294            term.set_scrollbar_size(0); // Restore default
295            assert_eq!(term.scrollbar_size(), 0);
296            assert_eq!(term.scrollbar_actual_size(), 16);
297
298            let sfc = term.selection_fg_color();
299            let sbc = term.selection_bg_color();
300            assert_eq!(sfc, Color::Black);
301            assert_eq!(sbc, Color::White);
302            term.append(&format!("Selection colors: {sfc} {sbc}\n"));
303            term.set_selection_fg_color(Color::Green);
304            term.set_selection_bg_color(Color::DarkBlue);
305            assert_eq!(term.selection_fg_color(), Color::Green);
306            assert_eq!(term.selection_bg_color(), Color::DarkBlue);
307            term.set_selection_fg_color(sfc);
308            term.set_selection_bg_color(sbc);
309            assert_eq!(term.selection_fg_color(), Color::Black);
310            assert_eq!(term.selection_bg_color(), Color::White);
311
312            let tfcd = term.text_fg_color_default();
313            let tbcd = term.text_bg_color_default();
314            assert_eq!(tfcd, Color::XtermWhite);
315            assert_eq!(tbcd, Color::TransparentBg);
316            term.append(&format!("Default text colors: {sfc} {sbc}\n"));
317            term.set_text_fg_color_default(Color::Green);
318            term.set_text_bg_color_default(Color::DarkBlue);
319            assert_eq!(term.text_fg_color_default(), Color::Green);
320            assert_eq!(term.text_bg_color_default(), Color::DarkBlue);
321            term.set_text_fg_color_default(tfcd);
322            term.set_text_bg_color_default(tbcd);
323            assert_eq!(term.text_fg_color_default(), Color::XtermWhite);
324            assert_eq!(term.text_bg_color_default(), Color::TransparentBg);
325
326            let tfc = term.text_fg_color();
327            let tbc = term.text_bg_color();
328            assert_eq!(tfc, Color::XtermWhite);
329            assert_eq!(tbc, Color::TransparentBg);
330            term.append(&format!("Text colors: {sfc} {sbc}\n"));
331            term.set_text_fg_color(Color::Green);
332            term.set_text_bg_color(Color::DarkBlue);
333            assert_eq!(term.text_fg_color(), Color::Green);
334            assert_eq!(term.text_bg_color(), Color::DarkBlue);
335            term.set_text_fg_color(tfc);
336            term.set_text_bg_color(tbc);
337            assert_eq!(term.text_fg_color(), Color::XtermWhite);
338            assert_eq!(term.text_bg_color(), Color::TransparentBg);
339
340            let tf = term.text_font();
341            term.append(&format!("Text font: {tf:?}\n"));
342            assert_eq!(tf, Font::Courier);
343            term.set_text_font(Font::Screen);
344            assert_eq!(term.text_font(), Font::Screen);
345            term.set_text_font(tf);
346            assert_eq!(term.text_font(), Font::Courier);
347
348            let ts = term.text_size();
349            let r = term.h_to_row(100);
350            let c = term.w_to_col(100);
351            term.append(&format!(
352                "Text size: {ts}, h_to_row(100): {r}, w_to_col(100): {c}\n"
353            ));
354            assert_eq!(ts, 14);
355            term.set_text_size(30);
356            assert_eq!(term.text_size(), 30);
357            term.append(&format!(
358                "Text size: {}, h_to_row(100): {}, w_to_col(100): {}\n",
359                term.text_size(),
360                term.h_to_row(100),
361                term.w_to_col(100)
362            ));
363            term.set_text_size(ts);
364            assert_eq!(term.text_size(), ts);
365            term.append(&format!(
366                "Text size: {}, h_to_row(100): {}, w_to_col(100): {}\n",
367                term.text_size(),
368                term.h_to_row(100),
369                term.w_to_col(100)
370            ));
371
372            // Keyboard handler
373            term.handle({
374                move |term, e| {
375                    match e {
376                        fltk::enums::Event::KeyDown
377                            if fltk::app::event_key() == fltk::enums::Key::Escape =>
378                        {
379                            // false to let FLTK handle ESC. true to hide ESC
380                            false
381                        }
382
383                        fltk::enums::Event::KeyDown
384                            if fltk::app::event_length() == 1 && fltk::app::is_event_ctrl() =>
385                        {
386                            // We handle control keystroke
387                            let k = fltk::app::event_text().unwrap();
388                            term.append_utf8(&k);
389                            true
390                        }
391
392                        fltk::enums::Event::KeyDown
393                            if fltk::app::event_length() == 1 && !fltk::app::is_event_alt() =>
394                        {
395                            // We handle normal printable keystroke
396                            let k = fltk::app::event_text().unwrap();
397                            term.take_focus().unwrap();
398                            term.append(&k);
399                            true
400                        }
401
402                        // fltk docs say that keyboard handler should always claim Focus and Unfocus events
403                        // We can do this, or else ignore them (return false)
404                        // fltk::enums::Event::Focus | fltk::enums::Event::Unfocus => {
405                        //     term.redraw();
406                        //     true
407                        // }
408                        _ => false, // Let FLTK handle everything else
409                    }
410                }
411            });
412
413            let attr_save = term.text_attrib();
414            term.set_text_attrib(Attrib::Inverse | Attrib::Italic);
415            term.append("\nStartup tests complete. Keyboard is live.\n");
416            assert_eq!(term.text_attrib(), Attrib::Inverse | Attrib::Italic);
417            term.set_text_attrib(attr_save);
418            assert_eq!(term.text_attrib(), attr_save);
419            term.redraw();
420        }
421    });
422
423    app.run().unwrap();
424}
Source

pub fn set_flag(&mut self, flag: MenuFlag)

Set the menu item’s shortcut

Trait Implementations§

Source§

impl Clone for MenuItem

Source§

fn clone(&self) -> MenuItem

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for MenuItem

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for MenuItem

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl IntoIterator for MenuItem

Source§

type Item = MenuItem

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<<MenuItem as IntoIterator>::Item>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl PartialEq for MenuItem

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for MenuItem

Source§

impl Send for MenuItem

Available on non-crate feature single-threaded only.
Source§

impl Sync for MenuItem

Available on non-crate feature single-threaded only.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.