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
use browser_window_ffi::*;
use futures_channel::oneshot;
use std::{
	error::Error,
	ffi::CStr,
	fmt,
	marker::PhantomData,
	ops::Deref,
	os::raw::*,
	rc::Rc
};

use crate::application::*;
use crate::common::*;

pub mod builder;

pub use builder::BrowserBuilder;



//type BrowserJsCallbackData<'a> = Box<dyn FnOnce(Browser, Result<String, JsEvaluationError>) + 'a>;

//type BrowserJsThreadedCallbackData<'a> = SendBoxFnOnce<'a,(BrowserHandle, Result<String, JsEvaluationError>),()>;


/// The future that dispatches a closure on the GUI thread.

pub type BrowserDelegateFuture<'a,R> = DelegateFuture<'a, BrowserHandle, R>;



/// A thread-unsafe handle to a browser window

// If the user closes the window, this handle remains valid.

// Also, if you lose this handle, window destruction and cleanup is only done when the user actually closes it.

// So you don't have to worry about lifetimes and/or propper destruction of the window either.

pub struct Browser {
	pub(in super) handle: BrowserHandle,
	_not_send: PhantomData<Rc<()>>
}

/// A thread-safe handle to a browser window.

/// It allows you to dispatch code to the GUI thread.

// It provides the same functionality as `Browser`.

// However, each function is async: it runs on the GUI thread, and returns when it is done.

pub struct BrowserThreaded {
	pub(in super) handle: BrowserHandle
}
unsafe impl Sync for BrowserThreaded {}

#[derive(Clone, Copy)]
pub struct BrowserHandle {
	pub(in super) ffi_handle: *mut bw_BrowserWindow
}
unsafe impl Send for BrowserHandle {}

/// An error that may occur when evaluating or executing JavaScript code.

#[derive(Debug)]
pub struct JsEvaluationError {
	message: String
	// TODO: Add line and column number files, and perhaps even more info about the JS error

}



impl Browser {

	/// Returns the application handle associated with this browser window.

	pub fn app( &self ) -> Application {
		Application::from_ffi_handle( unsafe { bw_BrowserWindow_getApp( self.handle.ffi_handle ) } )
	}

	/// Closes the browser.

	// The browser will be freed from memory when the last handle to it gets dropped.

	pub fn close( self ) {
		unsafe { bw_BrowserWindow_close( self.handle.ffi_handle ); }
	}

	/// Executes the given javascript code and returns the output as a string.

	/// If you don't need the result, see `exec_js`.

	pub async fn eval_js( &self, js: &str ) -> Result<String, JsEvaluationError> {
		let (tx, rx) = oneshot::channel::<Result<String, JsEvaluationError>>();

		self._eval_js( js, |_, result| {
			if let Err(_) = tx.send( result ) {
				panic!("Unable to send JavaScript result back")
			}
		} );

		rx.await.unwrap()
	}

	fn _eval_js<'a,H>( &self, js: &str, on_complete: H ) where
		H: FnOnce( Browser, Result<String, JsEvaluationError> ) + 'a
	{
		let data_ptr: *mut H = Box::into_raw(
			Box::new( on_complete )
		);

		unsafe { bw_BrowserWindow_evalJs(
			self.handle.ffi_handle,
			js.into(),
			ffi_eval_js_callback::<H>,
			data_ptr as _
		) };
	}

	/// Executes the given javascript code without waiting on it to finish.

	pub fn exec_js( &self, js: &str ) {
		self._eval_js( js, |_,_|{} );
	}

	fn from_ffi_handle( ptr: *mut bw_BrowserWindow ) -> Self {
		Self {
			handle: BrowserHandle::new( ptr ),
			_not_send: PhantomData
		}
	}

	/// Causes the browser to navigate to the given url.

	pub fn navigate( &self, url: &str ) -> Result<(), Box<dyn Error + Send>> {
		let err = unsafe { bw_BrowserWindow_navigate( self.handle.ffi_handle, url.into() ) };

		if err.code == 0 {
			return Ok(());
		}

		Err( Box::new( err ) )
	}
}

impl Deref for Browser {
	type Target = BrowserHandle;

	fn deref( &self ) -> &BrowserHandle {
		&self.handle
	}
}

impl Drop for Browser {
	fn drop( &mut self ) {
		unsafe { bw_BrowserWindow_drop( self.handle.ffi_handle ) }
	}
}

impl From<BrowserHandle> for Browser {

	fn from( handle: BrowserHandle ) -> Self {
		Self {
			handle: handle,
			_not_send: PhantomData
		}
	}
}

impl HasAppHandle for Browser {

	fn app_handle( &self ) -> ApplicationHandle {
		self.handle.app_handle()
	}
}



impl BrowserThreaded {

	/// The thread-safe application handle associated with this browser window.

	pub fn app( &self ) -> ApplicationThreaded {
		ApplicationThreaded::from_ffi_handle( unsafe { bw_BrowserWindow_getApp( self.handle.ffi_handle ) } )
	}

	/// Closes the browser.

	pub fn close( self ) {
		self.dispatch(|bw| {
			bw.close()
		});
	}

	/// Executes the given closure within the GUI thread, and return the value that the closure returned.

	/// Keep in mind that in multi-threaded environments, it is generally a good idea to use a Box return type,

	///  or use something else to put the value on the heap when dealing with large types.

	pub fn delegate<'a,F,R>( &self, func: F ) -> BrowserDelegateFuture<'a,R> where
		F: FnOnce( Browser ) -> R + Send + 'a,
		R: Send
	{
		BrowserDelegateFuture::new( self.handle.clone(), |handle| {
			func( handle.into() )
		} )
	}

	/// Executes the given close on the GUI thread.

	pub fn dispatch<'a,F>( &self, func: F ) where
		F:  FnOnce( Browser ) + Send + 'a
	{
		let handle = self.handle;

		self.app().dispatch(move |_| {
			func( handle.into() );
		})
	}

	/// Executes the given javascript code, and returns the resulting output as a string when done.

	pub async fn eval_js( &self, js: &str ) -> Result<String, JsEvaluationError> {
		let (tx, rx) = oneshot::channel::<Result<String, JsEvaluationError>>();

		self._eval_js( js, |_, result| {
			if let Err(_) = tx.send( result ) {
				panic!("Unable to send JavaScript result back")
			}
		} );

		rx.await.unwrap()
	}

	/// Causes the browser to navigate to the given url.

	pub async fn navigate( &self, url: &str ) -> Result<(), Box<dyn Error + Send>> {
		self.delegate(|bw| {
			bw.navigate( url )
		}).await
	}

	fn _eval_js<'a,H>( &self, js: &str, on_complete: H ) where
		H: FnOnce( BrowserThreaded, Result<String, JsEvaluationError> ) + Send + 'a
	{
		let data_ptr: *mut H = Box::into_raw(
			Box::new( on_complete )
		);

		unsafe { bw_BrowserWindow_evalJsThreaded(
			self.handle.ffi_handle,
			js.into(),
			ffi_eval_js_threaded_callback::<H>,
			data_ptr as _
		) };
	}
}

impl Deref for BrowserThreaded {
	type Target = BrowserHandle;

	fn deref( &self ) -> &BrowserHandle {
		&self.handle
	}
}

impl Drop for BrowserThreaded {
	fn drop( &mut self ) {
		unsafe { bw_Application_dispatch( self.app().handle.ffi_handle, ffi_free_browser_window, self.handle.ffi_handle as _ ); }
	}
}

impl From<BrowserHandle> for BrowserThreaded {

	fn from( handle: BrowserHandle ) -> Self {
		Self {
			handle: handle
		}
	}
}

impl HasAppHandle for BrowserThreaded {

	fn app_handle( &self ) -> ApplicationHandle {
		self.handle.app_handle()
	}
}



impl BrowserHandle {
	fn new( ffi_handle: *mut bw_BrowserWindow ) -> Self {
		Self {
			ffi_handle: ffi_handle
		}
	}
}

impl HasAppHandle for BrowserHandle {

	fn app_handle( &self ) -> ApplicationHandle {
		ApplicationHandle::new(
			unsafe { bw_BrowserWindow_getApp( self.ffi_handle ) }
		)
	}
}



impl JsEvaluationError {
	pub(in super) unsafe fn new( err: *const bw_Err ) -> Self {

		let msg_ptr = ((*err).alloc_message)( (*err).code, (*err).data );
		let cstr = CStr::from_ptr( msg_ptr );
		let message: String = cstr.to_string_lossy().into();

		Self {
			message: message
		}
	}
}

impl Error for JsEvaluationError {
	fn source(&self) -> Option<&(dyn Error + 'static)> { None }
}

impl fmt::Display for JsEvaluationError {

	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {

		write!(f, "{}", self.message.as_str())
	}
}



/// Callback for dropping a browser window.

/// This gets dispatch to the GUI thread when a `BrowserThreaded` handle gets dropped.

unsafe extern "C" fn ffi_free_browser_window( _app: *mut bw_Application, data: *mut c_void ) {
	bw_BrowserWindow_drop( data as *mut bw_BrowserWindow );
}

unsafe extern "C" fn ffi_eval_js_callback<H>( bw: *mut bw_BrowserWindow, cb_data: *mut c_void, _result: *const c_char, error: *const bw_Err ) where
	H: FnOnce(Browser, Result<String, JsEvaluationError>)
{
	let data_ptr = cb_data as *mut H;
	let data = Box::from_raw( data_ptr );

	let (handle, result) = ffi_eval_js_callback_result( bw, _result, error );

	(*data)( handle.into(), result );
}

unsafe fn ffi_eval_js_callback_result(
	bw: *mut bw_BrowserWindow,
	result: *const c_char,
	error: *const bw_Err
) -> ( BrowserHandle, Result<String, JsEvaluationError> ) {


	// Construct a result value depending on whether the result or error parameters are set

	let result_val: Result<String, JsEvaluationError> = if error.is_null() {
		let result_str = CStr::from_ptr( result ).to_string_lossy().to_owned().to_string();
		Ok( result_str )
	}
	else {
		Err( JsEvaluationError::new( error ) )
	};

	let handle = BrowserHandle::new( bw );

	// return

	( handle, result_val )
}

/// Callback for catching JavaScript results.

///

/// # Warning

/// This may get invoked from another thread than the GUI thread, depending on the implementation of the browser engine.

unsafe extern "C" fn ffi_eval_js_threaded_callback<H>( bw: *mut bw_BrowserWindow, cb_data: *mut c_void, _result: *const c_char, error: *const bw_Err ) where
	H: FnOnce(BrowserThreaded, Result<String, JsEvaluationError>) + Send
{
	let data_ptr = cb_data as *mut H;
	let data = Box::from_raw( data_ptr );

	let (handle, result) = ffi_eval_js_callback_result( bw, _result, error );

	(*data)( handle.into(), result );
}