use super::*;
#[must_use]
pub fn web_system_theme() -> ThemeMode {
let Some(win) = window() else {
return ThemeMode::Light;
};
let matches_dark: bool = win
.match_media(WEB_DARK_MEDIA_QUERY)
.ok()
.flatten()
.map(|mql: MediaQueryList| mql.matches())
.unwrap_or(false);
if matches_dark {
ThemeMode::Dark
} else {
ThemeMode::Light
}
}
#[must_use]
pub fn web_device_pixel_ratio() -> f32 {
window()
.map(|width_val: Window| {
let raw: f64 = width_val.device_pixel_ratio();
if raw.is_finite() && raw > 0.0 {
(raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
} else {
1.0
}
})
.unwrap_or(1.0)
}
#[must_use]
pub(crate) fn web_open_external_url(url: &str) -> bool {
let Some(win) = window() else {
return false;
};
win.open_with_url_and_target_and_features(url, WEB_OPEN_TARGET_BLANK, WEB_OPEN_FEATURES_SAFE)
.is_ok()
}
pub(crate) fn web_webview_open(url: &str, title: &str) -> bool {
let Some(doc) = window().and_then(|win: Window| win.document()) else {
return false;
};
let iframe_el: Element = if let Some(existing) = doc.get_element_by_id(WEB_WEBVIEW_IFRAME_ID) {
existing
} else {
let Ok(created) = doc.create_element(WEB_TAG_IFRAME) else {
return false;
};
drop(created.set_attribute(WEB_ATTR_ID, WEB_WEBVIEW_IFRAME_ID));
drop(created.set_attribute(WEB_ATTR_REFERRER_POLICY, WEB_REFERRER_POLICY_STRICT));
drop(created.set_attribute(WEB_ATTR_STYLE, WEB_WEBVIEW_HIDDEN_STYLE));
let Some(body_el) = doc.body() else {
return false;
};
if body_el.append_child(&created).is_err() {
return false;
}
created
};
drop(iframe_el.set_attribute(WEB_ATTR_TITLE, title));
iframe_el.set_attribute(WEB_ATTR_SRC, url).is_ok()
}
pub(crate) fn web_webview_frame(
left_px: f32,
top_px: f32,
width_px: f32,
height_px: f32,
alpha_val: f32,
) -> bool {
let Some(doc) = window().and_then(|win: Window| win.document()) else {
return false;
};
let Some(iframe_el) = doc.get_element_by_id(WEB_WEBVIEW_IFRAME_ID) else {
return false;
};
let is_empty_rect: bool = width_px < 1.0 || height_px < 1.0;
if is_empty_rect || alpha_val <= 0.005 {
return iframe_el
.set_attribute(WEB_ATTR_STYLE, WEB_WEBVIEW_HIDDEN_STYLE)
.is_ok();
}
let pointer_css: &str = if alpha_val >= 0.98 { "auto" } else { "none" };
let inline_css: String = format!(
"position:fixed;left:{left_px:.2}px;top:{top_px:.2}px;width:{width_px:.2}px;height:{height_px:.2}px;border:0;z-index:20;background:#ffffff;display:block;pointer-events:{pointer_css};opacity:{alpha_val:.3};"
);
iframe_el.set_attribute(WEB_ATTR_STYLE, &inline_css).is_ok()
}
pub(crate) fn web_webview_reload(url: &str) -> bool {
let Some(doc) = window().and_then(|win: Window| win.document()) else {
return false;
};
let Some(iframe_el) = doc.get_element_by_id(WEB_WEBVIEW_IFRAME_ID) else {
return false;
};
iframe_el.set_attribute(WEB_ATTR_SRC, url).is_ok()
}
pub(crate) fn web_webview_close() -> bool {
let Some(doc) = window().and_then(|win: Window| win.document()) else {
return false;
};
let Some(iframe_el) = doc.get_element_by_id(WEB_WEBVIEW_IFRAME_ID) else {
return false;
};
iframe_el.remove();
true
}
#[must_use]
fn web_query_viewport_css_size(
win: &Window,
doc: &Document,
fallback_w: f64,
fallback_h: f64,
) -> (f64, f64) {
if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
&& !vv.is_null()
&& !vv.is_undefined()
{
let vv_scale: f64 = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_SCALE))
.ok()
.and_then(|item_val: JsValue| item_val.as_f64())
.filter(|tex_v: &f64| tex_v.is_finite() && *tex_v > 0.0)
.unwrap_or(1.0);
if vv_scale <= WEB_PINCH_ZOOM_THRESHOLD {
let vw: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_WIDTH))
.ok()
.and_then(|bary_v: JsValue| bary_v.as_f64())
.filter(|sample_val: &f64| sample_val.is_finite() && *sample_val >= 64.0);
let vh: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_HEIGHT))
.ok()
.and_then(|item_val_primary: JsValue| item_val_primary.as_f64())
.filter(|item_val_secondary: &f64| {
item_val_secondary.is_finite() && *item_val_secondary >= 64.0
});
if let (Some(width_val), Some(height_val)) = (vw, vh) {
return (width_val, height_val);
}
}
}
if let Some(root) = doc.document_element() {
let cw: f64 = f64::from(root.client_width());
let ch: f64 = f64::from(root.client_height());
if cw >= 64.0 && ch >= 64.0 {
return (cw, ch);
}
}
let span_width: f64 = win
.inner_width()
.ok()
.and_then(|item_val_next: JsValue| item_val_next.as_f64())
.filter(|item_val_alt: &f64| item_val_alt.is_finite() && *item_val_alt >= 64.0)
.unwrap_or(fallback_w.max(64.0));
let span_height: f64 = win
.inner_height()
.ok()
.and_then(|item_val_inner: JsValue| item_val_inner.as_f64())
.filter(|item_val_local: &f64| item_val_local.is_finite() && *item_val_local >= 64.0)
.unwrap_or(fallback_h.max(64.0));
(span_width, span_height)
}
fn web_write_clipboard_exec_command(doc: &Document, text: &str) -> bool {
let Some(body) = doc.body() else {
return false;
};
let prev_active: Option<HtmlElement> = doc
.active_element()
.and_then(|el: Element| el.dyn_into::<HtmlElement>().ok());
let Ok(ta_el) = doc.create_element(WEB_TAG_TEXTAREA) else {
return false;
};
drop(ta_el.set_attribute(WEB_ATTR_READONLY, ""));
drop(ta_el.set_attribute(WEB_ATTR_COPY_PROXY, WEB_COPY_PROXY_FLAG));
drop(ta_el.set_attribute(WEB_ATTR_STYLE, WEB_COPY_PROXY_STYLE));
let _: Result<bool, JsValue> = Reflect::set(
ta_el.as_ref(),
&JsValue::from_str(WEB_PROP_VALUE),
&JsValue::from_str(text),
);
if body.append_child(&ta_el).is_err() {
return false;
}
if let Ok(ta_html) = ta_el.clone().dyn_into::<HtmlElement>() {
drop(ta_html.focus());
}
if let Ok(sel_val) = Reflect::get(ta_el.as_ref(), &JsValue::from_str(WEB_METHOD_SELECT))
&& let Ok(sel_fn) = sel_val.dyn_into::<Function>()
{
drop(sel_fn.call0(ta_el.as_ref()));
}
if let Ok(rng_val) = Reflect::get(
ta_el.as_ref(),
&JsValue::from_str(WEB_METHOD_SET_SELECTION_RANGE),
) && let Ok(rng_fn) = rng_val.dyn_into::<Function>()
{
let utf16_len: f64 = text.encode_utf16().count() as f64;
drop(rng_fn.call2(
ta_el.as_ref(),
&JsValue::from_f64(0.0),
&JsValue::from_f64(utf16_len),
));
}
let copied: bool = Reflect::get(doc.as_ref(), &JsValue::from_str(WEB_METHOD_EXEC_COMMAND))
.ok()
.and_then(|item_val: JsValue| item_val.dyn_into::<Function>().ok())
.and_then(|factor_val: Function| {
factor_val
.call1(doc.as_ref(), &JsValue::from_str(WEB_CMD_COPY))
.ok()
})
.and_then(|res: JsValue| res.as_bool())
.unwrap_or(false);
drop(body.remove_child(&ta_el));
if let Some(prev) = prev_active {
drop(prev.focus());
}
copied
}
pub(crate) fn web_write_clipboard(text: &str) -> bool {
let Some(win) = window() else {
return false;
};
let exec_ok: bool = win
.document()
.map(|doc: Document| web_write_clipboard_exec_command(&doc, text))
.unwrap_or(false);
let nav: Navigator = win.navigator();
let mut async_ok: bool = false;
if let Ok(clip) = Reflect::get(nav.as_ref(), &JsValue::from_str(WEB_PROP_CLIPBOARD))
&& !clip.is_null()
&& !clip.is_undefined()
&& let Ok(write_val) = Reflect::get(&clip, &JsValue::from_str(WEB_METHOD_WRITE_TEXT))
&& let Ok(write_fn) = write_val.dyn_into::<Function>()
&& let Ok(promise_val) = write_fn.call1(&clip, &JsValue::from_str(text))
{
async_ok = true;
if let Ok(catch_val) = Reflect::get(&promise_val, &JsValue::from_str(WEB_METHOD_CATCH))
&& let Ok(catch_fn) = catch_val.dyn_into::<Function>()
{
let noop: Function = Function::new_no_args(WEB_JS_NOOP_BODY);
drop(catch_fn.call1(&promise_val, &noop));
}
}
exec_ok || async_ok
}
#[must_use]
pub(crate) fn web_document_hidden() -> bool {
window()
.and_then(|width_val: Window| width_val.document())
.map(|delta_val: Document| delta_val.hidden())
.unwrap_or(false)
}
#[must_use]
pub(crate) fn web_navigator_online() -> bool {
window()
.map(|width_val: Window| width_val.navigator().on_line())
.unwrap_or(true)
}
#[must_use]
pub(crate) fn web_navigator_locale() -> String {
window()
.and_then(|width_val: Window| width_val.navigator().language())
.filter(|text_value: &String| !text_value.trim().is_empty())
.unwrap_or_else(|| DEFAULT_SYSTEM_LOCALE.to_string())
}
#[must_use]
fn web_read_css_px_prop(style_decl: &JsValue, get_prop_fn: &Function, prop_name: &str) -> f32 {
let Ok(raw_val) = get_prop_fn.call1(style_decl, &JsValue::from_str(prop_name)) else {
return 0.0;
};
let Some(text) = raw_val.as_string() else {
return 0.0;
};
parse_css_safe_area_px(&text)
}
fn web_ensure_safe_area_probe(doc: &Document) -> Option<Element> {
if let Some(existing) = doc.get_element_by_id(WEB_SAFE_PROBE_ID) {
return Some(existing);
}
let probe: Element = doc.create_element(WEB_TAG_DIV).ok()?;
drop(probe.set_attribute(WEB_ATTR_ID, WEB_SAFE_PROBE_ID));
drop(probe.set_attribute(WEB_ATTR_STYLE, WEB_SAFE_PROBE_STYLE));
let parent: Element = doc
.body()
.map(|blue_val: HtmlElement| blue_val.into())
.or_else(|| doc.document_element())?;
drop(parent.append_child(probe.as_ref()));
Some(probe)
}
#[must_use]
pub fn web_query_safe_area_insets() -> SafeAreaInsets {
let Some(win) = window() else {
return SafeAreaInsets::default();
};
let Some(doc): Option<Document> = win.document() else {
return SafeAreaInsets::default();
};
let Ok(get_style_val) = Reflect::get(
win.as_ref(),
&JsValue::from_str(WEB_METHOD_GET_COMPUTED_STYLE),
) else {
return SafeAreaInsets::default();
};
let Ok(get_style_fn) = get_style_val.dyn_into::<Function>() else {
return SafeAreaInsets::default();
};
let mut probe_insets: SafeAreaInsets = SafeAreaInsets::default();
if let Some(probe) = web_ensure_safe_area_probe(&doc)
&& let Ok(style_decl) = get_style_fn.call1(win.as_ref(), probe.as_ref())
&& let Ok(get_prop_val) = Reflect::get(
&style_decl,
&JsValue::from_str(WEB_METHOD_GET_PROPERTY_VALUE),
)
&& let Ok(get_prop_fn) = get_prop_val.dyn_into::<Function>()
{
probe_insets = SafeAreaInsets::new(
web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_PADDING_TOP),
web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_PADDING_RIGHT),
web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_PADDING_BOTTOM),
web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_PADDING_LEFT),
);
}
if probe_insets != SafeAreaInsets::default() {
return probe_insets;
}
let Some(root): Option<Element> = doc.document_element() else {
return SafeAreaInsets::default();
};
let Ok(style_decl) = get_style_fn.call1(win.as_ref(), root.as_ref()) else {
return SafeAreaInsets::default();
};
let Ok(get_prop_val) = Reflect::get(
&style_decl,
&JsValue::from_str(WEB_METHOD_GET_PROPERTY_VALUE),
) else {
return SafeAreaInsets::default();
};
let Ok(get_prop_fn) = get_prop_val.dyn_into::<Function>() else {
return SafeAreaInsets::default();
};
let top: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_TOP);
let right: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_RIGHT);
let bottom: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_BOTTOM);
let left: f32 = web_read_css_px_prop(&style_decl, &get_prop_fn, WEB_CSS_SAFE_LEFT);
SafeAreaInsets::new(top, right, bottom, left)
}
#[must_use]
pub fn web_has_webgpu() -> bool {
let Some(win) = window() else {
return false;
};
let nav: Navigator = win.navigator();
Reflect::get(nav.as_ref(), &JsValue::from_str(WEB_PROP_GPU))
.map(|val: JsValue| !val.is_undefined() && !val.is_null())
.unwrap_or(false)
}
#[must_use]
pub fn web_attach_resize_observer(
canvas: &HtmlCanvasElement,
callback: &Function,
) -> Option<Object> {
let win: Window = window()?;
let ctor_val: JsValue =
Reflect::get(win.as_ref(), &JsValue::from_str(WEB_CTOR_RESIZE_OBSERVER)).ok()?;
let ctor_fn: Function = ctor_val.dyn_into::<Function>().ok()?;
let args_obj: Object = Object::new();
let _: bool = Reflect::set(
args_obj.as_ref(),
&JsValue::from_str(WEB_REFLECT_ARG0_KEY),
callback.as_ref(),
)
.ok()?;
let ro_val: JsValue = Reflect::construct(&ctor_fn, &Object::values(&args_obj)).ok()?;
let observe_val: JsValue =
Reflect::get(&ro_val, &JsValue::from_str(WEB_METHOD_OBSERVE)).ok()?;
let observe_fn: Function = observe_val.dyn_into::<Function>().ok()?;
let _: JsValue = observe_fn.call1(&ro_val, canvas.as_ref()).ok()?;
ro_val.dyn_into::<Object>().ok()
}
pub fn web_disconnect_resize_observer(observer: &Object) {
if let Ok(disc_val) = Reflect::get(observer.as_ref(), &JsValue::from_str(WEB_METHOD_DISCONNECT))
&& let Ok(disc_fn) = disc_val.dyn_into::<Function>()
{
drop(disc_fn.call0(observer.as_ref()));
}
}
#[must_use]
fn web_gl2_context_options() -> Object {
let opts: Object = Object::new();
let _: Result<bool, JsValue> = Reflect::set(
opts.as_ref(),
&JsValue::from_str(WEB_GL_OPT_ALPHA),
&JsValue::from_bool(false),
);
let _: Result<bool, JsValue> = Reflect::set(
opts.as_ref(),
&JsValue::from_str(WEB_GL_OPT_ANTIALIAS),
&JsValue::from_bool(false),
);
let _: Result<bool, JsValue> = Reflect::set(
opts.as_ref(),
&JsValue::from_str(WEB_GL_OPT_DEPTH),
&JsValue::from_bool(false),
);
let _: Result<bool, JsValue> = Reflect::set(
opts.as_ref(),
&JsValue::from_str(WEB_GL_OPT_DESYNCHRONIZED),
&JsValue::from_bool(false),
);
let _: Result<bool, JsValue> = Reflect::set(
opts.as_ref(),
&JsValue::from_str(WEB_GL_OPT_POWER_PREF),
&JsValue::from_str(WEB_GL_OPT_HIGH_PERFORMANCE),
);
let _: Result<bool, JsValue> = Reflect::set(
opts.as_ref(),
&JsValue::from_str(WEB_GL_OPT_PRESERVE_DRAWING),
&JsValue::from_bool(false),
);
opts
}
fn web_configure_gl2_unpack_state(gl: &WebGl2RenderingContext) {
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ALIGNMENT, 4);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_FLIP_Y_WEBGL, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
gl.pixel_storei(
WebGl2RenderingContext::UNPACK_COLORSPACE_CONVERSION_WEBGL,
WebGl2RenderingContext::NONE as i32,
);
}
fn web_init_gl2_direct_pipeline(gl: &WebGl2RenderingContext) -> Option<WebGl2DirectPipeline> {
let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
gl.shader_source(&vs, WEB_GL2_DIRECT_VERT_SHADER);
gl.compile_shader(&vs);
let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
gl.shader_source(&fs, WEB_GL2_DIRECT_FRAG_SHADER);
gl.compile_shader(&fs);
let prog: WebGlProgram = gl.create_program()?;
gl.attach_shader(&prog, &vs);
gl.attach_shader(&prog, &fs);
gl.link_program(&prog);
let view_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&prog, WEB_GL2_UNIFORM_VIEW);
let rect_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&prog, WEB_GL2_DIRECT_UNIFORM_RECT);
let color_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&prog, WEB_GL2_DIRECT_UNIFORM_COLOR);
Some(WebGl2DirectPipeline {
program: prog,
view_loc,
rect_loc,
color_loc,
})
}
fn web_init_gl2_blit_pipeline(gl: &WebGl2RenderingContext) -> Option<WebGl2BlitPipeline> {
let vs: WebGlShader = gl.create_shader(WebGl2RenderingContext::VERTEX_SHADER)?;
gl.shader_source(&vs, WEB_GL2_BLIT_VERT_SHADER);
gl.compile_shader(&vs);
let fs: WebGlShader = gl.create_shader(WebGl2RenderingContext::FRAGMENT_SHADER)?;
gl.shader_source(&fs, WEB_GL2_BLIT_FRAG_SHADER);
gl.compile_shader(&fs);
let prog: WebGlProgram = gl.create_program()?;
gl.attach_shader(&prog, &vs);
gl.attach_shader(&prog, &fs);
gl.link_program(&prog);
gl.use_program(Some(&prog));
if let Some(loc) = gl.get_uniform_location(&prog, WEB_GL2_UNIFORM_TEX) {
gl.uniform1i(Some(&loc), 0);
}
let view_loc: Option<WebGlUniformLocation> =
gl.get_uniform_location(&prog, WEB_GL2_UNIFORM_VIEW);
web_configure_gl2_unpack_state(gl);
let texture: Option<JsValue> =
Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_CREATE_TEXTURE))
.ok()
.and_then(|item_val: JsValue| item_val.dyn_into::<Function>().ok())
.and_then(|factor_val: Function| factor_val.call0(gl.as_ref()).ok())
.filter(|blend_factor: &JsValue| {
!blend_factor.is_null() && !blend_factor.is_undefined()
});
if let Some(tex) = texture.as_ref() {
let target: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
if let Ok(bind_val) = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_BIND_TEXTURE))
&& let Ok(bind_fn) = bind_val.dyn_into::<Function>()
{
drop(bind_fn.call2(gl.as_ref(), &target, tex));
}
if let Ok(param_val) = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_TEX_PARAMETERI))
&& let Ok(param_fn) = param_val.dyn_into::<Function>()
{
let linear: JsValue = JsValue::from_f64(WebGl2RenderingContext::LINEAR as f64);
let clamp: JsValue = JsValue::from_f64(WebGl2RenderingContext::CLAMP_TO_EDGE as f64);
drop(param_fn.call3(
gl.as_ref(),
&target,
&JsValue::from_f64(WebGl2RenderingContext::TEXTURE_MIN_FILTER as f64),
&linear,
));
drop(param_fn.call3(
gl.as_ref(),
&target,
&JsValue::from_f64(WebGl2RenderingContext::TEXTURE_MAG_FILTER as f64),
&linear,
));
drop(param_fn.call3(
gl.as_ref(),
&target,
&JsValue::from_f64(WebGl2RenderingContext::TEXTURE_WRAP_S as f64),
&clamp,
));
drop(param_fn.call3(
gl.as_ref(),
&target,
&JsValue::from_f64(WebGl2RenderingContext::TEXTURE_WRAP_T as f64),
&clamp,
));
}
}
Some(WebGl2BlitPipeline {
program: prog,
texture,
view_loc,
})
}
fn web_invoke_promise_method(target: &JsValue, method: &str) -> bool {
let Ok(func_val) = Reflect::get(target, &JsValue::from_str(method)) else {
return false;
};
let Ok(func) = func_val.dyn_into::<Function>() else {
return false;
};
if let Ok(ret) = func.call0(target)
&& let Ok(promise) = ret.dyn_into::<Promise>()
{
WEB_PROMISE_NOOP_REJECT.with(|callback_fn: &Closure<dyn FnMut(JsValue)>| {
let _: Promise = promise.catch(callback_fn);
});
}
true
}
#[must_use]
fn web_doc_has_fullscreen_element(doc: &Document) -> bool {
if doc.fullscreen_element().is_some() {
return true;
}
Reflect::get(
doc.as_ref(),
&JsValue::from_str(WEB_PROP_WEBKIT_FULLSCREEN_ELEMENT),
)
.ok()
.map(|item_val: JsValue| !item_val.is_null() && !item_val.is_undefined())
.unwrap_or(false)
}
pub fn web_set_fullscreen(enabled: bool) {
let Some(doc) = window().and_then(|width_val: Window| width_val.document()) else {
return;
};
let is_fs: bool = web_doc_has_fullscreen_element(&doc);
if enabled {
if !is_fs
&& let Some(root) = doc.document_element()
&& !web_invoke_promise_method(root.as_ref(), WEB_METHOD_REQUEST_FULLSCREEN)
{
let _: bool =
web_invoke_promise_method(root.as_ref(), WEB_METHOD_WEBKIT_REQUEST_FULLSCREEN);
}
} else if is_fs && !web_invoke_promise_method(doc.as_ref(), WEB_METHOD_EXIT_FULLSCREEN) {
let _: bool = web_invoke_promise_method(doc.as_ref(), WEB_METHOD_WEBKIT_EXIT_FULLSCREEN);
}
}
fn web_ensure_reset_stylesheet(doc: &Document) {
if doc.get_element_by_id(WEB_RESET_STYLE_ID).is_some() {
return;
}
let Ok(style_el) = doc.create_element(WEB_STYLE_TAG) else {
return;
};
drop(style_el.set_attribute(WEB_ATTR_ID, WEB_RESET_STYLE_ID));
style_el.set_text_content(Some(WEB_RESET_STYLE_CSS));
if let Ok(Some(head)) = doc.query_selector(WEB_HEAD_SELECTOR) {
drop(head.append_child(&style_el));
} else if let Some(root) = doc.document_element() {
drop(root.append_child(&style_el));
}
}
pub(crate) fn web_create_canvas(
config: &WindowConfig,
dpr: f32,
reuse_existing: bool,
) -> Result<WebCanvasSurface, PlatformError> {
let win: Window = window()
.ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
let doc: Document = win
.document()
.ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
doc.set_title(config.get_title());
web_ensure_reset_stylesheet(&doc);
let mut existing_canvas: Option<HtmlCanvasElement> = None;
if reuse_existing
&& let Ok(Some(found)) = doc.query_selector(WEB_CANVAS_TAG)
&& let Ok(existing) = found.dyn_into::<HtmlCanvasElement>()
{
existing_canvas = Some(existing);
}
let (canvas, needs_append): (HtmlCanvasElement, bool) = match existing_canvas {
Some(existing) => (existing, false),
None => {
let el: Element = doc.create_element(WEB_CANVAS_TAG).map_err(|_: JsValue| {
PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
})?;
let created: HtmlCanvasElement =
el.dyn_into::<HtmlCanvasElement>().map_err(|_: Element| {
PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
})?;
(created, true)
}
};
let (win_w, win_h): (f64, f64) = web_query_viewport_css_size(
&win,
&doc,
config.get_width() as f64,
config.get_height() as f64,
);
let safe_dpr: f64 = f64::from(dpr.clamp(WEB_DPR_MIN, WEB_DPR_MAX));
let phys_w: u32 = (win_w * safe_dpr)
.round()
.clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
let phys_h: u32 = (win_h * safe_dpr)
.round()
.clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
canvas.set_width(phys_w);
canvas.set_height(phys_h);
let css_style: String =
format!("{WEB_CANVAS_STYLE_PREFIX}{WEB_CURSOR_DEFAULT}{WEB_CANVAS_STYLE_SUFFIX}");
drop(canvas.set_attribute(WEB_ATTR_STYLE, &css_style));
drop(canvas.set_attribute(WEB_ATTR_CANVAS_ROLE, WEB_CANVAS_ROLE_ACTIVE));
drop(canvas.set_attribute(WEB_ATTR_TABINDEX, WEB_ATTR_TABINDEX_ZERO));
if let Some(body) = doc.body() {
drop(body.set_attribute(WEB_ATTR_STYLE, WEB_BODY_STYLE));
if needs_append {
drop(body.append_child(&canvas));
}
}
let render_mode: RenderMode = config.get_render().get_mode();
let prefer_direct: bool = config.get_render().get_direct_gpu_present();
if render_mode == RenderMode::Hardware
&& web_has_webgpu()
&& let Ok(Some(gpu_ctx)) = canvas.get_context(WEB_CONTEXT_WEBGPU)
{
return Ok(WebCanvasSurface {
canvas,
context_kind: WebCanvasContextKind::WebGpu,
presentation_mode: WebPresentationMode::GpuDirect,
webgpu_ctx: Some(gpu_ctx),
gl2: None,
gl2_direct_program: None,
gl2_direct_view_loc: None,
gl2_direct_rect_loc: None,
gl2_direct_color_loc: None,
gl2_program: None,
gl2_texture: None,
gl2_view_loc: None,
ctx2d: None,
});
}
if render_mode != RenderMode::Software {
let gl_opts: Object = web_gl2_context_options();
if let Ok(Some(raw_gl)) =
canvas.get_context_with_context_options(WEB_CONTEXT_WEBGL2, gl_opts.as_ref())
&& let Ok(gl2) = raw_gl.dyn_into::<WebGl2RenderingContext>()
{
let direct: Option<WebGl2DirectPipeline> = web_init_gl2_direct_pipeline(&gl2);
let (
gl2_direct_program,
gl2_direct_view_loc,
gl2_direct_rect_loc,
gl2_direct_color_loc,
): (
Option<WebGlProgram>,
Option<WebGlUniformLocation>,
Option<WebGlUniformLocation>,
Option<WebGlUniformLocation>,
) = match direct {
Some(delta_val) => (
Some(delta_val.program),
delta_val.view_loc,
delta_val.rect_loc,
delta_val.color_loc,
),
None => (None, None, None, None),
};
let pipeline: Option<WebGl2BlitPipeline> = web_init_gl2_blit_pipeline(&gl2);
let (gl2_program, gl2_texture, gl2_view_loc): (
Option<WebGlProgram>,
Option<JsValue>,
Option<WebGlUniformLocation>,
) = match pipeline {
Some(point_val) => (
Some(point_val.program),
point_val.texture,
point_val.view_loc,
),
None => (None, None, None),
};
let _: bool = prefer_direct;
let pres_mode: WebPresentationMode = WebPresentationMode::GpuUpload;
return Ok(WebCanvasSurface {
canvas,
context_kind: WebCanvasContextKind::WebGl2,
presentation_mode: pres_mode,
webgpu_ctx: None,
gl2: Some(gl2),
gl2_direct_program,
gl2_direct_view_loc,
gl2_direct_rect_loc,
gl2_direct_color_loc,
gl2_program,
gl2_texture,
gl2_view_loc,
ctx2d: None,
});
}
}
let raw_ctx: Object = canvas
.get_context(WEB_CONTEXT_2D)
.map_err(|_: JsValue| PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string()))?
.ok_or_else(|| PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string()))?;
let ctx2d: CanvasRenderingContext2d = raw_ctx
.dyn_into::<CanvasRenderingContext2d>()
.map_err(|_: Object| PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string()))?;
Ok(WebCanvasSurface {
canvas,
context_kind: WebCanvasContextKind::Canvas2d,
presentation_mode: WebPresentationMode::Software,
webgpu_ctx: None,
gl2: None,
gl2_direct_program: None,
gl2_direct_view_loc: None,
gl2_direct_rect_loc: None,
gl2_direct_color_loc: None,
gl2_program: None,
gl2_texture: None,
gl2_view_loc: None,
ctx2d: Some(ctx2d),
})
}
pub(crate) fn web_create_independent_standby_canvas(
parent_el: Option<&Element>,
target_mode: WebPresentationMode,
phys_w: u32,
phys_h: u32,
) -> Result<WebCanvasSurface, PlatformError> {
let win: Window = window()
.ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
let doc: Document = win
.document()
.ok_or_else(|| PlatformError::InitializationFailed(ERR_WEB_WINDOW_MISSING.to_string()))?;
let el: Element = doc.create_element(WEB_CANVAS_TAG).map_err(|_: JsValue| {
PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
})?;
let canvas: HtmlCanvasElement = el.dyn_into::<HtmlCanvasElement>().map_err(|_: Element| {
PlatformError::InitializationFailed(ERR_WEB_CANVAS_CREATE.to_string())
})?;
canvas.set_width(phys_w.max(1));
canvas.set_height(phys_h.max(1));
drop(canvas.set_attribute(WEB_ATTR_STYLE, WEB_STANDBY_CANVAS_STYLE));
drop(canvas.set_attribute(WEB_ATTR_CANVAS_ROLE, WEB_CANVAS_ROLE_STANDBY));
drop(canvas.set_attribute(WEB_ATTR_TABINDEX, WEB_ATTR_TABINDEX_ZERO));
if let Some(container) = parent_el {
drop(container.append_child(&canvas));
} else if let Some(body) = doc.body() {
drop(body.append_child(&canvas));
}
match target_mode {
WebPresentationMode::GpuDirect | WebPresentationMode::GpuUpload => {
let gl_opts: Object = web_gl2_context_options();
let raw_gl: Object = canvas
.get_context_with_context_options(WEB_CONTEXT_WEBGL2, gl_opts.as_ref())
.map_err(|_: JsValue| {
canvas.remove();
PlatformError::SurfaceError(ERR_WEB_GL2_CONTEXT_MISSING.to_string())
})?
.ok_or_else(|| {
canvas.remove();
PlatformError::SurfaceError(ERR_WEB_GL2_CONTEXT_MISSING.to_string())
})?;
let gl2: WebGl2RenderingContext =
raw_gl
.dyn_into::<WebGl2RenderingContext>()
.map_err(|_: Object| {
canvas.remove();
PlatformError::SurfaceError(ERR_WEB_GL2_CONTEXT_MISSING.to_string())
})?;
let direct: Option<WebGl2DirectPipeline> = web_init_gl2_direct_pipeline(&gl2);
let (
gl2_direct_program,
gl2_direct_view_loc,
gl2_direct_rect_loc,
gl2_direct_color_loc,
): (
Option<WebGlProgram>,
Option<WebGlUniformLocation>,
Option<WebGlUniformLocation>,
Option<WebGlUniformLocation>,
) = match direct {
Some(delta_val) => (
Some(delta_val.program),
delta_val.view_loc,
delta_val.rect_loc,
delta_val.color_loc,
),
None => (None, None, None, None),
};
let pipeline: Option<WebGl2BlitPipeline> = web_init_gl2_blit_pipeline(&gl2);
let (gl2_program, gl2_texture, gl2_view_loc): (
Option<WebGlProgram>,
Option<JsValue>,
Option<WebGlUniformLocation>,
) = match pipeline {
Some(point_val) => (
Some(point_val.program),
point_val.texture,
point_val.view_loc,
),
None => (None, None, None),
};
if target_mode == WebPresentationMode::GpuDirect && gl2_direct_program.is_none() {
canvas.remove();
return Err(PlatformError::SurfaceError(
ERR_WEB_GL2_DIRECT_MISSING.to_string(),
));
}
Ok(WebCanvasSurface {
canvas,
context_kind: WebCanvasContextKind::WebGl2,
presentation_mode: target_mode,
webgpu_ctx: None,
gl2: Some(gl2),
gl2_direct_program,
gl2_direct_view_loc,
gl2_direct_rect_loc,
gl2_direct_color_loc,
gl2_program,
gl2_texture,
gl2_view_loc,
ctx2d: None,
})
}
WebPresentationMode::Software => {
let raw_ctx: Object = canvas
.get_context(WEB_CONTEXT_2D)
.map_err(|_: JsValue| {
canvas.remove();
PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string())
})?
.ok_or_else(|| {
canvas.remove();
PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string())
})?;
let ctx2d: CanvasRenderingContext2d = raw_ctx
.dyn_into::<CanvasRenderingContext2d>()
.map_err(|_: Object| {
canvas.remove();
PlatformError::SurfaceError(ERR_WEB_CONTEXT_2D_MISSING.to_string())
})?;
Ok(WebCanvasSurface {
canvas,
context_kind: WebCanvasContextKind::Canvas2d,
presentation_mode: WebPresentationMode::Software,
webgpu_ctx: None,
gl2: None,
gl2_direct_program: None,
gl2_direct_view_loc: None,
gl2_direct_rect_loc: None,
gl2_direct_color_loc: None,
gl2_program: None,
gl2_texture: None,
gl2_view_loc: None,
ctx2d: Some(ctx2d),
})
}
}
}
#[must_use]
pub(crate) fn web_batches_support_gl2_direct(batches: &[GpuBatch]) -> bool {
for batch_entry in batches.iter() {
for primitive_item in batch_entry.get_primitives().iter() {
if primitive_item.prim_kind() != PrimKind::RoundedRect
|| primitive_item.get_radii_border() != [0, 0, 0, 0]
|| primitive_item.get_extra_param() != 0
{
return false;
}
}
}
true
}
pub(crate) fn web_draw_gl2_direct_batches(
gl: &WebGl2RenderingContext,
program: &WebGlProgram,
view_loc: Option<&WebGlUniformLocation>,
rect_loc: Option<&WebGlUniformLocation>,
color_loc: Option<&WebGlUniformLocation>,
width: u32,
height: u32,
clear_color: Color,
batches: &[GpuBatch],
) -> u32 {
let draw_w: i32 = width.max(1) as i32;
let draw_h: i32 = height.max(1) as i32;
gl.viewport(0, 0, draw_w, draw_h);
gl.enable(WebGl2RenderingContext::BLEND);
gl.blend_func(
WebGl2RenderingContext::SRC_ALPHA,
WebGl2RenderingContext::ONE_MINUS_SRC_ALPHA,
);
gl.clear_color(
f32::from(clear_color.get_red()) / 255.0,
f32::from(clear_color.get_green()) / 255.0,
f32::from(clear_color.get_blue()) / 255.0,
f32::from(clear_color.get_alpha()) / 255.0,
);
gl.clear(WebGl2RenderingContext::COLOR_BUFFER_BIT);
gl.use_program(Some(program));
if let Some(loc) = view_loc {
gl.uniform2f(Some(loc), draw_w as f32, draw_h as f32);
}
let mut drawn: u32 = 0;
for batch in batches.iter() {
for prim in batch.get_primitives().iter() {
let rect: [f32; 4] = prim.get_rect();
let packed: u32 = prim.get_color_rgba();
let red_val: f32 = f32::from((packed & 0xFF) as u8) / 255.0;
let green_val: f32 = f32::from(((packed >> 8) & 0xFF) as u8) / 255.0;
let blue_val: f32 = f32::from(((packed >> 16) & 0xFF) as u8) / 255.0;
let alpha_val: f32 = f32::from(((packed >> 24) & 0xFF) as u8) / 255.0;
if let Some(loc) = rect_loc {
gl.uniform4f(Some(loc), rect[0], rect[1], rect[2], rect[3]);
}
if let Some(loc) = color_loc {
gl.uniform4f(Some(loc), red_val, green_val, blue_val, alpha_val);
}
gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 6);
drawn = drawn.saturating_add(1);
}
}
drawn
}
fn web_pack_rgba_subrect_into(
framebuffer: &Framebuffer,
x0: u32,
y0: u32,
width: u32,
height: u32,
out: &mut Vec<u8>,
) {
let fb_w: usize = framebuffer.get_width() as usize;
let src: &[u8] = framebuffer.get_pixels().as_slice();
let row_bytes: usize = (width as usize) * 4;
let needed: usize = row_bytes * (height as usize);
out.clear();
if out.capacity() < needed {
out.reserve(needed - out.capacity());
}
for row in y0..(y0 + height) {
let start: usize = ((row as usize) * fb_w + (x0 as usize)) * 4;
let end: usize = start + row_bytes;
if end <= src.len() {
out.extend_from_slice(&src[start..end]);
}
}
}
pub(crate) fn web_present_gl2_region(
rec: &mut WebWindowRecord,
framebuffer: &Framebuffer,
damage: DamageRegion,
) -> Result<Option<u64>, PlatformError> {
let WebWindowRecord {
canvas,
gl2,
gl2_program,
gl2_texture,
gl2_view_loc,
gl2_tex_width,
gl2_tex_height,
..
} = rec;
let (Some(gl), Some(program), Some(texture)) =
(gl2.as_ref(), gl2_program.as_ref(), gl2_texture.as_ref())
else {
return Ok(None);
};
let fb_w: u32 = framebuffer.get_width();
let fb_h: u32 = framebuffer.get_height();
if fb_w == 0 || fb_h == 0 {
return Ok(Some(0));
}
let pixels: &[u8] = framebuffer.get_pixels().as_slice();
let required_bytes: usize = (fb_w as usize)
.saturating_mul(fb_h as usize)
.saturating_mul(4);
if pixels.len() < required_bytes {
return Err(PlatformError::SurfaceError(
ERR_WEB_PRESENT_FAILED.to_string(),
));
}
let mut drawing_resized: bool =
gl.drawing_buffer_width() != (fb_w as i32) || gl.drawing_buffer_height() != (fb_h as i32);
if drawing_resized && let Some(el) = canvas.as_ref() {
if el.width() != fb_w {
el.set_width(fb_w);
}
if el.height() != fb_h {
el.set_height(fb_h);
}
drawing_resized = true;
}
let tex_dims_changed: bool = *gl2_tex_width != fb_w || *gl2_tex_height != fb_h;
let resolved_rect: Option<Rect> = damage.resolve(fb_w, fb_h);
if resolved_rect.is_none() && !drawing_resized && !tex_dims_changed {
return Ok(Some(0));
}
let target_val: JsValue = JsValue::from_f64(WebGl2RenderingContext::TEXTURE_2D as f64);
if let Ok(active_val) = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_ACTIVE_TEXTURE))
&& let Ok(active_fn) = active_val.dyn_into::<Function>()
{
drop(active_fn.call1(
gl.as_ref(),
&JsValue::from_f64(WebGl2RenderingContext::TEXTURE0 as f64),
));
}
if let Ok(bind_val) = Reflect::get(gl.as_ref(), &JsValue::from_str(WEB_GL_BIND_TEXTURE))
&& let Ok(bind_fn) = bind_val.dyn_into::<Function>()
{
drop(bind_fn.call2(gl.as_ref(), &target_val, texture));
}
web_configure_gl2_unpack_state(gl);
let surface_dirty: bool = drawing_resized || tex_dims_changed;
let needs_full_upload: bool = damage.get_full_damage() || surface_dirty;
let mut upload_bytes: u64 = 0;
if needs_full_upload {
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
gl.tex_image_2d_with_i32_and_i32_and_i32_and_format_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
WebGl2RenderingContext::RGBA8 as i32,
fb_w as i32,
fb_h as i32,
0,
WebGl2RenderingContext::RGBA,
WebGl2RenderingContext::UNSIGNED_BYTE,
Some(view.as_ref()),
)
.map_err(|_: JsValue| PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string()))?;
*gl2_tex_width = fb_w;
*gl2_tex_height = fb_h;
upload_bytes = required_bytes as u64;
} else if let Some(rect) = resolved_rect {
let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(fb_w);
let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(fb_h);
let x1: u32 = (rect.right().ceil().max(0.0) as u32).min(fb_w);
let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).min(fb_h);
if x1 > x0 && y1 > y0 {
let rw: u32 = x1 - x0;
let rh: u32 = y1 - y0;
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, fb_w as i32);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, x0 as i32);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, y0 as i32);
let view: Uint8Array = unsafe { Uint8Array::view(pixels) };
let upload_res: Result<(), JsValue> = gl
.tex_sub_image_2d_with_i32_and_i32_and_u32_and_type_and_opt_array_buffer_view(
WebGl2RenderingContext::TEXTURE_2D,
0,
x0 as i32,
y0 as i32,
rw as i32,
rh as i32,
WebGl2RenderingContext::RGBA,
WebGl2RenderingContext::UNSIGNED_BYTE,
Some(view.as_ref()),
);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_ROW_LENGTH, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_PIXELS, 0);
gl.pixel_storei(WebGl2RenderingContext::UNPACK_SKIP_ROWS, 0);
upload_res.map_err(|_: JsValue| {
PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
})?;
upload_bytes = u64::from(rw)
.saturating_mul(u64::from(rh))
.saturating_mul(4);
}
}
let draw_w: i32 = gl.drawing_buffer_width().max(1);
let draw_h: i32 = gl.drawing_buffer_height().max(1);
gl.viewport(0, 0, draw_w, draw_h);
gl.use_program(Some(program));
if let Some(loc) = gl2_view_loc.as_ref() {
gl.uniform2f(Some(loc), draw_w as f32, draw_h as f32);
}
gl.draw_arrays(WebGl2RenderingContext::TRIANGLES, 0, 3);
Ok(Some(upload_bytes))
}
pub(crate) fn web_present_image_data_region(
canvas: Option<&HtmlCanvasElement>,
ctx2d: &CanvasRenderingContext2d,
framebuffer: &Framebuffer,
damage: DamageRegion,
) -> Result<u64, PlatformError> {
let fb_w: u32 = framebuffer.get_width();
let fb_h: u32 = framebuffer.get_height();
let mut backing_resized: bool = false;
if let Some(el) = canvas {
if el.width() != fb_w {
el.set_width(fb_w);
backing_resized = true;
}
if el.height() != fb_h {
el.set_height(fb_h);
backing_resized = true;
}
}
let effective_damage: DamageRegion = if backing_resized {
DamageRegion::full()
} else {
damage
};
let Some(rect) = effective_damage.resolve(fb_w, fb_h) else {
return Ok(0);
};
if effective_damage.get_full_damage() {
let pixels: &[u8] = framebuffer.get_pixels().as_slice();
let clamped: Clamped<&[u8]> = Clamped(pixels);
let img: ImageData = ImageData::new_with_u8_clamped_array_and_sh(clamped, fb_w, fb_h)
.map_err(|_: JsValue| {
PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
})?;
ctx2d.put_image_data(&img, 0.0, 0.0).map_err(|_: JsValue| {
PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
})?;
Ok(pixels.len() as u64)
} else {
let x0: u32 = (rect.get_x().floor().max(0.0) as u32).min(fb_w);
let y0: u32 = (rect.get_y().floor().max(0.0) as u32).min(fb_h);
let x1: u32 = (rect.right().ceil().max(0.0) as u32).min(fb_w);
let y1: u32 = (rect.bottom().ceil().max(0.0) as u32).min(fb_h);
if x1 <= x0 || y1 <= y0 {
return Ok(0);
}
let rw: u32 = x1 - x0;
let rh: u32 = y1 - y0;
let (img, copied_bytes): (ImageData, u64) = WEB_SUBRECT_SCRATCH.with(
|cell: &RefCell<Vec<u8>>| -> Result<(ImageData, u64), PlatformError> {
let Ok(mut sub) = cell.try_borrow_mut() else {
return Err(PlatformError::SurfaceError(
ERR_WEB_PRESENT_FAILED.to_string(),
));
};
web_pack_rgba_subrect_into(framebuffer, x0, y0, rw, rh, &mut sub);
let copied_bytes: u64 = sub.len() as u64;
let clamped: Clamped<&[u8]> = Clamped(sub.as_slice());
let img_res: Result<ImageData, JsValue> =
ImageData::new_with_u8_clamped_array_and_sh(clamped, rw, rh);
drop(sub);
let img: ImageData = img_res.map_err(|_: JsValue| {
PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
})?;
Ok((img, copied_bytes))
},
)?;
ctx2d
.put_image_data(&img, x0 as f64, y0 as f64)
.map_err(|_: JsValue| {
PlatformError::SurfaceError(ERR_WEB_PRESENT_FAILED.to_string())
})?;
Ok(copied_bytes)
}
}
fn web_read_opt_f32(target: &JsValue, key: &str) -> Option<f32> {
let val: JsValue = Reflect::get(target, &JsValue::from_str(key)).ok()?;
let num: f64 = val.as_f64()?;
if num.is_finite() {
Some(num as f32)
} else {
None
}
}
fn web_read_vec3_prop(event_val: &JsValue, prop: &str) -> Option<[f32; 3]> {
let sub: JsValue = Reflect::get(event_val, &JsValue::from_str(prop)).ok()?;
if sub.is_null() || sub.is_undefined() {
return None;
}
let ox: Option<f32> = web_read_opt_f32(&sub, WEB_PROP_AXIS_X);
let oy: Option<f32> = web_read_opt_f32(&sub, WEB_PROP_AXIS_Y);
let oz: Option<f32> = web_read_opt_f32(&sub, WEB_PROP_AXIS_Z);
if ox.is_none() && oy.is_none() && oz.is_none() {
return None;
}
Some([ox.unwrap_or(0.0), oy.unwrap_or(0.0), oz.unwrap_or(0.0)])
}
fn web_read_rotation_rate_rad(event_val: &JsValue) -> [f32; 3] {
let Ok(sub) = Reflect::get(event_val, &JsValue::from_str(WEB_PROP_ROTATION_RATE)) else {
return [0.0, 0.0, 0.0];
};
if sub.is_null() || sub.is_undefined() {
return [0.0, 0.0, 0.0];
}
let alpha_dps: f32 = web_read_opt_f32(&sub, WEB_PROP_ALPHA).unwrap_or(0.0);
let beta_dps: f32 = web_read_opt_f32(&sub, WEB_PROP_BETA).unwrap_or(0.0);
let gamma_dps: f32 = web_read_opt_f32(&sub, WEB_PROP_GAMMA).unwrap_or(0.0);
[
beta_dps * WEB_DEG_TO_RAD,
gamma_dps * WEB_DEG_TO_RAD,
alpha_dps * WEB_DEG_TO_RAD,
]
}
#[must_use]
pub fn web_screen_orientation_angle_deg() -> i32 {
let Some(win) = window() else {
return 0;
};
if let Ok(screen_val) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_SCREEN))
&& !screen_val.is_null()
&& !screen_val.is_undefined()
&& let Ok(orient_val) = Reflect::get(&screen_val, &JsValue::from_str(WEB_PROP_ORIENTATION))
&& !orient_val.is_null()
&& !orient_val.is_undefined()
&& let Some(angle) = web_read_opt_f32(&orient_val, WEB_PROP_ANGLE)
{
return angle.round() as i32;
}
if let Some(legacy_angle) = web_read_opt_f32(win.as_ref(), WEB_PROP_ORIENTATION) {
return legacy_angle.round() as i32;
}
0
}
#[must_use]
fn web_monotonic_now_ns() -> u64 {
window()
.and_then(|win: Window| win.performance())
.map(|perf: Performance| (perf.now().max(0.0) * 1_000_000.0) as u64)
.unwrap_or(0)
}
fn web_handle_device_orientation(event: &Event) {
let ev_val: &JsValue = event.as_ref();
let Some(beta_deg) = web_read_opt_f32(ev_val, WEB_PROP_BETA) else {
return;
};
let Some(gamma_deg) = web_read_opt_f32(ev_val, WEB_PROP_GAMMA) else {
return;
};
let alpha_deg: f32 = web_read_opt_f32(ev_val, WEB_PROP_ALPHA).unwrap_or(0.0);
let blue_val: f32 = beta_deg * WEB_DEG_TO_RAD;
let green_val: f32 = gamma_deg * WEB_DEG_TO_RAD;
let yaw_rad: f32 = alpha_deg * WEB_DEG_TO_RAD;
let g_dev: [f32; 3] = [
STANDARD_GRAVITY_MPS2 * blue_val.cos() * green_val.sin(),
-STANDARD_GRAVITY_MPS2 * blue_val.sin(),
-STANDARD_GRAVITY_MPS2 * blue_val.cos() * green_val.cos(),
];
let angle_deg: i32 = web_screen_orientation_angle_deg();
let ts_ns: u64 = web_monotonic_now_ns();
WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
if let Ok(mut node_style) = cell.try_borrow_mut() {
node_style.set_orient_gravity_dev(Some(g_dev));
node_style.set_last_yaw_rad(yaw_rad);
if !node_style.get_has_motion_event() {
let mut sample: DeviceMotionSample = DeviceMotionSample::from_device_axes(
g_dev,
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
angle_deg,
ts_ns,
);
sample.set_yaw_rad(yaw_rad);
node_style.set_pending_sample(sample);
node_style.set_has_pending_sample(true);
}
}
});
}
#[inline(always)]
#[must_use]
fn web_apply_sensor_deadzone(item_val: f32, dz: f32) -> f32 {
if !item_val.is_finite() {
return 0.0;
}
let abs_v: f32 = item_val.abs();
if abs_v <= dz {
0.0
} else {
item_val.signum() * (abs_v - dz)
}
}
fn web_handle_device_motion(event: &Event) {
let ev_val: &JsValue = event.as_ref();
let accel_incl: Option<[f32; 3]> = web_read_vec3_prop(ev_val, WEB_PROP_ACCEL_INCLUDING_GRAVITY);
let accel_lin: Option<[f32; 3]> = web_read_vec3_prop(ev_val, WEB_PROP_ACCELERATION);
let raw_gyro: [f32; 3] = web_read_rotation_rate_rad(ev_val);
let gyro_dev: [f32; 3] = [
web_apply_sensor_deadzone(raw_gyro[0], WEB_GYRO_DEADZONE_RAD_S),
web_apply_sensor_deadzone(raw_gyro[1], WEB_GYRO_DEADZONE_RAD_S),
web_apply_sensor_deadzone(raw_gyro[2], WEB_GYRO_DEADZONE_RAD_S),
];
let angle_deg: i32 = web_screen_orientation_angle_deg();
let ts_ns: u64 = web_monotonic_now_ns();
WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
if let Ok(mut node_style) = cell.try_borrow_mut() {
let first_motion: bool = !node_style.get_has_motion_event();
let mut g_dev_opt: Option<[f32; 3]> = None;
let mut lin_dev: [f32; 3] = [0.0, 0.0, 0.0];
if let Some(ag) = accel_incl {
node_style.set_has_motion_event(true);
let (raw_g_unsmoothed, raw_lin): ([f32; 3], [f32; 3]) = if let Some(al) = accel_lin
{
([ag[0] - al[0], ag[1] - al[1], ag[2] - al[2]], al)
} else {
let prev: [f32; 3] = node_style.get_filtered_gravity_dev().unwrap_or(ag);
let alpha_val: f32 = WEB_GRAVITY_LPF_ALPHA;
let filt: [f32; 3] = [
prev[0] * (1.0 - alpha_val) + ag[0] * alpha_val,
prev[1] * (1.0 - alpha_val) + ag[1] * alpha_val,
prev[2] * (1.0 - alpha_val) + ag[2] * alpha_val,
];
node_style.set_filtered_gravity_dev(Some(filt));
(filt, [ag[0] - filt[0], ag[1] - filt[1], ag[2] - filt[2]])
};
let prev_g: [f32; 3] = node_style
.get_filtered_gravity_dev()
.unwrap_or(raw_g_unsmoothed);
let dg2: f32 = (raw_g_unsmoothed[0] - prev_g[0]).powi(2)
+ (raw_g_unsmoothed[1] - prev_g[1]).powi(2)
+ (raw_g_unsmoothed[2] - prev_g[2]).powi(2);
let lpf_a: f32 = if dg2 < 0.09 { 0.18 } else { 0.65 };
let raw_g: [f32; 3] = [
prev_g[0] * (1.0 - lpf_a) + raw_g_unsmoothed[0] * lpf_a,
prev_g[1] * (1.0 - lpf_a) + raw_g_unsmoothed[1] * lpf_a,
prev_g[2] * (1.0 - lpf_a) + raw_g_unsmoothed[2] * lpf_a,
];
node_style.set_filtered_gravity_dev(Some(raw_g));
if let Some(og) = node_style.get_orient_gravity_dev() {
let dot: f32 = raw_g[0] * og[0] + raw_g[1] * og[1] + raw_g[2] * og[2];
if dot > WEB_GRAVITY_SIGN_DOT_THRESHOLD {
node_style.set_gravity_sign(1.0);
} else if dot < -WEB_GRAVITY_SIGN_DOT_THRESHOLD {
node_style.set_gravity_sign(-1.0);
}
} else if first_motion && raw_g[1].abs() > 4.2 {
node_style.set_gravity_sign(if raw_g[1] < 0.0 { 1.0 } else { -1.0 });
}
let source_val: f32 = node_style.get_gravity_sign();
g_dev_opt = Some([
raw_g[0] * source_val,
raw_g[1] * source_val,
raw_g[2] * source_val,
]);
let lin_sign: f32 = if source_val > 0.0 { -1.0 } else { 1.0 };
lin_dev = [
web_apply_sensor_deadzone(
raw_lin[0] * lin_sign,
WEB_LINEAR_ACCEL_DEADZONE_MPS2,
),
web_apply_sensor_deadzone(
raw_lin[1] * lin_sign,
WEB_LINEAR_ACCEL_DEADZONE_MPS2,
),
web_apply_sensor_deadzone(
raw_lin[2] * lin_sign,
WEB_LINEAR_ACCEL_DEADZONE_MPS2,
),
];
} else if let Some(og) = node_style.get_orient_gravity_dev() {
g_dev_opt = Some(og);
if let Some(al) = accel_lin {
lin_dev = [
web_apply_sensor_deadzone(al[0], WEB_LINEAR_ACCEL_DEADZONE_MPS2),
web_apply_sensor_deadzone(al[1], WEB_LINEAR_ACCEL_DEADZONE_MPS2),
web_apply_sensor_deadzone(al[2], WEB_LINEAR_ACCEL_DEADZONE_MPS2),
];
}
}
if let Some(g_dev) = g_dev_opt {
let mut sample: DeviceMotionSample = DeviceMotionSample::from_device_axes(
g_dev, lin_dev, gyro_dev, angle_deg, ts_ns,
);
sample.set_yaw_rad(node_style.get_last_yaw_rad());
node_style.set_pending_sample(sample);
node_style.set_has_pending_sample(true);
}
}
});
}
pub fn web_attach_device_motion_listeners() -> bool {
let already: bool = WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
cell.try_borrow()
.map(|node_style: Ref<'_, WebDeviceMotionState>| node_style.get_listeners_attached())
.unwrap_or(false)
});
if already {
return true;
}
let Some(win) = window() else {
return false;
};
let on_motion: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(|ui_event: Event| {
web_handle_device_motion(&ui_event);
}) as Box<dyn FnMut(Event)>);
let motion_ok: bool = win
.add_event_listener_with_callback(
WEB_EVENT_DEVICE_MOTION,
on_motion.as_ref().unchecked_ref(),
)
.is_ok();
on_motion.forget();
let on_orient: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(|dispatched_event: Event| {
web_handle_device_orientation(&dispatched_event);
}) as Box<dyn FnMut(Event)>);
let orient_ok: bool = win
.add_event_listener_with_callback(
WEB_EVENT_DEVICE_ORIENTATION,
on_orient.as_ref().unchecked_ref(),
)
.is_ok();
on_orient.forget();
let attached: bool = motion_ok || orient_ok;
if attached {
WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
if let Ok(mut active_style) = cell.try_borrow_mut() {
active_style.set_listeners_attached(true);
}
});
}
attached
}
#[must_use]
pub fn web_take_pending_device_motion() -> Option<DeviceMotionSample> {
WEB_DEVICE_MOTION_STATE.with(|cell: &RefCell<WebDeviceMotionState>| {
cell.try_borrow_mut()
.ok()
.and_then(|mut node_style: RefMut<'_, WebDeviceMotionState>| {
if node_style.get_has_pending_sample() {
node_style.set_has_pending_sample(false);
Some(node_style.get_pending_sample())
} else {
None
}
})
})
}
fn web_try_request_ctor_permission(win: &Window, ctor_name: &str) -> bool {
let Ok(ctor_val) = Reflect::get(win.as_ref(), &JsValue::from_str(ctor_name)) else {
return false;
};
if ctor_val.is_null() || ctor_val.is_undefined() {
return false;
}
let Ok(req_val) = Reflect::get(&ctor_val, &JsValue::from_str(WEB_METHOD_REQUEST_PERMISSION))
else {
return false;
};
let Ok(req_fn) = req_val.dyn_into::<Function>() else {
return false;
};
if let Ok(ret) = req_fn.call0(&ctor_val)
&& let Ok(promise) = ret.dyn_into::<Promise>()
{
let on_granted: Closure<dyn FnMut(JsValue)> = Closure::wrap(Box::new(|res: JsValue| {
if res.as_string().as_deref() == Some(WEB_PERMISSION_GRANTED) {
let _: bool = web_attach_device_motion_listeners();
}
})
as Box<dyn FnMut(JsValue)>);
let chained: Promise = promise.then(&on_granted);
on_granted.forget();
WEB_PROMISE_NOOP_REJECT.with(|callback_fn: &Closure<dyn FnMut(JsValue)>| {
let _: Promise = chained.catch(callback_fn);
});
return true;
}
false
}
pub(crate) fn web_request_motion_permission_impl() -> bool {
let Some(win) = window() else {
return false;
};
let motion_req: bool = web_try_request_ctor_permission(&win, WEB_CTOR_DEVICE_MOTION_EVENT);
let orient_req: bool = web_try_request_ctor_permission(&win, WEB_CTOR_DEVICE_ORIENTATION_EVENT);
if motion_req || orient_req {
return true;
}
web_attach_device_motion_listeners()
}
fn web_rasterize_loaded_img(doc: &Document, img: &Element, url: &str) -> Option<ImageBuffer> {
let raw_w: u32 = Reflect::get(img.as_ref(), &JsValue::from_str(WEB_PROP_NATURAL_WIDTH))
.ok()
.and_then(|item_val: JsValue| item_val.as_f64())
.map(|item_count: f64| item_count.round().max(0.0) as u32)
.unwrap_or(0);
let raw_h: u32 = Reflect::get(img.as_ref(), &JsValue::from_str(WEB_PROP_NATURAL_HEIGHT))
.ok()
.and_then(|tex_v: JsValue| tex_v.as_f64())
.map(|node_entry: f64| node_entry.round().max(0.0) as u32)
.unwrap_or(0);
let lower_url: String = url.to_ascii_lowercase();
let is_svg_url: bool =
lower_url.contains(WEB_EXT_SVG) || lower_url.starts_with(WEB_DATA_SVG_PREFIX);
let missing_intrinsic: bool = raw_w == 0 || raw_h == 0;
let is_vector_svg: bool = is_svg_url || missing_intrinsic;
let (base_w, base_h): (u32, u32) = if !missing_intrinsic {
(raw_w, raw_h)
} else {
(WEB_SVG_FALLBACK_WIDTH, WEB_SVG_FALLBACK_HEIGHT)
};
let (src_w, src_h): (u32, u32) = if is_vector_svg {
let svg_scale: f64 = f64::from(web_device_pixel_ratio().clamp(1.0, WEB_SVG_RASTER_MAX_DPR));
(
(f64::from(base_w) * svg_scale).round().max(1.0) as u32,
(f64::from(base_h) * svg_scale).round().max(1.0) as u32,
)
} else {
(base_w, base_h)
};
let max_side: u32 = src_w.max(src_h);
let (out_w, out_h): (u32, u32) = if max_side > WEB_IMAGE_MAX_DIM {
let scale: f64 = f64::from(WEB_IMAGE_MAX_DIM) / f64::from(max_side);
(
(f64::from(src_w) * scale).round().max(1.0) as u32,
(f64::from(src_h) * scale).round().max(1.0) as u32,
)
} else {
(src_w, src_h)
};
let canvas_el: Element = doc.create_element(WEB_CANVAS_TAG).ok()?;
let canvas: HtmlCanvasElement = canvas_el.dyn_into::<HtmlCanvasElement>().ok()?;
canvas.set_width(out_w);
canvas.set_height(out_h);
let ctx_obj: Object = canvas.get_context(WEB_CONTEXT_2D).ok()??;
let ctx2d: CanvasRenderingContext2d = ctx_obj.dyn_into::<CanvasRenderingContext2d>().ok()?;
let _: Result<bool, JsValue> = Reflect::set(
ctx2d.as_ref(),
&JsValue::from_str(WEB_PROP_IMAGE_SMOOTHING_QUALITY),
&JsValue::from_str(WEB_IMG_SMOOTHING_HIGH),
);
ctx2d.clear_rect(0.0, 0.0, f64::from(out_w), f64::from(out_h));
let draw_val: JsValue =
Reflect::get(ctx2d.as_ref(), &JsValue::from_str(WEB_METHOD_DRAW_IMAGE)).ok()?;
let draw_fn: Function = draw_val.dyn_into::<Function>().ok()?;
let args: Array = Array::of5(
img.as_ref(),
&JsValue::from_f64(0.0),
&JsValue::from_f64(0.0),
&JsValue::from_f64(f64::from(out_w)),
&JsValue::from_f64(f64::from(out_h)),
);
let _: JsValue = draw_fn.apply(ctx2d.as_ref(), &args).ok()?;
let img_data: ImageData = ctx2d
.get_image_data(0.0, 0.0, f64::from(out_w), f64::from(out_h))
.ok()?;
let pixels: Vec<u8> = img_data.data().0;
Some(ImageBuffer::new(out_w, out_h, pixels))
}
pub(crate) fn web_load_network_image(url: &str) {
let Some(doc) = window().and_then(|width_val: Window| width_val.document()) else {
complete_network_image_load(url, None);
return;
};
let Ok(img) = doc.create_element(WEB_TAG_IMG) else {
complete_network_image_load(url, None);
return;
};
let lower: String = url.to_ascii_lowercase();
if lower.starts_with(WEB_SCHEME_HTTP) || lower.starts_with(WEB_SCHEME_HTTPS) {
let _: Result<bool, JsValue> = Reflect::set(
img.as_ref(),
&JsValue::from_str(WEB_PROP_CROSS_ORIGIN),
&JsValue::from_str(WEB_CORS_ANONYMOUS),
);
}
let url_load: String = url.to_string();
let img_load: Element = img.clone();
let doc_load: Document = doc.clone();
let on_load: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
let decoded: Option<ImageBuffer> =
web_rasterize_loaded_img(&doc_load, &img_load, &url_load);
complete_network_image_load(&url_load, decoded);
}) as Box<dyn FnMut(Event)>);
let url_err: String = url.to_string();
let on_err: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
complete_network_image_load(&url_err, None);
}) as Box<dyn FnMut(Event)>);
drop(img.add_event_listener_with_callback(WEB_EVENT_LOAD, on_load.as_ref().unchecked_ref()));
drop(img.add_event_listener_with_callback(WEB_EVENT_ERROR, on_err.as_ref().unchecked_ref()));
on_load.forget();
on_err.forget();
let _: Result<bool, JsValue> = Reflect::set(
img.as_ref(),
&JsValue::from_str(WEB_PROP_SRC),
&JsValue::from_str(url),
);
}