Struct fltk::app::GlobalState

source ·
pub struct GlobalState<T: Send + Sync> { /* private fields */ }
Expand description

Represents global state

Implementations§

source§

impl<T: Sync + Send + 'static> GlobalState<T>

source

pub fn new(val: T) -> Self

Creates a new global state

Examples found in repository?
examples/widget_id.rs (line 51)
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
fn main() {
    let counter = Counter { count: 0 };
    let _state = app::GlobalState::new(counter);
    let app = app::App::default().with_scheme(app::Scheme::Gtk);
    let mut wind = window::Window::default()
        .with_size(160, 200)
        .with_label("Counter");
    let col = group::Flex::default_fill().column();
    button::Button::default()
        .with_label("+")
        .on_trigger(increment); // passed by function object
    frame::Frame::default().with_label("0").with_id("my_frame"); // pass id here
    button::Button::default()
        .with_label("-")
        .on_trigger(|_| increment_by(-1)); // called in closure
    col.end();
    wind.make_resizable(true);
    wind.end();
    wind.show();

    app.run().unwrap();
}
More examples
Hide additional examples
examples/editor2.rs (line 231)
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
fn main() {
    let a = app::App::default().with_scheme(app::Scheme::Oxy);
    app::get_system_colors();

    let mut buf = text::TextBuffer::default();
    buf.set_tab_distance(4);

    let state = State::new(buf.clone());
    app::GlobalState::new(state);

    let mut w = window::Window::default()
        .with_size(WIDTH, HEIGHT)
        .with_label("Ted");
    w.set_xclass("ted");
    {
        let mut col = group::Flex::default_fill().column();
        col.set_pad(0);
        let mut m = menu::SysMenuBar::default();
        init_menu(&mut m);
        let mut ed = text::TextEditor::default().with_id("ed");
        ed.set_buffer(buf);
        ed.set_linenumber_width(40);
        ed.set_text_font(Font::Courier);
        ed.set_trigger(CallbackTrigger::Changed);
        ed.set_callback(editor_cb);
        handle_drag_drop(&mut ed);
        w.resizable(&col);
        col.fixed(&m, 30);
        col.end();
    }
    w.end();
    w.show();
    w.set_callback(win_cb);
    a.run().unwrap();
}
source

pub fn with<V: Clone, F: 'static + FnMut(&mut T) -> V>(&self, cb: F) -> V

Modifies the global state by acquiring a mutable reference

Panics

Panics on state downcast errors

Examples found in repository?
examples/widget_id.rs (lines 31-34)
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
fn increment_by(step: i32) {
    let mut frame: frame::Frame = app::widget_from_id("my_frame").unwrap();
    let state = app::GlobalState::<Counter>::get();
    let count = state.with(move |c| {
        c.count += step;
        c.count
    });
    frame.set_label(&count.to_string());
}

// To pass a function object directly!
fn increment(_w: &mut impl WidgetExt) {
    let mut frame: frame::Frame = app::widget_from_id("my_frame").unwrap();
    let state = app::GlobalState::<Counter>::get();
    let count = state.with(|c| {
        c.count += 1;
        c.count
    });
    frame.set_label(&count.to_string());
}
More examples
Hide additional examples
examples/editor2.rs (lines 89-103)
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
fn quit_cb() {
    STATE.with(|s| {
        if s.saved {
            app::quit();
        } else {
            let c = dialog::choice2_default(
                "Are you sure you want to exit without saving?",
                "Yes",
                "No",
                "",
            );
            if c == Some(0) {
                app::quit();
            }
        }
    });
}

fn win_cb(_w: &mut window::Window) {
    if app::event() == Event::Close {
        quit_cb();
    }
}

fn editor_cb(_e: &mut text::TextEditor) {
    STATE.with(|s| s.saved = false);
}

fn handle_drag_drop(editor: &mut text::TextEditor) {
    editor.handle({
        let mut dnd = false;
        let mut released = false;
        let buf = editor.buffer().unwrap();
        move |_, ev| match ev {
            Event::DndEnter => {
                dnd = true;
                true
            }
            Event::DndDrag => true,
            Event::DndRelease => {
                released = true;
                true
            }
            Event::Paste => {
                if dnd && released {
                    let path = app::event_text();
                    let path = path.trim();
                    let path = path.replace("file://", "");
                    let path = std::path::PathBuf::from(&path);
                    if path.exists() {
                        // we use a timeout to avoid pasting the path into the buffer
                        app::add_timeout3(0.0, {
                            let mut buf = buf.clone();
                            move |_| match buf.load_file(&path) {
                                Ok(_) => (),
                                Err(e) => dialog::alert_default(&format!(
                                    "An issue occured while loading the file: {e}"
                                )),
                            }
                        });
                    }
                    dnd = false;
                    released = false;
                    true
                } else {
                    false
                }
            }
            Event::DndLeave => {
                dnd = false;
                released = false;
                true
            }
            _ => false,
        }
    });
}

fn menu_cb(m: &mut impl MenuExt) {
    if let Ok(mpath) = m.item_pathname(None) {
        let ed: text::TextEditor = app::widget_from_id("ed").unwrap();
        match mpath.as_str() {
            "&File/New\t" => {
                STATE.with(|s| {
                    if !s.buf.text().is_empty() {
                        let c = dialog::choice2_default(
                            "Are you sure you want to clear the buffer?",
                            "Yes",
                            "No",
                            "",
                        );
                        if c == Some(0) {
                            s.buf.set_text("");
                            s.saved = false;
                        }
                    }
                });
            }
            "&File/Open...\t" => {
                let c = nfc_get_file(dialog::NativeFileChooserType::BrowseFile);
                if let Ok(text) = std::fs::read_to_string(&c) {
                    STATE.with(move |s| {
                        s.buf.set_text(&text);
                        s.saved = false;
                        s.current_file = c.clone();
                    });
                }
            }
            "&File/Save\t" => {
                STATE.with(|s| {
                    if !s.saved && s.current_file.exists() {
                        std::fs::write(&s.current_file, s.buf.text()).ok();
                    }
                });
            }
            "&File/Save as...\t" => {
                let c = nfc_get_file(dialog::NativeFileChooserType::BrowseSaveFile);
                STATE.with(move |s| {
                    std::fs::write(&c, s.buf.text()).ok();
                    s.saved = true;
                    s.current_file = c.clone();
                });
            }
            "&File/Quit\t" => quit_cb(),
            "&Edit/Cut\t" => ed.cut(),
            "&Edit/Copy\t" => ed.copy(),
            "&Edit/Paste\t" => ed.paste(),
            "&Help/About\t" => {
                dialog::message_default("A minimal text editor written using fltk-rs!")
            }
            _ => unreachable!(),
        }
    }
}
source

pub fn get() -> Self

Gets the already initialized global state

Examples found in repository?
examples/widget_id.rs (line 30)
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
fn increment_by(step: i32) {
    let mut frame: frame::Frame = app::widget_from_id("my_frame").unwrap();
    let state = app::GlobalState::<Counter>::get();
    let count = state.with(move |c| {
        c.count += step;
        c.count
    });
    frame.set_label(&count.to_string());
}

// To pass a function object directly!
fn increment(_w: &mut impl WidgetExt) {
    let mut frame: frame::Frame = app::widget_from_id("my_frame").unwrap();
    let state = app::GlobalState::<Counter>::get();
    let count = state.with(|c| {
        c.count += 1;
        c.count
    });
    frame.set_label(&count.to_string());
}

Trait Implementations§

source§

impl<T: Send + Sync> Clone for GlobalState<T>

source§

fn clone(&self) -> Self

Returns a copy 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<T: Debug + Send + Sync> Debug for GlobalState<T>

source§

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

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

impl<T: Copy + Send + Sync> Copy for GlobalState<T>

Auto Trait Implementations§

§

impl<T> RefUnwindSafe for GlobalState<T>where T: RefUnwindSafe,

§

impl<T> Send for GlobalState<T>

§

impl<T> Sync for GlobalState<T>

§

impl<T> Unpin for GlobalState<T>where T: Unpin,

§

impl<T> UnwindSafe for GlobalState<T>where T: UnwindSafe,

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

source§

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

Mutably borrows from an owned value. 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 Twhere 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 Twhere T: Clone,

§

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 Twhere U: Into<T>,

§

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 Twhere U: TryFrom<T>,

§

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.