//! Sciter host application helpers. use ::{_API}; use capi::scdef::SCITER_RT_OPTIONS; use capi::sctypes::*; use capi::screquest::HREQUEST; use capi::schandler::NativeHandler; use dom::event::EventHandler; use eventhandler::*; use value::{Value}; pub use capi::scdef::{LOAD_RESULT, OUTPUT_SUBSYTEMS, OUTPUT_SEVERITY}; pub use capi::scdef::{SCN_LOAD_DATA, SCN_DATA_LOADED, SCN_ATTACH_BEHAVIOR, SCN_INVALIDATE_RECT}; /// A specialized `Result` type for Sciter host operations. pub type Result = ::std::result::Result; macro_rules! ok_or { ($ok:ident) => { if $ok != 0 { Ok(()) } else { Err(()) } }; ($ok:ident, $rv:expr) => { if $ok != 0 { Ok($rv) } else { Err(()) } }; ($ok:ident, $rv:expr, $err:expr) => { if $ok != 0 { Ok($rv) } else { Err($err) } }; } /** Sciter notification handler for [`Window.sciter_handler()`](../window/struct.Window.html#method.sciter_handler). ## Resource handling and custom resource loader HTML loaded into Sciter may contain external resources: CSS (Cascading Style Sheets), images, fonts, cursors and scripts. To get any of such resources Sciter will first send a `on_data_load(SCN_LOAD_DATA)` notification to your application using the callback handler registered with `sciter::Window.sciter_handler()` function. Your application can provide your own data for such resources (for example, from the resource section, database or other storage of your choice) or delegate the resource loading to the built-in HTTP client or file loader, or discard the loading at all. Note: This handler should be registered before any [`load_html()`](struct.Host.html#method.load_html) or [`load_file()`](struct.Host.html#method.load_file) calls in order to send notifications while loading. */ #[allow(unused_variables)] pub trait HostHandler { /// Notifies that Sciter is about to download the referred resource. /// /// You can load or overload data immediately by calling `self.data_ready()` with parameters provided by `SCN_LOAD_DATA`, /// or save them (including `request_id`) for later usage and answer here with `LOAD_RESULT::LOAD_DELAYED` code. /// /// Also you can discard the request (data will not be loaded at the document) /// or take care about this request completely by yourself (via the [request API](../request/index.html)). fn on_data_load(&mut self, pnm: &mut SCN_LOAD_DATA) -> Option { return None; } /// This notification indicates that external data (for example, image) download process completed. fn on_data_loaded(&mut self, pnm: &SCN_DATA_LOADED) { } /// This notification is sent on parsing the document and while processing elements /// having non empty `behavior: ` style attribute value. fn on_attach_behavior(&mut self, pnm: &mut SCN_ATTACH_BEHAVIOR) -> bool { return false; } /// This notification is sent when instance of the engine is destroyed. fn on_engine_destroyed(&mut self) { } /// This notification is sent when the engine encounters critical rendering error: e.g. DirectX gfx driver error. /// Most probably bad gfx drivers. fn on_graphics_critical_failure(&mut self) { } /// This notification is sent when the engine needs some area to be redrawn. fn on_invalidate(&mut self, pnm: &SCN_INVALIDATE_RECT) {} /// This output function will be used for reporting problems found while loading html and css documents. fn on_debug_output(&mut self, subsystem: OUTPUT_SUBSYTEMS, severity: OUTPUT_SEVERITY, message: &str) { if !message.is_empty() { if severity == OUTPUT_SEVERITY::INFO { // e.g. `stdout.println` in TIScript println!("{:?}:{:?}: {}", severity, subsystem, message); } else { // e.g. `stderr.println` or CSS/script errors and warnings. eprintln!("{:?}:{:?}: {}", severity, subsystem, message); } } } /// This function is used as response to [`on_data_load`](#method.on_data_load) request. /// /// Parameters here must be taken from [`SCN_LOAD_DATA`](struct.SCN_LOAD_DATA.html) structure. You can store them for later usage, /// but you must answer as [`LOAD_DELAYED`](enum.LOAD_RESULT.html#variant.LOAD_DELAYED) code and provide an `request_id` here. fn data_ready(&self, hwnd: HWINDOW, uri: &str, data: &[u8], request_id: Option) { let s = s2w!(uri); match request_id { Some(req) => { (_API.SciterDataReadyAsync)(hwnd, s.as_ptr(), data.as_ptr(), data.len() as UINT, req) }, None => { (_API.SciterDataReady)(hwnd, s.as_ptr(), data.as_ptr(), data.len() as UINT) }, }; } /// This function is used as a response to the [`on_attach_behavior`](#method.on_attach_behavior) request /// to attach a newly created behavior `handler` to the requested element. fn attach_behavior(&self, pnm: &mut SCN_ATTACH_BEHAVIOR, handler: Handler) { // make native handler let boxed = Box::new(handler); let ptr = Box::into_raw(boxed); // dropped in `_event_handler_proc` pnm.elementProc = ::eventhandler::_event_handler_proc::; pnm.elementTag = ptr as LPVOID; } } /// Default `HostHandler` implementation #[derive(Default)] struct DefaultHandler; /// Default `HostHandler` implementation impl HostHandler for DefaultHandler { } use std::rc::Rc; use std::cell::RefCell; type BehaviorList = Vec<(String, Box Box>)>; type SharedBehaviorList = Rc>; type SharedArchive = Rc>>; #[repr(C)] struct HostCallback { sig: u32, behaviors: SharedBehaviorList, handler: Callback, archive: SharedArchive, } /// Sciter host runtime support. pub struct Host { hwnd: HWINDOW, behaviors: SharedBehaviorList, handler: RefCell, archive: SharedArchive, } impl Host { /// Attach Sciter host to existing window. /// /// Usually Sciter window created by a [`sciter::Window::create()`](../window/struct.Window.html#method.create), /// but you can attach Sciter to an existing native window. /// In this case you need to mix-in window events processing with `SciterProcND` (Windows only). /// Sciter engine will be initialized either on `WM_CREATE` or `WM_INITDIALOG` response /// or by calling `SciterCreateOnDirectXWindow` (again, Windows only). pub fn attach(hwnd: HWINDOW) -> Host { // Host with default debug handler installed let host = Host { hwnd, behaviors: Default::default(), handler: Default::default(), archive: Default::default(), }; host.setup_callback(DefaultHandler::default()); return host; } /// Attach Sciter host to an existing window with the given Host handler. pub fn attach_with(hwnd: HWINDOW, handler: Handler) -> Host { let host = Host { hwnd, behaviors: Default::default(), handler: Default::default(), archive: Default::default(), }; host.setup_callback(handler); return host; } /// Attach [`dom::EventHandler`](../dom/event/trait.EventHandler.html) to the Sciter window. pub fn event_handler(&self, handler: Handler) { self.attach_handler(handler) } /// Attach [`dom::EventHandler`](../dom/event/trait.EventHandler.html) to the Sciter window. #[doc(hidden)] pub fn attach_handler(&self, handler: Handler) { let hwnd = self.get_hwnd(); let boxed = Box::new( WindowHandler { hwnd, handler } ); let ptr = Box::into_raw(boxed); // dropped in `_event_handler_window_proc` // eprintln!("{}: {:?}", std::any::type_name::(), ptr); let func = _event_handler_window_proc::; let flags = ::dom::event::default_events(); (_API.SciterWindowAttachEventHandler)(hwnd, func, ptr as LPVOID, flags as UINT); } /// Set callback for Sciter engine events. pub(crate) fn setup_callback(&self, handler: Callback) { let payload: HostCallback = HostCallback { sig: 17, behaviors: Rc::clone(&self.behaviors), archive: Rc::clone(&self.archive), handler: handler, }; *self.handler.borrow_mut() = NativeHandler::from(payload); let ptr = self.handler.borrow().as_mut_ptr(); (_API.SciterSetCallback)(self.get_hwnd(), _on_handle_notification::, ptr); (_API.SciterSetupDebugOutput)(0 as HWINDOW, ptr, _on_debug_notification::); } /// Register a native event handler for the specified behavior name. /// /// See the [`Window::register_behavior`](../window/struct.Window.html#method.register_behavior) for an example. pub fn register_behavior(&self, name: &str, factory: Factory) where Factory: Fn() -> Box + 'static { let make: Box Box> = Box::new(factory); let pair = (name.to_owned(), make); self.behaviors.borrow_mut().push(pair); } /// Register an archive produced by `packfolder`. /// /// See documentation of the [`Archive`](struct.Archive.html). pub fn register_archive(&self, resource: &[u8]) -> Result<()> { *self.archive.borrow_mut() = Some(Archive::open(resource)?); Ok(()) } /// Set debug mode for this window. pub fn enable_debug(&self, enable: bool) { (_API.SciterSetOption)(self.hwnd, SCITER_RT_OPTIONS::SCITER_SET_DEBUG_MODE, enable as UINT_PTR); } /// Get native window handle. pub fn get_hwnd(&self) -> HWINDOW { self.hwnd } /// Get window root DOM element. pub fn get_root(&self) -> Option<::dom::Element> { ::dom::Element::from_window(self.hwnd).ok() } /// Load an HTML document from file. pub fn load_file(&self, uri: &str) -> bool { // TODO: it should be `Result<()>` instead `bool` let s = s2w!(uri); (_API.SciterLoadFile)(self.hwnd, s.as_ptr()) != 0 } /// Load an HTML document from memory. pub fn load_html(&self, html: &[u8], uri: Option<&str>) -> bool { match uri { Some(uri) => { let s = s2w!(uri); (_API.SciterLoadHtml)(self.hwnd, html.as_ptr(), html.len() as UINT, s.as_ptr()) != 0 }, None => { (_API.SciterLoadHtml)(self.hwnd, html.as_ptr(), html.len() as UINT, 0 as LPCWSTR) != 0 } } } /// This function is used as response to [`HostHandler::on_data_load`](trait.HostHandler.html#method.on_data_load) request. pub fn data_ready(&self, uri: &str, data: &[u8]) { let s = s2w!(uri); (_API.SciterDataReady)(self.hwnd, s.as_ptr(), data.as_ptr(), data.len() as UINT); } /// Use this function outside of [`HostHandler::on_data_load`](trait.HostHandler.html#method.on_data_load) request. /// /// It can be used for two purposes: /// /// 1. Asynchronious resource loading in respect of [`on_data_load`](trait.HostHandler.html#method.on_data_load) /// requests (you must use `request_id` in this case). /// 2. Refresh of an already loaded resource (for example, dynamic image updates). pub fn data_ready_async(&self, uri: &str, data: &[u8], request_id: Option) { let s = s2w!(uri); let req = request_id.unwrap_or(::std::ptr::null_mut()); (_API.SciterDataReadyAsync)(self.hwnd, s.as_ptr(), data.as_ptr(), data.len() as UINT, req); } /// Evaluate the given script in context of the current document. /// /// This function returns `Result` with script function result value or with Sciter script error. pub fn eval_script(&self, script: &str) -> ::std::result::Result { let (s,n) = s2wn!(script); let mut rv = Value::new(); let ok = (_API.SciterEval)(self.hwnd, s.as_ptr(), n, rv.as_ptr()); ok_or!(ok, rv, rv) } /// Call a script function defined in the global namespace. /// /// This function returns `Result` with script function result value or with Sciter script error. /// /// You can use the [`&make_args!(args...)`](../macro.make_args.html) macro which helps you /// to construct script arguments from Rust types. pub fn call_function(&self, name: &str, args: &[Value]) -> ::std::result::Result { let mut rv = Value::new(); let s = s2u!(name); let argv = Value::pack_args(args); let ok = (_API.SciterCall)(self.hwnd, s.as_ptr(), argv.len() as UINT, argv.as_ptr(), rv.as_ptr()); ok_or!(ok, rv, rv) } /// Set home url for Sciter resources. /// /// If you set it like `set_home_url("https://sciter.com/modules/")` then /// /// `