1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
//! # Preamble
//!
//! [Docs](https://docs.rs/neutrino) |
//! [Repo](https://github.com/alexislozano/neutrino) |
//! [Wiki](https://github.com/alexislozano/neutrino/wiki) |
//! [Crate](https://crates.io/crates/neutrino)
//!
//! Neutrino is a MVC GUI framework written in Rust. It lets users create GUI
//! applications by positioning widgets on a window and by handling events.
//! Neutrino is based on the [web-view](https://crates.io/crates/web-view) crate
//! provided by Boscop. As such, Neutrino renders the application using web
//! technologies as HTML and CSS.
//!
//! As it is based on web-view, Neutrino does not embed a whole web browser. So
//! don't worry, due to the very lightweight footprint of web-view, you won't
//! have to buy more memory for your computer.
//!
//! # Install
//!
//! In order to use Neutrino, you will have to use cargo. Just add the following
//! line to your `Cargo.toml` and you'll be done :
//!
//! ```text
//! neutrino = "<last_version>"
//! ```
//!
//! # Examples
//!
//! ![](https://raw.githubusercontent.com/wiki/alexislozano/neutrino/images/image_viewer/3.png)
//!
//! ![](https://raw.githubusercontent.com/wiki/alexislozano/neutrino/images/styling/3.png)
//!
//! ![](https://raw.githubusercontent.com/wiki/alexislozano/neutrino/images/styling/4.png)
//! 
//! ![](https://raw.githubusercontent.com/wiki/alexislozano/neutrino/images/styling/5.png)
//! 
//! ![](https://raw.githubusercontent.com/wiki/alexislozano/neutrino/images/styling/6.png)

use web_view::*;

pub mod utils;
pub mod widgets;

use utils::event::{Event, Key};
use utils::style::{inline_script, inline_style, scss_to_css};
use utils::theme::Theme;
use widgets::menubar::MenuBar;
use widgets::widget::Widget;

use json;

/// # An abstract application
///
/// ## Example
///
/// ```text
/// App::run(my_window);
/// ```
pub struct App;

impl App {
    /// Run the application
    pub fn run(mut window: Window) {
        let title = &window.title.to_owned();
        let width = window.width;
        let height = window.height;
        let resizable = window.resizable;
        let debug = window.debug;

        let context = if debug {
            ""
        } else {
            r#"(function() { event.preventDefault(); } )()"#
        };

        let timer = match window.timer {
            None => "".to_string(),
            Some(period) => {
                format!(r#"<script>{}</script>"#, Event::tick_js(period))
            }
        };

        let html = format!(
            r#"
            <!doctype html>
            <html>
                <head>
                    <meta charset="UTF-8">
                    {styles}
                </head>
                <body onkeydown="{key}" onmousedown="{click}" oncontextmenu="{context}">
                    <div id="app"></div>
                    {scripts}
                    {timer}
                </body>
            </html>
            "#,
            styles = format!(
                "{}\n{}\n{}\n",
                inline_style(include_str!(concat!(
                    env!("OUT_DIR"),
                    "/app.css"
                ))),
                inline_style(&window.theme.css()),
                inline_style(&window.style),
            ),
            scripts = format!(
                "{}\n{}\n",
                inline_script(include_str!("www/app/morphdom.min.js")),
                inline_script(include_str!("www/app/app.js"))
            ),
            key = Event::key_js(),
            click = Event::undefined_js(),
            context = context,
            timer = timer,
        );

        let webview = web_view::builder()
            .title(title)
            .content(Content::Html(html))
            .size(width, height)
            .resizable(resizable)
            .user_data("")
            .debug(debug)
            .invoke_handler(|webview, arg| {
                let event: Event = match json::parse(arg) {
                    Ok(value) => match value["type"].as_str().unwrap() {
                        "Update" => Event::Update,
                        "Tick" => Event::Tick,
                        "Key" => match Key::new(value["key"].as_str().unwrap())
                        {
                            Some(key) => Event::Key { key },
                            None => Event::Undefined,
                        },
                        "Change" => Event::Change {
                            source: value["source"]
                                .as_str()
                                .unwrap()
                                .to_string(),
                            value: value["value"].as_str().unwrap().to_string(),
                        },
                        _ => Event::Undefined,
                    },
                    Err(_) => Event::Undefined,
                };
                window.trigger(&event);
                match event {
                    Event::Undefined => (),
                    _ => window.trigger(&Event::Update),
                };
                window.render(webview)
            })
            .build()
            .unwrap();

        webview.run().unwrap();
        std::process::exit(0);
    }
}

/// # The listener of a Window
pub trait WindowListener {
    /// Function triggered on key event
    fn on_key(&self, _key: Key);

    /// Function triggered on tick event
    fn on_tick(&self);
}

/// # A window containing the widgets
///
/// ## Fields
///
/// ```text
/// title: String
/// width: i32
/// height: i32
/// resizable: bool
/// debug: bool
/// theme: Theme
/// style: String
/// child: Option<Box<dyn Widget>>
/// menubar: Option<MenuBar>
/// listener: Option<Box<dyn WindowListener>>
/// timer: Option<u32>;
/// ```
///
/// # Default values
///
/// ```text
/// title: "Untitled".to_string(),
/// width: 640
/// height: 480
/// resizable: false
/// debug: false
/// theme: Theme::Default
/// style: "".to_string()
/// child: None
/// menubar: None
/// listener: None
/// timer: None
/// ```
///
/// ## Example
///
/// ```
/// use neutrino::{Window, App};
///
/// fn main() {
///     let mut my_window = Window::new();
///     my_window.set_title("Title");
///     my_window.set_size(800, 600);
///     my_window.set_resizable();
///
///     // App::run(window);
/// }
/// ```
pub struct Window {
    title: String,
    width: i32,
    height: i32,
    resizable: bool,
    debug: bool,
    theme: Theme,
    style: String,
    child: Option<Box<dyn Widget>>,
    menubar: Option<MenuBar>,
    listener: Option<Box<dyn WindowListener>>,
    timer: Option<u32>,
}

impl Window {
    /// Create a Window
    pub fn new() -> Self {
        Self {
            title: "Untitled".to_string(),
            width: 640,
            height: 480,
            resizable: false,
            debug: false,
            theme: Theme::Default,
            style: "".to_string(),
            child: None,
            menubar: None,
            listener: None,
            timer: None,
        }
    }

    /// Set the child
    pub fn set_child(&mut self, widget: Box<dyn Widget>) {
        self.child = Some(widget);
    }

    /// Set the menubar
    pub fn set_menubar(&mut self, menubar: MenuBar) {
        self.menubar = Some(menubar);
    }

    /// Set the title
    pub fn set_title(&mut self, title: &str) {
        self.title = title.to_string();
    }

    /// Set the size (width and height)
    pub fn set_size(&mut self, width: i32, height: i32) {
        self.width = width;
        self.height = height;
    }

    /// Set the resizable flag to true
    pub fn set_resizable(&mut self) {
        self.resizable = true;
    }

    /// Set the debug flag to true
    pub fn set_debug(&mut self) {
        self.debug = true;
    }

    /// Set the theme
    pub fn set_theme(&mut self, theme: Theme) {
        self.theme = theme;
    }

    /// Set the style
    pub fn set_style(&mut self, style: &str) {
        self.style = scss_to_css(style);
    }

    /// Set the listener
    pub fn set_listener(&mut self, listener: Box<dyn WindowListener>) {
        self.listener = Some(listener);
    }

    /// Set the timer
    ///
    /// The app will send a Tick event with a defined period
    pub fn set_timer(&mut self, period: u32) {
        self.timer = Some(period);
    }

    /// Render the menubar and widget tree
    fn render(&self, webview: &mut WebView<&str>) -> WVResult {
        let rendered = format!(
            r#"render("<div id=\"app\">{}</div>")"#,
            self.eval().replace(r#"""#, r#"\""#)
        );
        webview.eval(&rendered)
    }

    /// Return the HTML representation of the menubar and the widget tree
    fn eval(&self) -> String {
        match (&self.menubar, &self.child) {
            (Some(menubar), Some(child)) => {
                format!("{}{}", menubar.eval(), child.eval())
            }
            (None, Some(child)) => child.eval().to_string(),
            (Some(menubar), None) => menubar.eval().to_string(),
            (None, None) => "".to_string(),
        }
    }

    /// Trigger the events in the widget tree
    fn trigger(&mut self, event: &Event) {
        match event {
            Event::Change { .. } | Event::Update | Event::Undefined => {
                match (&mut self.menubar, &mut self.child) {
                    (Some(menubar), Some(child)) => {
                        menubar.trigger(event);
                        child.trigger(event);
                    }
                    (None, Some(child)) => child.trigger(event),
                    (Some(menubar), None) => menubar.trigger(event),
                    (None, None) => (),
                };
            }
            Event::Key { key } => {
                match &self.listener {
                    None => (),
                    Some(listener) => {
                        listener.on_key(*key);
                    }
                };
                match (&mut self.menubar, &mut self.child) {
                    (Some(menubar), Some(child)) => {
                        menubar.trigger(event);
                        child.trigger(event);
                    }
                    (None, Some(child)) => child.trigger(event),
                    (Some(menubar), None) => menubar.trigger(event),
                    (None, None) => (),
                };
            }
            Event::Tick => {
                match &self.listener {
                    None => (),
                    Some(listener) => {
                        listener.on_tick();
                    }
                };
            }
        }
    }
}