Skip to content

Truly independent web browser

LibWeb+LibCompositing+Compositor: Fill canvas text with glyphs

Andreas Kling86f608a2ea92
diff --git a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rs b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rs
index a961ad1b3ed..3b98d13bcee 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d.rs
@@ -254,19 +254,21 @@ impl TapeWriter {
self.append(&command, &inline_data);
}
- pub fn draw_glyph_run(
+ pub fn draw_glyph_runs(
&mut self,
- font_id: FontResourceId,
+ runs: &[Canvas2DGlyphRun],
glyphs: &[DisplayListGlyph],
translation: FloatPoint,
+ horizontal_scale: f32,
paint: &Paint,
compositing: &Compositing,
) {
- let mut inline_data = InlineData::new::<Canvas2DDrawGlyphRun>();
- let command = Canvas2DDrawGlyphRun {
- font_id,
+ let mut inline_data = InlineData::new::<Canvas2DDrawGlyphRuns>();
+ let command = Canvas2DDrawGlyphRuns {
+ runs: inline_data.append_objects(runs),
glyphs: inline_data.append_objects(glyphs),
translation,
+ horizontal_scale,
paint: inline_data.append_paint(paint),
compositing: inline_data.append_compositing(compositing),
};
@@ -490,13 +492,17 @@ mod tests {
});
writer.clear_rect(FloatRect::new(0.0, 0.0, 10.0, 10.0), Color(0));
writer.clip_path(&[4, 4, 4, 4], WindingRule::Nonzero);
- writer.draw_glyph_run(
- FontResourceId(7),
+ writer.draw_glyph_runs(
+ &[Canvas2DGlyphRun {
+ font_id: FontResourceId(7),
+ glyph_count: 1,
+ }],
&[DisplayListGlyph {
position: FloatPoint { x: 1.0, y: 0.0 },
glyph_id: 42,
}],
FloatPoint { x: 10.0, y: 20.0 },
+ 1.0,
&Paint::Color(Color(0xff00_ff00)),
&Compositing::default(),
);
@@ -515,7 +521,7 @@ mod tests {
DisplayListCommandType::Canvas2DSetTransform,
DisplayListCommandType::Canvas2DClearRect,
DisplayListCommandType::Canvas2DClipPath,
- DisplayListCommandType::Canvas2DDrawGlyphRun,
+ DisplayListCommandType::Canvas2DDrawGlyphRuns,
DisplayListCommandType::Canvas2DRestore,
DisplayListCommandType::Canvas2DReset,
DisplayListCommandType::Canvas2DClearCanvas,
@@ -639,6 +645,49 @@ mod tests {
}
}
+ #[test]
+ fn glyph_runs_that_do_not_split_their_glyphs_exactly_are_rejected() {
+ let glyph = DisplayListGlyph {
+ position: FloatPoint { x: 0.0, y: 0.0 },
+ glyph_id: 1,
+ };
+ let run = |glyph_count| Canvas2DGlyphRun {
+ font_id: FontResourceId(1),
+ glyph_count,
+ };
+ for (runs, scale, expected) in [
+ (vec![run(1), run(1)], 1.0, Ok(())),
+ (vec![run(2), run(0)], 0.5, Ok(())),
+ (vec![run(1)], 1.0, Err("Canvas glyph runs do not cover their glyphs")),
+ (
+ vec![run(2), run(1)],
+ 1.0,
+ Err("Canvas glyph runs do not cover their glyphs"),
+ ),
+ (
+ vec![run(u64::MAX), run(3)],
+ 1.0,
+ Err("Canvas glyph runs do not cover their glyphs"),
+ ),
+ (
+ vec![run(2)],
+ f32::NAN,
+ Err("Canvas glyph runs have a horizontal scale that is not finite"),
+ ),
+ ] {
+ let mut writer = TapeWriter::default();
+ writer.draw_glyph_runs(
+ &runs,
+ &[glyph, glyph],
+ FloatPoint { x: 0.0, y: 0.0 },
+ scale,
+ &Paint::Color(Color(0xff00_0000)),
+ &Compositing::default(),
+ );
+ assert_eq!(validate_canvas_2d_tape(writer.bytes()), expected);
+ }
+ }
+
#[test]
fn a_command_with_a_bounding_rect_is_rejected() {
let mut writer = TapeWriter::default();
diff --git a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs
index afdc28810ae..8ef70149484 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/canvas_2d_recorder.rs
@@ -141,16 +141,24 @@ impl<T: Transport> Recorder<T> {
self.record(|tape| tape.stroke_path(path, paint, stroke, compositing));
}
- pub fn draw_glyph_run(
+ /// Draws the glyphs of a text as one draw. Each run is a font and how many of the next glyphs it draws.
+ pub fn draw_glyph_runs(
&mut self,
- font: &T::Font,
+ runs: &[(&T::Font, usize)],
glyphs: &[DisplayListGlyph],
translation: FloatPoint,
+ horizontal_scale: f32,
paint: &Paint,
compositing: &Compositing,
) {
- let font_id = self.transport.add_font(font);
- self.record(|tape| tape.draw_glyph_run(font_id, glyphs, translation, paint, compositing));
+ let runs: Vec<Canvas2DGlyphRun> = runs
+ .iter()
+ .map(|(font, glyph_count)| Canvas2DGlyphRun {
+ font_id: self.transport.add_font(font),
+ glyph_count: *glyph_count as u64,
+ })
+ .collect();
+ self.record(|tape| tape.draw_glyph_runs(&runs, glyphs, translation, horizontal_scale, paint, compositing));
}
pub fn clear_rect(&mut self, rect: FloatRect, color: Color) {
@@ -337,15 +345,17 @@ mod tests {
}
#[test]
- fn a_glyph_run_adds_its_font_before_its_record_names_it() {
+ fn glyph_runs_add_their_fonts_before_their_record_names_them() {
+ let glyph = DisplayListGlyph {
+ position: FloatPoint { x: 0.0, y: 0.0 },
+ glyph_id: 3,
+ };
let mut recorder = Recorder::new(FakeTransport::default());
- recorder.draw_glyph_run(
- &77,
- &[DisplayListGlyph {
- position: FloatPoint { x: 0.0, y: 0.0 },
- glyph_id: 3,
- }],
+ recorder.draw_glyph_runs(
+ &[(&77, 2), (&78, 1)],
+ &[glyph, glyph, glyph],
FloatPoint { x: 1.0, y: 2.0 },
+ 0.5,
&Paint::Color(Color(0xff00_0000)),
&Compositing::default(),
);
@@ -353,12 +363,13 @@ mod tests {
*recorder.transport.events.borrow(),
[
Event::AddFont(77),
- Event::Record(DisplayListCommandType::Canvas2DDrawGlyphRun)
+ Event::AddFont(78),
+ Event::Record(DisplayListCommandType::Canvas2DDrawGlyphRuns)
]
);
- let command = read_command::<Canvas2DDrawGlyphRun>(&payload_of(&recorder.transport.records.borrow()[0]));
- assert_eq!(command.font_id, FontResourceId(77));
+ let command = read_command::<Canvas2DDrawGlyphRuns>(&payload_of(&recorder.transport.records.borrow()[0]));
assert_eq!(command.translation, FloatPoint { x: 1.0, y: 2.0 });
+ assert_eq!(command.horizontal_scale, 0.5);
}
#[test]
diff --git a/Libraries/LibCompositing/Rust/src/display_list/commands.rs b/Libraries/LibCompositing/Rust/src/display_list/commands.rs
index e267f54c225..b5a65f8ff44 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/commands.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/commands.rs
@@ -56,7 +56,7 @@ pub enum DisplayListCommandType {
CompositorNestedContextWheelRegion,
Canvas2DFillPath,
Canvas2DStrokePath,
- Canvas2DDrawGlyphRun,
+ Canvas2DDrawGlyphRuns,
Canvas2DClearRect,
Canvas2DDrawImageFrame,
Canvas2DDrawCanvas,
@@ -107,7 +107,7 @@ impl DisplayListCommandType {
self,
Self::Canvas2DFillPath
| Self::Canvas2DStrokePath
- | Self::Canvas2DDrawGlyphRun
+ | Self::Canvas2DDrawGlyphRuns
| Self::Canvas2DClearRect
| Self::Canvas2DDrawImageFrame
| Self::Canvas2DDrawCanvas
@@ -164,7 +164,7 @@ impl DisplayListCommandType {
Self::CompositorNestedContextWheelRegion => "CompositorNestedContextWheelRegion",
Self::Canvas2DFillPath => "Canvas2DFillPath",
Self::Canvas2DStrokePath => "Canvas2DStrokePath",
- Self::Canvas2DDrawGlyphRun => "Canvas2DDrawGlyphRun",
+ Self::Canvas2DDrawGlyphRuns => "Canvas2DDrawGlyphRuns",
Self::Canvas2DClearRect => "Canvas2DClearRect",
Self::Canvas2DDrawImageFrame => "Canvas2DDrawImageFrame",
Self::Canvas2DDrawCanvas => "Canvas2DDrawCanvas",
@@ -1884,26 +1884,39 @@ impl DisplayListCommand for Canvas2DStrokePath {
const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DStrokePath;
}
-// The glyphs of one font, positioned relative to the translation, with the top of the line box at the glyph position.
+// A font and how many of the next glyphs of a Canvas2DDrawGlyphRuns it draws.
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(C)]
-pub struct Canvas2DDrawGlyphRun {
+pub struct Canvas2DGlyphRun {
pub font_id: FontResourceId,
+ pub glyph_count: u64,
+}
+ffi_bytes_fields!(Canvas2DGlyphRun { font_id, glyph_count });
+
+// The glyphs of a text, positioned relative to the translation, with the top of the line box at the glyph position.
+// The text is a single draw, so that its runs of different fonts share one shadow and one composite. The horizontal
+// scale condenses the glyphs and their positions towards the translation.
+#[derive(Clone, Copy, Debug, PartialEq)]
+#[repr(C)]
+pub struct Canvas2DDrawGlyphRuns {
+ pub runs: DisplayListDataSpan,
pub glyphs: DisplayListDataSpan,
pub translation: FloatPoint,
+ pub horizontal_scale: f32,
pub paint: Canvas2DPaint,
pub compositing: Canvas2DCompositing,
}
-ffi_bytes_fields!(Canvas2DDrawGlyphRun {
- font_id,
+ffi_bytes_fields!(Canvas2DDrawGlyphRuns {
+ runs,
glyphs,
translation,
+ horizontal_scale,
paint,
compositing
});
-impl DisplayListCommand for Canvas2DDrawGlyphRun {
- const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DDrawGlyphRun;
+impl DisplayListCommand for Canvas2DDrawGlyphRuns {
+ const COMMAND_TYPE: DisplayListCommandType = DisplayListCommandType::Canvas2DDrawGlyphRuns;
}
#[derive(Clone, Copy, Debug, PartialEq)]
diff --git a/Libraries/LibCompositing/Rust/src/display_list/summary.rs b/Libraries/LibCompositing/Rust/src/display_list/summary.rs
index 4e9bc36fd43..646e459934c 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/summary.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/summary.rs
@@ -151,7 +151,7 @@ fn note_referenced_ids(command_type: DisplayListCommandType, payload: &[u8], ids
// The display list of a page holds none of the commands of the canvas 2D stream.
| T::Canvas2DFillPath
| T::Canvas2DStrokePath
- | T::Canvas2DDrawGlyphRun
+ | T::Canvas2DDrawGlyphRuns
| T::Canvas2DClearRect
| T::Canvas2DDrawImageFrame
| T::Canvas2DDrawCanvas
@@ -304,7 +304,7 @@ fn command_blend(
// The display list of a page holds none of the commands of the canvas 2D stream.
| T::Canvas2DFillPath
| T::Canvas2DStrokePath
- | T::Canvas2DDrawGlyphRun
+ | T::Canvas2DDrawGlyphRuns
| T::Canvas2DClearRect
| T::Canvas2DDrawImageFrame
| T::Canvas2DDrawCanvas
diff --git a/Libraries/LibCompositing/Rust/src/display_list/validate.rs b/Libraries/LibCompositing/Rust/src/display_list/validate.rs
index 8f5393eb705..1e0800d77df 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/validate.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/validate.rs
@@ -112,6 +112,10 @@ impl Payload<'_> {
u32::from_ne_bytes(self.bytes[offset..offset + 4].try_into().unwrap())
}
+ fn u64_at(self, offset: usize) -> u64 {
+ u64::from_ne_bytes(self.bytes[offset..offset + 8].try_into().unwrap())
+ }
+
fn i32_at(self, offset: usize) -> i32 {
i32::from_ne_bytes(self.bytes[offset..offset + 4].try_into().unwrap())
}
@@ -265,6 +269,31 @@ fn validate_paint_style(
}
}
+// The runs must split the glyphs exactly, since the player hands each run the glyphs that follow the previous run.
+fn validate_canvas_2d_glyph_runs(payload: Payload) -> Result<(), ValidationError> {
+ const MISMATCH: ValidationError = "Canvas glyph runs do not cover their glyphs";
+
+ let run_count = payload.array_span_at::<Canvas2DGlyphRun>(offset_of!(Canvas2DDrawGlyphRuns, runs))?;
+ let glyph_count = payload.array_span_at::<DisplayListGlyph>(offset_of!(Canvas2DDrawGlyphRuns, glyphs))?;
+ let (runs_start, _) = payload.span_at(offset_of!(Canvas2DDrawGlyphRuns, runs))?;
+ let mut remaining_glyphs = glyph_count as u64;
+ for run in 0..run_count {
+ let run_offset = runs_start + run * size_of::<Canvas2DGlyphRun>();
+ let run_glyph_count = payload.u64_at(run_offset + offset_of!(Canvas2DGlyphRun, glyph_count));
+ remaining_glyphs = remaining_glyphs.checked_sub(run_glyph_count).ok_or(MISMATCH)?;
+ }
+ if remaining_glyphs != 0 {
+ return Err(MISMATCH);
+ }
+ if !payload
+ .f32_at(offset_of!(Canvas2DDrawGlyphRuns, horizontal_scale))
+ .is_finite()
+ {
+ return Err("Canvas glyph runs have a horizontal scale that is not finite");
+ }
+ Ok(())
+}
+
fn validate_canvas_2d_paint(payload: Payload, offset: usize) -> Result<(), ValidationError> {
payload.enum_at::<Canvas2DPaintKind>(offset + offset_of!(Canvas2DPaint, kind))?;
payload.enum_at::<Canvas2DPatternRepetition>(offset + offset_of!(Canvas2DPaint, pattern_repetition))?;
@@ -343,7 +372,7 @@ fn command_struct_size(command_type: DisplayListCommandType) -> usize {
T::CompositorNestedContextWheelRegion => size_of::<CompositorNestedContextWheelRegion>(),
T::Canvas2DFillPath => size_of::<Canvas2DFillPath>(),
T::Canvas2DStrokePath => size_of::<Canvas2DStrokePath>(),
- T::Canvas2DDrawGlyphRun => size_of::<Canvas2DDrawGlyphRun>(),
+ T::Canvas2DDrawGlyphRuns => size_of::<Canvas2DDrawGlyphRuns>(),
T::Canvas2DClearRect => size_of::<Canvas2DClearRect>(),
T::Canvas2DDrawImageFrame => size_of::<Canvas2DDrawImageFrame>(),
T::Canvas2DDrawCanvas => size_of::<Canvas2DDrawCanvas>(),
@@ -554,10 +583,10 @@ fn validate_command_fields(
p.array_span_at::<f32>(offset_of!(Canvas2DStrokePath, dash_array))?;
validate_canvas_2d_compositing(p, offset_of!(Canvas2DStrokePath, compositing))?;
}
- T::Canvas2DDrawGlyphRun => {
- p.array_span_at::<DisplayListGlyph>(offset_of!(Canvas2DDrawGlyphRun, glyphs))?;
- validate_canvas_2d_paint(p, offset_of!(Canvas2DDrawGlyphRun, paint))?;
- validate_canvas_2d_compositing(p, offset_of!(Canvas2DDrawGlyphRun, compositing))?;
+ T::Canvas2DDrawGlyphRuns => {
+ validate_canvas_2d_glyph_runs(p)?;
+ validate_canvas_2d_paint(p, offset_of!(Canvas2DDrawGlyphRuns, paint))?;
+ validate_canvas_2d_compositing(p, offset_of!(Canvas2DDrawGlyphRuns, compositing))?;
}
T::Canvas2DDrawImageFrame => {
p.enum_at::<ScalingMode>(offset_of!(Canvas2DDrawImageFrame, scaling_mode))?;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_text.rs b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_text.rs
index 74967a99328..ef1b2aadd54 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/canvas_text.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/canvas_text.rs
@@ -13,7 +13,7 @@ use ak::Utf16String;
use libcompositing_rust::display_list::commands::DisplayListGlyph;
use libgfx_rust::path::Path;
use libgfx_rust::text_layout::glyph_run_ink_bounding_box;
-use libgfx_rust::{CompositingAndBlendingOperator, FloatPoint, WindingRule};
+use libgfx_rust::{CompositingAndBlendingOperator, FloatPoint};
use super::text_metrics::{TextMeasurements, TextMetrics};
use crate::bindings::interface::Ref;
@@ -71,40 +71,6 @@ impl<K: CanvasKind> RenderingContext2D<K> {
if !are_finite(x, y, max_width) {
return Ok(());
}
- // https://html.spec.whatwg.org/multipage/canvas.html#text-preparation-algorithm
- // 2. Replace all ASCII whitespace in text with U+0020 SPACE characters.
- let text = replace_ascii_whitespace(&text.to_utf16());
-
- // Complex text effects continue to use the combined outline so they are applied once to the entire text,
- // including runs that use different fallback fonts.
- let has_shadow = {
- let state = self.drawing_state();
- state.shadow_blur != 0.0 || state.shadow_offset_x != 0.0 || state.shadow_offset_y != 0.0
- };
- if max_width.is_some() || has_shadow {
- self.fill_internal(&self.text_path(cx.vm(), &text, x, y, max_width), WindingRule::Nonzero);
- return Ok(());
- }
-
- let font = self.current_font(cx.vm());
- let letter_spacing = self.resolved_letter_spacing();
- let word_spacing = self.resolved_word_spacing();
- let runs = shape_text(
- &font.cascade,
- &text,
- FloatPoint { x: 0.0, y: 0.0 },
- letter_spacing,
- word_spacing,
- );
- let [run] = runs.as_slice() else {
- self.fill_internal(&self.text_path(cx.vm(), &text, x, y, max_width), WindingRule::Nonzero);
- return Ok(());
- };
- if run.font.is_invisible() {
- self.fill_internal(&self.text_path(cx.vm(), &text, x, y, max_width), WindingRule::Nonzero);
- return Ok(());
- }
-
if !self.recorder_is_ready() {
return Ok(());
}
@@ -116,23 +82,63 @@ impl<K: CanvasKind> RenderingContext2D<K> {
return Ok(());
}
}
- let glyphs: Vec<DisplayListGlyph> = run
- .glyphs
- .placed()
- .filter(|placed| placed.glyph.should_paint())
- .map(DisplayListGlyph::from)
+
+ // https://html.spec.whatwg.org/multipage/canvas.html#text-preparation-algorithm
+ // 2. Replace all ASCII whitespace in text with U+0020 SPACE characters.
+ let text = replace_ascii_whitespace(&text.to_utf16());
+
+ let font = self.current_font(cx.vm());
+ let letter_spacing = self.resolved_letter_spacing();
+ let word_spacing = self.resolved_word_spacing();
+ let runs = if max_width.is_some_and(|max_width| max_width <= 0.0) {
+ Vec::new()
+ } else {
+ shape_text(
+ &font.cascade,
+ &text,
+ FloatPoint { x: 0.0, y: 0.0 },
+ letter_spacing,
+ word_spacing,
+ )
+ };
+
+ // NB: The glyphs are not filled as outlines, since the glyphs of a color font can have none. All runs are a
+ // single draw, so that the fallback fonts of the text share one shadow and one composite.
+ let lent_fonts: Vec<LentFont> = runs
+ .iter()
+ .map(|run| LentFont(NonNull::new(run.font.as_raw().cast_mut()).expect("a font has a font")))
.collect();
+ let mut glyphs = Vec::new();
+ let mut glyph_runs = Vec::with_capacity(runs.len());
+ let mut text_width = 0.0;
+ for (run, lent_font) in runs.iter().zip(&lent_fonts) {
+ text_width += run.width;
+ if run.font.is_invisible() {
+ continue;
+ }
+ let first_glyph = glyphs.len();
+ glyphs.extend(
+ run.glyphs
+ .placed()
+ .filter(|placed| placed.glyph.should_paint())
+ .map(DisplayListGlyph::from),
+ );
+ if glyphs.len() > first_glyph {
+ glyph_runs.push((lent_font, glyphs.len() - first_glyph));
+ }
+ }
let first_font = font.cascade.first();
let state = self.drawing_state();
- let translation = text_transform(&state, self.direction_is_rtl(), &first_font, x, run.width, None)
- .map_point(FloatPoint { x, y });
- let lent_font = LentFont(NonNull::new(run.font.as_raw().cast_mut()).expect("a font has a font"));
+ let transform = text_transform(&state, self.direction_is_rtl(), &first_font, x, text_width, max_width);
+ let translation = transform.map_point(FloatPoint { x, y });
+ let horizontal_scale = transform.a();
self.record(|recorder| {
let paint = paint_of(recorder, &state.fill_style, self.context_attributes.color_space);
- recorder.draw_glyph_run(
- &lent_font,
+ recorder.draw_glyph_runs(
+ &glyph_runs,
&glyphs,
translation,
+ horizontal_scale,
&paint,
&ContextState::compositing(&state),
);
diff --git a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs
index 5edbf016431..9ecb46284b1 100644
--- a/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs
+++ b/Libraries/LibWeb/Rust/src/painting/display_list/dump.rs
@@ -665,7 +665,7 @@ fn dump_command(output: &mut String, command_type: DisplayListCommandType, paylo
// The display list of a page holds none of the commands of the canvas 2D stream.
DisplayListCommandType::Canvas2DFillPath
| DisplayListCommandType::Canvas2DStrokePath
- | DisplayListCommandType::Canvas2DDrawGlyphRun
+ | DisplayListCommandType::Canvas2DDrawGlyphRuns
| DisplayListCommandType::Canvas2DClearRect
| DisplayListCommandType::Canvas2DDrawImageFrame
| DisplayListCommandType::Canvas2DDrawCanvas
diff --git a/Services/Compositor/Canvas2DCommandPlayer.cpp b/Services/Compositor/Canvas2DCommandPlayer.cpp
index c335965a48b..90169a617fa 100644
--- a/Services/Compositor/Canvas2DCommandPlayer.cpp
+++ b/Services/Compositor/Canvas2DCommandPlayer.cpp
@@ -6,7 +6,6 @@
#include <AK/Assertions.h>
#include <Compositor/Canvas2DCommandPlayer.h>
-#include <Compositor/FontSkia.h>
#include <Compositor/PainterSkia.h>
#include <Compositor/PaintingSurface.h>
#include <Compositor/SkiaUtils.h>
@@ -18,7 +17,6 @@
#include <LibGfx/PaintStyle.h>
#include <LibGfx/Path.h>
#include <core/SkCanvas.h>
-#include <core/SkFont.h>
#include <core/SkPaint.h>
namespace Compositor {
@@ -172,16 +170,10 @@ void Canvas2DCommandPlayer::play_command(Canvas2DStrokePath const& command)
m_painter->stroke_path(path, *paint_style, image_filter_from(command.compositing), command.thickness, command.compositing.global_alpha, command.compositing.compositing_and_blending_operator, command.cap_style, command.join_style, command.miter_limit, dash_array, command.dash_offset, shadow_from(command.compositing));
}
-void Canvas2DCommandPlayer::play_command(Canvas2DDrawGlyphRun const& command)
+void Canvas2DCommandPlayer::play_command(Canvas2DDrawGlyphRuns const& command)
{
if (!m_resolvers.font)
return;
- auto const* font = m_resolvers.font(command.font_id.value());
- if (!font)
- return;
- auto sk_font = skia_font(*font, 1);
- if (!sk_font.has_value())
- return;
auto paint_style = paint_style_from(command.paint);
if (!paint_style)
return;
@@ -190,7 +182,21 @@ void Canvas2DCommandPlayer::play_command(Canvas2DDrawGlyphRun const& command)
glyphs.ensure_capacity(tape_glyphs.size());
for (auto const& glyph : tape_glyphs)
glyphs.unchecked_append({ .position = glyph.position, .glyph_id = glyph.glyph_id });
- m_painter->draw_glyph_run(*font, sk_font.release_value(), glyphs, command.translation, *paint_style, image_filter_from(command.compositing), command.compositing.global_alpha, command.compositing.compositing_and_blending_operator, shadow_from(command.compositing));
+
+ auto tape_runs = inline_objects<Canvas2DGlyphRun>(inline_data(command.runs));
+ Vector<Gfx::CanvasGlyphRun, 2> runs;
+ runs.ensure_capacity(tape_runs.size());
+ size_t first_glyph = 0;
+ for (auto const& run : tape_runs) {
+ // NB: The tape validation guarantees that the runs split the glyphs exactly.
+ auto run_glyphs = glyphs.span().slice(first_glyph, run.glyph_count);
+ first_glyph += run.glyph_count;
+ auto const* font = m_resolvers.font(run.font_id.value());
+ if (!font)
+ continue;
+ runs.unchecked_append({ .font = *font, .glyphs = run_glyphs });
+ }
+ m_painter->draw_glyph_runs(runs, command.translation, command.horizontal_scale, *paint_style, image_filter_from(command.compositing), command.compositing.global_alpha, command.compositing.compositing_and_blending_operator, shadow_from(command.compositing));
}
void Canvas2DCommandPlayer::play_command(Canvas2DClearRect const& command)
diff --git a/Services/Compositor/PainterSkia.cpp b/Services/Compositor/PainterSkia.cpp
index 4bd1edd584d..d2ad5eab48f 100644
--- a/Services/Compositor/PainterSkia.cpp
+++ b/Services/Compositor/PainterSkia.cpp
@@ -12,6 +12,7 @@
#include <AK/GenericShorthands.h>
#include <AK/String.h>
#include <AK/TypeCasts.h>
+#include <Compositor/FontSkia.h>
#include <Compositor/PainterSkia.h>
#include <Compositor/SkiaUtils.h>
#include <LibGfx/DecodedImageFrame.h>
@@ -387,24 +388,42 @@ void PainterSkia::fill_path(Gfx::Path const& path, Gfx::PaintStyle const& paint_
});
}
-void PainterSkia::draw_glyph_run(Font const& font, SkFont sk_font, ReadonlySpan<CanvasGlyph> glyphs, FloatPoint translation, PaintStyle const& style, sk_sp<SkImageFilter> image_filter, float global_alpha, CompositingAndBlendingOperator compositing_and_blending_operator, Optional<CanvasShadow> const& shadow)
+void PainterSkia::draw_glyph_runs(ReadonlySpan<CanvasGlyphRun> runs, FloatPoint translation, float horizontal_scale, PaintStyle const& style, sk_sp<SkImageFilter> image_filter, float global_alpha, CompositingAndBlendingOperator compositing_and_blending_operator, Optional<CanvasShadow> const& shadow)
{
- if (glyphs.is_empty() || font.is_invisible())
- return;
+ struct SkiaGlyphRun {
+ SkFont font;
+ Vector<SkGlyphID, 32> glyph_ids;
+ Vector<SkPoint, 32> glyph_positions;
+ };
+
+ Vector<SkiaGlyphRun, 2> skia_runs;
+ skia_runs.ensure_capacity(runs.size());
+ for (auto const& run : runs) {
+ if (run.glyphs.is_empty() || run.font.is_invisible())
+ continue;
+
+ auto sk_font = Compositor::skia_font(run.font, 1);
+ if (!sk_font.has_value())
+ continue;
+
+ SkiaGlyphRun skia_run { .font = sk_font.release_value(), .glyph_ids = {}, .glyph_positions = {} };
+
+ // NB: Preserve canvas text's fractional baseline and unhinted outline geometry.
+ skia_run.font.setHinting(SkFontHinting::kNone);
+ skia_run.font.setForceAutoHinting(false);
+ skia_run.font.setBaselineSnap(false);
- // NB: Preserve canvas text's fractional baseline and unhinted outline geometry.
- sk_font.setHinting(SkFontHinting::kNone);
- sk_font.setForceAutoHinting(false);
- sk_font.setBaselineSnap(false);
-
- Vector<SkGlyphID, 32> glyph_ids;
- Vector<SkPoint, 32> glyph_positions;
- glyph_ids.ensure_capacity(glyphs.size());
- glyph_positions.ensure_capacity(glyphs.size());
- auto font_ascent = font.pixel_metrics().ascent;
- for (auto const& glyph : glyphs) {
- glyph_ids.unchecked_append(static_cast<SkGlyphID>(glyph.glyph_id));
- glyph_positions.unchecked_append({ glyph.position.x(), glyph.position.y() + font_ascent });
+ // NB: The scale goes on the font rather than the canvas, as it must not scale the paint of the text.
+ skia_run.font.setScaleX(skia_run.font.getScaleX() * horizontal_scale);
+
+ skia_run.glyph_ids.ensure_capacity(run.glyphs.size());
+ skia_run.glyph_positions.ensure_capacity(run.glyphs.size());
+ auto font_ascent = run.font.pixel_metrics().ascent;
+ for (auto const& glyph : run.glyphs) {
+ skia_run.glyph_ids.unchecked_append(static_cast<SkGlyphID>(glyph.glyph_id));
+ skia_run.glyph_positions.unchecked_append({ glyph.position.x() * horizontal_scale, glyph.position.y() + font_ascent });
+ }
+ skia_runs.unchecked_append(move(skia_run));
}
auto paint = to_skia_paint(style, move(image_filter), color_space());
@@ -414,7 +433,27 @@ void PainterSkia::draw_glyph_run(Font const& font, SkFont sk_font, ReadonlySpan<
// scanning every entry of that blob. Canvas text is often redrawn at moving fractional positions, which
// piles up thousands of entries per blob and makes each draw scan all of them.
draw_with_compositing(m_painting_surface->canvas(), paint, compositing_and_blending_operator, shadow, [&](SkCanvas& canvas, SkPaint const& paint) {
- canvas.drawGlyphs({ glyph_ids.data(), glyph_ids.size() }, { glyph_positions.data(), glyph_positions.size() }, to_skia_point(translation), sk_font, paint);
+ auto draw_runs = [&](SkPaint const& run_paint) {
+ for (auto const& run : skia_runs)
+ canvas.drawGlyphs({ run.glyph_ids.data(), run.glyph_ids.size() }, { run.glyph_positions.data(), run.glyph_positions.size() }, to_skia_point(translation), run.font, run_paint);
+ };
+
+ if (skia_runs.size() <= 1 || !paint.getImageFilter()) {
+ draw_runs(paint);
+ return;
+ }
+
+ // NB: The filter of the context applies to the text as a whole, so it goes on a layer that holds all runs.
+ // Otherwise, what the filter makes of one run would land on top of the other runs.
+ SkPaint layer_paint;
+ layer_paint.setImageFilter(paint.refImageFilter());
+ layer_paint.setBlender(paint.refBlender());
+ SkPaint run_paint = paint;
+ run_paint.setImageFilter(nullptr);
+ run_paint.setBlender(nullptr);
+ canvas.saveLayer(nullptr, &layer_paint);
+ draw_runs(run_paint);
+ canvas.restore();
});
}
diff --git a/Services/Compositor/PainterSkia.h b/Services/Compositor/PainterSkia.h
index 8a14951daad..9964a3c7bba 100644
--- a/Services/Compositor/PainterSkia.h
+++ b/Services/Compositor/PainterSkia.h
@@ -20,7 +20,6 @@
#include <LibGfx/WindingRule.h>
class SkColorSpace;
-class SkFont;
class SkImage;
class SkImageFilter;
template<typename T>
@@ -41,6 +40,11 @@ struct CanvasGlyph {
u32 glyph_id { 0 };
};
+struct CanvasGlyphRun {
+ Font const& font;
+ ReadonlySpan<CanvasGlyph> glyphs;
+};
+
class PainterSkia final {
public:
AK_ALLOC_WITH_KMALLOC;
@@ -54,7 +58,7 @@ public:
void draw_image(SkImage const&, Gfx::FloatRect const& dst_rect, Gfx::FloatRect const& src_rect, Gfx::ScalingMode, sk_sp<SkImageFilter>, float global_alpha, Gfx::CompositingAndBlendingOperator compositing_and_blending_operator, Optional<CanvasShadow> const&);
void stroke_path(Gfx::Path const&, Gfx::PaintStyle const&, sk_sp<SkImageFilter>, float thickness, float global_alpha, Gfx::CompositingAndBlendingOperator compositing_and_blending_operator, Gfx::Path::CapStyle const&, Gfx::Path::JoinStyle const&, float miter_limit, Vector<float> const&, float dash_offset, Optional<CanvasShadow> const&);
void fill_path(Gfx::Path const&, Gfx::PaintStyle const&, sk_sp<SkImageFilter>, float global_alpha, Gfx::CompositingAndBlendingOperator compositing_and_blending_operator, Gfx::WindingRule, Optional<CanvasShadow> const&);
- void draw_glyph_run(Font const&, SkFont, ReadonlySpan<CanvasGlyph>, FloatPoint translation, PaintStyle const&, sk_sp<SkImageFilter>, float global_alpha, CompositingAndBlendingOperator, Optional<CanvasShadow> const&);
+ void draw_glyph_runs(ReadonlySpan<CanvasGlyphRun>, FloatPoint translation, float horizontal_scale, PaintStyle const&, sk_sp<SkImageFilter>, float global_alpha, CompositingAndBlendingOperator, Optional<CanvasShadow> const&);
void set_transform(Gfx::AffineTransform const&);
void save();
void restore();
diff --git a/Tests/LibWeb/Screenshot/expected/canvas-text.png b/Tests/LibWeb/Screenshot/expected/canvas-text.png
index befedd16d81..3ad8bc8eb81 100644
Binary files a/Tests/LibWeb/Screenshot/expected/canvas-text.png and b/Tests/LibWeb/Screenshot/expected/canvas-text.png differ
diff --git a/Tests/LibWeb/Text/expected/canvas/fill-text-color-glyphs.txt b/Tests/LibWeb/Text/expected/canvas/fill-text-color-glyphs.txt
index d0833d1ad5c..c0ca5fc5b6e 100644
--- a/Tests/LibWeb/Text/expected/canvas/fill-text-color-glyphs.txt
+++ b/Tests/LibWeb/Text/expected/canvas/fill-text-color-glyphs.txt
@@ -1,8 +1,8 @@
alone: color ink: true
-mixed: first glyph: true, color ink: false
-maxWidth that fits: first glyph: true, color ink: false
-maxWidth that condenses: color ink inside: false, color ink outside: false
-shadow: color ink: false, shadow of the color glyph: false
-shadow on an earlier run: first glyph: true, color ink: false
-filter: first glyph: true, color ink: false
-copy: first glyph: true, color ink: false
+mixed: first glyph: true, color ink: true
+maxWidth that fits: first glyph: true, color ink: true
+maxWidth that condenses: color ink inside: true, color ink outside: false
+shadow: color ink: true, shadow of the color glyph: true
+shadow on an earlier run: first glyph: true, color ink: true
+filter: first glyph: true, color ink: true
+copy: first glyph: true, color ink: true