Skip to content

Truly independent web browser

LibGfx+LibCompositing+Compositor: Render LCD text on Linux

Timothy Flynncf61b3ec1ff0
diff --git a/Libraries/LibCompositing/Rust/src/display_list/commands.rs b/Libraries/LibCompositing/Rust/src/display_list/commands.rs
index fdfc1fc2c40..09ba8131958 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/commands.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/commands.rs
@@ -247,6 +247,7 @@ pub struct ReplayClip {
pub struct ReplayLayer {
pub opacity: f32,
pub blend_mode: CompositingAndBlendingOperator,
+ pub can_draw_directly_for_lcd_text: bool,
pub filter_bytes: *const u8,
pub filter_bytes_size: usize,
pub backdrop_filter_bytes: *const u8,
diff --git a/Libraries/LibCompositing/Rust/src/display_list/replay.rs b/Libraries/LibCompositing/Rust/src/display_list/replay.rs
index 76de236d14a..e169daf1004 100644
--- a/Libraries/LibCompositing/Rust/src/display_list/replay.rs
+++ b/Libraries/LibCompositing/Rust/src/display_list/replay.rs
@@ -679,6 +679,7 @@ fn return_replay_scratch_storage(mut storage: ReplayScratchStorage) {
pub struct ReplaySelection<'a> {
pub record_spans: Option<&'a [RecordSpan]>,
pub skip_root_isolation_layer: bool,
+ pub allows_lcd_text: bool,
}
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -757,6 +758,7 @@ fn replay_layer_of(
ReplayLayer {
opacity: effects.opacity,
blend_mode: effects.blend_mode,
+ can_draw_directly_for_lcd_text: false,
filter_bytes,
filter_bytes_size,
backdrop_filter_bytes,
@@ -1126,6 +1128,11 @@ impl<Painter: ReplayPainter + ?Sized> ReplayDriver<'_, Painter> {
layer.backdrop_base_color = self.backdrop_base_color(effect);
layer.backdrop_blur_edge = self.backdrop_blur_edge(effect);
}
+ // The canvas fill was recorded before this group. Where it painted opaque pixels,
+ // the painter can blend text directly into them.
+ layer.can_draw_directly_for_lcd_text = self.selection.allows_lcd_text
+ && tree.root_isolation_effect == Some(effect)
+ && !effects.needs_layer();
self.painter.push_layer(&layer);
}
}
@@ -1449,6 +1456,7 @@ mod tests {
base_matrix: FloatMatrix4x4,
fully_clipped_x: i32,
layer_content_bounds: Vec<Option<FloatRect>>,
+ layers_that_can_draw_directly_for_lcd_text: Vec<bool>,
backdrop_base_colors: Vec<Color>,
run_record_sizes: Vec<usize>,
filled_rects: Vec<IntRect>,
@@ -1462,6 +1470,7 @@ mod tests {
base_matrix: translation_matrix(100.0, 200.0, 0.0),
fully_clipped_x: i32::MIN,
layer_content_bounds: Vec::new(),
+ layers_that_can_draw_directly_for_lcd_text: Vec::new(),
backdrop_base_colors: Vec::new(),
run_record_sizes: Vec::new(),
filled_rects: Vec::new(),
@@ -1489,6 +1498,8 @@ mod tests {
fn push_layer(&mut self, layer: &ReplayLayer) {
self.events.push(PainterEvent::PushLayer(layer.opacity));
self.layer_content_bounds.push(layer.content_bounds.get());
+ self.layers_that_can_draw_directly_for_lcd_text
+ .push(layer.can_draw_directly_for_lcd_text);
if layer.backdrop_filter_bytes_size != 0 {
self.backdrop_base_colors.push(layer.backdrop_base_color);
}
@@ -1720,7 +1731,7 @@ mod tests {
8,
ReplaySelection {
record_spans: Some(&spans),
- skip_root_isolation_layer: false,
+ ..Default::default()
},
);
assert_eq!(
@@ -1751,7 +1762,7 @@ mod tests {
16,
ReplaySelection {
record_spans: Some(&spans),
- skip_root_isolation_layer: false,
+ ..Default::default()
},
);
assert_eq!(painter.events, vec![PainterEvent::Run(0), PainterEvent::Run(1)]);
@@ -1779,8 +1790,8 @@ mod tests {
&mut runs,
8,
ReplaySelection {
- record_spans: None,
skip_root_isolation_layer: true,
+ ..Default::default()
},
);
assert_eq!(
@@ -1794,6 +1805,48 @@ mod tests {
);
}
+ #[test]
+ fn only_the_plain_root_layer_of_an_lcd_presentation_can_draw_directly() {
+ let mut tree = identity_tree();
+ let root = effect_under(&mut tree, effects(1.0), EffectNodeIndex::NONE, ClipNodeIndex::NONE);
+ tree.root_isolation_effect = Some(root);
+ let nested = effect_under(&mut tree, effects(0.5), root, ClipNodeIndex::NONE);
+ let runs = [root, nested].map(|effect| {
+ run(
+ VISUAL_VIEWPORT_NODE_INDEX,
+ ContextRef {
+ effect,
+ ..ContextRef::default()
+ },
+ visible_bounds(),
+ )
+ });
+ let effect_clips = EffectClipPlan::new(&tree, &runs).unwrap();
+
+ let white = Color::from_rgb(255, 255, 255);
+ for (color, allows_lcd_text, expected) in [
+ (white, true, [true, false]),
+ (white, false, [false, false]),
+ (Color::TRANSPARENT, true, [true, false]),
+ ] {
+ let mut painter = RecordingPainter::new();
+ replay_display_list(
+ &tree,
+ &[],
+ &runs,
+ &effect_clips,
+ color,
+ &ReplayFrame::unscrolled(0),
+ ReplaySelection {
+ allows_lcd_text,
+ ..Default::default()
+ },
+ &mut painter,
+ );
+ assert_eq!(painter.layers_that_can_draw_directly_for_lcd_text, expected);
+ }
+ }
+
#[test]
fn an_inline_clip_in_a_space_of_its_own_is_pushed_under_the_matrix_of_that_space() {
let clip_space = SpatialNodeIndex(7);
diff --git a/Libraries/LibCompositing/Rust/src/host/replay.rs b/Libraries/LibCompositing/Rust/src/host/replay.rs
index e0ff0adb848..fb705c14e55 100644
--- a/Libraries/LibCompositing/Rust/src/host/replay.rs
+++ b/Libraries/LibCompositing/Rust/src/host/replay.rs
@@ -42,6 +42,7 @@ impl FfiReplaySelection {
.replays_only_record_spans
.then(|| unsafe { ak::slice_from_raw_parts(self.record_spans, self.record_span_count) }),
skip_root_isolation_layer: self.skip_root_isolation_layer,
+ allows_lcd_text: false,
}
}
}
diff --git a/Libraries/LibGfx/Font/GlobalFontConfig.cpp b/Libraries/LibGfx/Font/GlobalFontConfig.cpp
index 2f0292f645a..3d7cd5629f3 100644
--- a/Libraries/LibGfx/Font/GlobalFontConfig.cpp
+++ b/Libraries/LibGfx/Font/GlobalFontConfig.cpp
@@ -8,6 +8,7 @@
#include <AK/ByteString.h>
#include <AK/LsanSuppressions.h>
#include <AK/NeverDestroyed.h>
+#include <AK/ScopeGuard.h>
#include <LibGfx/Font/GlobalFontConfig.h>
#include <fontconfig/fontconfig.h>
@@ -31,9 +32,56 @@ GlobalFontConfig::GlobalFontConfig()
FcConfigReference(m_config);
}
-FontHintingOptions GlobalFontConfig::hinting_for_font(FlyString const& family, float pixel_size, u16 weight, u8 slope)
+static FcPattern* resolve_rendering_pattern(FcConfig* config, FcPattern* query, FcChar8 const* font_family = nullptr)
{
- FontHintingOptions options;
+ FcConfigSubstitute(config, query, FcMatchPattern);
+ // The display-wide lookup has no font size or style for a rule to match.
+ if (font_family)
+ FcDefaultSubstitute(query);
+
+ // Substitute a duplicate of the query in place of a matched font, so that font-target rules apply without
+ // matching against the font set.
+ auto* pattern = FcPatternDuplicate(query);
+ if (!pattern)
+ return nullptr;
+
+ // Pattern substitution can add default families even when querying the display's pixel order. Only a
+ // selected font should match a font-target family rule.
+ FcPatternDel(pattern, FC_FAMILY);
+ if (font_family && !FcPatternAddString(pattern, FC_FAMILY, font_family)) {
+ FcPatternDestroy(pattern);
+ return nullptr;
+ }
+
+ FcConfigSubstituteWithPat(config, pattern, query, FcMatchFont);
+ return pattern;
+}
+
+static FontSubpixelOrder subpixel_order_of(FcPattern* pattern)
+{
+ FcBool antialias = FcTrue;
+ FcPatternGetBool(pattern, FC_ANTIALIAS, 0, &antialias);
+ int rgba = FC_RGBA_UNKNOWN;
+ if (!antialias || FcPatternGetInteger(pattern, FC_RGBA, 0, &rgba) != FcResultMatch)
+ return FontSubpixelOrder::None;
+
+ switch (rgba) {
+ case FC_RGBA_RGB:
+ return FontSubpixelOrder::RGB;
+ case FC_RGBA_BGR:
+ return FontSubpixelOrder::BGR;
+ case FC_RGBA_VRGB:
+ return FontSubpixelOrder::VerticalRGB;
+ case FC_RGBA_VBGR:
+ return FontSubpixelOrder::VerticalBGR;
+ default:
+ return FontSubpixelOrder::None;
+ }
+}
+
+FontRenderingOptions GlobalFontConfig::rendering_options_for_font(FlyString const& family, float pixel_size, u16 weight, u8 slope)
+{
+ FontRenderingOptions options;
FcPattern* pattern = FcPatternCreate();
if (!pattern)
@@ -47,24 +95,10 @@ FontHintingOptions GlobalFontConfig::hinting_for_font(FlyString const& family, f
FcPatternAddInteger(pattern, FC_SLANT, fontconfig_slant(slope));
- FcConfigSubstitute(m_config, pattern, FcMatchPattern);
- FcDefaultSubstitute(pattern);
-
- // Substitute a duplicate of the query pattern in place of a matched font, so that font-target
- // rules testing family or size apply without matching against the font set.
- FcPattern* font_pattern = FcPatternDuplicate(pattern);
- if (!font_pattern) {
- FcPatternDestroy(pattern);
- return options;
- }
- // Font-target rules apply to the selected family. Pattern substitution adds fallback families to the query.
- FcPatternDel(font_pattern, FC_FAMILY);
- if (!FcPatternAddString(font_pattern, FC_FAMILY, font_family)) {
- FcPatternDestroy(font_pattern);
- FcPatternDestroy(pattern);
+ auto* font_pattern = resolve_rendering_pattern(m_config, pattern, font_family);
+ FcPatternDestroy(pattern);
+ if (!font_pattern)
return options;
- }
- FcConfigSubstituteWithPat(m_config, font_pattern, pattern, FcMatchFont);
FcBool hinting_enabled = FcTrue;
FcPatternGetBool(font_pattern, FC_HINTING, 0, &hinting_enabled);
@@ -73,23 +107,37 @@ FontHintingOptions GlobalFontConfig::hinting_for_font(FlyString const& family, f
FcPatternGetInteger(font_pattern, FC_HINT_STYLE, 0, &hint_style);
if (!hinting_enabled || hint_style == FC_HINT_NONE)
- options.style = FontHintingStyle::None;
+ options.hinting_style = FontHintingStyle::None;
else if (hint_style == FC_HINT_SLIGHT)
- options.style = FontHintingStyle::Slight;
+ options.hinting_style = FontHintingStyle::Slight;
else if (hint_style == FC_HINT_MEDIUM)
- options.style = FontHintingStyle::Normal;
+ options.hinting_style = FontHintingStyle::Normal;
else
- options.style = FontHintingStyle::Full;
+ options.hinting_style = FontHintingStyle::Full;
FcBool autohint = FcFalse;
FcPatternGetBool(font_pattern, FC_AUTOHINT, 0, &autohint);
options.force_autohinting = autohint;
+ options.allows_lcd_text = subpixel_order_of(font_pattern) != FontSubpixelOrder::None;
FcPatternDestroy(font_pattern);
- FcPatternDestroy(pattern);
return options;
}
+FontSubpixelOrder GlobalFontConfig::subpixel_order() const
+{
+ auto* query = FcPatternCreate();
+ if (!query)
+ return FontSubpixelOrder::None;
+ auto* pattern = resolve_rendering_pattern(m_config, query);
+ FcPatternDestroy(query);
+ if (!pattern)
+ return FontSubpixelOrder::None;
+ ScopeGuard destroy_pattern = [&] { FcPatternDestroy(pattern); };
+
+ return subpixel_order_of(pattern);
+}
+
GlobalFontConfig::~GlobalFontConfig()
{
FcConfigDestroy(m_config);
diff --git a/Libraries/LibGfx/Font/GlobalFontConfig.h b/Libraries/LibGfx/Font/GlobalFontConfig.h
index 34a4f9bf85a..2fe253ead51 100644
--- a/Libraries/LibGfx/Font/GlobalFontConfig.h
+++ b/Libraries/LibGfx/Font/GlobalFontConfig.h
@@ -25,9 +25,18 @@ enum class FontHintingStyle {
Full,
};
-struct FontHintingOptions {
- FontHintingStyle style { FontHintingStyle::Normal };
+enum class FontSubpixelOrder {
+ None,
+ RGB,
+ BGR,
+ VerticalRGB,
+ VerticalBGR,
+};
+
+struct FontRenderingOptions {
+ FontHintingStyle hinting_style { FontHintingStyle::Normal };
bool force_autohinting { false };
+ bool allows_lcd_text { false };
};
// The FC_SLANT value for a slope of 0 for upright, 1 for italic or 2 for oblique.
@@ -38,7 +47,8 @@ public:
static GlobalFontConfig& the();
FcConfig* get();
- FontHintingOptions hinting_for_font(FlyString const& family, float pixel_size, u16 weight, u8 slope);
+ FontRenderingOptions rendering_options_for_font(FlyString const& family, float pixel_size, u16 weight, u8 slope);
+ FontSubpixelOrder subpixel_order() const;
private:
friend class AK::NeverDestroyed<GlobalFontConfig>;
diff --git a/Libraries/LibWebView/Application.cpp b/Libraries/LibWebView/Application.cpp
index be6436aa6c0..e52cec1c920 100644
--- a/Libraries/LibWebView/Application.cpp
+++ b/Libraries/LibWebView/Application.cpp
@@ -1658,6 +1658,13 @@ void Application::update_compositor_context_presents_from_cpu_memory(Web::Compos
m_compositor_client->async_set_context_presents_from_cpu_memory(context_id, presents_from_cpu_memory);
}
+void Application::update_compositor_context_scales_frames_to_fit(Web::CompositorContextId context_id, bool scales_frames_to_fit)
+{
+ if (!can_send_compositor_process_ipc(m_compositor_client))
+ return;
+ m_compositor_client->async_set_context_scales_frames_to_fit(context_id, scales_frames_to_fit);
+}
+
bool Application::handle_and_dispatch_key_event_in_compositor(Web::CompositorContextId context_id, Web::KeyEvent const& event, bool allow_keyboard_scroll)
{
if (!can_send_compositor_process_ipc(m_compositor_presentation_client))
diff --git a/Libraries/LibWebView/Application.h b/Libraries/LibWebView/Application.h
index 05226ced263..0d8308f2e82 100644
--- a/Libraries/LibWebView/Application.h
+++ b/Libraries/LibWebView/Application.h
@@ -274,6 +274,7 @@ public:
void update_compositor_display_metadata(Web::CompositorContextId, Optional<u64> display_id, double refresh_rate);
void update_compositor_context_visibility(Web::CompositorContextId, Web::HTML::VisibilityState);
void update_compositor_context_presents_from_cpu_memory(Web::CompositorContextId, bool);
+ void update_compositor_context_scales_frames_to_fit(Web::CompositorContextId, bool);
struct RemoteLayer {
u64 id { 0 };
diff --git a/Libraries/LibWebView/ViewImplementation.cpp b/Libraries/LibWebView/ViewImplementation.cpp
index dbac65baf5a..5b03fa47dc6 100644
--- a/Libraries/LibWebView/ViewImplementation.cpp
+++ b/Libraries/LibWebView/ViewImplementation.cpp
@@ -522,7 +522,12 @@ void ViewImplementation::commit_synchronized_resize(u64 token)
void ViewImplementation::set_scales_frames_to_fit(bool scales_frames_to_fit)
{
+ if (m_scales_frames_to_fit == scales_frames_to_fit)
+ return;
+
m_scales_frames_to_fit = scales_frames_to_fit;
+ if (has_traversable())
+ Application::the().update_compositor_context_scales_frames_to_fit(page().compositor_context_id(), scales_frames_to_fit);
update_remote_layer_fit();
}
@@ -3680,6 +3685,7 @@ void ViewImplementation::prepare_page_for_tab(WebContentPage& page)
// The window handle names the tab to WebDriver, and the viewport is the tab's: both belong to the page displaying
// it, whose traversable is local.
page.async_set_window_handle(m_window_handle);
+ Application::the().update_compositor_context_scales_frames_to_fit(page.compositor_context_id(), m_scales_frames_to_fit);
page.async_set_viewport(viewport_size(), m_device_pixel_ratio, m_is_fullscreen);
Application::the().update_compositor_viewport(page.compositor_context_id(), viewport_size().to_type<int>(), m_device_pixel_ratio);
}
@@ -3756,6 +3762,7 @@ void ViewImplementation::display_page_changed(RefPtr<WebContentPage> previous_pa
install_backing_stores(move(backing_stores->bitmap_ids), move(backing_stores->backing_stores));
auto compositor_context_id = page.compositor_context_id();
+ Application::the().update_compositor_context_scales_frames_to_fit(compositor_context_id, m_scales_frames_to_fit);
// The remote layer goes on showing the outgoing page's last frame until the page presents its first one.
if (m_remote_layer_id.has_value())
Application::the().show_context_in_remote_layer(*m_remote_layer_id, compositor_context_id);
diff --git a/Libraries/LibWebView/ViewImplementation.h b/Libraries/LibWebView/ViewImplementation.h
index 7d5b6389439..f71dce3491d 100644
--- a/Libraries/LibWebView/ViewImplementation.h
+++ b/Libraries/LibWebView/ViewImplementation.h
@@ -314,6 +314,7 @@ public:
// Sends the screens that screen_rects() reports to every page hosting documents of the tab.
void update_screen_rects();
void set_scales_frames_to_fit(bool);
+ bool scales_frames_to_fit() const { return m_scales_frames_to_fit; }
void enable_picture_in_picture_controls();
void enqueue_input_event(Web::InputEvent);
// The page reporting on an event must be the one handling it.
diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cpp
index 61fd4e91d23..97c9bc0cdb6 100644
--- a/Libraries/LibWebView/WebContentClient.cpp
+++ b/Libraries/LibWebView/WebContentClient.cpp
@@ -570,6 +570,7 @@ void WebContentClient::replay_compositor_view_state_after_reconnect(Badge<Applic
if (!m_compositor_contexts.contains(context_id))
continue;
auto& view = page->view();
+ Application::the().update_compositor_context_scales_frames_to_fit(context_id, view.scales_frames_to_fit());
view.recreate_remote_layer_after_compositor_reconnect({});
Application::the().update_compositor_viewport(context_id, view.viewport_size().to_type<int>(), view.device_pixel_ratio());
Application::the().update_compositor_display_metadata(context_id, view.display_id(), view.maximum_frames_per_second());
diff --git a/Services/Compositor/BackingStoreManager.cpp b/Services/Compositor/BackingStoreManager.cpp
index 241e796f090..b1f19c8d4fd 100644
--- a/Services/Compositor/BackingStoreManager.cpp
+++ b/Services/Compositor/BackingStoreManager.cpp
@@ -26,7 +26,7 @@ namespace Compositor {
#if defined(USE_DIRECTX) || defined(USE_VULKAN)
static NonnullRefPtr<Gfx::PaintingSurface> create_gpu_painting_surface_with_bitmap_flush(Gfx::IntSize size, Gfx::SharedImageBuffer& buffer, RefPtr<Gfx::SkiaBackendContext> const& skia_backend_context)
{
- auto surface = Gfx::PaintingSurface::create_with_size(size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, skia_backend_context);
+ auto surface = Gfx::PaintingSurface::create_with_size(size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, skia_backend_context, {}, Gfx::PaintingSurface::TextAntialiasing::LCD);
auto bitmap = buffer.bitmap();
surface->on_flush = [bitmap = move(bitmap)](auto& surface) {
surface.read_into_bitmap(*bitmap);
@@ -49,7 +49,7 @@ static NonnullRefPtr<Gfx::PaintingSurface> create_shareable_bitmap_backing_store
# endif
#endif
- return Gfx::PaintingSurface::wrap_bitmap(*buffer.bitmap());
+ return Gfx::PaintingSurface::wrap_bitmap(*buffer.bitmap(), Gfx::PaintingSurface::TextAntialiasing::LCD);
}
#if defined(USE_VULKAN_DMABUF_IMAGES) || defined(USE_DIRECTX)
@@ -97,7 +97,7 @@ static ErrorOr<GpuBackingStore> create_shared_gpu_backing_store(Gfx::IntSize siz
auto shared_image = Gfx::duplicate_shared_image(*image);
return GpuBackingStore {
- .surface = Gfx::PaintingSurface::create_from_vkimage(skia_backend_context, move(image), Gfx::PaintingSurface::Origin::TopLeft),
+ .surface = Gfx::PaintingSurface::create_from_vkimage(skia_backend_context, move(image), Gfx::PaintingSurface::Origin::TopLeft, Gfx::PaintingSurface::TextAntialiasing::LCD),
.shared_image = move(shared_image),
};
}
diff --git a/Services/Compositor/CompositorControlServer.ipc b/Services/Compositor/CompositorControlServer.ipc
index 567dcedd807..a4b931f5634 100644
--- a/Services/Compositor/CompositorControlServer.ipc
+++ b/Services/Compositor/CompositorControlServer.ipc
@@ -34,5 +34,6 @@ endpoint CompositorControlServer
set_context_visibility(Web::CompositorContextId context_id, Compositing::ContextVisibility visibility) =|
set_context_presents_from_cpu_memory(Web::CompositorContextId context_id, bool presents_from_cpu_memory) =|
+ set_context_scales_frames_to_fit(Web::CompositorContextId context_id, bool scales_frames_to_fit) =|
crash() =|
}
diff --git a/Services/Compositor/CompositorCore.cpp b/Services/Compositor/CompositorCore.cpp
index 733ee1377b1..a0e64158209 100644
--- a/Services/Compositor/CompositorCore.cpp
+++ b/Services/Compositor/CompositorCore.cpp
@@ -222,6 +222,11 @@ void CompositorCore::set_presents_from_cpu_memory(Web::CompositorContextId conte
RustFFI::compositor_core_set_presents_from_cpu_memory(m_core, context_id.value(), presents_from_cpu_memory, now().nanoseconds());
}
+void CompositorCore::set_scales_frames_to_fit(Web::CompositorContextId context_id, bool scales_frames_to_fit)
+{
+ RustFFI::compositor_core_set_scales_frames_to_fit(m_core, context_id.value(), scales_frames_to_fit, now().nanoseconds());
+}
+
void CompositorCore::request_rendering_opportunity(Web::CompositorContextId context_id, double maximum_frames_per_second)
{
RustFFI::compositor_core_request_rendering_opportunity(m_core, context_id.value(), maximum_frames_per_second, now().nanoseconds());
diff --git a/Services/Compositor/CompositorCore.h b/Services/Compositor/CompositorCore.h
index 897b71fb074..dad382162ab 100644
--- a/Services/Compositor/CompositorCore.h
+++ b/Services/Compositor/CompositorCore.h
@@ -59,6 +59,7 @@ public:
void set_display_metadata(Web::CompositorContextId, Optional<u64> display_id, double refresh_rate);
void set_window_server_may_show_high_dynamic_range(bool);
void set_presents_from_cpu_memory(Web::CompositorContextId, bool);
+ void set_scales_frames_to_fit(Web::CompositorContextId, bool);
void request_rendering_opportunity(Web::CompositorContextId, double maximum_frames_per_second);
void request_clock_tick(Web::CompositorContextId, double maximum_frames_per_second);
diff --git a/Services/Compositor/CompositorState.cpp b/Services/Compositor/CompositorState.cpp
index fe84630057a..918559ecde5 100644
--- a/Services/Compositor/CompositorState.cpp
+++ b/Services/Compositor/CompositorState.cpp
@@ -883,6 +883,13 @@ void CompositorState::set_context_presents_from_cpu_memory(Web::CompositorContex
m_core.set_presents_from_cpu_memory(context_id, presents_from_cpu_memory);
}
+void CompositorState::set_context_scales_frames_to_fit(Web::CompositorContextId context_id, bool scales_frames_to_fit)
+{
+ if (!presented_context_if_present(context_id))
+ return;
+ m_core.set_scales_frames_to_fit(context_id, scales_frames_to_fit);
+}
+
void CompositorState::request_rendering_opportunity(Web::CompositorContextId context_id, double maximum_frames_per_second)
{
VERIFY(presented_context_if_present(context_id));
@@ -1103,7 +1110,7 @@ CompositorState::PresentedContext& CompositorState::presented_context(Web::Compo
return *context;
}
-Compositing::RustFFI::FfiRasterPainter CompositorState::begin_painting(Web::CompositorContextId context_id, Gfx::PaintingSurface& surface, RustFFI::PaintingResources resources)
+Compositing::RustFFI::FfiRasterPainter CompositorState::begin_painting(Web::CompositorContextId context_id, Gfx::PaintingSurface& surface, RustFFI::PaintingResources resources, bool allows_lcd_text)
{
auto& context = presented_context(context_id);
auto& raster_targets = context.raster_targets;
@@ -1112,9 +1119,7 @@ Compositing::RustFFI::FfiRasterPainter CompositorState::begin_painting(Web::Comp
auto& player = *m_display_list_players[m_painting_depth++];
switch (resources) {
case RustFFI::PaintingResources::Page:
- return player.begin_painting(surface, raster_targets.fonts(), &raster_targets.image_frames(), raster_targets.raster_cache(), &raster_targets.canvas_surfaces(), [this, &client = context.web_content_client](Media::VideoSinkHandle handle) {
- return current_video_frame(client, handle);
- });
+ return player.begin_painting(surface, raster_targets.fonts(), &raster_targets.image_frames(), raster_targets.raster_cache(), &raster_targets.canvas_surfaces(), [this, &client = context.web_content_client](Media::VideoSinkHandle handle) { return current_video_frame(client, handle); }, allows_lcd_text);
case RustFFI::PaintingResources::Overlays:
return player.begin_painting(surface, raster_targets.overlay_fonts(), nullptr, raster_targets.overlay_raster_cache(), nullptr, nullptr);
}
@@ -1680,9 +1685,12 @@ RustFFI::FfiRasterHost CompositorState::raster_host(CompositorState& state)
.surface_retain = [](void* surface) { painting_surface_of(surface).ref(); },
.surface_release = [](void* surface) { painting_surface_of(surface).unref(); },
.surface_size = [](void* surface, Gfx::IntSize* size) { *size = painting_surface_of(surface).size(); },
- .create_surface = [](void* host, Gfx::IntSize size, void* like) -> void* {
+ .create_surface = [](void* host, Gfx::IntSize size, void* like, bool inherits_lcd_text) -> void* {
auto skia_backend_context = like ? painting_surface_of(like).skia_backend_context() : state_of(host).m_skia_backend_context;
- auto surface = Gfx::PaintingSurface::try_create_with_size(size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, skia_backend_context);
+ auto text_antialiasing = Gfx::PaintingSurface::TextAntialiasing::Grayscale;
+ if (inherits_lcd_text && like && canvas_of(like).getBaseProps().pixelGeometry() != kUnknown_SkPixelGeometry)
+ text_antialiasing = Gfx::PaintingSurface::TextAntialiasing::LCD;
+ auto surface = Gfx::PaintingSurface::try_create_with_size(size, Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, skia_backend_context, {}, text_antialiasing);
if (surface.is_error())
return nullptr;
return &surface.release_value().leak_ref();
@@ -1701,7 +1709,7 @@ RustFFI::FfiRasterHost CompositorState::raster_host(CompositorState& state)
paint.setBlendMode(blend == RustFFI::SurfaceBlend::Source ? SkBlendMode::kSrc : SkBlendMode::kSrcOver);
canvas_of(target).drawImageRect(image.get(), Gfx::to_skia_rect(source_rect), Gfx::to_skia_rect(target_rect), SkSamplingOptions {}, &paint, SkCanvas::kStrict_SrcRectConstraint); },
.flush_surface = [](void*, void* surface) { DisplayListPlayerSkia::flush(painting_surface_of(surface)); },
- .begin_painting = [](void* host, u64 context_id, void* surface, RustFFI::PaintingResources resources, Compositing::RustFFI::FfiRasterPainter* painter) { *painter = state_of(host).begin_painting(Context { context_id }, painting_surface_of(surface), resources); },
+ .begin_painting = [](void* host, u64 context_id, void* surface, RustFFI::PaintingResources resources, bool allows_lcd_text, Compositing::RustFFI::FfiRasterPainter* painter) { *painter = state_of(host).begin_painting(Context { context_id }, painting_surface_of(surface), resources, allows_lcd_text); },
.end_painting = [](void* host) { state_of(host).end_painting(); },
.start_raster_cache_frame = [](void* host, u64 context_id) { state_of(host).presented_context(Context { context_id }).raster_targets.raster_cache().drop_what_was_not_used_since_last_frame(); },
.store_state = [](void* host, u64 context_id) -> RustFFI::FfiStoreState {
diff --git a/Services/Compositor/CompositorState.h b/Services/Compositor/CompositorState.h
index bc087afd48c..76a1649b47b 100644
--- a/Services/Compositor/CompositorState.h
+++ b/Services/Compositor/CompositorState.h
@@ -143,6 +143,7 @@ public:
void set_display_metadata(Web::CompositorContextId, Optional<u64> display_id, double refresh_rate);
void set_context_visibility(Web::CompositorContextId, Compositing::ContextVisibility);
void set_context_presents_from_cpu_memory(Web::CompositorContextId, bool);
+ void set_context_scales_frames_to_fit(Web::CompositorContextId, bool);
void set_window_server_may_show_high_dynamic_range(bool);
void present_frame(Web::CompositorContextId, Gfx::IntRect viewport_rect);
// Delivers the rendering opportunity a context requested now rather than at the next display tick: a
@@ -225,7 +226,7 @@ private:
// into that logic.
static RustFFI::FfiRasterHost raster_host(CompositorState&);
static RustFFI::GpuBackend gpu_backend(RefPtr<Gfx::SkiaBackendContext> const&);
- Compositing::RustFFI::FfiRasterPainter begin_painting(Web::CompositorContextId, Gfx::PaintingSurface&, RustFFI::PaintingResources);
+ Compositing::RustFFI::FfiRasterPainter begin_painting(Web::CompositorContextId, Gfx::PaintingSurface&, RustFFI::PaintingResources, bool allows_lcd_text);
void end_painting();
RustFFI::StoreResizeOutcome resize_stores(Web::CompositorContextId, RustFFI::FfiStoreResize const&);
bool add_store_if_window_server_reads_every_released_store(Web::CompositorContextId, Optional<PresentationId>);
diff --git a/Services/Compositor/ConnectionFromClient.cpp b/Services/Compositor/ConnectionFromClient.cpp
index dc7a080fd08..761ea3f0540 100644
--- a/Services/Compositor/ConnectionFromClient.cpp
+++ b/Services/Compositor/ConnectionFromClient.cpp
@@ -159,6 +159,11 @@ void ConnectionFromClient::set_context_presents_from_cpu_memory(Web::CompositorC
m_compositor_state->set_context_presents_from_cpu_memory(context_id, presents_from_cpu_memory);
}
+void ConnectionFromClient::set_context_scales_frames_to_fit(Web::CompositorContextId context_id, bool scales_frames_to_fit)
+{
+ m_compositor_state->set_context_scales_frames_to_fit(context_id, scales_frames_to_fit);
+}
+
void ConnectionFromClient::crash()
{
warnln("Crashing Compositor process by request from Browser");
diff --git a/Services/Compositor/ConnectionFromClient.h b/Services/Compositor/ConnectionFromClient.h
index 4cde5c97571..abca639f594 100644
--- a/Services/Compositor/ConnectionFromClient.h
+++ b/Services/Compositor/ConnectionFromClient.h
@@ -49,6 +49,7 @@ private:
virtual void set_display_metadata(Web::CompositorContextId, Optional<u64>, double) override;
virtual void set_context_visibility(Web::CompositorContextId, Compositing::ContextVisibility) override;
virtual void set_context_presents_from_cpu_memory(Web::CompositorContextId, bool) override;
+ virtual void set_context_scales_frames_to_fit(Web::CompositorContextId, bool) override;
virtual void crash() override;
ConnectionFromWebContent* web_content_connection(i32 web_content_connection_id);
diff --git a/Services/Compositor/DisplayListPlayerSkia.cpp b/Services/Compositor/DisplayListPlayerSkia.cpp
index 3c50f2e076f..a416e0868f5 100644
--- a/Services/Compositor/DisplayListPlayerSkia.cpp
+++ b/Services/Compositor/DisplayListPlayerSkia.cpp
@@ -23,6 +23,7 @@
#include <core/SkPictureRecorder.h>
#include <core/SkRRect.h>
#include <core/SkSurface.h>
+#include <core/SkSurfaceProps.h>
#include <core/SkTextBlob.h>
#include <effects/SkDashPathEffect.h>
#include <effects/SkGradient.h>
@@ -52,6 +53,9 @@ using namespace Compositing;
struct DisplayListPlayerSkia::RasterState {
AK_ALLOC_WITH_KMALLOC;
+ int base_save_count { 0 };
+ SkRect opaque_text_background { SkRect::MakeEmpty() };
+
struct TileRaster {
RustFFI::TileRaster tile;
RefPtr<Gfx::PaintingSurface> surface;
@@ -128,7 +132,7 @@ struct DisplayListPlayerSkia::PainterCallbacks {
}
};
-RustFFI::FfiRasterPainter DisplayListPlayerSkia::begin_painting(Gfx::PaintingSurface& surface, DrawnFonts const& fonts, DrawnImageFrames const* image_frames, DisplayListRasterCache& raster_cache, OwnedCanvasSurfaces const* canvas_surfaces, CurrentVideoFrame current_video_frame)
+RustFFI::FfiRasterPainter DisplayListPlayerSkia::begin_painting(Gfx::PaintingSurface& surface, DrawnFonts const& fonts, DrawnImageFrames const* image_frames, DisplayListRasterCache& raster_cache, OwnedCanvasSurfaces const* canvas_surfaces, CurrentVideoFrame current_video_frame, bool allows_lcd_text)
{
VERIFY(m_surfaces.is_empty());
m_surfaces.append(surface);
@@ -136,6 +140,8 @@ RustFFI::FfiRasterPainter DisplayListPlayerSkia::begin_painting(Gfx::PaintingSur
m_image_frames = image_frames;
m_raster_cache = &raster_cache;
m_canvas_surfaces = canvas_surfaces;
+ m_allows_lcd_text = allows_lcd_text;
+ m_raster_state->base_save_count = surface.canvas().getSaveCount();
m_current_video_frame = move(current_video_frame);
return PainterCallbacks::for_player(*this);
}
@@ -151,6 +157,8 @@ void DisplayListPlayerSkia::end_painting()
m_image_frames = nullptr;
m_raster_cache = nullptr;
m_canvas_surfaces = nullptr;
+ m_allows_lcd_text = false;
+ m_raster_state->opaque_text_background = SkRect::MakeEmpty();
m_current_video_frame = nullptr;
}
@@ -325,7 +333,20 @@ void DisplayListPlayerSkia::play_command(DrawGlyphRun const& command)
if (glyphs.is_empty())
return;
- auto blob = raster_cache().text_blob(font(command.font_id), command.font_id, command.scale, glyphs, command.font_smoothing);
+ auto& canvas = surface().canvas();
+ auto const& opaque_background = m_raster_state->opaque_text_background;
+ bool uses_lcd_text = !opaque_background.isEmpty()
+ && m_surfaces.size() == 1
+ && command.stroke_width == 0
+ && command.orientation == Gfx::Orientation::Horizontal
+ && canvas.getTopProps().pixelGeometry() != kUnknown_SkPixelGeometry
+ && canvas.getLocalToDeviceAs3x3().isTranslate();
+ if (uses_lcd_text) {
+ auto bounds = to_skia_rect(command.glyph_bounding_rect);
+ bounds.outset(2, 2);
+ uses_lcd_text = opaque_background.contains(canvas.getLocalToDeviceAs3x3().mapRect(bounds));
+ }
+ auto blob = raster_cache().text_blob(font(command.font_id), command.font_id, command.scale, glyphs, command.font_smoothing, uses_lcd_text);
if (!blob)
return;
@@ -337,7 +358,7 @@ void DisplayListPlayerSkia::play_command(DrawGlyphRun const& command)
paint.setStrokeMiter(4);
paint.setAntiAlias(true);
}
- draw_glyph_run(surface().canvas(), *blob, command.rect, command.translation, command.orientation, paint);
+ draw_glyph_run(canvas, *blob, command.rect, command.translation, command.orientation, paint);
}
static void apply_compositing_and_blending_operator(SkPaint& paint, Gfx::CompositingAndBlendingOperator compositing_and_blending_operator)
@@ -353,7 +374,23 @@ void DisplayListPlayerSkia::fill_rect(RustFFI::ResolvedFillRect const& fill)
paint.setAntiAlias(true);
paint.setColor(to_skia_color(fill.color));
apply_compositing_and_blending_operator(paint, fill.compositing_and_blending_operator);
- canvas.drawRect(to_skia_rect(fill.rect), paint);
+ auto rect = to_skia_rect(fill.rect);
+ canvas.drawRect(rect, paint);
+
+ if (m_allows_lcd_text
+ && fill.color.alpha() == 255
+ && fill.compositing_and_blending_operator == Gfx::CompositingAndBlendingOperator::Normal
+ && m_surfaces.size() == 1
+ && canvas.getSaveCount() == m_raster_state->base_save_count
+ && canvas.getTopProps().pixelGeometry() != kUnknown_SkPixelGeometry
+ && canvas.getLocalToDeviceAs3x3().isTranslate()) {
+ // This fill passed through only the compositor's damage clip, which also clips the text.
+ // Store the fill's bounds independent of that clip so partial repaints use the same edging.
+ auto opaque_bounds = SkRect::Make(canvas.getLocalToDeviceAs3x3().mapRect(rect).roundIn());
+ auto& opaque_background = m_raster_state->opaque_text_background;
+ if (opaque_background.isEmpty() || opaque_bounds.contains(opaque_background))
+ opaque_background = opaque_bounds;
+ }
}
void DisplayListPlayerSkia::play_command(PaintCaret const& command)
@@ -1567,6 +1604,11 @@ void DisplayListPlayerSkia::push_transform(Gfx::AffineTransform const& transform
void DisplayListPlayerSkia::push_layer(ReplayLayer const& layer)
{
auto& canvas = surface().canvas();
+ if (layer.can_draw_directly_for_lcd_text && m_surfaces.size() == 1 && !m_raster_state->opaque_text_background.isEmpty()) {
+ canvas.save();
+ return;
+ }
+
SkPaint paint;
bool paint_has_effects = false;
@@ -1588,7 +1630,7 @@ void DisplayListPlayerSkia::push_layer(ReplayLayer const& layer)
if (!layer.backdrop_filter_bytes_size) {
if (layer.content_bounds.has_value()) {
auto content_bounds = to_skia_rect(*layer.content_bounds);
- canvas.saveLayer(&content_bounds, &paint);
+ canvas.saveLayer(content_bounds, &paint);
} else {
canvas.saveLayer(nullptr, &paint);
}
diff --git a/Services/Compositor/DisplayListPlayerSkia.h b/Services/Compositor/DisplayListPlayerSkia.h
index a2efb90f659..efe75f32ee1 100644
--- a/Services/Compositor/DisplayListPlayerSkia.h
+++ b/Services/Compositor/DisplayListPlayerSkia.h
@@ -55,7 +55,7 @@ public:
// The painter paints into `surface`, with `fonts`, `image_frames` and the caches of `raster_cache`, until
// end_painting(). It draws no image frame without `image_frames`, no canvas without `canvas_surfaces`, and no video
// without `current_video_frame`.
- Compositing::RustFFI::FfiRasterPainter begin_painting(Gfx::PaintingSurface&, DrawnFonts const&, DrawnImageFrames const*, DisplayListRasterCache&, OwnedCanvasSurfaces const*, CurrentVideoFrame);
+ Compositing::RustFFI::FfiRasterPainter begin_painting(Gfx::PaintingSurface&, DrawnFonts const&, DrawnImageFrames const*, DisplayListRasterCache&, OwnedCanvasSurfaces const*, CurrentVideoFrame, bool allows_lcd_text = false);
void end_painting();
static void flush(Gfx::PaintingSurface&);
@@ -135,6 +135,7 @@ private:
DrawnImageFrames const* m_image_frames { nullptr };
DisplayListRasterCache* m_raster_cache { nullptr };
OwnedCanvasSurfaces const* m_canvas_surfaces { nullptr };
+ bool m_allows_lcd_text { false };
CurrentVideoFrame m_current_video_frame;
ReadonlyBytes m_current_command_payload;
diff --git a/Services/Compositor/DisplayListRasterCache.cpp b/Services/Compositor/DisplayListRasterCache.cpp
index f0a60f934b4..14af8e2e9e3 100644
--- a/Services/Compositor/DisplayListRasterCache.cpp
+++ b/Services/Compositor/DisplayListRasterCache.cpp
@@ -456,11 +456,11 @@ static u64 text_blob_glyph_hash(ReadonlySpan<DisplayListGlyph> glyphs)
return hash;
}
-static sk_sp<SkTextBlob> make_text_blob(Gfx::Font const& font, float scale, ReadonlySpan<DisplayListGlyph> glyphs, [[maybe_unused]] u8 font_smoothing)
+static sk_sp<SkTextBlob> make_text_blob(Gfx::Font const& font, float scale, ReadonlySpan<DisplayListGlyph> glyphs, [[maybe_unused]] u8 font_smoothing, bool uses_lcd_text)
{
if (font.is_invisible())
return nullptr;
- auto maybe_sk_font = skia_font(font, scale);
+ auto maybe_sk_font = skia_font(font, scale, uses_lcd_text);
if (!maybe_sk_font.has_value())
return nullptr;
auto& sk_font = *maybe_sk_font;
@@ -494,13 +494,13 @@ static sk_sp<SkTextBlob> make_text_blob(Gfx::Font const& font, float scale, Read
return builder.make();
}
-sk_sp<SkTextBlob> DisplayListRasterCache::text_blob(Gfx::Font const& font, FontResourceId font_id, float scale, ReadonlySpan<DisplayListGlyph> glyphs, u8 font_smoothing)
+sk_sp<SkTextBlob> DisplayListRasterCache::text_blob(Gfx::Font const& font, FontResourceId font_id, float scale, ReadonlySpan<DisplayListGlyph> glyphs, u8 font_smoothing, bool uses_lcd_text)
{
constexpr size_t max_text_blob_cache_bytes = 16 * MiB;
constexpr auto text_blob_idle_duration = AK::Duration::from_milliseconds(250);
ReadonlyBytes glyph_bytes { reinterpret_cast<u8 const*>(glyphs.data()), glyphs.size() * sizeof(DisplayListGlyph) };
- TextBlobCacheKey key { font_id.value(), bit_cast<u32>(scale), font_smoothing, text_blob_glyph_hash(glyphs) };
+ TextBlobCacheKey key { font_id.value(), bit_cast<u32>(scale), font_smoothing, uses_lcd_text, text_blob_glyph_hash(glyphs) };
auto now = MonotonicTime::now();
if (auto cached = m_text_blobs.find(key); cached != m_text_blobs.end()) {
@@ -513,7 +513,7 @@ sk_sp<SkTextBlob> DisplayListRasterCache::text_blob(Gfx::Font const& font, FontR
m_text_blobs.remove(cached);
}
- auto blob = make_text_blob(font, scale, glyphs, font_smoothing);
+ auto blob = make_text_blob(font, scale, glyphs, font_smoothing, uses_lcd_text);
if (!blob)
return nullptr;
diff --git a/Services/Compositor/DisplayListRasterCache.h b/Services/Compositor/DisplayListRasterCache.h
index 9a97fcc49d0..4ee9b6413bc 100644
--- a/Services/Compositor/DisplayListRasterCache.h
+++ b/Services/Compositor/DisplayListRasterCache.h
@@ -43,6 +43,7 @@ struct TextBlobCacheKey {
u64 font_id { 0 };
u32 scale_bits { 0 };
u8 font_smoothing { 0 };
+ bool uses_lcd_text { false };
u64 glyph_hash { 0 };
bool operator==(TextBlobCacheKey const&) const = default;
@@ -56,7 +57,8 @@ template<>
struct Traits<Compositor::TextBlobCacheKey> : public DefaultTraits<Compositor::TextBlobCacheKey> {
static unsigned hash(Compositor::TextBlobCacheKey const& key)
{
- return pair_int_hash(pair_int_hash(u64_hash(key.font_id ^ key.glyph_hash), key.scale_bits), key.font_smoothing);
+ auto font_options = (static_cast<unsigned>(key.font_smoothing) << 1) | key.uses_lcd_text;
+ return pair_int_hash(pair_int_hash(u64_hash(key.font_id ^ key.glyph_hash), key.scale_bits), font_options);
}
};
@@ -96,7 +98,7 @@ public:
bool reserve_vector_image_raster(Compositing::DisplayListResourceId, RefPtr<Gfx::SkiaBackendContext> const&, Gfx::IntRect rect_in_recorded_space);
// Keeps the raster that was reserved, unless it could not be made.
sk_sp<SkImage> finish_vector_image_raster(Compositing::DisplayListResourceId, RefPtr<Gfx::SkiaBackendContext> const&, Gfx::IntRect rect_in_recorded_space, sk_sp<SkImage>);
- sk_sp<SkTextBlob> text_blob(Gfx::Font const&, Compositing::FontResourceId, float scale, ReadonlySpan<Compositing::DisplayListGlyph>, u8 font_smoothing);
+ sk_sp<SkTextBlob> text_blob(Gfx::Font const&, Compositing::FontResourceId, float scale, ReadonlySpan<Compositing::DisplayListGlyph>, u8 font_smoothing, bool uses_lcd_text = false);
sk_sp<SkImageFilter> layer_image_filter(Compositing::ReplayLayer const&, Function<sk_sp<SkImageFilter>()> const& create);
sk_sp<SkImageFilter> backdrop_image_filter(Compositing::ReplayLayer const&, Optional<Gfx::FloatRect> blur_edge, bool limited_to_region, Function<sk_sp<SkImageFilter>()> const& create);
diff --git a/Services/Compositor/FontSkia.cpp b/Services/Compositor/FontSkia.cpp
index 14ea4b005e2..97938a17240 100644
--- a/Services/Compositor/FontSkia.cpp
+++ b/Services/Compositor/FontSkia.cpp
@@ -19,6 +19,7 @@
#include <core/SkFontMgr.h>
#include <core/SkFontTypes.h>
#include <core/SkStream.h>
+#include <core/SkSurfaceProps.h>
#include <core/SkTypeface.h>
#include <ports/SkFontMgr_empty.h>
@@ -39,10 +40,9 @@
namespace Compositor {
static FontRasterizer s_font_rasterizer { FontRasterizer::Platform };
+static bool s_use_test_font_rendering { false };
#if defined(USE_FONTCONFIG)
-static bool s_force_hinting_for_testing { false };
-
static SkFontHinting to_skia_hinting(Gfx::FontHintingStyle style)
{
switch (style) {
@@ -59,15 +59,16 @@ static SkFontHinting to_skia_hinting(Gfx::FontHintingStyle style)
}
// The scale's bits sit above, bit 0 says the word holds an answer, bits 1 and 2 carry the style and bit 3 the
-// autohinting flag.
-static constexpr u64 hinting_memo_holds_answer = 1;
+// autohinting flag, and bit 4 records whether the font allows LCD text.
+static constexpr u64 rendering_options_memo_holds_answer = 1;
-static u64 encode_hinting_memo(float scale, Gfx::FontHintingOptions options)
+static u64 encode_rendering_options(float scale, Gfx::FontRenderingOptions options)
{
return (static_cast<u64>(bit_cast<u32>(scale)) << 32)
- | hinting_memo_holds_answer
- | (static_cast<u64>(to_underlying(options.style)) << 1)
- | (static_cast<u64>(options.force_autohinting) << 3);
+ | rendering_options_memo_holds_answer
+ | (static_cast<u64>(to_underlying(options.hinting_style)) << 1)
+ | (static_cast<u64>(options.force_autohinting) << 3)
+ | (static_cast<u64>(options.allows_lcd_text) << 4);
}
#endif
@@ -192,7 +193,7 @@ struct FontData final : public Gfx::RasterizerData {
#if defined(USE_FONTCONFIG)
// A font is drawn at one scale most of the time, and fontconfig's answer is a pure function of the family, the
// scaled pixel size, the weight and the slope, so one answer is kept.
- Atomic<u64> hinting_memo { 0 };
+ Atomic<u64> rendering_options_memo { 0 };
#endif
};
@@ -202,19 +203,20 @@ FontData& font_data(Gfx::Font const& font)
}
#if defined(USE_FONTCONFIG)
-Gfx::FontHintingOptions hinting_options(Gfx::Font const& font, float scale)
+Gfx::FontRenderingOptions rendering_options(Gfx::Font const& font, float scale, FontData& data)
{
- auto& memo = font_data(font).hinting_memo;
+ auto& memo = data.rendering_options_memo;
auto value = memo.load(AK::MemoryOrder::memory_order_relaxed);
- if ((value & hinting_memo_holds_answer) != 0 && bit_cast<float>(static_cast<u32>(value >> 32)) == scale) {
- return Gfx::FontHintingOptions {
- .style = static_cast<Gfx::FontHintingStyle>((value >> 1) & 3),
+ if ((value & rendering_options_memo_holds_answer) != 0 && bit_cast<float>(static_cast<u32>(value >> 32)) == scale) {
+ return Gfx::FontRenderingOptions {
+ .hinting_style = static_cast<Gfx::FontHintingStyle>((value >> 1) & 3),
.force_autohinting = ((value >> 3) & 1) != 0,
+ .allows_lcd_text = ((value >> 4) & 1) != 0,
};
}
- auto options = Gfx::GlobalFontConfig::the().hinting_for_font(font.family(), font.pixel_size() * scale, font.weight(), font.slope());
- memo.store(encode_hinting_memo(scale, options), AK::MemoryOrder::memory_order_relaxed);
+ auto options = Gfx::GlobalFontConfig::the().rendering_options_for_font(font.family(), font.pixel_size() * scale, font.weight(), font.slope());
+ memo.store(encode_rendering_options(scale, options), AK::MemoryOrder::memory_order_relaxed);
return options;
}
#endif
@@ -226,14 +228,43 @@ void set_font_rasterizer(FontRasterizer rasterizer)
s_font_rasterizer = rasterizer;
}
-void force_font_hinting_for_testing()
+void use_test_font_rendering()
{
-#if defined(USE_FONTCONFIG)
- s_force_hinting_for_testing = true;
+ s_use_test_font_rendering = true;
+}
+
+#if defined(AK_OS_LINUX) && defined(USE_FONTCONFIG)
+static SkPixelGeometry configured_pixel_geometry()
+{
+ switch (Gfx::GlobalFontConfig::the().subpixel_order()) {
+ case Gfx::FontSubpixelOrder::None:
+ return kUnknown_SkPixelGeometry;
+ case Gfx::FontSubpixelOrder::RGB:
+ return kRGB_H_SkPixelGeometry;
+ case Gfx::FontSubpixelOrder::BGR:
+ return kBGR_H_SkPixelGeometry;
+ case Gfx::FontSubpixelOrder::VerticalRGB:
+ return kRGB_V_SkPixelGeometry;
+ case Gfx::FontSubpixelOrder::VerticalBGR:
+ return kBGR_V_SkPixelGeometry;
+ }
+ VERIFY_NOT_REACHED();
+}
+#endif
+
+SkSurfaceProps skia_text_surface_properties(u32 flags, [[maybe_unused]] bool allows_lcd_text)
+{
+ auto geometry = kUnknown_SkPixelGeometry;
+#if defined(AK_OS_LINUX) && defined(USE_FONTCONFIG)
+ if (allows_lcd_text && !s_use_test_font_rendering) {
+ static auto const configured_geometry = configured_pixel_geometry();
+ geometry = configured_geometry;
+ }
#endif
+ return { flags, geometry };
}
-Optional<SkFont> skia_font(Gfx::Font const& font, float scale)
+Optional<SkFont> skia_font(Gfx::Font const& font, float scale, [[maybe_unused]] bool requests_lcd_text)
{
auto& data = font_data(font);
if (!data.typeface)
@@ -250,12 +281,14 @@ Optional<SkFont> skia_font(Gfx::Font const& font, float scale)
sk_font.setSkewX(-AK::tan(AK::to_radians(synthesis.oblique_angle)));
#if defined(USE_FONTCONFIG)
- if (s_force_hinting_for_testing) {
+ if (s_use_test_font_rendering) {
sk_font.setHinting(SkFontHinting::kNormal);
} else {
- auto options = hinting_options(font, scale);
- sk_font.setHinting(to_skia_hinting(options.style));
+ auto options = rendering_options(font, scale, data);
+ sk_font.setHinting(to_skia_hinting(options.hinting_style));
sk_font.setForceAutoHinting(options.force_autohinting);
+ if (requests_lcd_text && options.allows_lcd_text)
+ sk_font.setEdging(SkFont::Edging::kSubpixelAntiAlias);
}
#endif
diff --git a/Services/Compositor/FontSkia.h b/Services/Compositor/FontSkia.h
index 63926aca10f..8547dac8ef5 100644
--- a/Services/Compositor/FontSkia.h
+++ b/Services/Compositor/FontSkia.h
@@ -10,6 +10,7 @@
#include <LibGfx/Forward.h>
class SkFont;
+class SkSurfaceProps;
namespace Compositor {
@@ -22,11 +23,13 @@ enum class FontRasterizer {
// Call this before any text is drawn.
void set_font_rasterizer(FontRasterizer);
-// Makes every font use normal hinting, so that text looks the same on every machine.
-void force_font_hinting_for_testing();
+// Keep the hinting and pixel geometry used by the rendering test baselines.
+void use_test_font_rendering();
+
+SkSurfaceProps skia_text_surface_properties(u32 flags, bool allows_lcd_text);
// The Skia font that draws the glyphs of a font at a scale. Empty if Skia cannot load the font's typeface; the caller
// then draws nothing.
-Optional<SkFont> skia_font(Gfx::Font const&, float scale);
+Optional<SkFont> skia_font(Gfx::Font const&, float scale, bool requests_lcd_text = false);
}
diff --git a/Services/Compositor/PaintingSurface.cpp b/Services/Compositor/PaintingSurface.cpp
index b6e5761a82c..bb6d1711d2b 100644
--- a/Services/Compositor/PaintingSurface.cpp
+++ b/Services/Compositor/PaintingSurface.cpp
@@ -4,6 +4,7 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <Compositor/FontSkia.h>
#include <Compositor/PaintingSurface.h>
#include <Compositor/SkiaUtils.h>
#include <LibGfx/Bitmap.h>
@@ -78,7 +79,7 @@ static void release_vulkan_image(void* context)
image->unref();
}
-NonnullRefPtr<PaintingSurface> PaintingSurface::create_from_vkimage(NonnullRefPtr<SkiaBackendContext> context, NonnullRefPtr<VulkanImage> vulkan_image, Origin origin)
+NonnullRefPtr<PaintingSurface> PaintingSurface::create_from_vkimage(NonnullRefPtr<SkiaBackendContext> context, NonnullRefPtr<VulkanImage> vulkan_image, Origin origin, TextAntialiasing text_antialiasing)
{
IntSize size(vulkan_image->info.extent.width, vulkan_image->info.extent.height);
GrVkImageInfo info = {
@@ -98,8 +99,9 @@ NonnullRefPtr<PaintingSurface> PaintingSurface::create_from_vkimage(NonnullRefPt
GrBackendRenderTarget rt = GrBackendRenderTargets::MakeVk(size.width(), size.height(), info);
// Note, we're implicitly giving Skia a reference to vulkan_image. It will eventually be released by the callback function.
vulkan_image->ref();
+ auto properties = Compositor::skia_text_surface_properties(SkSurfaceProps::kDefault_Flag, text_antialiasing == TextAntialiasing::LCD);
sk_sp<SkSurface> surface = SkSurfaces::WrapBackendRenderTarget(context->sk_context(), rt, origin_to_sk_origin(origin), vk_format_to_sk_color_type(vulkan_image->info.format),
- SkColorSpace::MakeSRGB(), nullptr, release_vulkan_image, vulkan_image.ptr());
+ SkColorSpace::MakeSRGB(), &properties, release_vulkan_image, vulkan_image.ptr());
return adopt_ref(*new PaintingSurface(make<Impl>(context, size, surface, nullptr, true)));
}
#endif
@@ -138,12 +140,12 @@ static sk_sp<SkColorSpace> skia_color_space_of_pixels(ColorSpace const& color_sp
return SkColorSpace::MakeSRGB();
}
-NonnullRefPtr<PaintingSurface> PaintingSurface::create_with_size(IntSize size, BitmapFormat color_type, AlphaType alpha_type, RefPtr<SkiaBackendContext> context, ColorSpace const& color_space)
+NonnullRefPtr<PaintingSurface> PaintingSurface::create_with_size(IntSize size, BitmapFormat color_type, AlphaType alpha_type, RefPtr<SkiaBackendContext> context, ColorSpace const& color_space, TextAntialiasing text_antialiasing)
{
- return MUST(try_create_with_size(size, color_type, alpha_type, move(context), color_space));
+ return MUST(try_create_with_size(size, color_type, alpha_type, move(context), color_space, text_antialiasing));
}
-ErrorOr<NonnullRefPtr<PaintingSurface>> PaintingSurface::try_create_with_size(IntSize size, BitmapFormat color_type, AlphaType alpha_type, RefPtr<SkiaBackendContext> context, ColorSpace const& color_space)
+ErrorOr<NonnullRefPtr<PaintingSurface>> PaintingSurface::try_create_with_size(IntSize size, BitmapFormat color_type, AlphaType alpha_type, RefPtr<SkiaBackendContext> context, ColorSpace const& color_space, TextAntialiasing text_antialiasing)
{
auto sk_color_type = to_skia_color_type(color_type);
auto sk_alpha_type = to_skia_alpha_type(color_type, alpha_type);
@@ -152,8 +154,8 @@ ErrorOr<NonnullRefPtr<PaintingSurface>> PaintingSurface::try_create_with_size(In
if (context) {
// NB: Dynamic MSAA lets Skia render complex antialiased paths on the GPU instead of
// rasterizing coverage masks on the CPU and uploading them as textures.
- SkSurfaceProps surface_properties { SkSurfaceProps::kDynamicMSAA_Flag, kUnknown_SkPixelGeometry };
- auto surface = SkSurfaces::RenderTarget(context->sk_context(), skgpu::Budgeted::kNo, image_info, 0, &surface_properties);
+ auto properties = Compositor::skia_text_surface_properties(SkSurfaceProps::kDynamicMSAA_Flag, text_antialiasing == TextAntialiasing::LCD);
+ auto surface = SkSurfaces::RenderTarget(context->sk_context(), skgpu::Budgeted::kNo, image_info, 0, &properties);
if (surface)
return adopt_ref(*new PaintingSurface(make<Impl>(context, size, surface, nullptr)));
dbgln("Unable to create GPU surface for size {}x{}, falling back to CPU", size.width(), size.height());
@@ -161,19 +163,21 @@ ErrorOr<NonnullRefPtr<PaintingSurface>> PaintingSurface::try_create_with_size(In
}
auto bitmap = TRY(Bitmap::create(color_type, alpha_type, size));
- auto surface = SkSurfaces::WrapPixels(image_info, bitmap->begin(), bitmap->pitch());
+ auto properties = Compositor::skia_text_surface_properties(SkSurfaceProps::kDefault_Flag, text_antialiasing == TextAntialiasing::LCD);
+ auto surface = SkSurfaces::WrapPixels(image_info, bitmap->begin(), bitmap->pitch(), &properties);
if (!surface)
return Error::from_string_literal("Unable to create a surface for the bitmap");
return adopt_ref(*new PaintingSurface(make<Impl>(context, size, surface, bitmap)));
}
-NonnullRefPtr<PaintingSurface> PaintingSurface::wrap_bitmap(Bitmap& bitmap)
+NonnullRefPtr<PaintingSurface> PaintingSurface::wrap_bitmap(Bitmap& bitmap, TextAntialiasing text_antialiasing)
{
auto color_type = to_skia_color_type(bitmap.format());
auto alpha_type = to_skia_alpha_type(bitmap.format(), bitmap.alpha_type());
auto size = bitmap.size();
auto image_info = SkImageInfo::Make(bitmap.width(), bitmap.height(), color_type, alpha_type, SkColorSpace::MakeSRGB());
- auto surface = SkSurfaces::WrapPixels(image_info, bitmap.begin(), bitmap.pitch());
+ auto properties = Compositor::skia_text_surface_properties(SkSurfaceProps::kDefault_Flag, text_antialiasing == TextAntialiasing::LCD);
+ auto surface = SkSurfaces::WrapPixels(image_info, bitmap.begin(), bitmap.pitch(), &properties);
return adopt_ref(*new PaintingSurface(make<Impl>(RefPtr<SkiaBackendContext> {}, size, surface, bitmap)));
}
diff --git a/Services/Compositor/PaintingSurface.h b/Services/Compositor/PaintingSurface.h
index a420ab8dc6c..f309db0a98c 100644
--- a/Services/Compositor/PaintingSurface.h
+++ b/Services/Compositor/PaintingSurface.h
@@ -51,20 +51,25 @@ public:
BottomLeft,
};
+ enum class TextAntialiasing {
+ Grayscale,
+ LCD,
+ };
+
Function<void(PaintingSurface&)> on_flush;
// A surface whose pixels are in the color space, which is sRGB unless one is given.
- static NonnullRefPtr<PaintingSurface> create_with_size(IntSize size, BitmapFormat color_type, AlphaType alpha_type, RefPtr<SkiaBackendContext> = {}, ColorSpace const& = {});
+ static NonnullRefPtr<PaintingSurface> create_with_size(IntSize size, BitmapFormat color_type, AlphaType alpha_type, RefPtr<SkiaBackendContext> = {}, ColorSpace const& = {}, TextAntialiasing = TextAntialiasing::Grayscale);
// Fails when neither a GPU surface nor a bitmap of the size can be allocated.
- static ErrorOr<NonnullRefPtr<PaintingSurface>> try_create_with_size(IntSize size, BitmapFormat color_type, AlphaType alpha_type, RefPtr<SkiaBackendContext> = {}, ColorSpace const& = {});
- static NonnullRefPtr<PaintingSurface> wrap_bitmap(Bitmap&);
+ static ErrorOr<NonnullRefPtr<PaintingSurface>> try_create_with_size(IntSize size, BitmapFormat color_type, AlphaType alpha_type, RefPtr<SkiaBackendContext> = {}, ColorSpace const& = {}, TextAntialiasing = TextAntialiasing::Grayscale);
+ static NonnullRefPtr<PaintingSurface> wrap_bitmap(Bitmap&, TextAntialiasing = TextAntialiasing::Grayscale);
#ifdef AK_OS_MACOS
static NonnullRefPtr<PaintingSurface> create_from_shared_image_buffer(SharedImageBuffer&, NonnullRefPtr<SkiaBackendContext>, Origin = Origin::TopLeft);
#endif
#ifdef USE_VULKAN_DMABUF_IMAGES
- static NonnullRefPtr<PaintingSurface> create_from_vkimage(NonnullRefPtr<SkiaBackendContext> context, NonnullRefPtr<VulkanImage> vulkan_image, Origin origin);
+ static NonnullRefPtr<PaintingSurface> create_from_vkimage(NonnullRefPtr<SkiaBackendContext> context, NonnullRefPtr<VulkanImage> vulkan_image, Origin origin, TextAntialiasing = TextAntialiasing::Grayscale);
#endif
#ifdef USE_DIRECTX
diff --git a/Services/Compositor/Rust/src/core/mod.rs b/Services/Compositor/Rust/src/core/mod.rs
index 2abb8eabd28..2e42a513eab 100644
--- a/Services/Compositor/Rust/src/core/mod.rs
+++ b/Services/Compositor/Rust/src/core/mod.rs
@@ -535,6 +535,24 @@ impl CompositorCore {
self.finish_entry(now);
}
+ pub fn set_scales_frames_to_fit(
+ &self,
+ context_id: CompositorContextId,
+ scales_frames_to_fit: bool,
+ now: MonotonicTime,
+ ) {
+ let _entered = self.enter();
+ let Some(presenting) = self.presenting_of(context_id) else {
+ return;
+ };
+ if presenting.borrow().scales_frames_to_fit == scales_frames_to_fit {
+ return;
+ }
+ presenting.borrow_mut().scales_frames_to_fit = scales_frames_to_fit;
+ self.present_current_frame(context_id, now);
+ self.finish_entry(now);
+ }
+
pub fn request_rendering_opportunity(
&self,
context_id: CompositorContextId,
diff --git a/Services/Compositor/Rust/src/ffi.rs b/Services/Compositor/Rust/src/ffi.rs
index 2a0c8387654..eed22abee38 100644
--- a/Services/Compositor/Rust/src/ffi.rs
+++ b/Services/Compositor/Rust/src/ffi.rs
@@ -300,6 +300,20 @@ pub extern "C" fn compositor_core_set_presents_from_cpu_memory(
);
}
+#[unsafe(no_mangle)]
+pub extern "C" fn compositor_core_set_scales_frames_to_fit(
+ core: &CompositorCore,
+ context_id: u64,
+ scales_frames_to_fit: bool,
+ now_nanoseconds: i64,
+) {
+ core.set_scales_frames_to_fit(
+ CompositorContextId(context_id),
+ scales_frames_to_fit,
+ time(now_nanoseconds),
+ );
+}
+
#[unsafe(no_mangle)]
pub extern "C" fn compositor_core_request_rendering_opportunity(
core: &CompositorCore,
diff --git a/Services/Compositor/Rust/src/overlays.rs b/Services/Compositor/Rust/src/overlays.rs
index c4295cbdd2a..b0b217cd885 100644
--- a/Services/Compositor/Rust/src/overlays.rs
+++ b/Services/Compositor/Rust/src/overlays.rs
@@ -299,6 +299,7 @@ impl OverlayPicture {
replay_records(self.ui_overlay_records.as_bytes(), &context, painter);
if let Some(controls) = &self.picture_in_picture_controls {
painter.push_layer(&ReplayLayer {
+ can_draw_directly_for_lcd_text: false,
opacity: controls.opacity,
blend_mode: CompositingAndBlendingOperator::Normal,
filter_bytes: std::ptr::null(),
diff --git a/Services/Compositor/Rust/src/presenting/damage.rs b/Services/Compositor/Rust/src/presenting/damage.rs
index e5d9cfa68ea..3c93d8541a1 100644
--- a/Services/Compositor/Rust/src/presenting/damage.rs
+++ b/Services/Compositor/Rust/src/presenting/damage.rs
@@ -27,6 +27,7 @@ pub struct PaintedFrame {
pub display_list: Rc<DisplayList>,
pub frame_inputs: FrameInputs,
pub viewport_size: IntSize,
+ allows_lcd_text: bool,
canvas_content_generations: HashMap<u64, u64>,
video_frame_ids: HashMap<u64, Option<u64>>,
image_frame_pixel_generations: HashMap<u64, u64>,
@@ -73,6 +74,35 @@ impl StoreDamage {
}
repaint_rect
}
+
+ /// Damage discovered while painting the current store is still owed to the other stores.
+ pub fn add_damage_to_other_stores(&mut self, bitmap_id: i32, damage: IntRect) {
+ for (id, accumulated) in &mut self.accumulated {
+ if *id != bitmap_id {
+ *accumulated = accumulated.united(damage);
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_late_full_repaint_is_owed_to_the_other_stores() {
+ let mut damage = StoreDamage::default();
+ let full_rect = IntRect::new(0, 0, 100, 100);
+ let partial_rect = IntRect::new(10, 10, 20, 20);
+ damage.take(1, full_rect, full_rect);
+ damage.take(2, full_rect, full_rect);
+ assert_eq!(damage.take(1, partial_rect, full_rect), full_rect);
+ assert_eq!(damage.take(2, partial_rect, full_rect), partial_rect);
+
+ damage.add_damage_to_other_stores(2, full_rect);
+ assert_eq!(damage.take(2, partial_rect, full_rect), partial_rect);
+ assert_eq!(damage.take(1, partial_rect, full_rect), full_rect);
+ }
}
// The canvases, video sinks, image frames and nested contexts whose pixels changed since the frame painted last.
@@ -151,6 +181,7 @@ impl ContextPresenting {
.iter()
.map(|&id| (id, env.nested_contexts.frame_generation_of(CompositorContextId(id))))
.collect();
+ let allows_lcd_text = self.allows_lcd_text(display_list, &frame_inputs);
self.painted_frame = Some(PaintedFrame {
display_list: display_list.clone(),
frame_inputs,
@@ -158,6 +189,7 @@ impl ContextPresenting {
width: viewport_rect.width,
height: viewport_rect.height,
},
+ allows_lcd_text,
canvas_content_generations,
video_frame_ids,
image_frame_pixel_generations,
@@ -170,6 +202,7 @@ impl ContextPresenting {
env: &PresentingEnvironment<'_>,
viewport_size: IntSize,
display_list: &DisplayList,
+ frame_inputs: &FrameInputs,
live_content: &LiveContent,
) -> LiveContentChangesSinceLastPaint {
let mut changes = LiveContentChangesSinceLastPaint::default();
@@ -179,6 +212,7 @@ impl ContextPresenting {
};
if painted_frame.viewport_size != viewport_size
|| painted_frame.display_list.surface_clear_color() != display_list.surface_clear_color()
+ || painted_frame.allows_lcd_text != self.allows_lcd_text(display_list, frame_inputs)
{
changes.repaints_everything = true;
}
@@ -261,7 +295,13 @@ impl ContextPresenting {
};
let viewport_rect = rect_of_size(viewport_size);
let forced_damage_rect = pending_frame.forced_damage_rect.intersected(viewport_rect);
- let changes = self.live_content_changes_since_last_paint(env, viewport_size, frame.display_list, live_content);
+ let changes = self.live_content_changes_since_last_paint(
+ env,
+ viewport_size,
+ frame.display_list,
+ frame.frame_inputs,
+ live_content,
+ );
self.layers.media_activity.note_updates(
&changes.media_updates,
frame.display_list.storage().summary(),
@@ -299,10 +339,7 @@ impl ContextPresenting {
let layer_count = layers.plan(&self.layers).map(|plan| plan.layers.len());
match layer_count {
- None => {
- layers.repaints_everything =
- layers_hold_last_frame || self.layers.repaint_everything_after_dropping_layers;
- }
+ None => layers.repaints_everything = layers_hold_last_frame,
Some(_) if !keeps_layer_rasters => {
layers.fully_repainted_layer_bits = u32::MAX;
layers.repaints_everything = true;
diff --git a/Services/Compositor/Rust/src/presenting/layers.rs b/Services/Compositor/Rust/src/presenting/layers.rs
index f2ddc59afd2..090c0298e5e 100644
--- a/Services/Compositor/Rust/src/presenting/layers.rs
+++ b/Services/Compositor/Rust/src/presenting/layers.rs
@@ -128,7 +128,6 @@ pub struct ContextLayers {
plan_active_media: Vec<LiveMedia>,
surfaces: Vec<LayerSurface>,
last_content_version: u64,
- pub repaint_everything_after_dropping_layers: bool,
// Whether the window server shows the canvases and videos of the latest frame above it.
window_server_shows_media: bool,
painted_layer_presentations: Vec<PaintedLayerPresentation>,
@@ -353,9 +352,6 @@ impl ContextPresenting {
pub(super) fn commit_layer_update(&mut self, env: &PresentingEnvironment<'_>, layer_update: LayerUpdate) {
let layers = &mut self.layers;
layers.window_server_shows_media = layer_update.has_plan() && layer_update.shown_by_window_server;
- if layer_update.repaints_everything {
- layers.repaint_everything_after_dropping_layers = false;
- }
if !layer_update.has_plan() {
layers.drop_layers(env);
return;
@@ -436,6 +432,7 @@ impl ContextPresenting {
height: rect.height,
},
Some(surface),
+ false,
) else {
self.layers.surfaces = surfaces;
return false;
diff --git a/Services/Compositor/Rust/src/presenting/mod.rs b/Services/Compositor/Rust/src/presenting/mod.rs
index 2b6b43aa0ab..eff629c5443 100644
--- a/Services/Compositor/Rust/src/presenting/mod.rs
+++ b/Services/Compositor/Rust/src/presenting/mod.rs
@@ -20,7 +20,7 @@ use crate::raster_host::{
};
use damage::{PaintedFrame, StoreDamage};
use layers::ContextLayers;
-use libcompositing_rust::display_list::commands::CompositorContextId;
+use libcompositing_rust::display_list::commands::{CompositorContextId, EffectNodeIndex};
use libcompositing_rust::display_list::replay::{
CompositedContexts, NoCompositedContexts, ReplayFrame, ReplaySelection, ResolvedCompositedContext,
replay_display_list,
@@ -28,7 +28,11 @@ use libcompositing_rust::display_list::replay::{
use libcompositing_rust::host::RecordSpan;
use libcompositing_rust::scrolling::DisplayList;
use libcompositing_rust::time::{Duration, MonotonicTime};
-use libgfx_rust::{Color, FloatMatrix4x4, FloatPoint, FloatRect, FloatSize, IntRect, IntSize, enclosing_int_rect};
+use libcompositing_rust::visual_context::EffectNodeData;
+use libgfx_rust::{
+ Color, CompositingAndBlendingOperator, FloatMatrix4x4, FloatPoint, FloatRect, FloatSize, IntRect, IntSize,
+ enclosing_int_rect,
+};
use pacing::PacedTickRequest;
use std::rc::Rc;
@@ -113,6 +117,7 @@ pub struct ContextPresenting {
pub display_refresh_rate: f64,
// Whether the presentation shows this context's frames from CPU memory for now, as when the UI paints it itself.
pub presents_from_cpu_memory: bool,
+ pub scales_frames_to_fit: bool,
pub shown_in_remote_layer: bool,
// The viewport size of the frame that the page presented last, which it laid out at.
pub size_laid_out_by_page: IntSize,
@@ -154,6 +159,7 @@ impl ContextPresenting {
display_id: None,
display_refresh_rate: 60.0,
presents_from_cpu_memory: false,
+ scales_frames_to_fit: false,
shown_in_remote_layer: false,
size_laid_out_by_page: IntSize::default(),
rendering_opportunity_request: PacedTickRequest::default(),
@@ -263,6 +269,8 @@ impl ContextPresenting {
self.store_publication = publication;
self.latest_rendered_surface = None;
self.painted_frame = None;
+ // A partial repaint must inherit the pixel geometry of the new backing stores.
+ self.damage_surface = None;
self.store_damage.forget_every_store();
}
outcome
@@ -594,12 +602,15 @@ impl ContextPresenting {
};
let store_rect = rect_of_size(env.raster.surface_size(&store));
let repaint_rect = self.store_damage.take(bitmap_id, raster_damage_rect, store_rect);
- let painted_rect = self.paint_frame(env, &store, &frame, repaint_rect, &mut frame_damage.layers);
- if painted_rect != repaint_rect {
- damage_rect = rect_of_size(IntSize {
- width: pending_frame.viewport_rect.width,
- height: pending_frame.viewport_rect.height,
- });
+ self.paint_frame(env, &store, &frame, repaint_rect, &mut frame_damage.layers);
+ let full_damage_rect = rect_of_size(IntSize {
+ width: pending_frame.viewport_rect.width,
+ height: pending_frame.viewport_rect.height,
+ });
+ if frame_damage.layers.repaints_everything && damage_rect != full_damage_rect {
+ damage_rect = full_damage_rect;
+ self.store_damage
+ .add_damage_to_other_stores(bitmap_id, self.raster_rect_of(damage_rect));
}
self.commit_layer_update(env, frame_damage.layers);
self.remember_painted_frame(
@@ -648,13 +659,13 @@ impl ContextPresenting {
(surface, self.raster_rect_of(frame_damage.rect))
}
_ => {
- let Some(surface) = env.raster.create_surface(raster_size, None) else {
+ let Some(surface) = env.raster.create_surface(raster_size, None, false) else {
return;
};
(surface, rect_of_size(raster_size))
}
};
- let _ = self.paint_frame(env, &surface, &frame, repaint_rect, &mut frame_damage.layers);
+ self.paint_frame(env, &surface, &frame, repaint_rect, &mut frame_damage.layers);
self.commit_layer_update(env, frame_damage.layers);
self.remember_painted_frame(
env,
@@ -700,7 +711,7 @@ impl ContextPresenting {
&& let Some(painted_frame) = self.painted_frame.take()
{
let source_size = env.raster.surface_size(&source);
- let composited = env.raster.create_surface(source_size, Some(&source));
+ let composited = env.raster.create_surface(source_size, Some(&source), false);
if let Some(composited) = composited {
let source_rect = rect_of_size(source_size);
env.raster
@@ -730,8 +741,6 @@ impl ContextPresenting {
Some((source, frame_size))
}
- // Returns the rect it painted, which grows to the whole frame when the frame has to hold media that the window
- // server was to show.
fn paint_frame(
&mut self,
env: &PresentingEnvironment<'_>,
@@ -739,26 +748,22 @@ impl ContextPresenting {
frame: &FrameToPaint<'_>,
mut damage_rect: IntRect,
layer_update: &mut layers::LayerUpdate,
- ) -> IntRect {
+ ) {
if layer_update.has_plan() {
if self.paint_layered_frame(env, surface, frame, damage_rect, layer_update) {
- return damage_rect;
- }
- // The sublayers that the window server was to show go away with this frame, so the store has to hold all
- // that they showed.
- if layer_update.shown_by_window_server {
- damage_rect = rect_of_size(self.raster_size());
+ return;
}
+ // Unlayered replay paints the media into the base and can change text antialiasing across the frame.
+ damage_rect = rect_of_size(self.raster_size());
+ layer_update.repaints_everything = true;
layer_update.new_plan = None;
layer_update.keeps_plan = false;
layer_update.shown_by_window_server = false;
self.layers.drop_layers(env);
- self.layers.repaint_everything_after_dropping_layers = true;
}
// NB: Only a frame shown on screen ages the rasters it did not use, so a screenshot keeps them.
env.raster.start_raster_cache_frame(env.context_id);
self.paint_current_display_list(env, surface, frame, Some(damage_rect), true, true);
- damage_rect
}
fn paint_current_display_list(
@@ -772,8 +777,17 @@ impl ContextPresenting {
) {
let raster = env.raster;
let surface_clear_color = frame.display_list.surface_clear_color().unwrap_or(Color::TRANSPARENT);
+ let allows_lcd_text = damage_rect.is_some() && self.allows_lcd_text(frame.display_list, frame.frame_inputs);
let paint_display_list = |target: &SurfaceHandle| {
- replay_into(env, target, frame, ReplaySelection::default());
+ replay_into(
+ env,
+ target,
+ frame,
+ ReplaySelection {
+ allows_lcd_text,
+ ..Default::default()
+ },
+ );
paint_overlays(env, target, frame.frame_inputs, paints_ui_overlays);
};
@@ -795,7 +809,7 @@ impl ContextPresenting {
.as_ref()
.is_none_or(|damage_surface| raster.surface_size(damage_surface) != damage_size)
{
- self.damage_surface = raster.create_surface(damage_size, Some(surface));
+ self.damage_surface = raster.create_surface(damage_size, Some(surface), true);
}
if let Some(damage_surface) = &self.damage_surface {
raster.clear(damage_surface, surface_clear_color);
@@ -830,6 +844,21 @@ impl ContextPresenting {
raster.translate(surface, self.raster_translation.x, self.raster_translation.y);
raster.scale(surface, self.raster_scale.width, self.raster_scale.height);
}
+
+ fn allows_lcd_text(&self, display_list: &DisplayList, frame_inputs: &FrameInputs) -> bool {
+ let tree = frame_inputs.visual_context_tree.as_arc();
+ // LCD coverage follows the physical pixel grid. Destination blending can erase pixels in the canvas fill.
+ self.store_publication == StorePublication::Published
+ && !self.scales_frames_to_fit
+ && self.device_pixel_ratio.fract() == 0.0
+ && display_list.storage().summary().destination_blending_records.is_empty()
+ // A blend or backdrop filter that reads the root group needs its original isolation from the canvas fill.
+ && !tree.effect_nodes.iter().enumerate().any(|(index, node)| {
+ matches!(&node.data, EffectNodeData::Effects(effects)
+ if effects.blend_mode != CompositingAndBlendingOperator::Normal || effects.backdrop_filter.is_some())
+ && tree.effect_backdrop_is_root_group(EffectNodeIndex(index as u32))
+ })
+ }
}
// Replays the frame's display list into the target, through the painter of the context's page.
@@ -845,8 +874,12 @@ pub(crate) fn replay_into(
display_list.compatible_visual_context_tree_structural_epoch(),
frame_inputs.visual_context_tree.structural_epoch()
);
- env.raster
- .paint(env.context_id, target, PaintingResources::Page, |painter| {
+ env.raster.paint(
+ env.context_id,
+ target,
+ PaintingResources::Page,
+ selection.allows_lcd_text,
+ |painter| {
let scrollbars = frame_inputs.scrollbars_shown_for_the_page();
let replay_frame = ReplayFrame {
scroll_offsets: frame_inputs.presented_scroll_state_snapshot.device_offsets(),
@@ -866,13 +899,15 @@ pub(crate) fn replay_into(
selection,
painter,
);
- });
+ },
+ );
}
pub(crate) fn replaying_only(record_spans: &[RecordSpan], skip_root_isolation_layer: bool) -> ReplaySelection<'_> {
ReplaySelection {
record_spans: Some(record_spans),
skip_root_isolation_layer,
+ allows_lcd_text: false,
}
}
@@ -885,7 +920,7 @@ pub(crate) fn paint_overlays(
paints_ui_overlays: bool,
) {
env.raster
- .paint(env.context_id, target, PaintingResources::Overlays, |painter| {
+ .paint(env.context_id, target, PaintingResources::Overlays, false, |painter| {
frame_inputs.overlays.paint(painter, paints_ui_overlays);
});
}
diff --git a/Services/Compositor/Rust/src/raster_host.rs b/Services/Compositor/Rust/src/raster_host.rs
index ec86edc395a..d37c65d1b64 100644
--- a/Services/Compositor/Rust/src/raster_host.rs
+++ b/Services/Compositor/Rust/src/raster_host.rs
@@ -209,8 +209,8 @@ pub struct FfiRasterHost {
/// on Windows, so the size does not come back as the return value.
pub surface_size: unsafe extern "C" fn(*mut c_void, *mut IntSize),
/// Null where the surface could not be made. The surface is made like the one given, or for the GPU the compositor
- /// renders with where none is given.
- pub create_surface: unsafe extern "C" fn(*mut c_void, IntSize, *mut c_void) -> *mut c_void,
+ /// renders with where none is given. The last argument also inherits LCD text for pixel-aligned copies.
+ pub create_surface: unsafe extern "C" fn(*mut c_void, IntSize, *mut c_void, bool) -> *mut c_void,
pub surfaces_share_backend: unsafe extern "C" fn(*mut c_void, *mut c_void) -> bool,
pub surface_uses_gpu: unsafe extern "C" fn(*mut c_void) -> bool,
pub surface_save: unsafe extern "C" fn(*mut c_void) -> i32,
@@ -224,9 +224,10 @@ pub struct FfiRasterHost {
pub surface_draw_surface: unsafe extern "C" fn(*mut c_void, *mut c_void, IntRect, IntRect, SurfaceBlend),
pub flush_surface: unsafe extern "C" fn(*mut c_void, *mut c_void),
- /// Arguments: the context, the surface, whose resources it draws with, and where the painter is written. The
- /// painting lasts until `end_painting`, and paintings nest.
- pub begin_painting: unsafe extern "C" fn(*mut c_void, u64, *mut c_void, PaintingResources, *mut FfiRasterPainter),
+ /// Arguments: the host, the context, the surface, whose resources it draws with, whether it allows LCD text,
+ /// and where the painter is written. The painting lasts until `end_painting`, and paintings nest.
+ pub begin_painting:
+ unsafe extern "C" fn(*mut c_void, u64, *mut c_void, PaintingResources, bool, *mut FfiRasterPainter),
pub end_painting: unsafe extern "C" fn(*mut c_void),
/// Lets the raster caches of the context's page drop what the frames before the one that starts did not use.
pub start_raster_cache_frame: unsafe extern "C" fn(*mut c_void, u64),
@@ -449,10 +450,15 @@ impl RasterHost {
size
}
- pub fn create_surface(&self, size: IntSize, like: Option<&SurfaceHandle>) -> Option<SurfaceHandle> {
+ pub fn create_surface(
+ &self,
+ size: IntSize,
+ like: Option<&SurfaceHandle>,
+ inherits_lcd_text: bool,
+ ) -> Option<SurfaceHandle> {
let like = like.map_or(std::ptr::null_mut(), SurfaceHandle::as_ptr);
// SAFETY: The host outlives this, and the surface it is made like is live.
- self.adopt_surface(unsafe { (self.0.create_surface)(self.host(), size, like) })
+ self.adopt_surface(unsafe { (self.0.create_surface)(self.host(), size, like, inherits_lcd_text) })
}
pub fn surfaces_share_backend(&self, a: &SurfaceHandle, b: &SurfaceHandle) -> bool {
@@ -523,6 +529,7 @@ impl RasterHost {
context_id: CompositorContextId,
surface: &SurfaceHandle,
resources: PaintingResources,
+ allows_lcd_text: bool,
paint: impl FnOnce(&mut FfiRasterPainter),
) {
let mut painter = std::mem::MaybeUninit::<FfiRasterPainter>::uninit();
@@ -533,6 +540,7 @@ impl RasterHost {
context_id.0,
surface.as_ptr(),
resources,
+ allows_lcd_text,
painter.as_mut_ptr(),
);
painter.assume_init()
diff --git a/Services/Compositor/main.cpp b/Services/Compositor/main.cpp
index d367268105f..62b5f1e9d43 100644
--- a/Services/Compositor/main.cpp
+++ b/Services/Compositor/main.cpp
@@ -96,7 +96,7 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
warnln("Could not set main thread QoS: {}", result.error());
if (enable_test_mode)
- Compositor::force_font_hinting_for_testing();
+ Compositor::use_test_font_rendering();
Core::ResourceImplementation::install(make<Core::ResourceImplementationFile>(TRY(String::from_utf8(resource_root))));
if (force_fontconfig)
diff --git a/Services/Hub/Application.cpp b/Services/Hub/Application.cpp
index a1f532105f4..3cb7e9ced9b 100644
--- a/Services/Hub/Application.cpp
+++ b/Services/Hub/Application.cpp
@@ -430,6 +430,7 @@ OwnPtr<WebView::PictureInPictureWindow> Application::create_picture_in_picture_w
auto initial_state = owner_view.initial_state_for_related_view();
initial_state.owner_view_id = owner_view.view_id();
initial_state.is_tab = false;
+ initial_state.scales_frames_to_fit = true;
auto screen_size = owner_view.screen_size();
auto& view = create_view(move(initial_state), traversable);
return make<PictureInPictureWindowInUI>(view, owner_view.view_id(), video_size, WebView::PictureInPictureWindow::initial_size(video_size, screen_size));
diff --git a/Services/Hub/View.cpp b/Services/Hub/View.cpp
index 8141e74a814..c8185ffb351 100644
--- a/Services/Hub/View.cpp
+++ b/Services/Hub/View.cpp
@@ -104,6 +104,7 @@ View::View(InitialState initial_state)
m_maximum_frames_per_second = initial_state.maximum_frames_per_second;
m_display_id = initial_state.display_id;
m_screen_shows_high_dynamic_range = initial_state.screen_shows_high_dynamic_range;
+ set_scales_frames_to_fit(initial_state.scales_frames_to_fit);
m_backing_stores = make<BackingStoresInUI>(*this);
forward_callbacks_to_ui(initial_state.is_tab);
diff --git a/Services/Hub/View.h b/Services/Hub/View.h
index 8ed5c14de6a..0d1d8198cc2 100644
--- a/Services/Hub/View.h
+++ b/Services/Hub/View.h
@@ -28,6 +28,7 @@ public:
bool websites_prefer_dark { false };
// The view of a tab can open others and ask the user about things, unlike that of a Picture-in-Picture window.
bool is_tab { true };
+ bool scales_frames_to_fit { false };
};
explicit View(InitialState);
@@ -48,7 +49,6 @@ public:
void set_viewport(Web::DevicePixelSize, double device_pixel_ratio);
void set_system_theme(Core::AnonymousBuffer);
void set_screen_rects(ScreenRects);
- bool scales_frames_to_fit() const { return m_scales_frames_to_fit; }
void set_wants_frame_notifications(bool wants_frame_notifications) { m_wants_frame_notifications = wants_frame_notifications; }
void did_install_backing_stores_in_ui();