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
use std::{ops::DerefMut, path::PathBuf, pin::Pin, vec::Vec};

#[cfg(feature = "threadsafe")]
use unsafe_send_sync::UnsafeSend;

use crate::{
	application::ApplicationHandle,
	browser::*,
	core::{browser_window::*, window::*},
	window::WindowBuilder,
};

/// The type of content to display in a browser window
pub enum Source {
	/// Displays the given HTML code in the browser.
	Html(String),
	/// Displays the local file for the given path.
	File(PathBuf),
	/// Displays the given URL in the browser.
	Url(String),
}

#[cfg(not(feature = "threadsafe"))]
type BrowserJsInvocationHandler =
	Box<dyn FnMut(BrowserWindowHandle, String, Vec<JsValue>) -> Pin<Box<dyn Future<Output = ()>>>>;
#[cfg(feature = "threadsafe")]
type BrowserJsInvocationHandler = Box<
	dyn FnMut(BrowserWindowHandle, String, Vec<JsValue>) -> Pin<Box<dyn Future<Output = ()>>>
		+ Send,
>;

/// The data that is passed to the C FFI handler function
struct BrowserUserData {
	handler: BrowserJsInvocationHandler,
}

/// Used to create a [`BrowserWindow`] or [`BrowserWindowThreaded`] instance,
/// depending on whether or not you have feature `threadsafe` enabled.
///
/// ```ignore
/// let mut bwb = BrowserWindowBuilder::new(Source::Url("https://www.duckduckgo.com".into()))
/// bwb.dev_tools(true);
/// bwb.title("DuckDuckGo");
/// let bw = bwb.build( app );
/// ```
pub struct BrowserWindowBuilder {
	dev_tools: bool,
	handler: Option<BrowserJsInvocationHandler>,
	source: Source,
	window: WindowBuilder,
}

impl BrowserWindowBuilder {
	/// Configure a closure that can be invoked from within JavaScript.
	/// The closure's second parameter specifies a command name.
	/// The closure's third parameter specifies an array of string arguments.
	#[cfg(not(feature = "threadsafe"))]
	pub fn async_handler<H, F>(&mut self, mut handler: H) -> &mut Self
	where
		H: FnMut(BrowserWindowHandle, String, Vec<JsValue>) -> F + 'static,
		F: Future<Output = ()> + 'static,
	{
		self.handler = Some(Box::new(move |handle, cmd, args| {
			Box::pin(handler(handle, cmd, args))
		}));
		self
	}

	/// Configure a closure that can be invoked from within JavaScript.
	/// The closure's second parameter specifies a command name.
	/// The closure's third parameter specifies an array of string arguments.
	#[cfg(feature = "threadsafe")]
	pub fn async_handler<H, F>(&mut self, mut handler: H) -> &mut Self
	where
		H: FnMut(BrowserWindowHandle, String, Vec<JsValue>) -> F + Send + 'static,
		F: Future<Output = ()> + 'static,
	{
		self.handler = Some(Box::new(move |handle, cmd, args| {
			Box::pin(handler(handle, cmd, args))
		}));
		self
	}

	/// Sets whether or not an extra window with developer tools will be opened
	/// together with this browser. When in debug mode the default is `true`.
	/// When in release mode the default is `false`.
	pub fn dev_tools(&mut self, enabled: bool) -> &mut Self {
		self.dev_tools = enabled;
		self
	}

	/// Creates an instance of a browser window builder.
	///
	/// # Arguments
	/// * `source` - The content that will be displayed in the browser window.
	pub fn new(source: Source) -> Self {
		Self {
			dev_tools: false,
			source,
			handler: None,
			window: WindowBuilder::new(),
		}
	}

	/// Creates the browser window.
	///
	/// # Arguments
	/// * `app` - An application handle that this browser window can spawn into
	pub async fn build(self, app: ApplicationHandle) -> BrowserWindow {
		let (tx, rx) = oneshot::channel::<BrowserWindowHandle>();

		self._build(app, move |handle| {
			if let Err(_) = tx.send(handle) {
				panic!("Unable to send browser handle back")
			}
		});

		BrowserWindow::new(rx.await.unwrap())
	}

	/// Creates the browser window.
	///
	/// Keep in mind that the description of this function is for when feature
	/// `threadsafe` is enabled. When it is not enabled, it looks like this:
	/// ```ignore
	/// pub async fn build( self, app: ApplicationHandle ) -> Result<BrowserWindowThreaded, DelegateError> { /* ... */ }
	/// ```
	///
	/// # Arguments
	/// * `app` - An (thread-safe) application handle.
	#[cfg(feature = "threadsafe")]
	pub async fn build_threaded(
		self, app: ApplicationHandleThreaded,
	) -> Result<BrowserWindowThreaded, DelegateError> {
		let (tx, rx) = oneshot::channel::<UnsafeSend<BrowserWindowHandle>>();

		// We need to dispatch the spawning of the browser to the GUI thread
		app.delegate(|app_handle| {
			self._build(app_handle, |inner_handle| {
				if let Err(_) = tx.send(UnsafeSend::new(inner_handle)) {
					panic!("Unable to send browser handle back")
				}
			});
		})
		.await?;

		Ok(BrowserWindowThreaded::new(rx.await.unwrap().i))
	}

	fn _build<H>(self, app: ApplicationHandle, on_created: H)
	where
		H: FnOnce(BrowserWindowHandle),
	{
		match self {
			Self {
				source,
				handler,
				dev_tools,
				window,
			} => {
				// Parent
				let parent_handle = match window.parent {
					None => WindowImpl::default(),
					Some(p) => p.i.inner,
				};

				// Title
				let title = match window.title.as_ref() {
					None => "Browser Window".into(),
					Some(t) => t.as_str().into(),
				};

				// Handler callback data
				let user_data = Box::into_raw(Box::new(BrowserUserData {
					handler: match handler {
						Some(f) => f,
						None => Box::new(|_, _, _| Box::pin(async {})),
					},
				}));
				let callback_data: *mut Box<dyn FnOnce(BrowserWindowHandle)> =
					Box::into_raw(Box::new(Box::new(on_created)));

				// Convert options to FFI structs
				let window_options = WindowOptions {
					borders: window.borders,
					minimizable: window.minimizable,
					resizable: window.resizable,
				};
				let other_options = BrowserWindowOptions {
					dev_tools: if dev_tools { 1 } else { 0 },
					resource_path: "".into(),
				};

				BrowserWindowImpl::new(
					app.inner,
					parent_handle,
					source,
					title,
					window.width,
					window.height,
					&window_options,
					&other_options,
					browser_window_invoke_handler,
					user_data as _,
					browser_window_created_callback,
					callback_data as _,
				);
			}
		}
	}
}

impl Deref for BrowserWindowBuilder {
	type Target = WindowBuilder;

	fn deref(&self) -> &Self::Target { &self.window }
}

impl DerefMut for BrowserWindowBuilder {
	fn deref_mut(&mut self) -> &mut Self::Target { &mut self.window }
}

/// The data that is passed to the creation callback function
//type BrowserCreationCallbackData<'a> = Box<dyn FnOnce( BrowserHandle ) + 'a>;

/// Takes the arguments received from the C FFI handler callback, and converts
/// it to a vector of strings
/*fn args_to_vec( args: *const cbw_CStrSlice, args_count: usize ) -> Vec<String> {

	let mut vec = Vec::with_capacity( args_count );

	for i in 0..args_count {
		let str_arg: String = unsafe { *args.offset(i as _) }.into();

		vec.push( str_arg );
	}

	vec
}*/

/// This external C function will be invoked by the underlying implementation
/// browser-window when it is invoked in JavaScript
/*unsafe extern "C" fn ffi_window_invoke_handler( inner_handle: *mut bw_BrowserWindow, _command: bw_CStrSlice, _args: *mut bw_CStrSlice, args_count: u64 ) {

	let data_ptr: *mut BrowserUserData = mem::transmute( bw_BrowserWindow_getUserData( inner_handle ) );
	let data: &mut BrowserUserData = &mut *data_ptr;

	match data {
		BrowserUserData{ handler } => {
			let outer_handle = BrowserWindowHandle::new( inner_handle );

			let args = args_to_vec( _args, args_count as _ );

			let future = handler( outer_handle, _command.into(), args );
			outer_handle.app().spawn( future );
		}
	}
}*/

fn browser_window_invoke_handler(inner_handle: BrowserWindowImpl, cmd: &str, args: Vec<JsValue>) {
	let data_ptr: *mut BrowserUserData = inner_handle.user_data() as _;
	let data = unsafe { &mut *data_ptr };

	match data {
		BrowserUserData { handler } => {
			let outer_handle = BrowserWindowHandle::new(inner_handle);

			let future = handler(outer_handle.clone(), cmd.into(), args);
			outer_handle.app().spawn(future);
		}
	}
}

fn browser_window_created_callback(inner_handle: BrowserWindowImpl, data: *mut ()) {
	let data_ptr = data as *mut Box<dyn FnOnce(BrowserWindowHandle)>;
	let func = unsafe { Box::from_raw(data_ptr) };

	let outer_handle = BrowserWindowHandle::new(inner_handle);

	func(outer_handle)
}