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
#[macro_use]
extern crate serde;
#[macro_use]
extern crate thiserror;
#[cfg(target_os = "macos")]
#[macro_use]
extern crate objc;

pub mod platform;

use crate::platform::{InnerWebView, CALLBACKS};

use std::cell::RefCell;
use std::sync::mpsc::{channel, Receiver, SendError, Sender};

use url::{ParseError, Url};

#[cfg(target_os = "linux")]
use gtk::Window;
#[cfg(target_os = "windows")]
use winit::platform::windows::WindowExtWindows;
#[cfg(not(target_os = "linux"))]
use winit::window::Window;

const DEBUG: bool = true;

pub struct WebViewBuilder {
    inner: WebView,
    url: Option<Url>,
}

impl WebViewBuilder {
    pub fn new(window: Window) -> Result<Self> {
        Ok(Self {
            inner: WebView::new(window)?,
            url: None,
        })
    }

    pub fn init(self, js: &str) -> Result<Self> {
        self.inner.webview.init(js)?;
        Ok(self)
    }

    pub fn dispatch_sender(&self) -> DispatchSender {
        DispatchSender(self.inner.tx.clone())
    }

    // TODO implement bind here
    pub fn bind<F>(self, name: &str, f: F) -> Result<Self>
    where
        F: FnMut(i8, Vec<String>) -> i32 + Send + 'static,
    {
        let js = format!(
            r#"var name = {:?};
                var RPC = window._rpc = (window._rpc || {{nextSeq: 1}});
                window[name] = function() {{
                var seq = RPC.nextSeq++;
                var promise = new Promise(function(resolve, reject) {{
                    RPC[seq] = {{
                    resolve: resolve,
                    reject: reject,
                    }};
                }});
                window.external.invoke(JSON.stringify({{
                    id: seq,
                    method: name,
                    params: Array.prototype.slice.call(arguments),
                }}));
                return promise;
                }}
            "#,
            name
        );
        self.inner.webview.init(&js)?;
        CALLBACKS
            .lock()
            .unwrap()
            .insert(name.to_string(), Box::new(f));
        Ok(self)
    }

    pub fn load_url(mut self, url: &str) -> Result<Self> {
        self.url = Some(Url::parse(url)?);
        Ok(self)
    }

    pub fn load_html(mut self, html: &str) -> Result<Self> {
        let url = match Url::parse(html) {
            Ok(url) => url,
            Err(_) => Url::parse(&format!("data:text/html,{}", html))?,
        };
        self.url = Some(url);
        Ok(self)
    }

    pub fn build(self) -> Result<WebView> {
        if let Some(url) = self.url {
            #[cfg(target_os = "windows")]
            {
                if url.cannot_be_a_base() {
                    self.inner.webview.navigate_to_string(url.as_str())?;
                } else {
                    self.inner.webview.navigate(url.as_str())?;
                }
            }
            #[cfg(not(target_os = "windows"))]
            {
                self.inner.webview.navigate(url.as_str())?;
            }
        }
        Ok(self.inner)
    }
}

thread_local!(static EVAL: RefCell<Option<Receiver<String>>> = RefCell::new(None));

pub struct WebView {
    window: Window,
    webview: InnerWebView,
    tx: Sender<String>,
}

impl WebView {
    pub fn new(window: Window) -> Result<Self> {
        #[cfg(target_os = "windows")]
        let webview = InnerWebView::new(window.hwnd())?;
        #[cfg(target_os = "macos")]
        let webview = InnerWebView::new(&window, DEBUG)?;
        #[cfg(target_os = "linux")]
        let webview = InnerWebView::new(&window, DEBUG);
        let (tx, rx) = channel();
        EVAL.with(|e| {
            *e.borrow_mut() = Some(rx);
        });
        Ok(Self {
            window,
            webview,
            tx,
        })
    }

    pub fn dispatch(&mut self, js: &str) -> Result<()> {
        self.tx.send(js.to_string())?;
        Ok(())
    }

    pub fn dispatch_sender(&self) -> DispatchSender {
        DispatchSender(self.tx.clone())
    }

    pub fn window(&self) -> &Window {
        &self.window
    }

    pub fn evaluate(&mut self) -> Result<()> {
        EVAL.with(|e| -> Result<()> {
            let e = &*e.borrow();
            if let Some(rx) = e {
                while let Ok(js) = rx.try_recv() {
                    self.webview.eval(&js)?;
                }
            } else {
                return Err(Error::EvalError);
            }
            Ok(())
        })?;

        Ok(())
    }

    pub fn resize(&self) {
        #[cfg(target_os = "windows")]
        self.webview.resize(self.window.hwnd());
    }
}

pub struct DispatchSender(Sender<String>);

impl DispatchSender {
    pub fn send(&self, js: &str) -> Result<()> {
        self.0.send(js.to_string())?;
        Ok(())
    }
}

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Error, Debug)]
pub enum Error {
    #[error("Script is not evaluated on the same thread with its webview!")]
    EvalError,
    #[error("Failed to initialize the script")]
    InitScriptError,
    #[error(transparent)]
    NulError(#[from] std::ffi::NulError),
    #[cfg(not(target_os = "linux"))]
    #[error(transparent)]
    OsError(#[from] winit::error::OsError),
    #[error(transparent)]
    SenderError(#[from] SendError<String>),
    #[error(transparent)]
    UrlError(#[from] ParseError),
    #[cfg(target_os = "windows")]
    #[error("Windows error: {0:?}")]
    WinrtError(windows::Error),
}

#[cfg(target_os = "windows")]
impl From<windows::Error> for Error {
    fn from(error: windows::Error) -> Self {
        Error::WinrtError(error)
    }
}