diff --git a/CHANGELOG.md b/CHANGELOG.md index 927b03b..fdd644b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ Released on tbd. - Fixed the background showing through where two border sides of different colors meet on a diagonal - Fixed `data:` images whose base64 is percent-encoded (e.g. `%2F` for `/`) not being shown - Added `object` elements showing an image instead of their fallback content +- Fixed an `object` with data that failed to load (e.g. a 404) showing it instead of its fallback content +- Fixed an `object` showing a page (e.g. `text/html`) showing its fallback content; it is an empty box of the size of an iframe +- Fixed the document of an empty iframe (e.g. 0 by 0) keeping the viewport of 300 by 150 +- Updated the document of an iframe to keep the render device of its browsing context, if it has one of its own # 0.12.0 diff --git a/src/AngleSharp.Renderer.Tests/Acid1ConformanceTests.cs b/src/AngleSharp.Renderer.Tests/Acid1ConformanceTests.cs new file mode 100644 index 0000000..5cc5ea1 --- /dev/null +++ b/src/AngleSharp.Renderer.Tests/Acid1ConformanceTests.cs @@ -0,0 +1,109 @@ +namespace AngleSharp.Renderer.Tests; + +using AngleSharp; +using AngleSharp.Css; +using AngleSharp.Dom; +using AngleSharp.Renderer.Rendering; + +/// +/// The Acid1 test (cases/test15-acid1.html, the CSS1 test "display/box/float/clear"): +/// every box above the paragraph has a size fixed in ems, so the reference rendering +/// (sec5526c.gif) pins each of them to the pixel. +/// +[Trait("Category", "Visual")] +public sealed class Acid1ConformanceTests +{ + private const int ViewportWidth = 960; + private const int ViewportHeight = 1420; + + [Fact] + public async Task Acid1_LaysOutTheBoxesOfTheReferenceRendering() + { + var document = await OpenAsync(); + + // html at 10px: body has a 15px margin and a 5px border, the dl a 5px padding + var body = Box(document, "body"); + Assert.Equal(15f, body.X, precision: 1); + Assert.Equal(15f, body.Y, precision: 1); + Assert.Equal(490f, body.Width, precision: 1); + AssertBox(document, "dt", 25f, 25f, 80f, 310f); + AssertBox(document, "dd", 115f, 25f, 380f, 310f); + AssertBox(document, "li:nth-child(1)", 135f, 45f, 80f, 120f); + AssertBox(document, "#bar", 225f, 45f, 160f, 110f); + AssertBox(document, "li:nth-child(3)", 395f, 45f, 80f, 120f); + // below "i grow old" (CSS 1 float rule 2), not beside it under #bar + AssertBox(document, "#baz", 135f, 175f, 120f, 120f); + AssertBox(document, "blockquote", 275f, 175f, 70f, 140f); + AssertBox(document, "h1", 355f, 175f, 120f, 120f); + + // the paragraph clears both floats + var paragraph = Box(document, "body > p"); + Assert.Equal(20f, paragraph.X, precision: 1); + Assert.Equal(335f, paragraph.Y, precision: 1); + Assert.Equal(480f, paragraph.Width, precision: 1); + } + + [Fact] + public async Task Acid1_MatchesTheSnapshot() + { + var document = await OpenAsync(); + var image = new HtmlRenderer().RenderToPng(document, CreateDevice()); + + VisualSnapshotVerifier.VerifyOrCreate( + snapshotName: "acid1.png", + actualPng: image.Data, + perChannelTolerance: 12, + maxDifferentPixels: 20); + } + + private static void AssertBox(IDocument document, string selector, float x, float y, float width, float height) + { + var box = Box(document, selector); + Assert.Equal(x, box.X, precision: 1); + Assert.Equal(y, box.Y, precision: 1); + Assert.Equal(width, box.Width, precision: 1); + Assert.Equal(height, box.Height, precision: 1); + } + + private static RenderRect Box(IDocument document, string selector) + { + var rect = document.QuerySelector(selector)!.GetBoundingClientRect(); + return new RenderRect((float)rect.Left, (float)rect.Top, (float)rect.Width, (float)rect.Height); + } + + private static DefaultRenderDevice CreateDevice() => new() + { + ViewPortWidth = ViewportWidth, + ViewPortHeight = ViewportHeight, + FontSize = 16f, + }; + + private static async Task OpenAsync() + { + var html = await File.ReadAllTextAsync(Path.Combine(FindProjectRoot(), "cases", "test15-acid1.html")); + // Verdana is installed on some hosts only; snapshots use the bundled fonts + html = html.Replace("Verdana, sans-serif", "sans-serif", StringComparison.Ordinal); + + var context = BrowsingContext.New(Configuration.Default.WithCss().WithRenderDevice(CreateDevice())); + var document = await context.OpenAsync(request => request.Content(html)); + context.GetDomHarness(); + return document; + } + + private static string FindProjectRoot() + { + var directory = new DirectoryInfo(AppContext.BaseDirectory); + + while (directory is not null) + { + if (File.Exists(Path.Combine(directory.FullName, "AngleSharp.Renderer.Tests.csproj"))) + { + return directory.FullName; + } + + directory = directory.Parent; + } + + throw new InvalidOperationException("Could not locate AngleSharp.Renderer.Tests project root."); + } +} diff --git a/src/AngleSharp.Renderer.Tests/Acid3RegressionTests.cs b/src/AngleSharp.Renderer.Tests/Acid3RegressionTests.cs new file mode 100644 index 0000000..c67e8cb --- /dev/null +++ b/src/AngleSharp.Renderer.Tests/Acid3RegressionTests.cs @@ -0,0 +1,101 @@ +namespace AngleSharp.Renderer.Tests; + +using System.Net; +using AngleSharp; +using AngleSharp.Css; +using AngleSharp.Dom; +using AngleSharp.Io; +using AngleSharp.Renderer; +using AngleSharp.Renderer.Rendering; + +/// +/// Reduced versions of what the Acid3 test (acid3.acidtests.org) showed to differ from browsers. +/// +public sealed class Acid3RegressionTests +{ + private static readonly DefaultRenderDevice Device = new() { ViewPortWidth = 800, ViewPortHeight = 600, FontSize = 16 }; + + // a 1x1 yellow PNG + private static readonly byte[] YellowPixel = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR42mP4/58BAAT/Af9jgNErAAAAAElFTkSuQmCC"); + + [Fact] + public async Task ObjectWithADocument_HidesItsFallback() + { + // test 16: a 404 (even of an image) shows the fallback, a page is shown instead of it + var document = await OpenAsync(""" + FAIL + """); + + Assert.Equal(300f, Rect(document, "b").Width, precision: 1); + Assert.Equal(150f, Rect(document, "b").Height, precision: 1); + Assert.DoesNotContain(new HtmlRenderer().BuildDisplayList(document, Device).Commands, command => command.GetType().Name.Contains("Text")); + } + + [Fact] + public async Task ObjectWithAMissingImage_ShowsItsFallback() + { + var document = await OpenAsync(""" + fallback + """); + + Assert.True(Rect(document, "fallback").Width > 0f); + } + + private static RenderRect Rect(IDocument document, string id) + { + var rect = document.GetElementById(id)!.GetBoundingClientRect(); + return new RenderRect((float)rect.Left, (float)rect.Top, (float)rect.Width, (float)rect.Height); + } + + private static async Task OpenAsync(string body) + { + var context = BrowsingContext.New(Configuration.Default + .WithCss() + .WithRenderDevice(Device) + .WithRendering() + .WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true }) + .With(new SiteRequester())); + var document = await context.OpenAsync(request => request.Address("http://localhost/").Content($$""" + + {{body}} + """)); + + // the objects show what they show once their data is there + foreach (var element in document.QuerySelectorAll("object").OfType()) + { + if (element.CurrentDownload?.Task is { } task) + { + await task; + } + } + + await Task.Delay(50); + context.GetDomHarness(); + return document; + } + + // what Acid3's server answers + private sealed class SiteRequester : BaseRequester + { + public override bool SupportsProtocol(string protocol) => + string.Equals(protocol, "http", StringComparison.OrdinalIgnoreCase); + + protected override Task PerformRequestAsync(Request request, CancellationToken cancel) + { + var (status, type, content) = request.Address.Path switch + { + "missing.png" => (HttpStatusCode.NotFound, "image/png", YellowPixel), + "page.png" => (HttpStatusCode.OK, "text/html; charset=utf-8", "FAIL

"u8.ToArray()), + _ => (HttpStatusCode.OK, "image/png", YellowPixel), + }; + var response = new DefaultResponse + { + Address = request.Address, + StatusCode = status, + Content = new MemoryStream(content), + }; + response.Headers[HeaderNames.ContentType] = type; + return Task.FromResult(response); + } + } +} diff --git a/src/AngleSharp.Renderer.Tests/cases/test15-acid1.html b/src/AngleSharp.Renderer.Tests/cases/test15-acid1.html new file mode 100644 index 0000000..3fffecd --- /dev/null +++ b/src/AngleSharp.Renderer.Tests/cases/test15-acid1.html @@ -0,0 +1,177 @@ + + + + + display/box/float/clear test + + + + +

+
+ toggle +
+
+
    +
  • + the way +
  • +
  • +

    + the world ends +

    +
    +

    + bang + +

    +

    + whimper + +

    +
    +
  • +
  • + i grow old +
  • +
  • + pluot? +
  • +
+
+
+ bar maids, +
+
+

+ sing to me, erbarme dich +

+
+
+

+ This is a nonsensical document, but syntactically valid HTML 4.0. All 100%-conformant CSS1 agents should be able to render the document elements above this paragraph indistinguishably (to the pixel) from this + reference rendering, + (except font rasterization and form widgets). All discrepancies should be traceable to CSS1 implementation shortcomings. Once you have finished evaluating this test, you can return to the parent page. +

+ + diff --git a/src/AngleSharp.Renderer.Tests/verification-assets/acid1.linux.png b/src/AngleSharp.Renderer.Tests/verification-assets/acid1.linux.png new file mode 100644 index 0000000..6ee19e4 Binary files /dev/null and b/src/AngleSharp.Renderer.Tests/verification-assets/acid1.linux.png differ diff --git a/src/AngleSharp.Renderer.Tests/verification-assets/acid1.macos.png b/src/AngleSharp.Renderer.Tests/verification-assets/acid1.macos.png new file mode 100644 index 0000000..2a6694b Binary files /dev/null and b/src/AngleSharp.Renderer.Tests/verification-assets/acid1.macos.png differ diff --git a/src/AngleSharp.Renderer.Tests/verification-assets/acid1.windows.png b/src/AngleSharp.Renderer.Tests/verification-assets/acid1.windows.png new file mode 100644 index 0000000..69d338c Binary files /dev/null and b/src/AngleSharp.Renderer.Tests/verification-assets/acid1.windows.png differ diff --git a/src/AngleSharp.Renderer/HtmlRenderer.Frames.cs b/src/AngleSharp.Renderer/HtmlRenderer.Frames.cs index 781df15..7c84609 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.Frames.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.Frames.cs @@ -39,22 +39,28 @@ internal sealed class SubframeEntry /// private static void PaintSubframe(DisplayList displayList, IElement element, LayoutContext context, float x, float y, float width, float height) { - if (s_trialDepth > 0 || width <= 0f || height <= 0f) + if (s_trialDepth > 0) { return; } - var viewport = new RenderRect(x, y, width, height); - var command = new DrawSubframeCommand(viewport); - displayList.Add(command); + var viewport = new RenderRect(x, y, Math.Max(0f, width), Math.Max(0f, height)); if (!context.Subframes.TryGetValue(element, out var entry)) { context.Subframes[element] = entry = new SubframeEntry(); } - entry.Commands.Add(command); entry.Viewport = viewport; + + // an empty iframe shows nothing, but its document still has that viewport (e.g. for + // its media queries) + if (width > 0f && height > 0f) + { + var command = new DrawSubframeCommand(viewport); + displayList.Add(command); + entry.Commands.Add(command); + } } private static void ResolveSubframes(IDocument document, LayoutContext context) @@ -83,7 +89,11 @@ private static void ResolveSubframes(IDocument document, LayoutContext context) { parent?.AttachSubframe(state); state.SetViewport((int)Math.Round(entry.Viewport.Width), (int)Math.Round(entry.Viewport.Height)); - entry.Frame = state.PrepareFrame(); + + if (entry.Commands.Count > 0) + { + entry.Frame = state.PrepareFrame(); + } } foreach (var command in entry.Commands) diff --git a/src/AngleSharp.Renderer/HtmlRenderer.cs b/src/AngleSharp.Renderer/HtmlRenderer.cs index b24da4a..e198070 100644 --- a/src/AngleSharp.Renderer/HtmlRenderer.cs +++ b/src/AngleSharp.Renderer/HtmlRenderer.cs @@ -9699,10 +9699,48 @@ element is not IPseudoElement && private static bool TryGetObjectImage(IElement element, out CachedImageResource? imageResource) { imageResource = null; + // an error (e.g. a 404 with an image) shows the fallback (HTML 4.8.6) return element is not ILoadableElement { CurrentDownload.Task.IsCompleted: false } && + (GetObjectResponse(element) is not { } response || IsSuccessful(response)) && TryGetOrLoadImageResource(element, element.GetAttribute("data"), out imageResource) && imageResource is not null; } + /// + /// An object showing a document (e.g. a page of HTML) rather than an image, which + /// hides its fallback like an iframe. The document itself isn't shown (Acid3 has a + /// transparent one), so the object is an empty box of the size of an iframe. + /// + private static bool ShowsObjectDocument(IElement element) + { + if (element is IPseudoElement || !string.Equals(element.LocalName, "object", StringComparison.OrdinalIgnoreCase) || + GetObjectResponse(element) is not { } response || !IsSuccessful(response)) + { + return false; + } + + return ObjectDocumentService.IsDocument(response); + } + + // the completed response of the data of an object, if any (one a request failed for is none) + private static IResponse? GetObjectResponse(IElement element) + { + if (element is not ILoadableElement { CurrentDownload.Task: { IsCompleted: true } task }) + { + return null; + } + + try + { + return task.Status == TaskStatus.RanToCompletion ? task.Result : null; + } + catch + { + return null; + } + } + + private static bool IsSuccessful(IResponse response) => (int)response.StatusCode is >= 200 and < 300; + private static bool HasLoadableImageSource(IElement element) => TryGetOrLoadImageResource(element, element.GetAttribute("src"), out var imageResource) && imageResource is not null; @@ -10699,7 +10737,7 @@ private static FormControlKind ResolveFormControlKind(ElementRenderNode node) return FormControlKind.Progress; } - if (string.Equals(tagName, "iframe", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(tagName, "iframe", StringComparison.OrdinalIgnoreCase) || ShowsObjectDocument(element)) { return FormControlKind.Frame; } @@ -11557,7 +11595,7 @@ private static void PaintFormControl( PaintListBox(displayList, element, textStyle, context, contentX, contentY, contentWidth, contentHeight); break; - case FormControlKind.Frame: + case FormControlKind.Frame when string.Equals(element.LocalName, "iframe", StringComparison.OrdinalIgnoreCase): PaintSubframe(displayList, element, context, contentX, contentY, contentWidth, contentHeight); break; diff --git a/src/AngleSharp.Renderer/InteractiveHtmlRendererStateExtensions.cs b/src/AngleSharp.Renderer/InteractiveHtmlRendererStateExtensions.cs index be87b75..1d18963 100644 --- a/src/AngleSharp.Renderer/InteractiveHtmlRendererStateExtensions.cs +++ b/src/AngleSharp.Renderer/InteractiveHtmlRendererStateExtensions.cs @@ -30,13 +30,16 @@ public static IDomHarness GetDomHarness(this IBrowsingContext context) throw new InvalidOperationException("No IRenderDevice service is registered in the browsing context. Register a render device service in IConfiguration before creating the context."); } - // the document of an iframe has a viewport of its own - if (browsingContext.Parent is not null) + // the document of an iframe has a viewport of its own, which is the device of its + // context if the host registered one per context (so its media queries see it too) + if (browsingContext.Parent is { } parentContext && + (renderDevice is not DefaultRenderDevice || ReferenceEquals(renderDevice, parentContext.GetServices().FirstOrDefault()))) { renderDevice = new DefaultRenderDevice { Category = renderDevice.Category, ColorBits = renderDevice.ColorBits, + MonochromeBits = renderDevice.MonochromeBits, Frequency = renderDevice.Frequency, IsInterlaced = renderDevice.IsInterlaced, IsScripting = renderDevice.IsScripting, diff --git a/src/AngleSharp.Renderer/Rendering/ObjectDocumentService.cs b/src/AngleSharp.Renderer/Rendering/ObjectDocumentService.cs new file mode 100644 index 0000000..06a7714 --- /dev/null +++ b/src/AngleSharp.Renderer/Rendering/ObjectDocumentService.cs @@ -0,0 +1,47 @@ +namespace AngleSharp.Renderer.Rendering; + +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using AngleSharp.Dom; +using AngleSharp.Io; +using AngleSharp.Media; + +/// +/// Notes the responses of object data that are documents (e.g. a page of HTML), which +/// an object shows instead of its fallback. AngleSharp clears the headers of a response once +/// it has been processed, so the type has to be noted while it is. +/// +internal sealed class ObjectDocumentService : IResourceService +{ + private static readonly ConditionalWeakTable s_documents = new(); + private static readonly object s_marker = new(); + + public static ObjectDocumentService Instance { get; } = new(); + + private ObjectDocumentService() + { + } + + public bool SupportsType(string mimeType) => IsDocumentType(mimeType); + + public Task CreateAsync(IResponse response, CancellationToken cancel) + { + s_documents.AddOrUpdate(response, s_marker); + return Task.FromResult(new ObjectInfo { Source = response.Address }); + } + + public static bool IsDocument(IResponse response) => s_documents.TryGetValue(response, out _); + + private static bool IsDocumentType(string? mimeType) => + mimeType?.Split(';')[0].Trim().ToLowerInvariant() is "text/html" or "application/xhtml+xml" or "text/plain" or "text/xml" or "application/xml"; + + private sealed class ObjectInfo : IObjectInfo + { + public required Url Source { get; set; } + + public int Width => 0; + + public int Height => 0; + } +} diff --git a/src/AngleSharp.Renderer/Rendering/RenderingConfigurationExtensions.cs b/src/AngleSharp.Renderer/Rendering/RenderingConfigurationExtensions.cs index 2e235a7..444ca5e 100644 --- a/src/AngleSharp.Renderer/Rendering/RenderingConfigurationExtensions.cs +++ b/src/AngleSharp.Renderer/Rendering/RenderingConfigurationExtensions.cs @@ -28,8 +28,13 @@ public static IConfiguration WithRendering(this IConfiguration configuration, Fu ArgumentNullException.ThrowIfNull(factory); configuration = configuration.WithOnly(factory); - return configuration.Services.OfType().Any() + configuration = configuration.Services.OfType().Any() ? configuration : configuration.With(ImageResourceService.Instance); + + // an object showing a document hides its fallback + return configuration.Services.OfType().Any() + ? configuration + : configuration.With(ObjectDocumentService.Instance); } }