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
extern crate fnv;
extern crate urlencoding;
extern crate webview_sys as ffi;

mod escape;
pub use escape::escape;

use ffi::*;
use fnv::FnvHashMap as HashMap; // faster than std HashMap for small keys
use std::ffi::{CStr, CString};
use std::marker::PhantomData;
use std::mem::transmute;
use std::os::raw::*;
use urlencoding::encode;

#[derive(Debug)]
pub struct OnCloseInformation {
	pub height: i32,
	pub width: i32,
	pub top: i32,
	pub left: i32,
}

/// Dialog alerts, should be specified in Dialog::Alert variant.
pub enum Alert {
	Info,
	Warning,
	Error,
}

/// Dialog variants that can be shown to user with WebView::dialog function.
pub enum Dialog {
	SaveFile,
	OpenFile,
	ChooseDirectory,
	Alert(Alert),
}

impl Dialog {
	fn parameters(self) -> (DialogType, DialogFlags) {
		match self {
			Dialog::SaveFile => (DialogType::Save, DialogFlags::FILE),
			Dialog::OpenFile => (DialogType::Open, DialogFlags::FILE),
			Dialog::ChooseDirectory => (DialogType::Open, DialogFlags::DIRECTORY),
			Dialog::Alert(alert) => match alert {
				Alert::Info => (DialogType::Alert, DialogFlags::INFO),
				Alert::Warning => (DialogType::Alert, DialogFlags::WARNING),
				Alert::Error => (DialogType::Alert, DialogFlags::ERROR),
			},
		}
	}
}

/// Wrapper around content that can be displayed inside webview.
/// Can be either Url or Html.
/// Url fetches contents from address and displays it.
/// Html displays strings contents.
pub enum Content<T: AsRef<str>> {
	Url(T),
	Html(T),
}

pub fn run<
	'a,
	T: 'a,
	I: FnOnce(MyUnique<WebView<'a, T>>),
	F: FnMut(&mut WebView<'a, T>, &str, &mut T) + 'a,
	C: AsRef<str>,
	E: FnOnce(OnCloseInformation),
>(
	title: &str,
	content: Content<C>,
	size: Option<(i32, i32)>,
	resizable: bool,
	debug: bool,
	init_cb: I,
	ext_cb: F,
	user_data: T,
	on_close_cb: E,
) -> (T, bool) {
	priv_run(
		title,
		content,
		size,
		resizable,
		false,
		false,
		debug,
		init_cb,
		ext_cb,
		user_data,
		on_close_cb,
	)
}

pub fn run_maximised<
	'a,
	T: 'a,
	I: FnOnce(MyUnique<WebView<'a, T>>),
	F: FnMut(&mut WebView<'a, T>, &str, &mut T) + 'a,
	C: AsRef<str>,
	E: FnOnce(OnCloseInformation),
>(
	title: &str,
	content: Content<C>,
	size: Option<(i32, i32)>,
	resizable: bool,
	debug: bool,
	init_cb: I,
	ext_cb: F,
	user_data: T,
	on_close_cb: E,
) -> (T, bool) {
	priv_run(
		title,
		content,
		size,
		resizable,
		true,
		false,
		debug,
		init_cb,
		ext_cb,
		user_data,
		on_close_cb,
	)
}

pub fn run_fullscreen<
	'a,
	T: 'a,
	I: FnOnce(MyUnique<WebView<'a, T>>),
	F: FnMut(&mut WebView<'a, T>, &str, &mut T) + 'a,
	C: AsRef<str>,
	E: FnOnce(OnCloseInformation),
>(
	title: &str,
	content: Content<C>,
	size: Option<(i32, i32)>,
	resizable: bool,
	debug: bool,
	init_cb: I,
	ext_cb: F,
	user_data: T,
	on_close_cb: E,
) -> (T, bool) {
	priv_run(
		title,
		content,
		size,
		resizable,
		false,
		true,
		debug,
		init_cb,
		ext_cb,
		user_data,
		on_close_cb,
	)
}

fn priv_run<
	'a,
	T: 'a,
	I: FnOnce(MyUnique<WebView<'a, T>>),
	F: FnMut(&mut WebView<'a, T>, &str, &mut T) + 'a,
	C: AsRef<str>,
	E: FnOnce(OnCloseInformation),
>(
	title: &str,
	content: Content<C>,
	size: Option<(i32, i32)>,
	resizable: bool,
	show_maximised: bool,
	fullscreen: bool,
	debug: bool,
	init_cb: I,
	ext_cb: F,
	user_data: T,
	on_close_cb: E,
) -> (T, bool) {
	let (width, height) = size.unwrap_or((800, 600));
	let title = CString::new(title).unwrap();
	let url = match content {
		Content::Url(url) => CString::new(url.as_ref()).unwrap(),
		Content::Html(html) => {
			CString::new(format!("data:text/html,{}", encode(html.as_ref()))).unwrap()
		}
	};
	let mut handler_data = Box::new(HandlerData {
		ext_cb: Box::new(ext_cb),
		index: 0,
		dispatched_cbs: Default::default(),
		user_data,
	});
	let webview = unsafe {
		wrapper_webview_new(
			title.as_ptr(),
			url.as_ptr(),
			width,
			height,
			resizable as c_int,
			show_maximised as c_int,
			debug as c_int,
			Some(transmute(handler_ext::<T> as ExternalInvokeFn<T>)),
			&mut *handler_data as *mut _ as *mut c_void,
		)
	};
	if webview.is_null() {
		(handler_data.user_data, false)
	} else {
		unsafe {
			webview_set_fullscreen(webview, fullscreen as _);
		}
		init_cb(MyUnique(webview as _));
		unsafe {
			while webview_loop(webview, 1) == 0 {}
			let close = OnCloseInformation {
				height: wrapper_webview_get_height(webview),
				width: wrapper_webview_get_width(webview),
				top: wrapper_webview_get_top(webview),
				left: wrapper_webview_get_left(webview),
			};
			on_close_cb(close);
			webview_exit(webview);
			wrapper_webview_free(webview);
		}
		(handler_data.user_data, true)
	}
}

struct HandlerData<'a, T: 'a> {
	ext_cb: Box<FnMut(&mut WebView<'a, T>, &str, &mut T) + 'a>,
	index: usize,
	dispatched_cbs: HashMap<usize, Box<FnMut(&mut WebView<'a, T>, &mut T) + Send + 'a>>,
	user_data: T,
}

pub struct WebView<'a, T: 'a>(PhantomData<&'a mut T>);

pub struct MyUnique<T>(*mut T);
unsafe impl<T> Send for MyUnique<T> {}
unsafe impl<T> Sync for MyUnique<T> {}

impl<'a, T> MyUnique<WebView<'a, T>> {
	#[inline(always)]
	pub fn dispatch<F: for<'b> FnMut(&mut WebView<'b, T>, &mut T) + Send /*+ 'a*/>(&self, f: F) {
		unsafe { &mut *self.0 }.dispatch(f);
	}
}

impl<'a, T> WebView<'a, T> {
	#[inline(always)]
	fn erase(&mut self) -> *mut CWebView {
		self as *mut _ as *mut _
	}

	#[inline(always)]
	fn get_userdata(&mut self) -> &mut HandlerData<T> {
		let user_data = unsafe { wrapper_webview_get_userdata(self.erase()) };
		let data: &mut HandlerData<T> = unsafe { &mut *(user_data as *mut HandlerData<T>) };
		data
	}

	pub fn terminate(&mut self) {
		unsafe { webview_terminate(self.erase()) }
	}

	pub fn dispatch<F: for<'b> FnMut(&mut WebView<'b, T>, &mut T) + Send /*+ 'a*/>(
		&'a mut self,
		f: F,
	) {
		let erased = self.erase();
		let index = {
			let data = self.get_userdata();
			let index = data.index;
			data.index += 1;
			data.dispatched_cbs.insert(index, Box::new(f));
			index
		};
		unsafe {
			webview_dispatch(
				erased,
				Some(transmute(handler_dispatch as DispatchFn<T>)),
				index as _,
			)
		}
	}

	pub fn eval(&mut self, js: &str) -> i32 {
		let js = CString::new(js).unwrap();
		unsafe { webview_eval(self.erase(), js.as_ptr()) }
	}

	pub fn inject_css(&mut self, css: &str) -> i32 {
		let css = CString::new(css).unwrap();
		unsafe { webview_inject_css(self.erase(), css.as_ptr()) }
	}

	pub fn dialog(&mut self, dialog: Dialog, title: &str, arg: &str) -> String {
		let (dtype, dflags) = dialog.parameters();
		let mut s = [0u8; 4096];

		unsafe {
			webview_dialog(
				self.erase(),
				dtype,
				dflags,
				CString::new(title).unwrap().as_ptr(),
				CString::new(arg).unwrap().as_ptr(),
				s.as_mut_ptr() as _,
				s.len(),
			);
		}

		read_str(&s)
	}
}

fn read_str(s: &[u8]) -> String {
	use std::ffi::CStr;
	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(),
	}
}

type ExternalInvokeFn<'a, T> = extern "system" fn(webview: *mut WebView<'a, T>, arg: *const c_char);
type DispatchFn<'a, T> = extern "system" fn(webview: *mut WebView<'a, T>, arg: *mut c_void);

extern "system" fn handler_dispatch<'a, T>(webview: *mut WebView<'a, T>, arg: *mut c_void) {
	let data = unsafe { (*webview).get_userdata() };
	let i = arg as _;
	use std::collections::hash_map::Entry;
	if let Entry::Occupied(mut e) = data.dispatched_cbs.entry(i) {
		e.get_mut()(unsafe { &mut *webview }, &mut data.user_data);
		e.remove_entry();
	} else {
		unreachable!();
	}
}

extern "system" fn handler_ext<'a, T>(webview: *mut WebView<'a, T>, arg: *const c_char) {
	let data = unsafe { (*webview).get_userdata() };
	let arg = unsafe { CStr::from_ptr(arg) }.to_string_lossy().to_string();
	(data.ext_cb)(unsafe { &mut *webview }, &arg, &mut data.user_data);
}