mirror of
https://github.com/lexmount/moli.git
synced 2026-11-24 08:02:58 +00:00
feat(emulation): render vision deficiency simulation
(cherry picked from commit b88fa7782613e4b104cbdaf014d837edb94bd545)
This commit is contained in:
@@ -56,6 +56,15 @@ impl RgbaImage {
|
||||
pub fn byte_len(&self) -> usize {
|
||||
self.rgba.len()
|
||||
}
|
||||
|
||||
pub fn gaussian_blur(&mut self, sigma: f32) -> Result<(), RgbaImageError> {
|
||||
self.validate()?;
|
||||
let image =
|
||||
image::RgbaImage::from_raw(self.width, self.height, std::mem::take(&mut self.rgba))
|
||||
.expect("validated RGBA dimensions");
|
||||
self.rgba = image::imageops::blur(&image, sigma).into_raw();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for RgbaImage {
|
||||
|
||||
@@ -216,6 +216,7 @@ pub enum EmulationAction {
|
||||
SetTimezoneOverride,
|
||||
SetUserAgentOverride,
|
||||
SetEmulatedMedia,
|
||||
SetEmulatedVisionDeficiency,
|
||||
SetDefaultBackgroundColorOverride,
|
||||
}
|
||||
|
||||
|
||||
@@ -35,9 +35,24 @@ impl TargetEmulationStateUpdate<'_> {
|
||||
self.effective.geolocation_override = geolocation_override;
|
||||
}
|
||||
|
||||
pub(crate) fn set_emulated_media(&mut self, emulated_media: EmulatedMediaOverrides) {
|
||||
pub(crate) fn set_emulated_media(
|
||||
&mut self,
|
||||
mut emulated_media: EmulatedMediaOverrides,
|
||||
) -> EmulatedMediaOverrides {
|
||||
emulated_media.vision_deficiency = self.raw.emulated_media.vision_deficiency;
|
||||
self.raw.emulated_media = emulated_media.clone();
|
||||
self.effective.emulated_media = emulated_media;
|
||||
emulated_media.vision_deficiency = self.effective.emulated_media.vision_deficiency;
|
||||
self.effective.emulated_media = emulated_media.clone();
|
||||
emulated_media
|
||||
}
|
||||
|
||||
pub(crate) fn set_vision_deficiency(
|
||||
&mut self,
|
||||
vision_deficiency: moli_page_types::VisionDeficiency,
|
||||
) -> EmulatedMediaOverrides {
|
||||
self.raw.emulated_media.vision_deficiency = vision_deficiency;
|
||||
self.effective.emulated_media.vision_deficiency = vision_deficiency;
|
||||
self.effective.emulated_media.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn set_emulated_device_metrics(
|
||||
|
||||
@@ -97,6 +97,7 @@ pub struct EmulatedMediaOverrides {
|
||||
pub reduced_transparency: Option<String>,
|
||||
pub forced_colors: Option<String>,
|
||||
pub contrast: Option<String>,
|
||||
pub vision_deficiency: moli_page_types::VisionDeficiency,
|
||||
}
|
||||
|
||||
impl From<EmulatedMediaOverrides> for moli_core::page::EmulatedMediaOverrides {
|
||||
@@ -108,6 +109,7 @@ impl From<EmulatedMediaOverrides> for moli_core::page::EmulatedMediaOverrides {
|
||||
reduced_transparency: value.reduced_transparency,
|
||||
forced_colors: value.forced_colors,
|
||||
contrast: value.contrast,
|
||||
vision_deficiency: value.vision_deficiency,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -121,6 +123,7 @@ impl From<&EmulatedMediaOverrides> for moli_core::page::EmulatedMediaOverrides {
|
||||
reduced_transparency: value.reduced_transparency.clone(),
|
||||
forced_colors: value.forced_colors.clone(),
|
||||
contrast: value.contrast.clone(),
|
||||
vision_deficiency: value.vision_deficiency,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -186,6 +189,9 @@ impl EffectiveTargetEmulationState {
|
||||
// Blink clears media on every Emulation handler disable. Keep the
|
||||
// target-wide side effect while retaining each handler's raw copy.
|
||||
self.emulated_media = EmulatedMediaOverrides::default();
|
||||
if raw.emulated_media.vision_deficiency == moli_page_types::VisionDeficiency::None {
|
||||
self.emulated_media.vision_deficiency = previous.emulated_media.vision_deficiency;
|
||||
}
|
||||
self.default_background_color = None;
|
||||
if raw.emulated_device_metrics.is_some() {
|
||||
self.emulated_device_metrics = None;
|
||||
|
||||
@@ -247,6 +247,9 @@ pub(crate) fn try_start_emulation_command_dispatch(
|
||||
Some(start_user_agent_override_command(conn, cmd))
|
||||
}
|
||||
Some(EmulationAction::SetEmulatedMedia) => Some(start_emulated_media_command(conn, cmd)),
|
||||
Some(EmulationAction::SetEmulatedVisionDeficiency) => {
|
||||
Some(start_vision_deficiency_command(conn, cmd))
|
||||
}
|
||||
Some(EmulationAction::SetDefaultBackgroundColorOverride) => Some(
|
||||
EmulationCommandTaskStep::Complete(default_background_color_command(conn, cmd)),
|
||||
),
|
||||
@@ -930,16 +933,46 @@ fn start_emulated_media_command(
|
||||
return EmulationCommandTaskStep::Complete(CommandOutputPlan::result(json!({})));
|
||||
}
|
||||
let overrides = media::emulated_media_overrides_from_params(params);
|
||||
if !conn.update_emulation_state_for_session_owner(cmd.session_id, |state| {
|
||||
if let Some(mut state) = state {
|
||||
state.set_emulated_media(overrides.clone());
|
||||
}
|
||||
}) {
|
||||
update_media_overrides(conn, cmd, |mut state| state.set_emulated_media(overrides))
|
||||
}
|
||||
|
||||
fn start_vision_deficiency_command(
|
||||
conn: &mut CdpConnection,
|
||||
cmd: &Cmd<'_>,
|
||||
) -> EmulationCommandTaskStep {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Params {
|
||||
r#type: moli_page_types::VisionDeficiency,
|
||||
}
|
||||
|
||||
let Ok(Some(params)) = cmd.get_params::<Params>() else {
|
||||
return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(
|
||||
-32602,
|
||||
"InvalidParams",
|
||||
));
|
||||
};
|
||||
update_media_overrides(conn, cmd, |mut state| {
|
||||
state.set_vision_deficiency(params.r#type)
|
||||
})
|
||||
}
|
||||
|
||||
fn update_media_overrides(
|
||||
conn: &mut CdpConnection,
|
||||
cmd: &Cmd<'_>,
|
||||
update: impl FnOnce(
|
||||
crate::conn::TargetEmulationStateUpdate<'_>,
|
||||
) -> crate::conn::EmulatedMediaOverrides,
|
||||
) -> EmulationCommandTaskStep {
|
||||
let mut overrides = None;
|
||||
conn.update_emulation_state_for_session_owner(cmd.session_id, |state| {
|
||||
overrides = state.map(update);
|
||||
});
|
||||
let Some(overrides) = overrides else {
|
||||
return EmulationCommandTaskStep::Complete(CommandOutputPlan::error(
|
||||
-31998,
|
||||
"BrowserContextNotLoaded",
|
||||
));
|
||||
}
|
||||
};
|
||||
let page_overrides: moli_core::page::EmulatedMediaOverrides = (&overrides).into();
|
||||
if !emulation_command_is_context_wide(conn, cmd.session_id)
|
||||
&& let Some(step) = native_configuration::try_start(
|
||||
|
||||
@@ -12,6 +12,8 @@ use std::time::Instant;
|
||||
|
||||
use super::{PageVm, RendererDocumentLifecycleIdentity};
|
||||
|
||||
mod vision;
|
||||
|
||||
#[derive(Default)]
|
||||
struct PaintFragmentProfile {
|
||||
push_layer: usize,
|
||||
@@ -440,6 +442,13 @@ impl PageVm {
|
||||
|
||||
let raster_started = profile_enabled.then(Instant::now);
|
||||
let mut raster = moli_paint::raster_snapshot(&snapshot)?;
|
||||
if reason != moli_layout::LayoutFlushReason::Print {
|
||||
vision::apply(
|
||||
&mut raster,
|
||||
self.document_settings.emulated_media.vision_deficiency,
|
||||
snapshot.surface.device_scale,
|
||||
)?;
|
||||
}
|
||||
let raster_us = raster_started
|
||||
.map(|started| started.elapsed().as_micros())
|
||||
.unwrap_or_default();
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
use moli_image::RgbaImage;
|
||||
use moli_page_types::VisionDeficiency;
|
||||
|
||||
pub(super) fn apply(
|
||||
raster: &mut RgbaImage,
|
||||
deficiency: VisionDeficiency,
|
||||
device_scale: f32,
|
||||
) -> Result<(), moli_image::RgbaImageError> {
|
||||
let (matrix, offset) = match deficiency {
|
||||
VisionDeficiency::None => return Ok(()),
|
||||
VisionDeficiency::BlurredVision => return blur_linear_rgba(raster, 2.0 * device_scale),
|
||||
VisionDeficiency::ReducedContrast => {
|
||||
([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], 0.5)
|
||||
}
|
||||
VisionDeficiency::Achromatopsia => ([[0.213, 0.715, 0.072]; 3], 0.0),
|
||||
// Machado, Oliveira and Fernandes (2009), severity 1.0, as in Blink.
|
||||
VisionDeficiency::Deuteranopia => (
|
||||
[
|
||||
[0.367, 0.861, -0.228],
|
||||
[0.280, 0.673, 0.047],
|
||||
[-0.012, 0.043, 0.969],
|
||||
],
|
||||
0.0,
|
||||
),
|
||||
VisionDeficiency::Protanopia => (
|
||||
[
|
||||
[0.152, 1.053, -0.205],
|
||||
[0.115, 0.786, 0.099],
|
||||
[-0.004, -0.048, 1.052],
|
||||
],
|
||||
0.0,
|
||||
),
|
||||
VisionDeficiency::Tritanopia => (
|
||||
[
|
||||
[1.256, -0.077, -0.179],
|
||||
[-0.078, 0.931, 0.148],
|
||||
[0.005, 0.691, 0.304],
|
||||
],
|
||||
0.0,
|
||||
),
|
||||
};
|
||||
let linear: [f32; 256] = std::array::from_fn(|byte| decode_srgb(byte as u8));
|
||||
for pixel in raster.rgba.as_chunks_mut::<4>().0 {
|
||||
let [r, g, b] = [pixel[0], pixel[1], pixel[2]].map(|byte| linear[usize::from(byte)]);
|
||||
for (channel, [red, green, blue]) in pixel[..3].iter_mut().zip(matrix) {
|
||||
*channel = encode_srgb(red * r + green * g + blue * b + offset);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn blur_linear_rgba(raster: &mut RgbaImage, sigma: f32) -> Result<(), moli_image::RgbaImageError> {
|
||||
for pixel in raster.rgba.as_chunks_mut::<4>().0 {
|
||||
let alpha = f32::from(pixel[3]);
|
||||
for channel in &mut pixel[..3] {
|
||||
*channel = (decode_srgb(*channel) * alpha).round() as u8;
|
||||
}
|
||||
}
|
||||
raster.gaussian_blur(sigma)?;
|
||||
for pixel in raster.rgba.as_chunks_mut::<4>().0 {
|
||||
let alpha = f32::from(pixel[3]).max(1.0);
|
||||
for channel in &mut pixel[..3] {
|
||||
*channel = encode_srgb(f32::from(*channel) / alpha);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decode_srgb(byte: u8) -> f32 {
|
||||
let value = f32::from(byte) / 255.0;
|
||||
if value <= 0.04045 {
|
||||
value / 12.92
|
||||
} else {
|
||||
((value + 0.055) / 1.055).powf(2.4)
|
||||
}
|
||||
}
|
||||
|
||||
fn encode_srgb(value: f32) -> u8 {
|
||||
let value = value.clamp(0.0, 1.0);
|
||||
let encoded = if value <= 0.0031308 {
|
||||
value * 12.92
|
||||
} else {
|
||||
1.055 * value.powf(1.0 / 2.4) - 0.055
|
||||
};
|
||||
(encoded * 255.0).round() as u8
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn protanopia_projects_linear_rgb_and_keeps_alpha() {
|
||||
let mut raster = RgbaImage::try_new(1, 1, vec![255, 0, 0, 128]).unwrap();
|
||||
apply(&mut raster, VisionDeficiency::Protanopia, 1.0).unwrap();
|
||||
assert_eq!(raster.rgba, [109, 95, 0, 128]);
|
||||
}
|
||||
}
|
||||
@@ -3413,6 +3413,20 @@ pub struct EmulatedMediaOverrides {
|
||||
pub reduced_transparency: Option<String>,
|
||||
pub forced_colors: Option<String>,
|
||||
pub contrast: Option<String>,
|
||||
pub vision_deficiency: VisionDeficiency,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum VisionDeficiency {
|
||||
#[default]
|
||||
None,
|
||||
BlurredVision,
|
||||
ReducedContrast,
|
||||
Achromatopsia,
|
||||
Deuteranopia,
|
||||
Protanopia,
|
||||
Tritanopia,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
|
||||
Reference in New Issue
Block a user