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

mod color;
mod dialog;
mod error;
mod escape;
mod routing;
pub use color::Color;
pub use dialog::DialogBuilder;
pub use error::{CustomError, Error, WVResult};
pub use escape::escape;
pub use routing::Router;
pub use routing::messages::{Request, Response};
pub use serde_json::{json, Value};

use boxfnonce::SendBoxFnOnce;
use ffi::*;
use std::{
    ffi::{CStr, CString},
    marker::PhantomData,
    mem,
    os::raw::*,
    sync::{Arc, RwLock, Weak},
};
use urlencoding::encode;

/// Content displayable inside a [`WebView`].
///
/// # Variants
///
/// - `Url` - Content to be fetched from a URL.
/// - `Html` - A string containing literal HTML.
///
/// [`WebView`]: struct.WebView.html
#[derive(Debug)]
pub enum Content<T> {
    Url(T),
    Html(T),
}

/// Builder for constructing a [`WebView`] instance.
///
/// # Example
///
/// ```no_run
/// extern crate web_view;
///
/// use web_view::*;
///
/// fn main() {
///     WebViewBuilder::new()
///         .title("Minimal webview example")
///         .content(Content::Url("https://en.m.wikipedia.org/wiki/Main_Page"))
///         .size(800, 600)
///         .resizable(true)
///         .debug(true)
///         .user_data(())
///         .router(Router::default())
///         .build()
///         .unwrap()
///         .run()
///         .unwrap();
/// }
/// ```
///
/// [`WebView`]: struct.WebView.html
pub struct WebViewBuilder<'a, T: 'a, C> {
    pub title: &'a str,
    pub content: Option<Content<C>>,
    pub width: i32,
    pub height: i32,
    pub resizable: bool,
    pub debug: bool,
    pub router: Option<Router<'a, T>>,
    pub user_data: Option<T>,
}

impl<'a, T: 'a, C> Default for WebViewBuilder<'a, T, C>
where
    C: AsRef<str>,
{
    fn default() -> Self {
        #[cfg(debug_assertions)]
        let debug = true;
        #[cfg(not(debug_assertions))]
        let debug = false;

        WebViewBuilder {
            title: "Application",
            content: None,
            width: 800,
            height: 600,
            resizable: true,
            debug,
            router: None,
            user_data: None,
        }
    }
}

impl<'a, T: 'a, C> WebViewBuilder<'a, T, C>
where
    C: AsRef<str>,
{
    /// Alias for [`WebViewBuilder::default()`].
    ///
    /// [`WebViewBuilder::default()`]: struct.WebviewBuilder.html#impl-Default
    pub fn new() -> Self {
        WebViewBuilder::default()
    }

    /// Sets the title of the WebView window.
    ///
    /// Defaults to `"Application"`.
    pub fn title(mut self, title: &'a str) -> Self {
        self.title = title;
        self
    }

    /// Sets the content of the WebView. Either a URL or a HTML string.
    pub fn content(mut self, content: Content<C>) -> Self {
        self.content = Some(content);
        self
    }

    /// Sets the size of the WebView window.
    ///
    /// Defaults to 800 x 600.
    pub fn size(mut self, width: i32, height: i32) -> Self {
        self.width = width;
        self.height = height;
        self
    }

    /// Sets the resizability of the WebView window. If set to false, the window cannot be resized.
    ///
    /// Defaults to `true`.
    pub fn resizable(mut self, resizable: bool) -> Self {
        self.resizable = resizable;
        self
    }

    /// Enables or disables debug mode.
    ///
    /// Defaults to `true` for debug builds, `false` for release builds.
    pub fn debug(mut self, debug: bool) -> Self {
        self.debug = debug;
        self
    }

    /// Sets the route. Sets a router. The router determine which callback is executed when 
    /// receives a javascript request
    pub fn router(mut self, router: Router<'a, T>) -> Self {
        self.router = Some(router);
        self
    }

    /// Sets the initial state of the user data. This is an arbitrary value stored on the WebView
    /// thread, accessible from dispatched closures without synchronization overhead.
    pub fn user_data(mut self, user_data: T) -> Self {
        self.user_data = Some(user_data);
        self
    }

    /// Validates provided arguments and returns a new WebView if successful.
    pub fn build(self) -> WVResult<WebView<'a, T>> {
        macro_rules! require_field {
            ($name:ident) => {
                self.$name
                    .ok_or_else(|| Error::UninitializedField(stringify!($name)))?
            };
        }

        let title = CString::new(self.title)?;
        let content = require_field!(content);
        let url = match content {
            Content::Url(url) => CString::new(url.as_ref())?,
            Content::Html(html) => {
                CString::new(format!("data:text/html,{}", encode(html.as_ref())))?
            }
        };
        let user_data = require_field!(user_data);
        let router = require_field!(router);

        let invoke_handler = move |webview: &mut WebView<T>, arg: &str| -> WVResult {
            router.resolve(webview, arg)
        };

        let mut webview = WebView::new(
            &title,
            &url,
            self.width,
            self.height,
            self.resizable,
            self.debug,
            user_data,
            invoke_handler,
        )?;

        webview.eval(include_str!("../dist/backend.js"))?;

        Ok(webview)
    }

    /// Validates provided arguments and runs a new WebView to completion, returning the user data.
    ///
    /// Equivalent to `build()?.run()`.
    pub fn run(self) -> WVResult<T> {
        self.build()?.run()
    }
}

/// Constructs a new builder for a [`WebView`].
///
/// Alias for [`WebViewBuilder::default()`].
///
/// [`WebView`]: struct.Webview.html
/// [`WebViewBuilder::default()`]: struct.WebviewBuilder.html#impl-Default
pub fn builder<'a, T, C>() -> WebViewBuilder<'a, T, C>
where
    C: AsRef<str>,
{
    WebViewBuilder::new()
}

struct UserData<'a, T> {
    inner: T,
    live: Arc<RwLock<()>>,
    invoke_handler: Box<FnMut(&mut WebView<T>, &str) -> WVResult + 'a>,
    result: WVResult,
}

/// An owned webview instance.
///
/// Construct via a [`WebViewBuilder`].
///
/// [`WebViewBuilder`]: struct.WebViewBuilder.html
#[derive(Debug)]
pub struct WebView<'a, T: 'a> {
    inner: *mut CWebView,
    _phantom: PhantomData<&'a mut T>,
}

impl<'a, T> WebView<'a, T> {
    #![cfg_attr(feature = "cargo-clippy", allow(clippy::too_many_arguments))]
    fn new<I>(
        title: &CStr,
        url: &CStr,
        width: i32,
        height: i32,
        resizable: bool,
        debug: bool,
        user_data: T,
        invoke_handler: I,
    ) -> WVResult<WebView<'a, T>>
    where
        I: FnMut(&mut WebView<T>, &str) -> WVResult + 'a,
    {
        let user_data = Box::new(UserData {
            inner: user_data,
            live: Arc::new(RwLock::new(())),
            invoke_handler: Box::new(invoke_handler),
            result: Ok(()),
        });
        let user_data_ptr = Box::into_raw(user_data);

        unsafe {
            let inner = wrapper_webview_new(
                title.as_ptr(),
                url.as_ptr(),
                width,
                height,
                resizable as _,
                debug as _,
                Some(ffi_invoke_handler::<T>),
                user_data_ptr as _,
            );

            if inner.is_null() {
                Box::<UserData<T>>::from_raw(user_data_ptr);
                Err(Error::Initialization)
            } else {
                Ok(WebView::from_ptr(inner))
            }
        }
    }

    unsafe fn from_ptr(inner: *mut CWebView) -> WebView<'a, T> {
        WebView {
            inner,
            _phantom: PhantomData,
        }
    }

    /// Creates a thread-safe [`Handle`] to the `WebView`, from which closures can be dispatched.
    ///
    /// [`Handle`]: struct.Handle.html
    pub fn handle(&self) -> Handle<T> {
        Handle {
            inner: self.inner,
            live: Arc::downgrade(&self.user_data_wrapper().live),
            _phantom: PhantomData,
        }
    }

    fn user_data_wrapper_ptr(&self) -> *mut UserData<'a, T> {
        unsafe { wrapper_webview_get_userdata(self.inner) as _ }
    }

    fn user_data_wrapper(&self) -> &UserData<'a, T> {
        unsafe { &(*self.user_data_wrapper_ptr()) }
    }

    fn user_data_wrapper_mut(&mut self) -> &mut UserData<'a, T> {
        unsafe { &mut (*self.user_data_wrapper_ptr()) }
    }

    /// Borrows the user data immutably.
    pub fn user_data(&self) -> &T {
        &self.user_data_wrapper().inner
    }

    /// Borrows the user data mutably.
    pub fn user_data_mut(&mut self) -> &mut T {
        &mut self.user_data_wrapper_mut().inner
    }

    /// Forces the `WebView` instance to end, without dropping.
    pub fn terminate(&mut self) {
        unsafe { webview_terminate(self.inner) }
    }

    /// Executes the provided string as JavaScript code within the `WebView` instance.
    pub fn eval(&mut self, js: &str) -> WVResult {
        let js = CString::new(js)?;
        let ret = unsafe { webview_eval(self.inner, js.as_ptr()) };
        if ret != 0 {
            Err(Error::JsEvaluation)
        } else {
            Ok(())
        }
    }

    /// Injects the provided string as CSS within the `WebView` instance.
    pub fn inject_css(&mut self, css: &str) -> WVResult {
        let css = CString::new(css)?;
        let ret = unsafe { webview_inject_css(self.inner, css.as_ptr()) };
        if ret != 0 {
            Err(Error::CssInjection)
        } else {
            Ok(())
        }
    }

    /// Sets the color of the title bar.
    ///
    /// # Examples
    ///
    /// Without specifying alpha (defaults to 255):
    /// ```ignore
    /// webview.set_color((123, 321, 213));
    /// ```
    ///
    /// Specifying alpha:
    /// ```ignore
    /// webview.set_color((123, 321, 213, 127));
    /// ```
    pub fn set_color<C: Into<Color>>(&mut self, color: C) {
        let color = color.into();
        unsafe { webview_set_color(self.inner, color.r, color.g, color.b, color.a) }
    }

    /// Sets the title displayed at the top of the window.
    ///
    /// # Errors
    ///
    /// If `title` contain a nul byte, returns [`Error::NulByte`].
    ///
    /// [`Error::NulByte`]: enum.Error.html#variant.NulByte
    pub fn set_title(&mut self, title: &str) -> WVResult {
        let title = CString::new(title)?;
        unsafe { webview_set_title(self.inner, title.as_ptr()) }
        Ok(())
    }

    /// Enables or disables fullscreen.
    pub fn set_fullscreen(&mut self, fullscreen: bool) {
        unsafe { webview_set_fullscreen(self.inner, fullscreen as _) };
    }

    /// Returns a builder for opening a new dialog window.
    pub fn dialog<'b>(&'b mut self) -> DialogBuilder<'a, 'b, T> {
        DialogBuilder::new(self)
    }

    /// Iterates the event loop. Returns `None` if the view has been closed or terminated.
    pub fn step(&mut self) -> Option<WVResult> {
        unsafe {
            match webview_loop(self.inner, 1) {
                0 => {
                    let closure_result = &mut self.user_data_wrapper_mut().result;
                    match closure_result {
                        Ok(_) => Some(Ok(())),
                        e => Some(mem::replace(e, Ok(()))),
                    }
                }
                _ => None,
            }
        }
    }

    /// Runs the event loop to completion and returns the user data.
    pub fn run(mut self) -> WVResult<T> {
        loop {
            match self.step() {
                Some(Ok(_)) => (),
                Some(e) => e?,
                None => return Ok(self.into_inner()),
            }
        }
    }

    /// Consumes the `WebView` and returns ownership of the user data.
    pub fn into_inner(mut self) -> T {
        unsafe {
            let user_data = self._into_inner();
            mem::forget(self);
            user_data
        }
    }

    unsafe fn _into_inner(&mut self) -> T {
        let _lock = self
            .user_data_wrapper()
            .live
            .write()
            .expect("A dispatch channel thread panicked while holding mutex to WebView.");

        let user_data_ptr = self.user_data_wrapper_ptr();
        webview_exit(self.inner);
        wrapper_webview_free(self.inner);
        let user_data = *Box::from_raw(user_data_ptr);
        user_data.inner
    }
}

impl<'a, T> Drop for WebView<'a, T> {
    fn drop(&mut self) {
        unsafe {
            self._into_inner();
        }
    }
}

/// A thread-safe handle to a [`WebView`] instance. Used to dispatch closures onto its task queue.
///
/// [`WebView`]: struct.WebView.html
pub struct Handle<T> {
    inner: *mut CWebView,
    live: Weak<RwLock<()>>,
    _phantom: PhantomData<T>,
}

impl<T> Handle<T> {
    /// Schedules a closure to be run on the [`WebView`] thread.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Dispatch`] if the [`WebView`] has been dropped.
    ///
    /// If the closure returns an `Err`, it will be returned on the next call to [`step()`].
    ///
    /// [`WebView`]: struct.WebView.html
    /// [`Error::Dispatch`]: enum.Error.html#variant.Dispatch
    /// [`step()`]: struct.WebView.html#method.step
    pub fn dispatch<F>(&self, f: F) -> WVResult
    where
        F: FnOnce(&mut WebView<T>) -> WVResult + Send + 'static,
    {
        // Abort if WebView has been dropped. Otherwise, keep it alive until closure has been
        // dispatched.
        let mutex = self.live.upgrade().ok_or(Error::Dispatch)?;
        let closure = Box::new(SendBoxFnOnce::new(f));
        let _lock = mutex.read().map_err(|_| Error::Dispatch)?;

        // Send closure to webview.
        unsafe {
            webview_dispatch(
                self.inner,
                Some(ffi_dispatch_handler::<T> as _),
                Box::into_raw(closure) as _,
            )
        }
        Ok(())
    }
}

unsafe impl<T> Send for Handle<T> {}
unsafe impl<T> Sync for Handle<T> {}

fn read_str(s: &[u8]) -> String {
    let end = s.iter().position(|&b| b == 0).map_or(0, |i| i + 1);
    match CStr::from_bytes_with_nul(&s[..end]) {
        Ok(s) => s.to_string_lossy().into_owned(),
        Err(_) => "".to_string(),
    }
}

extern "system" fn ffi_dispatch_handler<T>(webview: *mut CWebView, arg: *mut c_void) {
    unsafe {
        let mut handle = mem::ManuallyDrop::new(WebView::<T>::from_ptr(webview));
        let result = {
            let callback =
                Box::<SendBoxFnOnce<'static, (&mut WebView<T>,), WVResult>>::from_raw(arg as _);
            callback.call(&mut handle)
        };
        handle.user_data_wrapper_mut().result = result;
    }
}

extern "system" fn ffi_invoke_handler<T>(webview: *mut CWebView, arg: *const c_char) {
    unsafe {
        let arg = CStr::from_ptr(arg).to_string_lossy().to_string();
        let mut handle = mem::ManuallyDrop::new(WebView::<T>::from_ptr(webview));
        let result = ((*handle.user_data_wrapper_ptr()).invoke_handler)(&mut *handle, &arg);
        handle.user_data_wrapper_mut().result = result;
    }
}