From 73ffca171eb0606e0799d199c78c025bc6a5dc5c Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Thu, 19 Nov 2026 12:29:45 +0100 Subject: [PATCH 1/6] Fixes for improving Acid3 --- AGENTS.md | 1 + CHANGELOG.md | 11 ++ src/AngleSharp.Browser.Tests/Acid3Tests.cs | 108 +++++++++++++++++ .../BrowserEngineTests.cs | 14 +++ .../BrowserEngine.Frames.cs | 25 ++++ src/AngleSharp.Browser/BrowserEngine.cs | 46 ++++++- src/AngleSharp.Browser/FrameRenderDevice.cs | 77 ++++++++++++ src/AngleSharp.Browser/VisitedLinks.cs | 114 ++++++++++++++++++ 8 files changed, 395 insertions(+), 1 deletion(-) create mode 100644 src/AngleSharp.Browser.Tests/Acid3Tests.cs create mode 100644 src/AngleSharp.Browser/FrameRenderDevice.cs create mode 100644 src/AngleSharp.Browser/VisitedLinks.cs diff --git a/AGENTS.md b/AGENTS.md index 61a7916..a8ea837 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,6 +16,7 @@ AngleSharp.Browser adds a fully usable (visible) browser based on top of the Ang - Iframes: the document of each one has its own browsing context and harness (with a viewport of the iframe's size); the page's layout leaves a `DrawSubframeCommand`, and the nested frame is prepared right after it, so layouts don't nest. The page's hit-test map delegates to the nested one, and `BrowserEngine.Subframes.cs` routes pointer coordinates, hover, focus, wheel and links. All contexts of an engine share one event loop (`FrameEventLoop` scopes cancelling), as the DOM isn't thread-safe. Script isolation is enforced at the boundary in AngleSharp.Js (`OriginPolicy`, `CrossOriginWindow`): C# code here, like the renderer, sees every document, so anything acting for a script in a frame has to act in that frame's document (see `RunScript`, `FollowHyperlink`). - `src/AngleSharp.Browser.Avalonia` (NuGet package): `BrowserView` displays frames and forwards input; with just a `Source` it creates and owns an engine while attached. Inside of this namespace `Avalonia` means the namespace itself, so `using` directives for the Avalonia framework stay above the namespace declaration. - Audio: `MediaHost` (one per engine) registers `AudioResourceService` as AngleSharp's `IResourceService`; it reads the whole response, picks an `IAudioCodec` by the data's first bytes (`AudioCodecs`: WAV, NLayer, NVorbis, Concentus) and gives the element an `AudioPlayback` (its `IMediaController`). A playing one opens an `IAudioStream` of `BrowserOptions.AudioOutput` (`SilentAudioOutput` by default), which pulls the samples, so the media's clock is what was pulled; it raises its events on the event loop, and AngleSharp's element fires those of its own state (play, pause, volumechange). Audible media needs a user activation (a press or a key, reset per document) unless `IsAutoplayAllowed`; `SyncActiveDocument` stops the media of documents that were left. The Renderer paints `audio[controls]` (its time and timeline as a command painted when rasterized, so `GetTimeToNextImageFrame` also covers playing media); `BrowserEngine.Media.cs` acts on presses on them (hit tested by the Renderer's `GetMediaControlAt`), and `MediaHost.Changed` lays out a frame when a media changes otherwise (play, pause, seek, volume), but only while a document shows `audio[controls]` (`SyncMediaChanges`): a page playing sounds without them (e.g. a game) keeps its frame. Vision's `Audio/OpenAlAudioOutput` (Silk.NET.OpenAL, one device for all windows) is where the audio is heard. +- Visited links: `VisitedLinks` records the address of every parsed document (each context's `HtmlParser` is created by the engine for that) and replaces the `:link`/`:visited` selectors (AngleSharp never matches `:visited`); visits are partitioned by the origin of the top-level page, so pages can't sniff the history. The documents of iframes get a render device of their own (`FrameRenderDevice`), which the Renderer's harness sizes; its viewport takes a pixel size of the iframe from its style first, so media queries follow a script resizing the iframe without a layout. - Site information: `BrowserEngine.Site.cs` finds the page's icon while syncing the document and records the certificate of each host in the HTTP handler's validation callback (unless the host set its own), keeping the platform's verdict. - `src/Vision`: the sample app (Avalonia), not packaged. Its icon lives in `Assets/` (`vision.ico` for Windows/Linux, `vision.png` with the macOS margins, `vision.icns`, each size rendered from the vector design in `Pages/logo.svg`, which the about page shows); on macOS a window's icon is the Dock icon, so the page's icon only shows in the address bar there, while other platforms also show it in the title bar. `App` hosts the windows and the user's `Models/BrowserSettings` (JSON in the app data directory), which apply to windows opened after saving. - Vision's address bar suggests the addresses of `Models/UrlHistory` (`history.json` in the profile directory, in memory for in-memory profiles, shared by the windows of a profile): the most visited first, equally visited ones by their similarity to the typed text (Levenshtein). Its own pages are also served at `vision:` addresses (`Pages/VisionPages`, registered via `BrowserOptions.SchemeHandlers` per window): the window's engine loads the page's source and the `HtmlPage` is attached to its document afterwards; an unknown name shows the list of pages (`VisionPages.Available`, add new pages there). `vision:start` (the default start page) shows the most visited addresses of the window's `UrlHistory`; `vision:requester` sends requests through the engine's `IRequester` services directly (not the loader), so it adds the cookies itself; its saved requests are `Models/SavedRequests` (`requests.json` in the profile directory, shared by the windows of a profile like the history), listed in a sheet the menu button (top left) opens and saved via a dialog from the button below the response. Holding the back/forward button (or a right-click) opens a menu of the history entries in that direction (`BrowserEngine.History`, `GoAsync`). In tests, `DoClick` dispatches after the current `InvokeAsync` callback, so wait between clicks that depend on each other. diff --git a/CHANGELOG.md b/CHANGELOG.md index e1abaf9..07d37fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,14 @@ +# 0.2.1 + +Released on tbd. + +- Fixed a page loaded with a fragment (e.g. `acid2.html#top`) not being scrolled to the element it names +- Fixed the rendering of the Acid2 test (AngleSharp.Css 1.5.1, AngleSharp.Io 1.3.4, AngleSharp.Renderer 0.12.1) +- Added `:visited` to links to pages shown before (partitioned by the site of the page, so pages can't learn of the history elsewhere) +- Fixed the media queries of an iframe's document not seeing its viewport, also right after a script resized the iframe +- Fixed `(max-monochrome: 0)` and the like not matching +- Improved the Acid3 score from 75 to 94 (AngleSharp 1.10.6, AngleSharp.Css 1.5.1, AngleSharp.Js 1.2.3, AngleSharp.Xml 1.3.1, AngleSharp.Renderer 0.12.1) + # 0.2.0 Released on Wednesday, November 18 2026. diff --git a/src/AngleSharp.Browser.Tests/Acid3Tests.cs b/src/AngleSharp.Browser.Tests/Acid3Tests.cs new file mode 100644 index 0000000..4344ac9 --- /dev/null +++ b/src/AngleSharp.Browser.Tests/Acid3Tests.cs @@ -0,0 +1,108 @@ +namespace AngleSharp.Browser.Tests; + +using System; +using System.Diagnostics; +using System.Globalization; +using System.Threading.Tasks; +using NUnit.Framework; + +/// +/// Behavior the Acid3 test (acid3.acidtests.org) relies on. +/// +[TestFixture] +public class Acid3Tests +{ + private BrowserEngine _engine = null!; + + [SetUp] + public void SetUp() + { + _engine = new BrowserEngine(new BrowserOptions { ViewportWidth = 800, ViewportHeight = 600 }); + } + + [TearDown] + public void TearDown() + { + _engine.Dispose(); + } + + [Test] + public async Task LinkToAPageShownInAFrameIsVisited() + { + using var server = new TestServer(new() + { + ["/"] = ("text/html", """ + + shownother + + """u8.ToArray()), + ["/frame.html"] = ("text/html", "

frame"u8.ToArray()), + }); + + await _engine.NavigateAsync(server.Address); + await Eventually(async () => await EvaluateAsync("document.querySelector('iframe').contentDocument.readyState") == "complete"); + // what the link's class changing does after the frame loaded in Acid3 + await _engine.EvaluateScriptAsync("document.getElementById('shown').className = 'x'; document.getElementById('other').className = 'x';"); + + Assert.That(await EvaluateAsync("getComputedStyle(document.getElementById('shown')).color"), Is.EqualTo("rgba(0, 128, 0, 1)")); + Assert.That(await EvaluateAsync("getComputedStyle(document.getElementById('other')).color"), Is.EqualTo("rgba(255, 0, 0, 1)")); + Assert.That(await EvaluateAsync("document.querySelectorAll(':link').length"), Is.EqualTo("1")); + } + + [Test] + public async Task VisitsAreNotSharedWithOtherSites() + { + using var server = new TestServer(new() + { + ["/"] = ("text/html", "

visited"u8.ToArray()), + }); + + await _engine.NavigateAsync(server.Address); + // the address of the server, linked to from another site + await _engine.LoadHtmlAsync($"link", "https://example.org/"); + + Assert.That(await EvaluateAsync("document.querySelectorAll(':visited').length"), Is.EqualTo("0")); + } + + [Test] + public async Task MediaQueriesOfAFrameSeeItsViewport() + { + await _engine.LoadHtmlAsync(""); + + await _engine.PrepareFrameAsync(); + await _engine.PrepareFrameAsync(); + + Assert.That(await EvaluateAsync("var w = document.getElementById('frame').contentWindow; [w.innerWidth, w.innerHeight, w.matchMedia('(max-width: 100px)').matches, w.matchMedia('(min-height: 51px)').matches].join()"), Is.EqualTo("100,50,true,false")); + Assert.That(await EvaluateAsync("matchMedia('(max-width: 100px)').matches"), Is.EqualTo("False").Or.EqualTo("false")); + } + + [Test] + public async Task MediaQueriesOfAFrameFollowItsSizeRightAway() + { + // Acid3 test 46 resizes the iframe and asks its media queries without a layout between + await _engine.LoadHtmlAsync(""); + await _engine.PrepareFrameAsync(); + + var script = "var f = document.getElementById('frame'); var w = f.contentWindow; var before = w.matchMedia('(max-width: 1em)').matches; f.setAttribute('style', 'border:0;width:100px;height:100px'); [before, w.matchMedia('(max-width: 1em)').matches, w.matchMedia('(min-height: 1em)').matches].join()"; + + Assert.That(await EvaluateAsync(script), Is.EqualTo("true,false,true")); + } + + private async Task EvaluateAsync(string script) => + Convert.ToString(await _engine.EvaluateScriptAsync(script), CultureInfo.InvariantCulture) ?? string.Empty; + + private static async Task Eventually(Func> condition) + { + var watch = Stopwatch.StartNew(); + + while (!await condition()) + { + if (watch.Elapsed > TimeSpan.FromSeconds(5)) + { + Assert.Fail("Condition was not met in time."); + } + + await Task.Delay(20); + } + } +} diff --git a/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs b/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs index b89a3b6..1a48952 100644 --- a/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs +++ b/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs @@ -170,6 +170,20 @@ public async Task TypingGoesToTheFieldInAnIframe() Assert.That(value, Is.EqualTo("Hello")); } + [Test] + [TestCase("visible")] + [TestCase("hidden")] + public async Task ALoadedPageScrollsToTheElementItsAddressNames(string overflow) + { + // Acid2's "#top": the page arrives there even if the user can't scroll it + await _engine.LoadHtmlAsync($"

Hello

", "https://example.org/acid2.html#top"); + + await _engine.PrepareFrameAsync(); + await _engine.PrepareFrameAsync(); + + Assert.That(_engine.ScrollTop, Is.EqualTo(2000)); + } + [Test] public async Task WheelScrollsTheIframeUnderThePointer() { diff --git a/src/AngleSharp.Browser/BrowserEngine.Frames.cs b/src/AngleSharp.Browser/BrowserEngine.Frames.cs index ee983b1..96bf3cc 100644 --- a/src/AngleSharp.Browser/BrowserEngine.Frames.cs +++ b/src/AngleSharp.Browser/BrowserEngine.Frames.cs @@ -25,6 +25,8 @@ partial class BrowserEngine private volatile bool _isLastFrameAnimating; private bool _isSyncingScroll; private volatile bool _isPageScrollLocked; + // the document whose address has a fragment to scroll to, once all of it is laid out + private IDocument? _pendingFragmentDocument; /// /// What the last frame painted where, together with what the pointer would show for each @@ -180,6 +182,7 @@ public bool HasPaintedDocument } AdoptScrollPosition(frame.ScrollTop); + ScrollToPendingFragment(document, frame); // the content below the pointer may have moved; like other browsers, the hover state // waits until scrolling ends, as each change of it needs a layout if (!IsScrolling) @@ -207,6 +210,28 @@ public bool HasPaintedDocument return new BrowserFrame(shown, raster => OnFramePainted(document, new FrameTiming(time, kind, layout, raster) { Metrics = metrics })); } + /// + /// Scrolls a newly loaded document to the element its address names (e.g. `page.html#top`), + /// once it is parsed and the frame has laid out all of it, unless the page has been scrolled + /// already. Like other browsers, also a page that cannot be scrolled by the user (overflow: + /// hidden on its root) gets there. Requires exclusive access. + /// + private void ScrollToPendingFragment(IDocument document, RenderedFrame frame) + { + if (!ReferenceEquals(_pendingFragmentDocument, document) || frame.IsPartial || document.ReadyState == DocumentReadyState.Loading) + { + return; + } + + _pendingFragmentDocument = null; + + if (ScrollTop == 0 && new Url(document.Url).Fragment is { Length: > 0 } fragment) + { + ScrollToFragment(document, fragment); + Invalidate(); + } + } + /// /// Asks for a frame once an animated image (e.g. a GIF) in view shows its next frame. Like the /// frame of a mutation that changed nothing, it is the last one, rasterized again: the image diff --git a/src/AngleSharp.Browser/BrowserEngine.cs b/src/AngleSharp.Browser/BrowserEngine.cs index 1db302e..f2204c5 100644 --- a/src/AngleSharp.Browser/BrowserEngine.cs +++ b/src/AngleSharp.Browser/BrowserEngine.cs @@ -68,6 +68,7 @@ function clamp(name, min) { private readonly IEventLoop? _loop; private readonly SemaphoreSlim _gate = new(1, 1); private readonly NavigationHistory _history = new(); + private readonly VisitedLinks _visited = new(); private readonly BrowserDiagnostics _diagnostics = new(); private readonly MediaHost _media; private readonly Timer _heartbeat; @@ -114,6 +115,8 @@ private BrowserEngine(BrowserOptions options, BrowserEngine? opener) { Category = DeviceCategory.Screen, ColorBits = 32, + // a color screen has no monochrome bits (the default of 16 makes (max-monochrome: 0) fail) + MonochromeBits = 0, DeviceWidth = options.ScreenWidth, DeviceHeight = options.ScreenHeight, ViewPortWidth = Math.Max(1, options.ViewportWidth), @@ -138,8 +141,24 @@ private BrowserEngine(BrowserOptions options, BrowserEngine? opener) // one loop for the page and its iframes: scripts of all of them run on it, and the // layout of the page holds it, as the DOM of an iframe is part of what it lays out .WithEventLoop(context => _eventLoop is null ? _eventLoop = new JsEventLoop(context) : new FrameEventLoop(_eventLoop)) - .WithRenderDevice(_device) + // the document of an iframe has a viewport of its own (the renderer sizes it), which its + // media queries see as well + .WithOnly(context => context.Parent is null ? _device : CreateFrameDevice(context, _device)) .WithXml() + // links to pages shown before match :visited (before the CSS extension wraps the selectors) + .WithOnly(_visited.CreateSelectors(() => _context?.Active)) + .WithOnly(context => + { + var parser = new HtmlParser(new HtmlParserOptions { IsScripting = context.IsScripting() }, context); + parser.Parsing += (_, ev) => + { + if (ev is AngleSharp.Html.Dom.Events.HtmlParseEvent { Document: { } document }) + { + _visited.Record(document, TopLevelOf(context)?.Active); + } + }; + return parser; + }) .WithCss() .WithIo(ioOptions) .WithCookies(_cookies) @@ -250,6 +269,30 @@ private BrowserEngine(BrowserOptions options, BrowserEngine? opener) _imageFrameTimer = new Timer(OnImageFrameDue); } + private static DefaultRenderDevice CreateFrameDevice(IBrowsingContext context, DefaultRenderDevice device) => new FrameRenderDevice(context) + { + Category = device.Category, + ColorBits = device.ColorBits, + MonochromeBits = device.MonochromeBits, + DeviceWidth = 300, + DeviceHeight = 150, + ViewPortWidth = 300, + ViewPortHeight = 150, + FontSize = device.FontSize, + IsScripting = device.IsScripting, + Preferences = device.Preferences, + }; + + private static IBrowsingContext? TopLevelOf(IBrowsingContext? context) + { + while (context?.Parent is { } parent) + { + context = parent; + } + + return context; + } + /// /// Raised when the visual output changed and a new frame should be painted. /// @@ -752,6 +795,7 @@ private void SyncActiveDocument() if (active is not null) { _history.Push(active.Url, active); + _pendingFragmentDocument = active.Url.Contains('#') ? active : null; _diagnostics.OnDocumentChanged(active.Url); } diff --git a/src/AngleSharp.Browser/FrameRenderDevice.cs b/src/AngleSharp.Browser/FrameRenderDevice.cs new file mode 100644 index 0000000..4cd0204 --- /dev/null +++ b/src/AngleSharp.Browser/FrameRenderDevice.cs @@ -0,0 +1,77 @@ +namespace AngleSharp.Browser; + +using AngleSharp.Css; +using AngleSharp.Dom; +using AngleSharp.Html.Dom; +using System; +using System.Globalization; +using System.Linq; + +/// +/// The render device of the document of an iframe. The renderer sets its viewport to the size +/// the iframe was laid out with, but a script resizing the iframe expects its media queries to +/// follow right away (Acid3 test 46), as a browser lays out to answer them. A size of the iframe +/// that is known without a layout (a length in pixels) is therefore taken from its style. +/// +sealed class FrameRenderDevice(IBrowsingContext context) : DefaultRenderDevice, IRenderDevice, IRenderDimensions +{ + [ThreadStatic] + private static bool s_isResolving; + + int IRenderDevice.ViewPortWidth => Resolve("width") ?? ViewPortWidth; + + int IRenderDevice.ViewPortHeight => Resolve("height") ?? ViewPortHeight; + + double IRenderDimensions.RenderWidth => ((IRenderDevice)this).ViewPortWidth; + + double IRenderDimensions.RenderHeight => ((IRenderDevice)this).ViewPortHeight; + + private int? Resolve(string dimension) + { + // computing the style of the iframe must not ask for this again (e.g. via a layout) + if (s_isResolving || context.Parent?.Active is not { DefaultView: { } window } parent) + { + return null; + } + + s_isResolving = true; + + try + { + var frame = parent.QuerySelectorAll("iframe") + .OfType() + .FirstOrDefault(m => ReferenceEquals(m.ContentDocument?.Context, context)); + + if (frame is null) + { + return null; + } + + var style = window.GetComputedStyle(frame); + + if (!string.Equals(style.GetPropertyValue("box-sizing"), "content-box", StringComparison.OrdinalIgnoreCase) && + !string.IsNullOrEmpty(style.GetPropertyValue("box-sizing"))) + { + return null; + } + + var value = style.GetPropertyValue(dimension)?.Trim(); + + if (value is not null && value.EndsWith("px", StringComparison.Ordinal) && + double.TryParse(value[..^2], NumberStyles.Float, CultureInfo.InvariantCulture, out var pixels) && pixels >= 0) + { + return (int)Math.Round(pixels); + } + + return null; + } + catch + { + return null; + } + finally + { + s_isResolving = false; + } + } +} diff --git a/src/AngleSharp.Browser/VisitedLinks.cs b/src/AngleSharp.Browser/VisitedLinks.cs new file mode 100644 index 0000000..a93d097 --- /dev/null +++ b/src/AngleSharp.Browser/VisitedLinks.cs @@ -0,0 +1,114 @@ +namespace AngleSharp.Browser; + +using AngleSharp.Css; +using AngleSharp.Css.Dom; +using AngleSharp.Dom; +using AngleSharp.Html.Dom; +using System; +using System.Collections.Generic; + +/// +/// The addresses of the documents an engine has shown, which links match :visited +/// for (AngleSharp itself never treats a link as visited). Like in current browsers the +/// visits are partitioned by the origin of the top-level page they happened in, so a page +/// can't learn of the user's history elsewhere by looking at the style of its links. +/// +sealed class VisitedLinks +{ + private readonly HashSet<(String Partition, String Address)> _visits = []; + private readonly Object _sync = new(); + + /// + /// Records the visit of the given document, shown in the given top-level page (the + /// document itself, if it is the top-level page). + /// + public void Record(IDocument document, IDocument? topLevel) + { + var address = Normalize(document.Url); + + if (address is null) + { + return; + } + + lock (_sync) + { + _visits.Add((PartitionOf(document), address)); + + if (topLevel is not null && topLevel != document) + { + _visits.Add((PartitionOf(topLevel), address)); + } + } + } + + /// + /// Checks if the given element is a link to a document visited in the top-level page + /// it is shown in. + /// + public Boolean IsVisited(IElement element, IDocument? topLevel) + { + var href = element switch + { + IHtmlAnchorElement anchor when anchor.HasAttribute("href") => anchor.Href, + IHtmlAreaElement area when area.HasAttribute("href") => area.Href, + _ => null, + }; + var address = Normalize(href); + + if (address is null || (topLevel ?? element.Owner) is not { } page) + { + return false; + } + + lock (_sync) + { + return _visits.Contains((PartitionOf(page), address)); + } + } + + /// + /// Registers :link and :visited for the visits of this list. + /// + public IPseudoClassSelectorFactory CreateSelectors(Func topLevel) + { + var factory = new DefaultPseudoClassSelectorFactory(); + factory.Unregister(PseudoClassNames.Visited); + factory.Unregister(PseudoClassNames.Link); + factory.Register(PseudoClassNames.Visited, new LinkSelector(PseudoClassNames.Visited, el => IsVisited(el, topLevel()))); + factory.Register(PseudoClassNames.Link, new LinkSelector(PseudoClassNames.Link, el => el.IsLink() && !IsVisited(el, topLevel()))); + return factory; + } + + private static String PartitionOf(IDocument document) => document.Origin ?? String.Empty; + + private static String? Normalize(String? address) + { + if (String.IsNullOrEmpty(address)) + { + return null; + } + + var url = new Url(address!); + + if (url.IsInvalid || (url.Scheme != "http" && url.Scheme != "https" && url.Scheme != "file")) + { + return null; + } + + // the fragment doesn't make another page + url.Fragment = null; + return url.Href; + } + + private sealed class LinkSelector(String name, Predicate matches) : ISelector + { + public String Text => PseudoClassNames.Separator + name; + + public Priority Specificity => Priority.OneClass; + + public void Accept(ISelectorVisitor visitor) => visitor.PseudoClass(name); + + public Boolean Match(IElement element, IElement? scope) => matches(element); + } +} From 8709a761bffe974f56a0389d26d82cdc9288e94d Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Sat, 21 Nov 2026 18:23:20 +0100 Subject: [PATCH 2/6] Rendering improvements --- AGENTS.md | 1 + CHANGELOG.md | 10 +- .../VisionAddressTests.cs | 5 +- src/AngleSharp.Browser.Tests/Acid3Tests.cs | 21 +++++ .../AngleSharp.Browser.csproj | 12 +-- src/AngleSharp.Browser/BrowserEngine.cs | 2 + src/AngleSharp.Browser/ParseErrorDocuments.cs | 37 ++++++++ src/Vision/Pages/StartPage.cs | 33 +++++-- src/Vision/Pages/start.html | 92 +++++++++++++------ 9 files changed, 164 insertions(+), 49 deletions(-) create mode 100644 src/AngleSharp.Browser/ParseErrorDocuments.cs diff --git a/AGENTS.md b/AGENTS.md index a8ea837..68b8344 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,6 +17,7 @@ AngleSharp.Browser adds a fully usable (visible) browser based on top of the Ang - `src/AngleSharp.Browser.Avalonia` (NuGet package): `BrowserView` displays frames and forwards input; with just a `Source` it creates and owns an engine while attached. Inside of this namespace `Avalonia` means the namespace itself, so `using` directives for the Avalonia framework stay above the namespace declaration. - Audio: `MediaHost` (one per engine) registers `AudioResourceService` as AngleSharp's `IResourceService`; it reads the whole response, picks an `IAudioCodec` by the data's first bytes (`AudioCodecs`: WAV, NLayer, NVorbis, Concentus) and gives the element an `AudioPlayback` (its `IMediaController`). A playing one opens an `IAudioStream` of `BrowserOptions.AudioOutput` (`SilentAudioOutput` by default), which pulls the samples, so the media's clock is what was pulled; it raises its events on the event loop, and AngleSharp's element fires those of its own state (play, pause, volumechange). Audible media needs a user activation (a press or a key, reset per document) unless `IsAutoplayAllowed`; `SyncActiveDocument` stops the media of documents that were left. The Renderer paints `audio[controls]` (its time and timeline as a command painted when rasterized, so `GetTimeToNextImageFrame` also covers playing media); `BrowserEngine.Media.cs` acts on presses on them (hit tested by the Renderer's `GetMediaControlAt`), and `MediaHost.Changed` lays out a frame when a media changes otherwise (play, pause, seek, volume), but only while a document shows `audio[controls]` (`SyncMediaChanges`): a page playing sounds without them (e.g. a game) keeps its frame. Vision's `Audio/OpenAlAudioOutput` (Silk.NET.OpenAL, one device for all windows) is where the audio is heard. - Visited links: `VisitedLinks` records the address of every parsed document (each context's `HtmlParser` is created by the engine for that) and replaces the `:link`/`:visited` selectors (AngleSharp never matches `:visited`); visits are partitioned by the origin of the top-level page, so pages can't sniff the history. The documents of iframes get a render device of their own (`FrameRenderDevice`), which the Renderer's harness sizes; its viewport takes a pixel size of the iframe from its style first, so media queries follow a script resizing the iframe without a layout. +- Documents that fail to be created: AngleSharp.Xml throws for XML that isn't well-formed (as a library should); the engine's `ParseErrorDocuments` (an AngleSharp `IDocumentErrorHandler`) shows a `parsererror` document of the same type instead, so the navigation (e.g. of an iframe) still loads, like in browsers. Handle similar errors there rather than in the libraries. - Site information: `BrowserEngine.Site.cs` finds the page's icon while syncing the document and records the certificate of each host in the HTTP handler's validation callback (unless the host set its own), keeping the platform's verdict. - `src/Vision`: the sample app (Avalonia), not packaged. Its icon lives in `Assets/` (`vision.ico` for Windows/Linux, `vision.png` with the macOS margins, `vision.icns`, each size rendered from the vector design in `Pages/logo.svg`, which the about page shows); on macOS a window's icon is the Dock icon, so the page's icon only shows in the address bar there, while other platforms also show it in the title bar. `App` hosts the windows and the user's `Models/BrowserSettings` (JSON in the app data directory), which apply to windows opened after saving. - Vision's address bar suggests the addresses of `Models/UrlHistory` (`history.json` in the profile directory, in memory for in-memory profiles, shared by the windows of a profile): the most visited first, equally visited ones by their similarity to the typed text (Levenshtein). Its own pages are also served at `vision:` addresses (`Pages/VisionPages`, registered via `BrowserOptions.SchemeHandlers` per window): the window's engine loads the page's source and the `HtmlPage` is attached to its document afterwards; an unknown name shows the list of pages (`VisionPages.Available`, add new pages there). `vision:start` (the default start page) shows the most visited addresses of the window's `UrlHistory`; `vision:requester` sends requests through the engine's `IRequester` services directly (not the loader), so it adds the cookies itself; its saved requests are `Models/SavedRequests` (`requests.json` in the profile directory, shared by the windows of a profile like the history), listed in a sheet the menu button (top left) opens and saved via a dialog from the button below the response. Holding the back/forward button (or a right-click) opens a menu of the history entries in that direction (`BrowserEngine.History`, `GoAsync`). In tests, `DoClick` dispatches after the current `InvokeAsync` callback, so wait between clicks that depend on each other. diff --git a/CHANGELOG.md b/CHANGELOG.md index 07d37fa..4c1bbb0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,13 +1,15 @@ -# 0.2.1 +# 0.3.0 Released on tbd. - Fixed a page loaded with a fragment (e.g. `acid2.html#top`) not being scrolled to the element it names -- Fixed the rendering of the Acid2 test (AngleSharp.Css 1.5.1, AngleSharp.Io 1.3.4, AngleSharp.Renderer 0.12.1) -- Added `:visited` to links to pages shown before (partitioned by the site of the page, so pages can't learn of the history elsewhere) +- Fixed the rendering of the Acid2 test - Fixed the media queries of an iframe's document not seeing its viewport, also right after a script resized the iframe - Fixed `(max-monochrome: 0)` and the like not matching -- Improved the Acid3 score from 75 to 94 (AngleSharp 1.10.6, AngleSharp.Css 1.5.1, AngleSharp.Js 1.2.3, AngleSharp.Xml 1.3.1, AngleSharp.Renderer 0.12.1) +- Fixed a navigated XML document that isn't well-formed failing to load (e.g. in an iframe, without a `load` event); like in browsers it shows the error as a `parsererror` element +- Improved the Acid3 score from 75 to 94 +- Improved the design of Vision's start page, which shows the six most visited pages and HTML5test as a demo +- Added `:visited` to links to pages shown before (partitioned by the site of the page, so pages can't learn of the history elsewhere) # 0.2.0 diff --git a/src/AngleSharp.Browser.Avalonia.Tests/VisionAddressTests.cs b/src/AngleSharp.Browser.Avalonia.Tests/VisionAddressTests.cs index dc726bf..87d869d 100644 --- a/src/AngleSharp.Browser.Avalonia.Tests/VisionAddressTests.cs +++ b/src/AngleSharp.Browser.Avalonia.Tests/VisionAddressTests.cs @@ -223,10 +223,11 @@ public async Task TheStartPageShowsTheMostVisitedPagesDemosAndVisionPages() d.QuerySelectorAll("#pages a").Select(m => m.GetAttribute("href")).ToArray(), d.QuerySelector("#most-visited .name")!.TextContent)); // the pages of Vision have their own section - Assert.That(visited, Is.EqualTo(new[] { "https://example.org/7", "https://example.org/6", "https://example.org/5", "https://example.org/4", "https://example.org/3" })); + Assert.That(visited, Is.EqualTo(new[] { "https://example.org/7", "https://example.org/6", "https://example.org/5", "https://example.org/4", "https://example.org/3", "https://example.org/2" })); Assert.That(heading, Is.EqualTo("Seven")); - Assert.That(demos, Has.Length.EqualTo(5)); + Assert.That(demos, Has.Length.EqualTo(6)); Assert.That(demos, Does.Contain("https://news.ycombinator.com")); + Assert.That(demos, Does.Contain("https://html5test.com")); Assert.That(vision, Is.EqualTo(new[] { "vision:requester", "vision:settings", "vision:about" })); Assert.That(BrowserSettings.DefaultStartPage, Is.EqualTo("vision:start")); pages.Dispose(); diff --git a/src/AngleSharp.Browser.Tests/Acid3Tests.cs b/src/AngleSharp.Browser.Tests/Acid3Tests.cs index 4344ac9..efe883c 100644 --- a/src/AngleSharp.Browser.Tests/Acid3Tests.cs +++ b/src/AngleSharp.Browser.Tests/Acid3Tests.cs @@ -88,6 +88,27 @@ public async Task MediaQueriesOfAFrameFollowItsSizeRightAway() Assert.That(await EvaluateAsync(script), Is.EqualTo("true,false,true")); } + [Test] + public async Task FrameWithAnXmlDocumentThatIsNotWellFormedShowsTheError() + { + using var server = new TestServer(new() + { + ["/"] = ("text/html", """ + + + """u8.ToArray()), + ["/bad.xml"] = ("application/xml", """ +

x

+ """u8.ToArray()), + }); + + await _engine.NavigateAsync(server.Address); + await Eventually(async () => await EvaluateAsync("document.querySelector('iframe').className") == "loaded"); + + Assert.That(await EvaluateAsync("document.querySelector('iframe').contentDocument.documentElement.localName"), Is.EqualTo("parsererror")); + Assert.That(await EvaluateAsync("String(notified)"), Is.EqualTo("false")); + } + private async Task EvaluateAsync(string script) => Convert.ToString(await _engine.EvaluateScriptAsync(script), CultureInfo.InvariantCulture) ?? string.Empty; diff --git a/src/AngleSharp.Browser/AngleSharp.Browser.csproj b/src/AngleSharp.Browser/AngleSharp.Browser.csproj index 177b591..103eae2 100644 --- a/src/AngleSharp.Browser/AngleSharp.Browser.csproj +++ b/src/AngleSharp.Browser/AngleSharp.Browser.csproj @@ -12,13 +12,13 @@ - - - - + + + + - - + + diff --git a/src/AngleSharp.Browser/BrowserEngine.cs b/src/AngleSharp.Browser/BrowserEngine.cs index f2204c5..2ad7e47 100644 --- a/src/AngleSharp.Browser/BrowserEngine.cs +++ b/src/AngleSharp.Browser/BrowserEngine.cs @@ -145,6 +145,8 @@ private BrowserEngine(BrowserOptions options, BrowserEngine? opener) // media queries see as well .WithOnly(context => context.Parent is null ? _device : CreateFrameDevice(context, _device)) .WithXml() + // an XML document that isn't well-formed shows the error instead of failing to load + .With(new ParseErrorDocuments()) // links to pages shown before match :visited (before the CSS extension wraps the selectors) .WithOnly(_visited.CreateSelectors(() => _context?.Active)) .WithOnly(context => diff --git a/src/AngleSharp.Browser/ParseErrorDocuments.cs b/src/AngleSharp.Browser/ParseErrorDocuments.cs new file mode 100644 index 0000000..64d5f71 --- /dev/null +++ b/src/AngleSharp.Browser/ParseErrorDocuments.cs @@ -0,0 +1,37 @@ +namespace AngleSharp.Browser; + +using AngleSharp.Dom; +using AngleSharp.Io; +using AngleSharp.Xml.Parser; +using System; +using System.Security; +using System.Threading; +using System.Threading.Tasks; + +/// +/// Shows a navigated XML document that isn't well-formed like a browser does: as a document with +/// just the error (a parsererror element), which loads, instead of failing the navigation +/// (AngleSharp.Xml throws). Its scripts don't run, as the document was never parsed (Acid3). +/// +sealed class ParseErrorDocuments : IDocumentErrorHandler +{ + private const String ParserErrorNamespace = "http://www.mozilla.org/newlayout/xml/parsererror.xml"; + + public async Task HandleAsync(IBrowsingContext context, CreateDocumentOptions options, Exception error, CancellationToken cancellationToken) + { + if (error is not XmlParseException) + { + return null; + } + + var content = $"{SecurityElement.Escape(error.Message)}"; + var response = VirtualResponse.Create(res => res + .Address(options.Response.Address) + .Status(options.Response.StatusCode) + .Content(content) + // the same kind of document (e.g. SVG), but the error is UTF-8 + .Header(HeaderNames.ContentType, options.ContentType.Content)); + var factory = context.GetFactory(); + return await factory.CreateAsync(context, new CreateDocumentOptions(response, null, options.ImportAncestor), cancellationToken).ConfigureAwait(false); + } +} diff --git a/src/Vision/Pages/StartPage.cs b/src/Vision/Pages/StartPage.cs index 21522e9..4d54838 100644 --- a/src/Vision/Pages/StartPage.cs +++ b/src/Vision/Pages/StartPage.cs @@ -2,6 +2,7 @@ namespace Vision.Pages; using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text; using AngleSharp.Dom; @@ -16,7 +17,7 @@ public sealed class StartPage(string? colorScheme, IReadOnlyList /// /// The most visited pages shown. /// - public const int MostVisitedCount = 5; + public const int MostVisitedCount = 6; /// /// The demos to try: address, title and what they show. @@ -27,7 +28,8 @@ public sealed class StartPage(string? colorScheme, IReadOnlyList ("https://picard-sspa-module-federation-tractor-v2.florian-rappl.de", "Tractor Store", "Micro frontends of single-spa and module federation, wired up by Picard.js."), ("https://en.wikipedia.org/wiki/CSS", "Wikipedia: CSS", "A long article with tables, images and references."), ("https://news.ycombinator.com", "Hacker News", "A classic table layout with plenty of links."), - ("https://anglesharp.github.io", "AngleSharp", "The home of the libraries this browser is made of."), + ("https://anglesharp-tests.anglevisions.com/renderer/", "Renderer Tests", "A collection of HTML5 rendering tests."), + ("https://html5test.com", "HTML5test", "How many of the features of HTML5 the browser supports."), ]; /// @@ -36,9 +38,19 @@ public sealed class StartPage(string? colorScheme, IReadOnlyList private static readonly string[] Pages = ["requester", "settings", "about"]; /// - /// The colors of the letters (white text on them is readable in both themes). + /// The gradients of the letters (white text on them is readable in both themes). /// - private static readonly string[] Colors = ["#1a73e8", "#d93025", "#188038", "#e37400", "#9334e6", "#007b83", "#c5221f", "#3949ab"]; + private static readonly (string From, string To)[] Colors = + [ + ("#4285f4", "#1a56c4"), + ("#f06b5c", "#c5221f"), + ("#34a853", "#146c2e"), + ("#f5a623", "#c25e00"), + ("#a46ef5", "#7128d6"), + ("#26a69a", "#00695c"), + ("#ec6fa8", "#b8306f"), + ("#5c6bc0", "#303f9f"), + ]; protected override string Prepare(string html) { @@ -51,7 +63,11 @@ protected override string Prepare(string html) .OrderBy(m => Array.IndexOf(Pages, m.Name)) .Select(m => Tile(m.Address, m.Title, m.Description))); + using var logo = new MemoryStream(); + OpenResource("logo.svg").CopyTo(logo); + return html + .Replace("{{logo}}", $"data:image/svg+xml;base64,{Convert.ToBase64String(logo.ToArray())}") .Replace("{{most-visited}}", visited) .Replace("{{demos}}", demos) .Replace("{{pages}}", pages); @@ -65,7 +81,7 @@ private static string Tile(string url, string title, string description) { var html = new StringBuilder(); html.Append($""""""); - html.Append($"""{Encode(GetLetter(title))}"""); + html.Append($"""{Encode(GetLetter(title))}"""); html.Append($"""{Encode(title)}"""); html.Append($"""{Encode(GetDisplayAddress(url))}"""); html.Append($"""{Encode(description)}"""); @@ -98,9 +114,9 @@ private static string GetLetter(string title) } /// - /// A color of the letter that stays the same for the address (by its host). + /// The background of the letter, which stays the same for the address (by its host). /// - private static string GetColor(string url) + private static string GetBackground(string url) { var key = GetDisplayAddress(url).Split('/')[0]; var hash = 17; @@ -110,6 +126,7 @@ private static string GetColor(string url) hash = unchecked(hash * 31 + character); } - return Colors[(hash & 0x7fffffff) % Colors.Length]; + var (from, to) = Colors[(hash & 0x7fffffff) % Colors.Length]; + return $"background: {to}; background: linear-gradient(135deg, {from} 0%, {to} 100%)"; } } diff --git a/src/Vision/Pages/start.html b/src/Vision/Pages/start.html index 230419a..5f1a9de 100644 --- a/src/Vision/Pages/start.html +++ b/src/Vision/Pages/start.html @@ -11,34 +11,62 @@ background: var(--surface); } -.page { - max-width: 880px; - margin: 0 auto; - padding: 36px 24px 24px; +.hero { + padding: 40px 24px 76px; + background: #0b57d0; + background: linear-gradient(135deg, #0b57d0 0%, #5b3fd6 55%, #a142c7 100%); + color: #ffffff; + text-align: center; } -.intro { - margin-bottom: 24px; - text-align: center; +.hero .logo { + display: inline-block; + border-radius: 18px; + box-shadow: 0 8px 24px rgba(20, 10, 80, 0.35); +} + +.hero .logo img { + display: block; + width: 72px; + height: 72px; } -.intro h1 { - font-size: 28px; - font-weight: 500; +.hero h1 { + margin-top: 14px; + font-size: 30px; + font-weight: 600; + letter-spacing: -0.01em; } -.intro p { - margin: 4px 0 0; +.hero p { + margin: 6px 0 0; + color: #e4e1ff; + font-size: 14px; +} + +.page { + max-width: 852px; + margin: -48px auto 0; + padding: 0 24px 32px; } .section { - margin-bottom: 24px; + margin-bottom: 20px; + padding: 20px 20px 8px; + border: 1px solid var(--border); + border-radius: 18px; + background: var(--bg); + box-shadow: 0 2px 10px rgba(32, 33, 36, 0.08); } .section h2 { - margin-bottom: 10px; - color: var(--accent); - font-size: 13px; + font-size: 15px; +} + +.section .hint { + margin: 2px 0 14px; + color: var(--muted); + font-size: 12px; } .tiles { @@ -50,31 +78,33 @@ .tile { display: flex; box-sizing: border-box; - width: 268px; + width: 262px; margin: 0 6px 12px; padding: 14px; border: 1px solid var(--border); border-radius: 14px; - background: var(--bg); + background: var(--surface); color: var(--text); } .tile:hover { border-color: var(--accent); background: var(--accent-soft); + box-shadow: 0 4px 14px rgba(11, 87, 208, 0.18); } .tile .letter { display: block; flex: none; - width: 36px; - height: 36px; + width: 40px; + height: 40px; margin-right: 12px; - border-radius: 18px; + border-radius: 12px; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2); color: #ffffff; - font-size: 16px; + font-size: 18px; font-weight: 600; - line-height: 36px; + line-height: 40px; text-align: center; } @@ -110,7 +140,7 @@ } .section .empty { - margin: 0; + margin: 0 0 12px; padding: 18px; border: 1px dashed var(--border); border-radius: 14px; @@ -119,24 +149,28 @@ -
-
-

Vision

-

A browser made of AngleSharp. Type an address above, or pick a page to start with.

-
+
+ +

Vision

+

A browser made of AngleSharp. Type an address above, or pick a page to start with.

+
+

Most visited

+

The pages you come back to.

{{most-visited}}

Demos

+

Sites showing what the engine can do.

{{demos}}

Vision

+

The tools and settings of this browser.

{{pages}}
From 70b92f440e75f805569cc0a951d65d94cf4039f4 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Tue, 24 Nov 2026 09:35:59 +0100 Subject: [PATCH 3/6] Removed docs --- .github/workflows/ci.yml | 37 ------------- src/AngleSharp.Browser.Docs/docs.config.json | 28 ---------- src/AngleSharp.Browser.Docs/package.json | 58 -------------------- src/AngleSharp.Browser.Docs/src/index.tsx | 7 --- src/AngleSharp.Browser.Docs/tsconfig.json | 25 --------- 5 files changed, 155 deletions(-) delete mode 100644 src/AngleSharp.Browser.Docs/docs.config.json delete mode 100644 src/AngleSharp.Browser.Docs/package.json delete mode 100644 src/AngleSharp.Browser.Docs/src/index.tsx delete mode 100644 src/AngleSharp.Browser.Docs/tsconfig.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 96d605a..325e2fa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,45 +4,8 @@ on: [push, pull_request] env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DOCS_PATH: ${{ secrets.DOCS_PATH }} - DOCS_BRANCH: ${{ secrets.DOCS_BRANCH }} jobs: - can_document: - runs-on: ubuntu-latest - outputs: - value: ${{ steps.check_job.outputs.value }} - steps: - - name: Checks whether documentation can be built - id: check_job - run: | - echo "value: ${{ env.DOCS_PATH != null && github.ref == env.DOCS_BRANCH }}" - echo "value=${{ env.DOCS_PATH != null && github.ref == env.DOCS_BRANCH }}" >> "$GITHUB_OUTPUT" - - documentation: - needs: [can_document] - runs-on: ubuntu-latest - if: needs.can_document.outputs.value == 'true' - - steps: - - uses: actions/checkout@v5 - - - name: Use Node.js - uses: actions/setup-node@v5 - with: - node-version: "20.x" - registry-url: 'https://registry.npmjs.org' - - - name: Install Dependencies - run: | - cd $DOCS_PATH - npm install - - - name: Deploy Doclet - run: | - cd $DOCS_PATH - npx pilet publish --fresh --url https://feed.piral.cloud/api/v1/pilet/anglesharp --api-key ${{ secrets.PIRAL_FEED_KEY }} - linux: runs-on: ubuntu-latest diff --git a/src/AngleSharp.Browser.Docs/docs.config.json b/src/AngleSharp.Browser.Docs/docs.config.json deleted file mode 100644 index 6ae43b6..0000000 --- a/src/AngleSharp.Browser.Docs/docs.config.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "AngleSharp.Browser", - "author": "Florian Rappl", - "branch": "devel", - "repositoryUrl": "https://github.com/AngleSharp/AngleSharp.Browser", - "rootDir": "../../", - "outputDir": "./dist", - "sitemap": { - "general": { - "sections": [ - { - "generator": "markdown", - "segment": "browser", - "dir": "general" - } - ] - }, - "docs": { - "sections": [ - { - "generator": "markdown", - "segment": "browser", - "dir": "tutorials" - } - ] - } - } -} \ No newline at end of file diff --git a/src/AngleSharp.Browser.Docs/package.json b/src/AngleSharp.Browser.Docs/package.json deleted file mode 100644 index 5af8122..0000000 --- a/src/AngleSharp.Browser.Docs/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "@anglesharp/browser", - "version": "0.2.0", - "preview": true, - "description": "The doclet for the AngleSharp.Browser documentation.", - "keywords": [ - "pilet" - ], - "dependencies": {}, - "devDependencies": { - "@anglesharp/website": "1.0.0", - "@types/react": "^17.0.5", - "@types/react-dom": "^17.0.5", - "@types/react-router": "latest", - "@types/react-router-dom": "^5.1.7", - "@types/node": "^15.3.0", - "typescript": "^4.2.4", - "@dbeining/react-atom": "4.1.19", - "@libre/atom": "1.3.3", - "history": "4.10.1", - "react": "17.0.2", - "react-dom": "17.0.2", - "react-router": "5.2.0", - "react-router-dom": "5.2.0", - "tslib": "2.2.0", - "path-to-regexp": "1.8.0", - "piral-cli": "^0.13.3-pre.2480", - "piral-cli-parcel": "^0.13.3-pre.2480" - }, - "peerDependencies": { - "@dbeining/react-atom": "*", - "@libre/atom": "*", - "history": "*", - "react": "*", - "react-dom": "*", - "react-router": "*", - "react-router-dom": "*", - "tslib": "*", - "path-to-regexp": "*", - "@anglesharp/website": "*" - }, - "scripts": { - "start": "pilet debug", - "build": "pilet build", - "upgrade": "pilet upgrade" - }, - "main": "dist/index.js", - "files": [ - "dist" - ], - "piral": { - "comment": "Keep this section to use the Piral CLI.", - "name": "@anglesharp/website" - }, - "peerModules": [ - "piral-docs-tools/components" - ] -} diff --git a/src/AngleSharp.Browser.Docs/src/index.tsx b/src/AngleSharp.Browser.Docs/src/index.tsx deleted file mode 100644 index dc50b37..0000000 --- a/src/AngleSharp.Browser.Docs/src/index.tsx +++ /dev/null @@ -1,7 +0,0 @@ -import { PiletApi } from 'piral-docs-tools'; - -const createDoclet = require('piral-docs-tools/doclet'); - -export function setup(api: PiletApi) { - createDoclet(api); -} diff --git a/src/AngleSharp.Browser.Docs/tsconfig.json b/src/AngleSharp.Browser.Docs/tsconfig.json deleted file mode 100644 index 610060f..0000000 --- a/src/AngleSharp.Browser.Docs/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "declaration": true, - "noImplicitAny": false, - "removeComments": false, - "noLib": false, - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "target": "es6", - "sourceMap": true, - "outDir": "./dist", - "skipLibCheck": true, - "lib": ["dom", "es2018"], - "moduleResolution": "node", - "module": "esnext", - "jsx": "react", - "importHelpers": true - }, - "include": [ - "./src" - ], - "exclude": [ - "node_modules" - ] -} From dd6578bc5b1d2332312c49cef564dcf7c9ef89b0 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Tue, 24 Nov 2026 09:36:11 +0100 Subject: [PATCH 4/6] Prepare for 1.11 --- AGENTS.md | 13 +- CHANGELOG.md | 16 +- docs/general/02-Engine.md | 15 + docs/general/04-Input.md | 9 +- docs/general/05-Configuration.md | 2 +- docs/tutorials/01-API.md | 4 +- docs/tutorials/03-Custom-Host.md | 1 + .../VisionAddressTests.cs | 2 +- .../VisionPanelTests.cs | 2 + src/AngleSharp.Browser.Tests/Acid3Tests.cs | 4 +- .../BrowserEngineTests.cs | 320 +++++++++++++++++- .../WebAssemblyTests.cs | 238 +++++++++++++ .../AngleSharp.Browser.csproj | 14 +- .../BrowserDocumentFactory.cs | 59 ++++ .../BrowserEngine.Frames.cs | 1 + .../BrowserEngine.Fullscreen.cs | 39 +++ src/AngleSharp.Browser/BrowserEngine.Input.cs | 68 ++-- src/AngleSharp.Browser/BrowserEngine.Media.cs | 25 ++ .../BrowserEngine.Popovers.cs | 129 +++++++ src/AngleSharp.Browser/BrowserEngine.Range.cs | 166 +++++++++ .../BrowserEngine.TextEntry.cs | 263 ++++++++++++++ src/AngleSharp.Browser/BrowserEngine.cs | 37 +- src/AngleSharp.Browser/BrowserOptions.cs | 40 ++- src/AngleSharp.Browser/FormControls.cs | 3 +- src/AngleSharp.Browser/Fullscreen.cs | 228 +++++++++++++ src/AngleSharp.Browser/PaintWorklets.cs | 175 ++++++++++ src/Vision/Models/BrowserSettings.cs | 2 +- src/Vision/Pages/settings.html | 2 +- src/Vision/Views/MainWindow.axaml | 290 ++++++++-------- src/Vision/Views/MainWindow.axaml.cs | 47 +++ 30 files changed, 2010 insertions(+), 204 deletions(-) create mode 100644 src/AngleSharp.Browser.Tests/WebAssemblyTests.cs create mode 100644 src/AngleSharp.Browser/BrowserDocumentFactory.cs create mode 100644 src/AngleSharp.Browser/BrowserEngine.Fullscreen.cs create mode 100644 src/AngleSharp.Browser/BrowserEngine.Popovers.cs create mode 100644 src/AngleSharp.Browser/BrowserEngine.Range.cs create mode 100644 src/AngleSharp.Browser/BrowserEngine.TextEntry.cs create mode 100644 src/AngleSharp.Browser/Fullscreen.cs create mode 100644 src/AngleSharp.Browser/PaintWorklets.cs diff --git a/AGENTS.md b/AGENTS.md index 68b8344..07a5512 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,12 +12,21 @@ AngleSharp.Browser adds a fully usable (visible) browser based on top of the Ang - Frames: `BrowserEngine.PrepareFrameAsync` lays out on the event loop (the first frame of a document only what is in view, `PrepareViewportFrame`, the next one the whole page); `BrowserFrame.Rasterize` (raw RGBA, overscan above/below the viewport) runs on any thread, so `BrowserView` pipelines layout and raster. Each frame's hit-test map answers cursor/link lookups without the DOM; scroll-only frames reuse the last display list unless the page has fixed/sticky boxes. - Page scrolling is smooth and runs ahead of the DOM (`ScrollPosition` vs `ScrollTop`); the view shifts the last frame meanwhile and draws an overlay scrollbar. While a script keeps the page busy, `PrepareFrameAsync` repositions the last frame (DOM-free, like a compositor) instead of waiting for the event loop. A frame after document mutations only (not resources, time or hover: `_needsFullLayout`) asks `IDomHarness.UpdateFrame()` first, which keeps or patches the last frame when the changes are confined to boxes that can be laid out on their own (out-of-flow boxes, flex and grid items, or in-flow blocks staying the same from outside). Until a page has a measured extent, scrolling is not clamped to it (the next frame clamps). A frame that animates asks for the next one as a mutation (`TryReuseLastFrame` advances the clock first), so the harness paints animated transforms/opacity/filters anew without a layout; frames with sticky boxes are repositioned with the boxes stuck anew (Renderer `StickyFrame`). A root with `overflow: hidden` can't be scrolled by the user, but keeps its position. - Text selection is opt-in (`BrowserOptions.IsTextSelectionEnabled`, Vision turns it on): the engine forwards presses (after an uncanceled `mousedown`), drags and Ctrl+A to the harness of the document pressed in (`BrowserEngine.Selection.cs`), which paints the selection without a layout; the I-beam over text comes from `RenderedFrame.HasTextAt` (DOM-free). Vision's own panels select too (controls have `user-select: none`). Animated images (GIFs) pick their frame when rasterized; `ScheduleImageFrame` asks for a frame once one in view changes, which reuses the last frame (`RenderedFrame.GetTimeToNextImageFrame`). +- Text fields: `BrowserEngine.TextEntry.cs` edits at the cursor, which is the field's `selectionStart`/`selectionEnd` (the Renderer paints the caret and the selected text there; a change of the cursor only is a `NotifyStateChanged`). Clicking a field puts the cursor at the end (there is no hit test of the value's characters yet). +- Fullscreen API: `Fullscreen` (a service of each engine's configuration) adds `requestFullscreen()` (needs `MediaHost.HasUserActivation`), `document.fullscreenElement`/`fullscreenEnabled`/`exitFullscreen()` as `[DomExposed]` extensions; the element (and the iframes of the documents around it) get AngleSharp.Css's `:fullscreen` forced (`SetPseudoClass`), whose UA rules cover the viewport (`Fullscreen.DefaultStyle` adds the z-index and black backdrop, as there is no top layer). `BrowserEngine.Fullscreen.cs` raises `FullscreenChanged` and lays out anew; Esc and leaving the document end it. Vision's `MainWindow` shows the window fullscreen without its toolbar meanwhile, and leaving the window's fullscreen calls `ExitFullscreenAsync`. +- User agent: `BrowserOptions.DefaultUserAgent` names the engine (`Mozilla/5.0 () AngleSharp.Browser/x.y`); don't claim to be Chrome: Cloudflare challenges a Chrome claim that doesn't behave like Chrome (w3.org showed "Browser not supported" for AngleSharp.Io's Chrome 45 default, and even for a current Chrome string), while an honest UA gets the page. +- WebAssembly: AngleSharp.Wasm gives scripts the API of browsers through AngleSharp.Js's interop (namespaces, delegates as functions, `Memory` as a shared ArrayBuffer, promises for `Task` parameters); the objects of a browsing context share one Wasmtime store (`WasmJsRealm`), and linear memories are pinned .NET arrays (`HostMemory`, Wasmtime's host memory creator), so `memory.buffer` is the memory. +- Input events: the engine fires what the user does via AngleSharp's `EventTargetExtensions.Fire` (trusted, `BrowserEngine.Input.cs`) and runs the activation itself (`Activate`); `Dispatch` is a script's `dispatchEvent`, which in AngleSharp runs the activation of a `click` too, so it would happen twice. +- Form controls the engine acts on itself: sliders (`BrowserEngine.Range.cs`: press, drag, arrow keys; `input` per value, `change` on release) and popovers (`BrowserEngine.Popovers.cs`: `popovertarget` buttons in `Activate`, light dismiss on a press outside and Esc). `FindActivationTarget` stops at `select`/`textarea`, so their `label` doesn't click them again (that recursed endlessly). +- Paint worklets (CSS Painting API): `PaintWorklets` is AngleSharp.Css's `IPaintWorkletModuleLoader` (scripting only): each document's worklet runs its modules in a Jint realm of its own (`registerPaint`; DOM members found case-insensitively, strings converted to DOM enums by `[DomName]`), and a registration lays the page out anew (`SyncPaintWorklets`). The Renderer draws `paint()` backgrounds via Css's `DrawPaintImages` and replays the recorded commands on a canvas. +- Spec mode: the static constructor of `BrowserEngine` sets AngleSharp.Css's process-wide `CssColorValue.UseSpecSerialization` (colors as `rgb(0, 128, 0)`), which the libraries leave off for their users; tests of the engine expect the spec's strings. - Windows: one `BrowserEngine` (browsing context, history) per window. `WindowRequested` (target=_blank, Ctrl+click) lets the host open one via `CreateWindow()`, which shares the profile data (one synchronized cookie provider, storage and cache factories) but gets its own HTTP handler; unhandled, the page navigates in place. - Iframes: the document of each one has its own browsing context and harness (with a viewport of the iframe's size); the page's layout leaves a `DrawSubframeCommand`, and the nested frame is prepared right after it, so layouts don't nest. The page's hit-test map delegates to the nested one, and `BrowserEngine.Subframes.cs` routes pointer coordinates, hover, focus, wheel and links. All contexts of an engine share one event loop (`FrameEventLoop` scopes cancelling), as the DOM isn't thread-safe. Script isolation is enforced at the boundary in AngleSharp.Js (`OriginPolicy`, `CrossOriginWindow`): C# code here, like the renderer, sees every document, so anything acting for a script in a frame has to act in that frame's document (see `RunScript`, `FollowHyperlink`). - `src/AngleSharp.Browser.Avalonia` (NuGet package): `BrowserView` displays frames and forwards input; with just a `Source` it creates and owns an engine while attached. Inside of this namespace `Avalonia` means the namespace itself, so `using` directives for the Avalonia framework stay above the namespace declaration. - Audio: `MediaHost` (one per engine) registers `AudioResourceService` as AngleSharp's `IResourceService`; it reads the whole response, picks an `IAudioCodec` by the data's first bytes (`AudioCodecs`: WAV, NLayer, NVorbis, Concentus) and gives the element an `AudioPlayback` (its `IMediaController`). A playing one opens an `IAudioStream` of `BrowserOptions.AudioOutput` (`SilentAudioOutput` by default), which pulls the samples, so the media's clock is what was pulled; it raises its events on the event loop, and AngleSharp's element fires those of its own state (play, pause, volumechange). Audible media needs a user activation (a press or a key, reset per document) unless `IsAutoplayAllowed`; `SyncActiveDocument` stops the media of documents that were left. The Renderer paints `audio[controls]` (its time and timeline as a command painted when rasterized, so `GetTimeToNextImageFrame` also covers playing media); `BrowserEngine.Media.cs` acts on presses on them (hit tested by the Renderer's `GetMediaControlAt`), and `MediaHost.Changed` lays out a frame when a media changes otherwise (play, pause, seek, volume), but only while a document shows `audio[controls]` (`SyncMediaChanges`): a page playing sounds without them (e.g. a game) keeps its frame. Vision's `Audio/OpenAlAudioOutput` (Silk.NET.OpenAL, one device for all windows) is where the audio is heard. - Visited links: `VisitedLinks` records the address of every parsed document (each context's `HtmlParser` is created by the engine for that) and replaces the `:link`/`:visited` selectors (AngleSharp never matches `:visited`); visits are partitioned by the origin of the top-level page, so pages can't sniff the history. The documents of iframes get a render device of their own (`FrameRenderDevice`), which the Renderer's harness sizes; its viewport takes a pixel size of the iframe from its style first, so media queries follow a script resizing the iframe without a layout. -- Documents that fail to be created: AngleSharp.Xml throws for XML that isn't well-formed (as a library should); the engine's `ParseErrorDocuments` (an AngleSharp `IDocumentErrorHandler`) shows a `parsererror` document of the same type instead, so the navigation (e.g. of an iframe) still loads, like in browsers. Handle similar errors there rather than in the libraries. +- Documents that fail to be created: AngleSharp.Xml throws for XML that isn't well-formed (as a library should); the engine's `ParseErrorDocuments` (an AngleSharp `IDocumentErrorHandler`) shows a `parsererror` document of the same type instead, so the navigation (e.g. of an iframe) still loads, like in browsers. Handle similar errors there rather than in the libraries. Likewise, responses that aren't documents are shown like in browsers by the engine's `BrowserDocumentFactory` (an AngleSharp `DefaultDocumentFactory`, installed before `WithXml` registers its creators at it): a navigated image (not SVG) becomes a document with just an `img`, keeping the response's address and content type. Add other browser-only document kinds there rather than in AngleSharp's factory. +- Images: AngleSharp's `img` requests nothing by itself. AngleSharp.Css picks its source for the render device (`GetImageSource()`, `ElementRenderNode.ImageSource`: `srcset`, `sizes`, a `picture`'s sources), and the Renderer loads it via Core's `LoadAsync` once it lays the image out: a frame goes on without it and the harness lays out anew on its `load`/`error`, while a static render waits. The natural size is divided by the selection's density (passed to `LoadAsync`, so `naturalWidth` is too). Lazy images (`loading=lazy`, with scripting) are recorded by a frame's layout (`LayoutPass.DeferredImages`, page coordinates, unscrolled by their scroll containers) and loaded by the harness once within `HtmlRenderer.LazyLoadMargin` of the viewport and of every clipping ancestor (`LayoutSnapshot.TakeNearImages`, which applies the containers' current scroll offsets), after each frame and each scroll (`LoadDeferredImages`, as scrolling needs no layout); layouts that aren't frames, and measurements of an image (made-up position), never load a lazy one. Images not in a document (e.g. sprites a game preloads) load once they have a source (the Renderer's `DetachedImageLoader`, an `IAttributeObserver`); a document's `load` waits for what started loading while it was still loading. So in tests, prepare a frame before waiting for an image. - Site information: `BrowserEngine.Site.cs` finds the page's icon while syncing the document and records the certificate of each host in the HTTP handler's validation callback (unless the host set its own), keeping the platform's verdict. - `src/Vision`: the sample app (Avalonia), not packaged. Its icon lives in `Assets/` (`vision.ico` for Windows/Linux, `vision.png` with the macOS margins, `vision.icns`, each size rendered from the vector design in `Pages/logo.svg`, which the about page shows); on macOS a window's icon is the Dock icon, so the page's icon only shows in the address bar there, while other platforms also show it in the title bar. `App` hosts the windows and the user's `Models/BrowserSettings` (JSON in the app data directory), which apply to windows opened after saving. - Vision's address bar suggests the addresses of `Models/UrlHistory` (`history.json` in the profile directory, in memory for in-memory profiles, shared by the windows of a profile): the most visited first, equally visited ones by their similarity to the typed text (Levenshtein). Its own pages are also served at `vision:` addresses (`Pages/VisionPages`, registered via `BrowserOptions.SchemeHandlers` per window): the window's engine loads the page's source and the `HtmlPage` is attached to its document afterwards; an unknown name shows the list of pages (`VisionPages.Available`, add new pages there). `vision:start` (the default start page) shows the most visited addresses of the window's `UrlHistory`; `vision:requester` sends requests through the engine's `IRequester` services directly (not the loader), so it adds the cookies itself; its saved requests are `Models/SavedRequests` (`requests.json` in the profile directory, shared by the windows of a profile like the history), listed in a sheet the menu button (top left) opens and saved via a dialog from the button below the response. Holding the back/forward button (or a right-click) opens a menu of the history entries in that direction (`BrowserEngine.History`, `GoAsync`). In tests, `DoClick` dispatches after the current `InvokeAsync` callback, so wait between clicks that depend on each other. @@ -25,7 +34,7 @@ AngleSharp.Browser adds a fully usable (visible) browser based on top of the Ang - `src/AngleSharp.Browser.Tests`: NUnit tests driving the engine headlessly. `src/AngleSharp.Browser.Avalonia.Tests`: NUnit tests of the control and of Vision's panels using Avalonia's headless platform with real Skia rendering. Don't use `Assert.ThrowsAsync` with the engine (it blocks and hangs); use an awaited try/catch. - `build/`: the Fallout build, run via `build.sh`/`build.ps1`, `.github/workflows/ci.yml` calls it. The version comes from the top of `CHANGELOG.md`; a push to `main` publishes a release, one to `devel` a pre-release. - `docs/`: the documentation, published through the doclet in `src/AngleSharp.Browser.Docs`. Keep it in sync with the public API. -- `BrowserEngine` patches a few upstream gaps (User-Agent header, `noscript` style, text documents never completing, timer delays clamped because a zero-delay `setInterval` never yields before AngleSharp 1.9.0, `label.control` not finding wrapped controls, event listener errors reported by an `ErrorEvent` without a type, and `NavigationHistory` reaching the protected `Document.DocumentUri` setter by reflection, as `pushState` has to change the document's address, and `LegacyKeyboardEvent.Code` as it knows the key's code by itself from then on); remove them once fixed upstream. +- `BrowserEngine` patches a few upstream gaps (User-Agent header, `noscript` style, text documents never completing, timer delays clamped because a zero-delay `setInterval` never yields before AngleSharp 1.9.0, `label.control` not finding wrapped controls, event listener errors reported by an `ErrorEvent` without a type, and `NavigationHistory` reaching the protected `Document.DocumentUri` setter by reflection, as `pushState` has to change the document's address, `LegacyKeyboardEvent.Code` as it knows the key's code by itself from then on, and a field's cursor moved to the end of a value a script set, which AngleSharp does from 1.11); remove them once fixed upstream. ## Most Important Commands diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c1bbb0..156aefd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,15 +1,27 @@ # 0.3.0 -Released on tbd. +Released on Tuesday, November 24 2026. +- Fixed Home, End and the arrow keys doing nothing in text fields; they move the cursor (with Shift selecting text), which typing, Backspace and Delete edit at, like in browsers - Fixed a page loaded with a fragment (e.g. `acid2.html#top`) not being scrolled to the element it names - Fixed the rendering of the Acid2 test - Fixed the media queries of an iframe's document not seeing its viewport, also right after a script resized the iframe - Fixed `(max-monochrome: 0)` and the like not matching +- Fixed a navigated image (e.g. a PNG in an iframe) being parsed as HTML; like in browsers it is shown in a document of its own - Fixed a navigated XML document that isn't well-formed failing to load (e.g. in an iframe, without a `load` event); like in browsers it shows the error as a `parsererror` element -- Improved the Acid3 score from 75 to 94 +- Fixed clicking a `select` or `textarea` inside a `label` crashing the browser (endless recursion) +- Fixed the events of the user (e.g. clicks and keys) not being trusted (`isTrusted`) +- Fixed images showing the first candidate of their `srcset` (e.g. pixelated, scaled up); they show the one fitting their `sizes`, the device pixel ratio and the media of a `picture`'s sources, are as large as their density says (e.g. `2x`), and are only loaded once shown (or right away when not in the page, e.g. `new Image()`); `loading=lazy` images load once scrolled near - Improved the design of Vision's start page, which shows the six most visited pages and HTML5test as a demo +- Updated the default user agent to name the engine (e.g. `Mozilla/5.0 (X11; Linux x86_64) AngleSharp.Browser/0.3`) +- Updated colors to be serialized as CSSOM says, e.g. `getComputedStyle` gives `rgb(0, 128, 0)` instead of `rgba(0, 128, 0, 1)` (`CssColorValue.UseSpecSerialization`, set process-wide) - Added `:visited` to links to pages shown before (partitioned by the site of the page, so pages can't learn of the history elsewhere) +- Added dragging sliders (`input[type=range]`) and changing them with the keyboard +- Added buttons with `popovertarget` showing, hiding or toggling their popover, and light dismiss of popovers (a press outside or Esc) +- Added paint worklets (`CSS.paintWorklet.addModule()` with `registerPaint`), whose `paint()` images backgrounds show +- Added the Fullscreen API: `requestFullscreen()` (after a press or a key), `document.exitFullscreen()`, `fullscreenElement` and `fullscreenEnabled`, with `fullscreenchange` events and Esc ending it; the engine raises `FullscreenChanged`, and Vision shows the page fullscreen meanwhile +- Added WebAssembly as in browsers (AngleSharp.Wasm with AngleSharp.Js): `WebAssembly.instantiate`/`instantiateStreaming` with import objects of scripts, exports scripts call, and `memory.buffer` sharing the memory; before, `WebAssembly` was undefined +- Added `crypto.subtle` (AngleSharp.Js) # 0.2.0 diff --git a/docs/general/02-Engine.md b/docs/general/02-Engine.md index 0b885bb..85e31ec 100644 --- a/docs/general/02-Engine.md +++ b/docs/general/02-Engine.md @@ -95,8 +95,23 @@ The underlying `IBrowsingContext` is available via `Context`, e.g., to retrieve | `HoverChanged` | The hovered link or the cursor changed. | | `ScrollChanged` | The scroll position changed. | | `WindowRequested` | The page asks for a new window. See [Configuration](05-Configuration.md#multiple-windows). | +| `FullscreenChanged` | The page started or ended showing an element fullscreen. See [Fullscreen](#fullscreen). | | `Error` | An operation failed, e.g., a navigation or a script. | +## Fullscreen + +A page shows an element fullscreen with `requestFullscreen()`, which needs a user activation (a press or a key), like in browsers. The element then covers the viewport (it matches `:fullscreen`), and the engine raises `FullscreenChanged` with `IsFullscreen` being `true`. A host should show the page fullscreen meanwhile, e.g. with a fullscreen window and without its toolbars: + +```cs +engine.FullscreenChanged += (_, _) => +{ + // raised on the engine's thread + Dispatcher.UIThread.Post(() => window.WindowState = engine.IsFullscreen ? WindowState.FullScreen : WindowState.Normal); +}; +``` + +Esc ends it, as does the page (`document.exitFullscreen()`) or leaving the document. When the user leaves the fullscreen mode of the host another way, call `ExitFullscreenAsync` to end it for the page as well. + ## Diagnostics `Diagnostics` collects what happens while showing the current page, like the developer tools of a browser. It starts over with every page and is thread-safe: diff --git a/docs/general/04-Input.md b/docs/general/04-Input.md index e1ded6e..a229c25 100644 --- a/docs/general/04-Input.md +++ b/docs/general/04-Input.md @@ -58,7 +58,14 @@ Console.WriteLine(await engine.CopySelectionAsync()); Keys are named by their DOM key value, e.g., `"a"`, `"Enter"`, `"Backspace"`, `"Tab"`, or `"ArrowDown"`. Keys and text are separate on purpose, just like in most UI frameworks: - `KeyDownAsync` and `KeyUpAsync` fire the keyboard events and perform the actions of keys, e.g., Tab moving the focus, or Enter submitting a form. -- `TextInputAsync` enters text into the focused text field. It works for whole strings, too. +- `TextInputAsync` enters text into the focused text field at its cursor, replacing the selected text. It works for whole strings, too. + +In a text field (`input` or `textarea`) the keys edit like in browsers. The cursor is the field's `selectionStart` and `selectionEnd`, so scripts see it and can place it: + +- The left and right keys move the cursor, by words with Ctrl (or Alt). Home and End go to the start and end of the line, with Ctrl of the whole text. In a `textarea` the up and down keys go to the line above and below. +- Shift extends the selection, Ctrl+A (or Cmd+A) selects all of the text. +- Backspace and Delete remove the selected text, or the character (with Ctrl the word) before or after the cursor. +- Focusing a field by clicking it puts the cursor at the end of its text; tabbing into an `input` selects its text. ```cs await engine.ClickAsync(100, 200); diff --git a/docs/general/05-Configuration.md b/docs/general/05-Configuration.md index 8c70339..a830605 100644 --- a/docs/general/05-Configuration.md +++ b/docs/general/05-Configuration.md @@ -11,7 +11,7 @@ Everything that touches the outside world is configured via `BrowserOptions`, wh | Option | Default | Description | | --- | --- | --- | | `ProfileDirectory` | `null` | Where cookies, web storage and the HTTP cache are persisted; `null` keeps everything in memory. | -| `UserAgent` | `null` | The user agent to report; `null` uses the default of AngleSharp.Io. | +| `UserAgent` | `null` | The user agent to report; `null` uses `BrowserOptions.DefaultUserAgent`, e.g. `Mozilla/5.0 (X11; Linux x86_64) AngleSharp.Browser/0.3`. It names the engine rather than claiming to be Chrome: bot protections (e.g. Cloudflare's) refuse a browser claiming to be Chrome that doesn't behave like it in every detail. | | `DefaultHeaders` | empty | Headers added to every request, unless a request sets them already. | | `ColorScheme` | `null` | The answer to `prefers-color-scheme`, e.g., `light` or `dark`. | | `IsScriptingEnabled` | `true` | If JavaScript should be evaluated. | diff --git a/docs/tutorials/01-API.md b/docs/tutorials/01-API.md index bf5dc36..22cd4ee 100644 --- a/docs/tutorials/01-API.md +++ b/docs/tutorials/01-API.md @@ -41,6 +41,7 @@ The following APIs cover most day-to-day tasks: | `HoveredLink`, `Cursor` | What is below the pointer. | | `ColorScheme` | The answer to `prefers-color-scheme`; may be changed. | | `HasPaintedDocument` | If the current document has been painted at least once. | +| `IsFullscreen` | If the page shows an element fullscreen. See [Fullscreen](../general/02-Engine.md#fullscreen). | | `Diagnostics` | The `BrowserDiagnostics` of the current page. | ### Methods @@ -60,6 +61,7 @@ The following APIs cover most day-to-day tasks: | `MovePointer`, `MovePointerAsync`, `PointerDownAsync`, `PointerUpAsync`, `ClickAsync` | Pointer input. | | `KeyDownAsync`, `KeyUpAsync`, `TextInputAsync` | Keyboard input. | | `CopySelectionAsync()` | Gets the selected text for the clipboard. | +| `ExitFullscreenAsync()` | Ends showing an element fullscreen. | | `ScrollAsync(deltaX, deltaY)`, `ScrollToAsync(top, animate)` | Scrolling. | | `CreateWindow()`, `CreateWindow(options)` | Creates an engine sharing the profile. | | `LoadIconAsync()`, `GetCertificate(host)` | Loads the page's icon, or gets the certificate of a host. | @@ -68,7 +70,7 @@ All asynchronous methods take an optional `CancellationToken`. ### Events -`Invalidated`, `StateChanged`, `HoverChanged`, `ScrollChanged`, `WindowRequested`, and `Error`. See [Browser Engine](../general/02-Engine.md#events). +`Invalidated`, `StateChanged`, `HoverChanged`, `ScrollChanged`, `WindowRequested`, `FullscreenChanged`, and `Error`. See [Browser Engine](../general/02-Engine.md#events). ## BrowserFrame diff --git a/docs/tutorials/03-Custom-Host.md b/docs/tutorials/03-Custom-Host.md index 64261a7..5802180 100644 --- a/docs/tutorials/03-Custom-Host.md +++ b/docs/tutorials/03-Custom-Host.md @@ -103,3 +103,4 @@ What else makes it feel like a browser: - Update `ColorScheme` when the theme changes. - Draw a scrollbar from `ScrollPosition`, `ScrollHeight` and `ViewportHeight`, and change the position using `ScrollToAsync`. - Handle `WindowRequested`, and open a window with an engine from `CreateWindow`. +- Handle `FullscreenChanged` to show the page fullscreen while `IsFullscreen`, and call `ExitFullscreenAsync` when the user leaves the fullscreen mode of the host. diff --git a/src/AngleSharp.Browser.Avalonia.Tests/VisionAddressTests.cs b/src/AngleSharp.Browser.Avalonia.Tests/VisionAddressTests.cs index 87d869d..e455aa1 100644 --- a/src/AngleSharp.Browser.Avalonia.Tests/VisionAddressTests.cs +++ b/src/AngleSharp.Browser.Avalonia.Tests/VisionAddressTests.cs @@ -193,7 +193,7 @@ public async Task AnUnknownVisionPageListsThePagesThereAre() Assert.That(links, Is.EqualTo(VisionPages.Available.Select(m => m.Address).ToArray())); await engine.InvokeAsync(d => ((IHtmlElement)d!.QuerySelector("#pages a[href='vision:about']")!).DoClick()); - await WaitUntil(engine, d => d?.Url == "vision:about" && d.GetElementById("version")!.TextContent.StartsWith("Version")); + await WaitUntil(engine, d => d?.Url == "vision:about" && d.GetElementById("version")?.TextContent.StartsWith("Version") == true); await engine.NavigateAsync("vision:pages"); Assert.That(await engine.InvokeAsync(d => d!.GetElementById("notice")), Is.Null); diff --git a/src/AngleSharp.Browser.Avalonia.Tests/VisionPanelTests.cs b/src/AngleSharp.Browser.Avalonia.Tests/VisionPanelTests.cs index 3af1d46..fe14f25 100644 --- a/src/AngleSharp.Browser.Avalonia.Tests/VisionPanelTests.cs +++ b/src/AngleSharp.Browser.Avalonia.Tests/VisionPanelTests.cs @@ -238,6 +238,8 @@ public async Task TheAboutPageShowsTheVisionLogo() { using var page = new AboutPage("light", () => { }); await page.LoadAsync(); + // the frame showing it loads it + await page.Engine.PrepareFrameAsync(); await WaitUntil(page, d => d!.QuerySelector(".logo img") is { IsCompleted: true }); var logo = await page.Engine.InvokeAsync(d => d!.QuerySelector(".logo img")!); diff --git a/src/AngleSharp.Browser.Tests/Acid3Tests.cs b/src/AngleSharp.Browser.Tests/Acid3Tests.cs index efe883c..037fdfc 100644 --- a/src/AngleSharp.Browser.Tests/Acid3Tests.cs +++ b/src/AngleSharp.Browser.Tests/Acid3Tests.cs @@ -44,8 +44,8 @@ public async Task LinkToAPageShownInAFrameIsVisited() // what the link's class changing does after the frame loaded in Acid3 await _engine.EvaluateScriptAsync("document.getElementById('shown').className = 'x'; document.getElementById('other').className = 'x';"); - Assert.That(await EvaluateAsync("getComputedStyle(document.getElementById('shown')).color"), Is.EqualTo("rgba(0, 128, 0, 1)")); - Assert.That(await EvaluateAsync("getComputedStyle(document.getElementById('other')).color"), Is.EqualTo("rgba(255, 0, 0, 1)")); + Assert.That(await EvaluateAsync("getComputedStyle(document.getElementById('shown')).color"), Is.EqualTo("rgb(0, 128, 0)")); + Assert.That(await EvaluateAsync("getComputedStyle(document.getElementById('other')).color"), Is.EqualTo("rgb(255, 0, 0)")); Assert.That(await EvaluateAsync("document.querySelectorAll(':link').length"), Is.EqualTo("1")); } diff --git a/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs b/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs index 1a48952..da9994b 100644 --- a/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs +++ b/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs @@ -85,6 +85,74 @@ public async Task CustomSchemesAreAnsweredByTheirHandlers() Assert.That(requested, Is.EqualTo(new[] { "app:start", "app:next" })); } + [Test] + public async Task ImagesShowTheCandidateOfTheirSrcsetFittingTheirSizes() + { + // the tractor store's machines: the 200w images were shown at 300px (pixelated) + using var server = new TestServer(new() + { + ["/"] = ("text/html", """"""u8.ToArray()), + ["/cat.png"] = ("image/png", Png(100)), + ["/cat-200.png"] = ("image/png", Png(200)), + ["/cat-400.png"] = ("image/png", Png(400)), + ["/cat-800.png"] = ("image/png", Png(800)), + }); + + await _engine.NavigateAsync(server.Address); + var img = (AngleSharp.Html.Dom.IHtmlImageElement)_engine.Document!.GetElementById("img")!; + await _engine.PrepareFrameAsync(); + await Eventually(() => img.IsCompleted); + + Assert.That(img.ActualSource, Does.EndWith("/cat-400.png")); + // 400 pixels for 300px (density 4/3), as browsers give it + Assert.That(img.OriginalWidth, Is.EqualTo(300)); + + static byte[] Png(int width) + { + using var bitmap = new SkiaSharp.SKBitmap(width, 1); + using var data = bitmap.Encode(SkiaSharp.SKEncodedImageFormat.Png, 100); + return data.ToArray(); + } + } + + [Test] + public async Task LazyImagesLoadOnceScrolledNear() + { + var page = "" + string.Concat(Enumerable.Range(0, 4).Select(i => + $"
")); + using var server = new TestServer(new() + { + ["/"] = ("text/html", System.Text.Encoding.UTF8.GetBytes(page)), + ["/p0.png"] = ("image/png", Png()), + ["/p1.png"] = ("image/png", Png()), + ["/p2.png"] = ("image/png", Png()), + ["/p3.png"] = ("image/png", Png()), + }); + + await _engine.NavigateAsync(server.Address); + await _engine.PrepareFrameAsync(); + await _engine.PrepareFrameAsync(); + var images = Enumerable.Range(0, 4).Select(i => (AngleSharp.Html.Dom.IHtmlImageElement)_engine.Document!.GetElementById($"i{i}")!).ToArray(); + await Eventually(() => images[0].IsCompleted); + + Assert.That(images.Skip(1).Select(image => ((ILoadableElement)image).CurrentDownload), Is.All.Null); + + await _engine.ScrollToAsync(6000, animate: false); + await _engine.PrepareFrameAsync(); + await Eventually(() => images[2].IsCompleted); + + // the ones passed by (above the margin) or still far below stay unloaded + Assert.That(((ILoadableElement)images[1]).CurrentDownload, Is.Null); + Assert.That(((ILoadableElement)images[3]).CurrentDownload, Is.Null); + + static byte[] Png() + { + using var bitmap = new SkiaSharp.SKBitmap(40, 20); + using var data = bitmap.Encode(SkiaSharp.SKEncodedImageFormat.Png, 100); + return data.ToArray(); + } + } + private async Task<(IDocument Nested, IHtmlInlineFrameElement Frame)> LoadFrameAsync(string frameHtml, string pageStyle = "") { var srcdoc = System.Net.WebUtility.HtmlEncode(frameHtml); @@ -147,6 +215,18 @@ public async Task ClickReachesTheElementInAnIframe() Assert.That(clicks, Is.EqualTo(new[] { (30d, 20d) })); } + [Test] + public async Task WhatTheUserDoesIsTrustedAndSubmitsOnce() + { + await _engine.LoadHtmlAsync("
" + + ""); + + await _engine.ClickAsync(20, 20); + + Assert.That(await _engine.EvaluateScriptAsync("log.join(',')"), Is.EqualTo("click true,submit true")); + } + [Test] public async Task HoveringAnElementInAnIframeMatchesHoverThere() { @@ -634,6 +714,92 @@ public async Task TypingIntoFocusedInputUpdatesValueAndAttribute() Assert.That(input.GetAttribute("value"), Is.EqualTo("Hell")); } + [Test] + public async Task HomeEndAndTheArrowKeysMoveTheCursorOfAnInput() + { + await _engine.LoadHtmlAsync(""); + var input = (IHtmlInputElement)_engine.Document!.GetElementById("name")!; + + var (x, y) = CenterOf("name"); + await _engine.ClickAsync(x, y); + await Eventually(() => input.IsFocused); + await _engine.TextInputAsync("World"); + await _engine.KeyDownAsync("Home"); + await _engine.TextInputAsync("Hello "); + Assert.That(input.Value, Is.EqualTo("Hello World")); + Assert.That(input.SelectionStart, Is.EqualTo(6)); + + await _engine.KeyDownAsync("End"); + await _engine.KeyDownAsync("ArrowLeft"); + await _engine.KeyDownAsync("ArrowLeft"); + await _engine.KeyDownAsync("Backspace"); + Assert.That(input.Value, Is.EqualTo("Hello Wold")); + + await _engine.KeyDownAsync("ArrowRight"); + await _engine.KeyDownAsync("Delete"); + Assert.That(input.Value, Is.EqualTo("Hello Wol")); + Assert.That(input.SelectionStart, Is.EqualTo(9)); + } + + [Test] + public async Task ShiftWithTheArrowKeysSelectsTextTypingReplaces() + { + await _engine.LoadHtmlAsync(""); + var input = (IHtmlInputElement)_engine.Document!.GetElementById("name")!; + + var (x, y) = CenterOf("name"); + await _engine.ClickAsync(x, y); + await Eventually(() => input.IsFocused); + await _engine.KeyDownAsync("ArrowLeft", InputModifiers.Control | InputModifiers.Shift); + Assert.That((input.SelectionStart, input.SelectionEnd, input.SelectionDirection), Is.EqualTo((6, 11, "backward"))); + + await _engine.TextInputAsync("There"); + Assert.That(input.Value, Is.EqualTo("Hello There")); + + await _engine.KeyDownAsync("Home", InputModifiers.Shift); + await _engine.KeyDownAsync("Backspace"); + Assert.That(input.Value, Is.Empty); + } + + [Test] + public async Task TheArrowKeysMoveBetweenTheLinesOfATextArea() + { + await _engine.LoadHtmlAsync(""); + var area = (IHtmlTextAreaElement)_engine.Document!.GetElementById("area")!; + + var (x, y) = CenterOf("area"); + await _engine.ClickAsync(x, y); + await Eventually(() => area.IsFocused); + await _engine.KeyDownAsync("ArrowUp"); + Assert.That(area.SelectionStart, Is.EqualTo(5)); + + await _engine.KeyDownAsync("Home"); + await _engine.KeyDownAsync("ArrowDown"); + await _engine.KeyDownAsync("End"); + await _engine.TextInputAsync("!"); + Assert.That(area.Value, Is.EqualTo("first\nsecond line!")); + + await _engine.KeyDownAsync("Home", InputModifiers.Control); + await _engine.TextInputAsync(">"); + Assert.That(area.Value, Is.EqualTo(">first\nsecond line!")); + } + + [Test] + public async Task AValueSetByAScriptMovesTheCursorToItsEnd() + { + await _engine.LoadHtmlAsync(""); + var input = (IHtmlInputElement)_engine.Document!.GetElementById("name")!; + + var (x, y) = CenterOf("name"); + await _engine.ClickAsync(x, y); + await Eventually(() => input.IsFocused); + await _engine.KeyDownAsync("Home"); + await _engine.InvokeAsync(_ => input.Value = "suggested"); + await _engine.TextInputAsync("!"); + + Assert.That(input.Value, Is.EqualTo("suggested!")); + } + [Test] public async Task ClickingCheckboxLabelTogglesIt() { @@ -925,6 +1091,107 @@ public async Task ClickingADropdownOpensItAndAgainClosesIt() Assert.That(_engine.IsSelectPopupOpen, Is.False); } + [Test] + public async Task APaintWorkletPaintsTheBackgroundsUsingIt() + { + var module = Uri.EscapeDataString("registerPaint('fill', class { static get inputProperties() { return ['--color']; } paint(ctx, size, props) { ctx.fillStyle = String(props.get('--color')).trim(); ctx.lineCap = 'round'; ctx.fillRect(0, 0, size.width / 2, size.height); } });"); + await _engine.LoadHtmlAsync($"
"); + + for (var i = 0; i < 20 && PixelOf((await _engine.PrepareFrameAsync())!, 10, 10) != (0, 0, 255); i++) + { + await Task.Delay(50); + } + + var frame = await _engine.PrepareFrameAsync(); + Assert.That(PixelOf(frame!, 10, 10), Is.EqualTo(((byte)0, (byte)0, (byte)255))); + // the painter fills the left half of the box only + Assert.That(PixelOf(frame!, 80, 10), Is.EqualTo(((byte)255, (byte)255, (byte)255))); + } + + [Test] + public async Task ClickingADropdownInALabelOpensIt() + { + // the label must not click the select again (it once did so endlessly) + var select = await LoadDropdownAsync(""); + + await _engine.ClickAsync(10, 30); + + Assert.That(_engine.IsSelectPopupOpen, Is.True); + Assert.That(_engine.Document!.ActiveElement, Is.EqualTo(select)); + } + + [Test] + public async Task DraggingASliderSetsItsValue() + { + await _engine.LoadHtmlAsync(""); + await _engine.PrepareFrameAsync(); + var slider = (IHtmlInputElement)_engine.Document!.QuerySelector("input")!; + var events = new List(); + slider.AddEventListener("input", (_, _) => events.Add("input:" + slider.Value)); + slider.AddEventListener("change", (_, _) => events.Add("change:" + slider.Value)); + + await _engine.PointerDownAsync(20, 10); + await _engine.MovePointerAsync(80, 10); + await _engine.PointerUpAsync(80, 10); + + Assert.That(slider.Value, Is.EqualTo("8")); + Assert.That(events, Is.EqualTo(new[] { "input:2", "input:8", "change:8" })); + + await PressKeyAsync("ArrowLeft"); + await PressKeyAsync("End"); + Assert.That(slider.Value, Is.EqualTo("10")); + } + + [Test] + public async Task APopoverTargetButtonTogglesItsPopover() + { + await _engine.LoadHtmlAsync("
Hint
"); + await _engine.PrepareFrameAsync(); + var popover = (IHtmlElement)_engine.Document!.GetElementById("pop")!; + + await _engine.ClickAsync(10, 10); + Assert.That(popover.IsPopoverOpen(), Is.True); + + await _engine.ClickAsync(10, 10); + Assert.That(popover.IsPopoverOpen(), Is.False); + + // a press outside of it closes it, as does Esc + await _engine.ClickAsync(10, 10); + await _engine.ClickAsync(10, 500); + Assert.That(popover.IsPopoverOpen(), Is.False); + + await _engine.ClickAsync(10, 10); + await PressKeyAsync("Escape"); + Assert.That(popover.IsPopoverOpen(), Is.False); + } + + [Test] + public async Task AClickedButtonShowsAnElementFullscreenUntilEscape() + { + await _engine.LoadHtmlAsync("" + + "
" + + ""); + await _engine.PrepareFrameAsync(); + var changes = 0; + _engine.FullscreenChanged += (_, _) => changes++; + + await _engine.ClickAsync(10, 10); + await _engine.PrepareFrameAsync(); + var video = _engine.Document!.GetElementById("v")!; + Assert.That(_engine.IsFullscreen, Is.True); + Assert.That(video.Matches(":fullscreen"), Is.True); + Assert.That(video.GetBoundingClientRect().Width, Is.EqualTo(800)); + + await PressKeyAsync("Escape"); + await _engine.PrepareFrameAsync(); + Assert.That(_engine.IsFullscreen, Is.False); + Assert.That(video.Matches(":fullscreen"), Is.False); + Assert.That(changes, Is.EqualTo(2)); + // without a user activation the page can't, and the page is told of each change + Assert.That(Convert.ToString(await _engine.EvaluateScriptAsync("log.join(',')")), Is.EqualTo("denied,v,none")); + } + [Test] public async Task ClickingARowOfADropdownSelectsIt() { @@ -1166,7 +1433,7 @@ public async Task ControlsDoNotTakeTheTextColorOfThePage() { var select = await LoadDropdownAsync(""); - Assert.That(select.ComputeCurrentStyle().GetPropertyValue("color"), Is.EqualTo("rgba(0, 0, 0, 1)")); + Assert.That(select.ComputeCurrentStyle().GetPropertyValue("color"), Is.EqualTo("rgb(0, 0, 0)")); } [Test] @@ -1466,12 +1733,38 @@ public async Task PagesWithLoadedImagesCanBePainted() await _engine.NavigateAsync(server.Address); var img = (ILoadableElement)_engine.Document!.QuerySelector("img")!; + // the frame showing it loads it + await _engine.PrepareFrameAsync(); await Eventually(() => img.CurrentDownload?.Task.IsCompleted == true); var image = await _engine.PaintAsync(); Assert.That(image, Is.Not.Null); } + [Test] + public async Task NavigatedImagesAreShownInADocumentOfTheirOwn() + { + var png = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="); + using var server = new TestServer(new() + { + ["/"] = ("text/html", ""u8.ToArray()), + ["/red.png"] = ("image/png", png), + }); + + await _engine.NavigateAsync(server.Address + "red.png"); + var document = _engine.Document!; + + Assert.That(document.ContentType, Is.EqualTo("image/png")); + Assert.That(document.QuerySelector("body > img")?.GetAttribute("src"), Is.EqualTo(document.Url)); + await Eventually(() => document.ReadyState == DocumentReadyState.Complete); + + await _engine.NavigateAsync(server.Address); + var frame = (IHtmlInlineFrameElement)_engine.Document!.QuerySelector("iframe")!; + await Eventually(() => frame.ContentDocument?.QuerySelector("img") is not null); + + Assert.That(frame.ContentDocument!.Body!.ChildElementCount, Is.EqualTo(1)); + } + [Test] public async Task FloatedInlineElementsCanBePaintedAndHitTested() { @@ -1497,6 +1790,21 @@ public async Task RequestsReportUserAgent() Assert.That(server.LastUserAgent, Is.EqualTo(_engine.Document!.DefaultView!.Navigator.UserAgent)); } + [Test] + public async Task UserAgentNamesTheEngineInsteadOfAnotherBrowser() + { + using var server = new TestServer(new() + { + ["/"] = ("text/html", "

Hi

"u8.ToArray()), + }); + + await _engine.NavigateAsync(server.Address); + + Assert.That(server.LastUserAgent, Is.EqualTo(BrowserOptions.DefaultUserAgent)); + Assert.That(server.LastUserAgent, Does.StartWith("Mozilla/5.0 (").And.Contain(") AngleSharp.Browser/")); + Assert.That(server.LastUserAgent, Does.Not.Contain("Chrome").And.Not.Contain("OPR")); + } + [Test] public async Task CompressedResponsesAreDecompressedEvenIfNotAskedFor() { @@ -1888,8 +2196,8 @@ public async Task ColorSchemeIsReportedToMediaQueries() _engine.ColorScheme = "light"; var lightColor = await _engine.InvokeAsync(document => document!.DefaultView!.GetComputedStyle(document.GetElementById("text")!).GetColor()); - Assert.That(color, Is.EqualTo("rgba(0, 0, 255, 1)")); - Assert.That(lightColor, Is.EqualTo("rgba(255, 0, 0, 1)")); + Assert.That(color, Is.EqualTo("rgb(0, 0, 255)")); + Assert.That(lightColor, Is.EqualTo("rgb(255, 0, 0)")); } [Test] @@ -2208,7 +2516,9 @@ await _engine.LoadHtmlAsync(""" for (var i = 0; i < 8; i++) { await Task.Delay(40); - pixels.Add(PixelOf((await _engine.PrepareFrameAsync())!, 58, 42)); + // right of the box (60px wide, its center at 30, 70), where its corners pass a + // quarter of the time: frames over 115 degrees show it and the page behind it + pixels.Add(PixelOf((await _engine.PrepareFrameAsync())!, 66, 70)); } var kinds = _engine.Diagnostics.Frames.Skip(start).Select(frame => frame.Kind).ToList(); @@ -2231,6 +2541,8 @@ public async Task AnimatedGifAsksForFramesShowingItsNextImages() 0x3B, ]; await _engine.LoadHtmlAsync($""); + // the frame showing it loads it + await _engine.PrepareFrameAsync(); await Eventually(() => _engine.Document?.QuerySelector("img") is IHtmlImageElement { IsCompleted: true }); await _engine.PrepareFrameAsync(); await _engine.PrepareFrameAsync(); diff --git a/src/AngleSharp.Browser.Tests/WebAssemblyTests.cs b/src/AngleSharp.Browser.Tests/WebAssemblyTests.cs new file mode 100644 index 0000000..bf8c292 --- /dev/null +++ b/src/AngleSharp.Browser.Tests/WebAssemblyTests.cs @@ -0,0 +1,238 @@ +namespace AngleSharp.Browser.Tests; + +using System; +using System.Linq; +using System.Threading.Tasks; +using NUnit.Framework; + +/// +/// The WebAssembly JavaScript API as pages use it: promises, imports of functions of scripts, +/// exports called as functions, and memory shared with scripts. +/// +[TestFixture] +public class WebAssemblyTests +{ + private const string Address = "https://example.com/"; + + private const string Program = """ + (module + (import "env" "log" (func $log (param i32) (result i32))) + (import "env" "offset" (global $offset i32)) + (memory (export "memory") 1 10) + (global $counter (export "counter") (mut i32) (i32.const 7)) + (table (export "table") 2 funcref) + (elem (i32.const 0) $double) + (func $double (export "double") (param i32) (result i32) local.get 0 i32.const 2 i32.mul) + (func (export "callLog") (param i32) (result i32) local.get 0 global.get $offset i32.add call $log) + (func (export "store") (param i32 i32) local.get 0 local.get 1 i32.store8) + (func (export "load") (param i32) (result i32) local.get 0 i32.load8_u) + (func (export "grow") (result i32) i32.const 1 memory.grow) + (func (export "add64") (param i64 i64) (result i64) local.get 0 local.get 1 i64.add) + (func (export "half") (param f64) (result f64) local.get 0 f64.const 2 f64.div) + (func (export "pair") (result i32 i32) i32.const 1 i32.const 2) + (func (export "fail") unreachable)) + """; + + private BrowserEngine _engine = null!; + + [SetUp] + public void Setup() + { + _engine = new BrowserEngine(new BrowserOptions { ProfileDirectory = null, ViewportWidth = 800, ViewportHeight = 600 }); + } + + [TearDown] + public void TearDown() + { + _engine.Dispose(); + } + + private static string ToBytes(string wat) => string.Join(",", Wasmtime.Module.ConvertText(wat).Select(b => b.ToString())); + + // Runs the body of an async function with the bytes of the program in "bytes"; the result + // (or what was thrown) ends up in window.result. + private async Task Run(string body, string wat = Program) + { + await _engine.LoadHtmlAsync("Wasm", Address); + await _engine.EvaluateScriptAsync($$""" + var bytes = new Uint8Array([{{ToBytes(wat)}}]); + var logged = []; + var imports = { env: { log: function (x) { logged.push(x); return x + 1; }, offset: 100 } }; + (async function () { {{body}} })().then(function (r) { window.result = 'ok:' + r; }, function (e) { window.result = 'error:' + (e && e.name) + ':' + (e && e.message); }); + """); + + for (var i = 0; i < 100; i++) + { + if (await _engine.EvaluateScriptAsync("window.result || ''") is string { Length: > 0 } result) + { + return result; + } + + await Task.Delay(20); + } + + return null; + } + + [Test] + public async Task WebAssemblyIsANamespaceWithItsInterfaces() + { + var result = await Run(""" + return [typeof WebAssembly, Object.prototype.toString.call(WebAssembly), typeof WebAssembly.Module, typeof WebAssembly.Instance, + typeof WebAssembly.Memory, typeof WebAssembly.Table, typeof WebAssembly.Global, typeof WebAssembly.CompileError, + typeof WebAssembly.RuntimeError, typeof window.Module, typeof window.Instance, 'validate' in window, WebAssembly.validate(bytes)].join(); + """); + + Assert.That(result, Is.EqualTo("ok:object,[object WebAssembly],function,function,function,function,function,function,function,undefined,undefined,false,true")); + } + + [Test] + public async Task InstantiateGivesAModuleAndAnInstanceWithFunctions() + { + var result = await Run(""" + var p = WebAssembly.instantiate(bytes, imports); + var source = await p; + var e = source.instance.exports; + return [p instanceof Promise, source.module instanceof WebAssembly.Module, source.instance instanceof WebAssembly.Instance, + typeof e.double, e.double(21), e.callLog(5), logged.join('+'), e.half(3), e.add64(2n ** 62n, 2n ** 62n), e.pair().join('|'), + Object.keys(e).join('|')].join(); + """); + + Assert.That(result, Is.EqualTo("ok:true,true,true,function,42,106,105,1.5,-9223372036854775808,1|2,memory|counter|table|double|callLog|store|load|grow|add64|half|pair|fail")); + } + + [Test] + public async Task MemoryBufferIsTheMemory() + { + var result = await Run(""" + var e = (await WebAssembly.instantiate(bytes, imports)).instance.exports; + var buffer = e.memory.buffer; + var view = new Uint8Array(buffer); + view[10] = 42; + e.store(11, 7); + var before = [buffer.byteLength, e.memory.buffer === buffer, e.load(10), view[11]]; + var old = e.grow(); + var grown = e.memory.buffer; + return before.concat([old, grown !== buffer, grown.byteLength, new Uint8Array(grown)[10], e.memory.grow(1), e.memory.buffer.byteLength]).join(); + """); + + Assert.That(result, Is.EqualTo("ok:65536,true,42,7,1,true,131072,42,2,196608")); + } + + [Test] + public async Task ModuleAndInstanceCanBeCreatedDirectly() + { + var result = await Run(""" + var module = new WebAssembly.Module(bytes); + var instance = new WebAssembly.Instance(module, imports); + var other = await WebAssembly.instantiate(module, imports); + return [WebAssembly.Module.exports(module).length, WebAssembly.Module.imports(module).map(function (i) { return i.module + '.' + i.name + ':' + i.kind; }).join('|'), + instance.exports.double(4), other instanceof WebAssembly.Instance].join(); + """); + + Assert.That(result, Is.EqualTo("ok:12,env.log:function|env.offset:global,8,true")); + } + + [Test] + public async Task ObjectsOfScriptsAreImported() + { + const string wat = """ + (module + (import "js" "mem" (memory 1)) + (import "js" "g" (global $g (mut i32))) + (import "js" "tbl" (table 1 funcref)) + (type $t (func (param i32) (result i32))) + (func (export "read") (result i32) i32.const 0 i32.load8_u) + (func (export "bump") global.get $g i32.const 1 i32.add global.set $g) + (func (export "callAt") (param i32 i32) (result i32) local.get 1 local.get 0 call_indirect (type $t))) + """; + var result = await Run($$""" + var mem = new WebAssembly.Memory({ initial: 1, maximum: 2 }); + var g = new WebAssembly.Global({ value: 'i32', mutable: true }, 41); + var tbl = new WebAssembly.Table({ element: 'anyfunc', initial: 1 }); + var other = (await WebAssembly.instantiate(new Uint8Array([{{ToBytes(Program)}}]), imports)).instance.exports; + tbl.set(0, other.double); + new Uint8Array(mem.buffer)[0] = 9; + var e = (await WebAssembly.instantiate(bytes, { js: { mem: mem, g: g, tbl: tbl } })).instance.exports; + e.bump(); + return [e.read(), g.value, e.callAt(0, 5), tbl.get(0) === other.double, tbl.length].join(); + """, wat); + + Assert.That(result, Is.EqualTo("ok:9,42,10,true,1")); + } + + [Test] + public async Task TrapIsARuntimeError() + { + var result = await Run(""" + var e = (await WebAssembly.instantiate(bytes, imports)).instance.exports; + try { e.fail(); } catch (x) { return [x instanceof WebAssembly.RuntimeError, x instanceof Error, x.name].join(); } + """); + + Assert.That(result, Is.EqualTo("ok:true,true,RuntimeError")); + } + + [Test] + public async Task ErrorOfAnImportReachesTheCaller() + { + var result = await Run(""" + var thrown = { reason: 'exit' }; + var e = (await WebAssembly.instantiate(bytes, { env: { log: function () { throw thrown; }, offset: 0 } })).instance.exports; + try { e.callLog(1); } catch (x) { return x === thrown; } + """); + + Assert.That(result, Is.EqualTo("ok:true")); + } + + [Test] + public async Task InvalidBytesRejectWithACompileError() + { + var result = await Run(""" + try { await WebAssembly.compile(new Uint8Array([0, 97, 115, 109, 9])); } catch (x) { return [x instanceof WebAssembly.CompileError, x instanceof Error, WebAssembly.validate(new Uint8Array([1, 2]))].join(); } + """); + + Assert.That(result, Is.EqualTo("ok:true,true,false")); + } + + [Test] + public async Task MissingImportRejectsWithALinkError() + { + var result = await Run(""" + try { await WebAssembly.instantiate(bytes, { env: { log: 5, offset: 0 } }); } catch (x) { return [x instanceof WebAssembly.LinkError, x.name].join(); } + """); + + Assert.That(result, Is.EqualTo("ok:true,LinkError")); + } + + [Test] + public async Task InstantiateStreamingTakesAFetch() + { + var wasm = Wasmtime.Module.ConvertText(Program); + using var server = new TestServer(new() + { + ["/"] = ("text/html", "Wasm"u8.ToArray()), + ["/program.wasm"] = ("application/wasm", wasm), + ["/wrong.wasm"] = ("text/plain", wasm), + }); + + await _engine.NavigateAsync(server.Address); + await _engine.EvaluateScriptAsync(""" + var imports = { env: { log: function (x) { return x; }, offset: 0 } }; + (async function () { + var source = await WebAssembly.instantiateStreaming(fetch('/program.wasm'), imports); + var module = await WebAssembly.compileStreaming(fetch('/program.wasm')); + var wrong = await WebAssembly.instantiateStreaming(fetch('/wrong.wasm'), imports).then(function () { return 'loaded'; }, function () { return 'rejected'; }); + return [source.instance.exports.double(8), module instanceof WebAssembly.Module, wrong].join(); + })().then(function (r) { window.result = 'ok:' + r; }, function (e) { window.result = 'error:' + e; }); + """); + string? result = null; + + for (var i = 0; i < 100 && result is null; i++) + { + await Task.Delay(20); + result = await _engine.EvaluateScriptAsync("window.result || ''") is string { Length: > 0 } text ? text : null; + } + + Assert.That(result, Is.EqualTo("ok:16,true,rejected")); + } +} diff --git a/src/AngleSharp.Browser/AngleSharp.Browser.csproj b/src/AngleSharp.Browser/AngleSharp.Browser.csproj index 103eae2..b4decaf 100644 --- a/src/AngleSharp.Browser/AngleSharp.Browser.csproj +++ b/src/AngleSharp.Browser/AngleSharp.Browser.csproj @@ -12,13 +12,13 @@ - - - - - - - + + + + + + + diff --git a/src/AngleSharp.Browser/BrowserDocumentFactory.cs b/src/AngleSharp.Browser/BrowserDocumentFactory.cs new file mode 100644 index 0000000..82bc48d --- /dev/null +++ b/src/AngleSharp.Browser/BrowserDocumentFactory.cs @@ -0,0 +1,59 @@ +namespace AngleSharp.Browser; + +using AngleSharp.Dom; +using AngleSharp.Io; +using AngleSharp.Text; +using System.Net; +using System.Threading; +using System.Threading.Tasks; + +/// +/// The document factory of the engine: creates documents like AngleSharp does, but shows +/// responses that aren't documents like a browser does (e.g. a navigated image). +/// +sealed class BrowserDocumentFactory : DefaultDocumentFactory +{ + public override Task CreateAsync(IBrowsingContext context, CreateDocumentOptions options, CancellationToken cancellationToken) + { + var contentType = options.ContentType; + + // an image (other than SVG, which has a creator of its own) is shown in a document of + // its own, its data isn't markup (e.g. a PNG in an iframe) + if (contentType.GeneralType.Is("image") && !contentType.Content.Is(MimeTypeNames.Svg)) + { + return LoadImageAsync(context, options, cancellationToken); + } + + return base.CreateAsync(context, options, cancellationToken); + } + + /// + /// Shows the response, an image, in a document with just that image. The document keeps the + /// address, headers and content type (e.g. image/png) of the response, but its content + /// is the markup showing the image, which completes (with a load event) once the image is there. + /// + private static async Task LoadImageAsync(IBrowsingContext context, CreateDocumentOptions options, CancellationToken cancellationToken) + { + var original = options.Response; + var address = original.Address.Href; + var content = $""; + var response = VirtualResponse.Create(res => + { + res.Address(original.Address).Status(original.StatusCode).Content(content); + + foreach (var header in original.Headers) + { + res.Header(header.Key, header.Value); + } + }); + var imageOptions = new CreateDocumentOptions(response, null, options.ImportAncestor) + { + IsScriptingDisabled = options.IsScriptingDisabled, + IsNavigationDisabled = options.IsNavigationDisabled, + }; + var document = await LoadHtmlAsync(context, imageOptions, cancellationToken).ConfigureAwait(false); + // the image itself is loaded by the img element, the data of the navigation isn't needed + original.Dispose(); + return document; + } +} diff --git a/src/AngleSharp.Browser/BrowserEngine.Frames.cs b/src/AngleSharp.Browser/BrowserEngine.Frames.cs index 96bf3cc..987b2a5 100644 --- a/src/AngleSharp.Browser/BrowserEngine.Frames.cs +++ b/src/AngleSharp.Browser/BrowserEngine.Frames.cs @@ -120,6 +120,7 @@ public bool HasPaintedDocument var document = _document!; SyncMediaChanges(document); + SyncPaintWorklets(); var version = Volatile.Read(ref _layoutVersion); var time = DateTimeOffset.Now; var start = Stopwatch.GetTimestamp(); diff --git a/src/AngleSharp.Browser/BrowserEngine.Fullscreen.cs b/src/AngleSharp.Browser/BrowserEngine.Fullscreen.cs new file mode 100644 index 0000000..b57d1fd --- /dev/null +++ b/src/AngleSharp.Browser/BrowserEngine.Fullscreen.cs @@ -0,0 +1,39 @@ +namespace AngleSharp.Browser; + +using System; + +/// +/// Elements the page shows fullscreen (Fullscreen API, see ): they cover +/// the viewport, the host is told to show the page fullscreen, and Esc ends it. +/// +partial class BrowserEngine +{ + private readonly Fullscreen _fullscreen; + private volatile bool _isFullscreen; + + /// + /// The page started or ended showing an element fullscreen (or another one), which is laid + /// out anew. Requires exclusive access. + /// + private void OnFullscreenChanged(bool isFullscreen) + { + if (_isDisposed) + { + return; + } + + var wasFullscreen = _isFullscreen; + _isFullscreen = isFullscreen; + Invalidate(); + + if (wasFullscreen != isFullscreen) + { + FullscreenChanged?.Invoke(this, EventArgs.Empty); + } + } + + /// + /// Ends showing an element fullscreen on Esc. Requires exclusive access. + /// + private bool ExitFullscreenOnEscape() => _isFullscreen && _fullscreen.ExitAll(_document); +} diff --git a/src/AngleSharp.Browser/BrowserEngine.Input.cs b/src/AngleSharp.Browser/BrowserEngine.Input.cs index b0f3916..16ec216 100644 --- a/src/AngleSharp.Browser/BrowserEngine.Input.cs +++ b/src/AngleSharp.Browser/BrowserEngine.Input.cs @@ -183,6 +183,7 @@ public Task PointerDownAsync(double x, double y, int clickCount, InputModifiers var hit = HitTest(x, y); var target = ResolveListBoxTarget(hit, x, y); _pressed = target; + LightDismissPopovers(hit ?? _document?.DocumentElement); if (target is not null) { @@ -206,6 +207,9 @@ public Task PointerDownAsync(double x, double y, int clickCount, InputModifiers else if (PressMediaControls(target, x, y)) { } + else if (PressRange(target, x)) + { + } else if (!IsDropdown(target)) { BeginTextSelection(hit, x, y, Math.Max(1, clickCount), modifiers); @@ -254,6 +258,7 @@ public async Task PointerUpAsync(double x, double y, InputModifiers modifiers = EndTextSelection(); _seekingMedia = null; + ReleaseRange(); var target = ResolveListBoxTarget(HitTest(x, y), x, y); var pressed = _pressed; _pressed = null; @@ -501,6 +506,7 @@ private void UpdateHover(double x, double y, bool isMove = true) if (isMove) { SeekMedia(x); + SlideRange(x); } if (element is not null && isMove) @@ -718,6 +724,11 @@ private static bool IsOptionOf(IHtmlSelectElement select, IElement? option) => ///
private Task? Activate(IElement? element, double x, double y, InputModifiers modifiers) { + if (element is not null && ActivatePopoverTarget(element)) + { + return null; + } + switch (element) { case IHtmlInputElement input when FormControls.IsToggle(input): @@ -889,6 +900,26 @@ private void ScrollToFragment(IDocument document, string fragment) return null; } + if (HandleRangeKey(focused, key)) + { + return null; + } + + if (key == "Escape" && ExitFullscreenOnEscape()) + { + return null; + } + + if (key == "Escape" && CloseLastPopover()) + { + return null; + } + + if (isTextEntry && HandleTextEntryKey(focused!, key, modifiers)) + { + return null; + } + switch (key) { case "a" or "A" when !isTextEntry && (modifiers.HasFlag(InputModifiers.Control) || modifiers.HasFlag(InputModifiers.Meta)): @@ -905,16 +936,6 @@ private void ScrollToFragment(IDocument document, string fragment) case "Enter" when focused is IHtmlAnchorElement or IHtmlButtonElement: case " " when focused is IHtmlButtonElement || FormControls.IsToggle(focused): return Click(focused!, 0, 0, modifiers); - case "Backspace" when isTextEntry: - var value = FormControls.GetValue(focused!); - - if (value.Length > 0) - { - FormControls.SetValue(focused!, value[..^1]); - Fire(focused!, new Event("input", true, false)); - } - - return null; case "ArrowUp" or "ArrowDown" when focused is IHtmlSelectElement listBox && listBox.IsListBox(): if (StepListBox(listBox, key == "ArrowUp" ? -1 : 1, modifiers)) { @@ -957,22 +978,6 @@ private void ScrollToFragment(IDocument document, string fragment) return document?.ActiveElement ?? document?.Body ?? document?.DocumentElement; } - private void InsertText(IElement element, string text) - { - if (element is IHtmlInputElement input) - { - text = text.Replace("\r", string.Empty).Replace("\n", string.Empty); - var room = input.MaxLength >= 0 ? input.MaxLength - input.Value.Length : int.MaxValue; - text = text.Length > room ? text[..Math.Max(0, room)] : text; - } - - if (text.Length > 0) - { - FormControls.SetValue(element, FormControls.GetValue(element) + text); - Fire(element, new Event("input", true, false)); - } - } - private void UpdateFocus(IElement target) { var focusable = target.ParentElement is null ? null : (IElement?)target; @@ -990,6 +995,7 @@ private void UpdateFocus(IElement target) { (current as IHtmlElement)?.DoBlur(); element.DoFocus(); + PlaceCursorOnFocus(element, selectAll: false); } else { @@ -1019,6 +1025,8 @@ private void MoveFocus(int direction) : (current + direction + candidates.Count) % candidates.Count; var previous = document.ActiveElement; (candidates[next] as IHtmlElement)?.DoFocus(); + // like in browsers, tabbing into a text input selects its text + PlaceCursorOnFocus(candidates[next], selectAll: candidates[next] is IHtmlInputElement); NotifyStateChanged(previous); NotifyStateChanged(candidates[next]); } @@ -1139,8 +1147,9 @@ private bool Fire(IEventTarget target, Event ev) { try { - // the return value of Dispatch is inverted in some AngleSharp versions - target.Dispatch(ev); + // what the user does is trusted, and the engine acts on it itself (Activate); + // a script's dispatchEvent (Dispatch) would have AngleSharp act on clicks as well + EventTargetExtensions.Fire(target, ev); return !ev.IsDefaultPrevented; } catch (Exception ex) @@ -1264,6 +1273,9 @@ private static MouseEvent CreateMouseEvent(IWindow? view, string type, double x, { case IHtmlAnchorElement or IHtmlAreaElement when element.HasAttribute("href"): case IHtmlButtonElement or IHtmlInputElement or IHtmlLabelElement or IHtmlElement { LocalName: "summary" }: + // a control has no activation of its own, but its label must not get the click + // either: that would click the control (in the label) again (HTML 4.10.4) + case IHtmlSelectElement or IHtmlTextAreaElement: return element; } } diff --git a/src/AngleSharp.Browser/BrowserEngine.Media.cs b/src/AngleSharp.Browser/BrowserEngine.Media.cs index 6f2b68e..18b47ed 100644 --- a/src/AngleSharp.Browser/BrowserEngine.Media.cs +++ b/src/AngleSharp.Browser/BrowserEngine.Media.cs @@ -100,6 +100,31 @@ private void SyncMediaChanges(IDocument document) } } + // a paint worklet registered painters, which the images of the page may use (any thread) + private volatile bool _hasPaintWorkletChanged; + + private void OnPaintWorkletChanged() + { + if (!_isDisposed) + { + _hasPaintWorkletChanged = true; + Invalidate(isMutation: true); + } + } + + /// + /// Lays out the next frame anew if a paint worklet registered painters since the last one. + /// Requires exclusive access. + /// + private void SyncPaintWorklets() + { + if (_hasPaintWorkletChanged) + { + _hasPaintWorkletChanged = false; + _needsFullLayout = true; + } + } + private static bool ShowsMediaControls(IDocument document) => document.QuerySelector("audio[controls]") is not null || document.QuerySelectorAll("iframe").OfType().Any(frame => frame.ContentDocument is { } content && ShowsMediaControls(content)); diff --git a/src/AngleSharp.Browser/BrowserEngine.Popovers.cs b/src/AngleSharp.Browser/BrowserEngine.Popovers.cs new file mode 100644 index 0000000..48e9d94 --- /dev/null +++ b/src/AngleSharp.Browser/BrowserEngine.Popovers.cs @@ -0,0 +1,129 @@ +namespace AngleSharp.Browser; + +using System; +using System.Linq; +using AngleSharp.Dom; +using AngleSharp.Html.Dom; + +/// +/// Popovers the user acts on: a button with a `popovertarget` shows, hides or toggles its +/// popover when activated, and a press outside of the open `auto` (and `hint`) popovers or Esc +/// closes them (light dismiss, HTML 6.12.4). +/// +partial class BrowserEngine +{ + /// + /// Runs the popover target activation behavior of a button, if it has a target. Requires exclusive access. + /// + private static bool ActivatePopoverTarget(IElement element) + { + var (target, action) = element switch + { + // a button submitting or resetting its form does that instead + IHtmlButtonElement button when button.Form is null || IsType(button.Type, "button") => + (button.GetPopoverTargetElement(), button.GetPopoverTargetAction()), + IHtmlInputElement input when IsType(input.Type, "button") || (input.Form is null && (IsType(input.Type, "submit") || IsType(input.Type, "reset") || IsType(input.Type, "image"))) => + (input.GetPopoverTargetElement(), input.GetPopoverTargetAction()), + _ => (null, null), + }; + + if (target is null) + { + return false; + } + + var isOpen = target.IsPopoverOpen(); + + try + { + if (isOpen && action is "hide" or "toggle") + { + target.HidePopover(); + } + else if (!isOpen && action is "show" or "toggle") + { + target.ShowPopover(); + } + } + catch (DomException) + { + // e.g. the target is no popover (anymore), which the page doesn't get to know of + } + + return true; + } + + /// + /// Closes the open popovers that light dismiss for a press on the element. Requires exclusive access. + /// + private static void LightDismissPopovers(IElement? pressed) + { + if (pressed?.Owner is not { } document) + { + return; + } + + foreach (var popover in GetLightDismissedPopovers(document)) + { + // a press in it or on what toggles it keeps it (the invoker closes it on its own) + if (popover.Contains(pressed) || IsInvokerOf(pressed, popover)) + { + continue; + } + + HidePopover(popover); + } + } + + /// + /// Closes the topmost light dismissed popover for Esc, if one is open. Requires exclusive access. + /// + private bool CloseLastPopover() + { + var document = FocusedDocument ?? _document; + + if (document is null || GetLightDismissedPopovers(document).LastOrDefault() is not { } popover) + { + return false; + } + + HidePopover(popover); + return true; + } + + private static IHtmlElement[] GetLightDismissedPopovers(IDocument document) => + document.QuerySelectorAll("[popover]").OfType() + .Where(element => element.IsPopoverOpen() && element.GetPopover() is "auto" or "hint") + .ToArray(); + + private static bool IsInvokerOf(IElement element, IHtmlElement popover) + { + for (var current = element; current is not null; current = current.ParentElement) + { + var target = current switch + { + IHtmlButtonElement button => button.GetPopoverTargetElement(), + IHtmlInputElement input => input.GetPopoverTargetElement(), + _ => null, + }; + + if (target == popover) + { + return true; + } + } + + return false; + } + + private static void HidePopover(IHtmlElement popover) + { + try + { + popover.HidePopover(); + } + catch (DomException) + { + } + } +} diff --git a/src/AngleSharp.Browser/BrowserEngine.Range.cs b/src/AngleSharp.Browser/BrowserEngine.Range.cs new file mode 100644 index 0000000..3d736ec --- /dev/null +++ b/src/AngleSharp.Browser/BrowserEngine.Range.cs @@ -0,0 +1,166 @@ +namespace AngleSharp.Browser; + +using System; +using System.Globalization; +using AngleSharp.Dom; +using AngleSharp.Dom.Events; +using AngleSharp.Html.Dom; +using AngleSharp.Renderer; + +/// +/// Sliders (`input[type=range]`): a press sets the value at the pointer and the slider follows +/// the pointer while the button is held, firing `input` for each new value and `change` once +/// released; the arrow keys, Page Up/Down, Home and End step it while it has the focus. +/// +partial class BrowserEngine +{ + // the slider dragged while the button is held, with the value it had when pressed + private IHtmlInputElement? _slidingRange; + private string? _slidingRangeStart; + + private static bool IsRange(IElement? element) => + element is IHtmlInputElement { IsDisabled: false } input && input.Type.Equals("range", StringComparison.OrdinalIgnoreCase); + + /// + /// Acts on a press on a slider, if it was one. Requires exclusive access. + /// + private bool PressRange(IElement? target, double x) + { + if (!IsRange(target)) + { + return false; + } + + var input = (IHtmlInputElement)target!; + _slidingRange = input; + _slidingRangeStart = input.Value; + SlideRange(x); + return true; + } + + /// + /// Moves the dragged slider to the position of the pointer. Requires exclusive access. + /// + private void SlideRange(double x) + { + if (_slidingRange is not { Owner: not null } input) + { + return; + } + + var box = input.GetBoundingClientRect(); + var style = input.ComputeCurrentStyle(); + var left = box.Left + ParsePixels(style.GetPropertyValue("border-left-width")) + ParsePixels(style.GetPropertyValue("padding-left")); + var width = box.Width - (left - box.Left) - ParsePixels(style.GetPropertyValue("border-right-width")) - ParsePixels(style.GetPropertyValue("padding-right")); + + if (width <= 0) + { + return; + } + + var (min, max, _) = GetRangeBounds(input); + var fraction = Math.Clamp((ToClient(input, x, 0).X - left) / width, 0d, 1d); + SetRangeValue(input, min + (fraction * (max - min))); + } + + /// + /// Ends dragging a slider: its change is committed. Requires exclusive access. + /// + private void ReleaseRange() + { + if (_slidingRange is { } input) + { + _slidingRange = null; + + if (input.Value != _slidingRangeStart) + { + Fire(input, new Event("change", true, false)); + } + } + } + + /// + /// Steps the focused slider for a key, if it is one. Requires exclusive access. + /// + private bool HandleRangeKey(IElement? focused, string key) + { + if (!IsRange(focused)) + { + return false; + } + + var input = (IHtmlInputElement)focused!; + var (min, max, step) = GetRangeBounds(input); + var value = ParseRangeNumber(input.Value, (min + max) / 2); + var large = Math.Max(step, (max - min) / 10); + var target = key switch + { + "ArrowRight" or "ArrowUp" => value + step, + "ArrowLeft" or "ArrowDown" => value - step, + "PageUp" => value + large, + "PageDown" => value - large, + "Home" => min, + "End" => max, + _ => double.NaN, + }; + + if (double.IsNaN(target)) + { + return false; + } + + if (SetRangeValue(input, target)) + { + Fire(input, new Event("change", true, false)); + } + + return true; + } + + /// + /// Sets the value of a slider, snapped to its step, firing `input` if it changed. + /// + private bool SetRangeValue(IHtmlInputElement input, double value) + { + var (min, max, step) = GetRangeBounds(input); + + if (step > 0) + { + value = min + (Math.Round((value - min) / step) * step); + + // a step not fitting the range ends below the maximum + if (value > max) + { + value -= step; + } + } + + value = Math.Clamp(value, min, max); + var text = Math.Round(value, 10).ToString("R", CultureInfo.InvariantCulture); + + if (text == input.Value) + { + return false; + } + + FormControls.SetValue(input, text); + Fire(input, new Event("input", true, false)); + return true; + } + + /// + /// The minimum, maximum and step of a slider, which default to 0, 100 and 1 (HTML 4.10.5.1.13); + /// a step of 0 is `any`. + /// + private static (double Min, double Max, double Step) GetRangeBounds(IHtmlInputElement input) + { + var min = ParseRangeNumber(input.GetAttribute("min"), 0); + var max = ParseRangeNumber(input.GetAttribute("max"), 100); + var stepText = input.GetAttribute("step"); + var step = string.Equals(stepText?.Trim(), "any", StringComparison.OrdinalIgnoreCase) ? 0 : ParseRangeNumber(stepText, 1) is > 0 and var given ? given : 1; + return (min, Math.Max(min, max), step); + } + + private static double ParseRangeNumber(string? text, double fallback) => + double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var value) && double.IsFinite(value) ? value : fallback; +} diff --git a/src/AngleSharp.Browser/BrowserEngine.TextEntry.cs b/src/AngleSharp.Browser/BrowserEngine.TextEntry.cs new file mode 100644 index 0000000..01ae9c8 --- /dev/null +++ b/src/AngleSharp.Browser/BrowserEngine.TextEntry.cs @@ -0,0 +1,263 @@ +namespace AngleSharp.Browser; + +using System; +using AngleSharp.Dom; +using AngleSharp.Dom.Events; +using AngleSharp.Html.Dom; + +/// +/// Editing the text of the focused text field (`input` or `textarea`) at its cursor, which is +/// the field's `selectionStart`/`selectionEnd` (AngleSharp.Renderer paints the caret and the +/// selected text there): the arrow keys, Home and End move the cursor (by words with Ctrl or +/// Alt, over the whole text with Ctrl+Home/End, extending the selection with Shift), text +/// replaces the selection, Backspace and Delete remove it or the character before or after it. +/// +partial class BrowserEngine +{ + // the field the engine last edited with its value and selection then: a value changed by a + // script while the selection stayed moves the cursor to its end (AngleSharp before 1.11 + // keeps the cursor where it was) + private IElement? _editedField; + private string? _editedValue; + private (int Start, int End) _editedSelection; + + /// + /// Acts on a key pressed in the focused text field, if the key edits text or moves the + /// cursor. Requires exclusive access. + /// + private bool HandleTextEntryKey(IElement field, string key, InputModifiers modifiers) + { + var value = FormControls.GetValue(field); + var (start, end, backward) = GetFieldSelection(field, value); + var anchor = backward ? end : start; + var focus = backward ? start : end; + var extend = modifiers.HasFlag(InputModifiers.Shift); + var byWord = modifiers.HasFlag(InputModifiers.Control) || modifiers.HasFlag(InputModifiers.Alt); + var command = modifiers.HasFlag(InputModifiers.Meta); + var isMultiline = field is IHtmlTextAreaElement; + int target; + + switch (key) + { + case "a" or "A" when modifiers.HasFlag(InputModifiers.Control) || command: + SetFieldSelection(field, value, 0, value.Length); + return true; + case "ArrowLeft" when command: + case "Home": + target = (byWord && key == "Home") || !isMultiline ? 0 : GetLineStart(value, focus); + break; + case "ArrowRight" when command: + case "End": + target = (byWord && key == "End") || !isMultiline ? value.Length : GetLineEnd(value, focus); + break; + case "ArrowUp" when command: + target = 0; + break; + case "ArrowDown" when command: + target = value.Length; + break; + case "ArrowLeft": + // without Shift a selection collapses to its start + target = start != end && !extend ? start : byWord ? GetPreviousWordStart(value, focus) : GetPreviousOffset(value, focus); + break; + case "ArrowRight": + target = start != end && !extend ? end : byWord ? GetNextWordEnd(value, focus) : GetNextOffset(value, focus); + break; + case "ArrowUp" when isMultiline: + target = GetOffsetOnAdjacentLine(value, focus, -1); + break; + case "ArrowDown" when isMultiline: + target = GetOffsetOnAdjacentLine(value, focus, 1); + break; + case "Backspace": + if (start == end) + { + start = byWord ? GetPreviousWordStart(value, start) : GetPreviousOffset(value, start); + } + + ReplaceFieldText(field, value, start, end, string.Empty); + return true; + case "Delete": + if (start == end) + { + end = byWord ? GetNextWordEnd(value, end) : GetNextOffset(value, end); + } + + ReplaceFieldText(field, value, start, end, string.Empty); + return true; + default: + return false; + } + + SetFieldSelection(field, value, extend ? anchor : target, target); + return true; + } + + private void InsertText(IElement element, string text) + { + var value = FormControls.GetValue(element); + var (start, end, _) = GetFieldSelection(element, value); + + if (element is IHtmlInputElement input) + { + text = text.Replace("\r", string.Empty).Replace("\n", string.Empty); + var room = input.MaxLength >= 0 ? input.MaxLength - (value.Length - (end - start)) : int.MaxValue; + text = text.Length > room ? text[..Math.Max(0, room)] : text; + } + + if (text.Length > 0) + { + ReplaceFieldText(element, value, start, end, text); + } + } + + /// + /// Puts the cursor of a text field the user focused at the end of its text (or selects + /// all of it), as the press isn't placed within the text. + /// + private void PlaceCursorOnFocus(IElement? element, bool selectAll) + { + if (FormControls.IsTextEntry(element)) + { + var value = FormControls.GetValue(element!); + SetFieldSelection(element!, value, selectAll ? 0 : value.Length, value.Length); + } + } + + private void ReplaceFieldText(IElement field, string value, int start, int end, string text) + { + if (start == end && text.Length == 0) + { + return; + } + + var newValue = string.Concat(value.AsSpan(0, start), text, value.AsSpan(end)); + FormControls.SetValue(field, newValue); + var cursor = start + text.Length; + SetFieldSelection(field, newValue, cursor, cursor); + Fire(field, new Event("input", true, false)); + } + + private (int Start, int End, bool Backward) GetFieldSelection(IElement field, string value) + { + var (start, end, direction) = field switch + { + IHtmlInputElement input => (input.SelectionStart, input.SelectionEnd, input.SelectionDirection), + IHtmlTextAreaElement area => (area.SelectionStart, area.SelectionEnd, area.SelectionDirection), + _ => (value.Length, value.Length, null), + }; + + if (ReferenceEquals(field, _editedField) && !string.Equals(value, _editedValue, StringComparison.Ordinal) && (start, end) == _editedSelection) + { + start = end = value.Length; + } + + start = Math.Clamp(start, 0, value.Length); + end = Math.Clamp(end, start, value.Length); + return (start, end, direction == "backward"); + } + + /// + /// Selects the text between the anchor (where the selection began) and the focus (where the + /// cursor is), which may come first. + /// + private void SetFieldSelection(IElement field, string value, int anchor, int focus) + { + var (start, end, direction) = focus < anchor ? (focus, anchor, "backward") : (anchor, focus, "forward"); + + switch (field) + { + case IHtmlInputElement input: + input.Select(start, end, direction); + break; + case IHtmlTextAreaElement area: + area.Select(start, end, direction); + break; + } + + _editedField = field; + _editedValue = value; + _editedSelection = (start, end); + + // the caret moved without the DOM changing, the next frame shows it + NotifyStateChanged(field); + } + + private static int GetPreviousOffset(string value, int offset) => + offset <= 0 ? 0 : offset >= 2 && char.IsSurrogatePair(value[offset - 2], value[offset - 1]) ? offset - 2 : offset - 1; + + private static int GetNextOffset(string value, int offset) => + offset >= value.Length ? value.Length : offset + 1 < value.Length && char.IsSurrogatePair(value[offset], value[offset + 1]) ? offset + 2 : offset + 1; + + private static int GetPreviousWordStart(string value, int offset) + { + while (offset > 0 && !IsWordCharacter(value[offset - 1])) + { + offset--; + } + + while (offset > 0 && IsWordCharacter(value[offset - 1])) + { + offset--; + } + + return offset; + } + + private static int GetNextWordEnd(string value, int offset) + { + while (offset < value.Length && !IsWordCharacter(value[offset])) + { + offset++; + } + + while (offset < value.Length && IsWordCharacter(value[offset])) + { + offset++; + } + + return offset; + } + + private static bool IsWordCharacter(char c) => char.IsLetterOrDigit(c) || c == '_' || char.IsSurrogate(c); + + private static int GetLineStart(string value, int offset) => + offset > 0 ? value.LastIndexOf('\n', offset - 1) + 1 : 0; + + private static int GetLineEnd(string value, int offset) + { + var end = value.IndexOf('\n', offset); + return end < 0 ? value.Length : end; + } + + /// + /// The offset in the line above or below the one of the given offset (by line breaks, not + /// how the lines wrap) with the same column, or the start or end of the text without one. + /// + private static int GetOffsetOnAdjacentLine(string value, int offset, int direction) + { + var lineStart = GetLineStart(value, offset); + var column = offset - lineStart; + + if (direction < 0) + { + if (lineStart == 0) + { + return 0; + } + + var previousStart = GetLineStart(value, lineStart - 1); + return Math.Min(previousStart + column, lineStart - 1); + } + + var lineEnd = GetLineEnd(value, offset); + + if (lineEnd >= value.Length) + { + return value.Length; + } + + var nextStart = lineEnd + 1; + return Math.Min(nextStart + column, GetLineEnd(value, nextStart)); + } +} diff --git a/src/AngleSharp.Browser/BrowserEngine.cs b/src/AngleSharp.Browser/BrowserEngine.cs index 2ad7e47..54305b7 100644 --- a/src/AngleSharp.Browser/BrowserEngine.cs +++ b/src/AngleSharp.Browser/BrowserEngine.cs @@ -92,6 +92,11 @@ function clamp(name, min) { private volatile bool _isPainting; private volatile bool _isDisposed; + // A browser serializes colors as CSSOM says (e.g. getComputedStyle gives "rgb(0, 128, 0)" + // for an opaque color), while AngleSharp.Css keeps "rgba(0, 128, 0, 1)" for its library + // users unless asked to. The switch is process-wide, which a browser process is. + static BrowserEngine() => AngleSharp.Css.Values.CssColorValue.UseSpecSerialization = true; + /// /// Creates a new browser engine. /// @@ -110,6 +115,7 @@ private BrowserEngine(BrowserOptions options, BrowserEngine? opener) _options = options; _media = new MediaHost(options); _media.Changed += OnMediaChanged; + _fullscreen = new Fullscreen(() => _media.HasUserActivation, OnFullscreenChanged); _device = new DefaultRenderDevice { @@ -144,11 +150,15 @@ private BrowserEngine(BrowserOptions options, BrowserEngine? opener) // the document of an iframe has a viewport of its own (the renderer sizes it), which its // media queries see as well .WithOnly(context => context.Parent is null ? _device : CreateFrameDevice(context, _device)) + // shows responses that aren't documents (e.g. images) like a browser; before the + // extensions, which register their creators at it (e.g. XML and SVG) + .WithOnly(new BrowserDocumentFactory()) .WithXml() // an XML document that isn't well-formed shows the error instead of failing to load .With(new ParseErrorDocuments()) // links to pages shown before match :visited (before the CSS extension wraps the selectors) .WithOnly(_visited.CreateSelectors(() => _context?.Active)) + .With(_fullscreen) .WithOnly(context => { var parser = new HtmlParser(new HtmlParserOptions { IsScripting = context.IsScripting() }, context); @@ -177,7 +187,9 @@ private BrowserEngine(BrowserOptions options, BrowserEngine? opener) { config = config .WithConsoleLogger(_ => new BrowserDiagnostics.ConsoleLogger(_diagnostics)) - .WithJs(); + .WithJs() + // the modules of paint worklets (CSS.paintWorklet.addModule) + .With(_ => new PaintWorklets(OnPaintWorkletChanged)); } // the top-level context shares the engine's history (window.history), frames get their own @@ -223,6 +235,8 @@ private BrowserEngine(BrowserOptions options, BrowserEngine? opener) requester.Requested += (_, ev) => _diagnostics.OnRequested(((RequestEvent)ev).Request, ((RequestEvent)ev).Response); } + _context.GetService()?.AppendDefault(Fullscreen.DefaultStyle); + if (options.IsScriptingEnabled) { // the default style sheet lacks the rule from the HTML standard (15.3.1) @@ -350,6 +364,25 @@ public string? ColorScheme ///
public IDocument? Document => _document; + /// + /// Gets if the page shows an element fullscreen (Fullscreen API), which the host shows + /// fullscreen as well. See . + /// + public bool IsFullscreen => _isFullscreen; + + /// + /// Raised when the page starts or ends showing an element fullscreen (see + /// ). Raised on the engine's thread. + /// + public event EventHandler? FullscreenChanged; + + /// + /// Ends showing an element of the page fullscreen, e.g. when the host leaves its own + /// fullscreen mode. + /// + /// The task finishing once it ended. + public Task ExitFullscreenAsync() => InvokeAsync(document => _fullscreen.ExitAll(document)); + /// /// Gets the address of the currently displayed document, or the address being navigated /// to while a navigation is in progress. @@ -786,6 +819,8 @@ private void SyncActiveDocument() _pressed = null; _seekingMedia = null; _focusedFrameDocument = null; + // a document that was left shows nothing fullscreen anymore + OnFullscreenChanged(false); _hoveredFrames.Clear(); _pointerFrame = null; _wasReadyForLayout = false; diff --git a/src/AngleSharp.Browser/BrowserOptions.cs b/src/AngleSharp.Browser/BrowserOptions.cs index e2e2485..80a2793 100644 --- a/src/AngleSharp.Browser/BrowserOptions.cs +++ b/src/AngleSharp.Browser/BrowserOptions.cs @@ -3,6 +3,7 @@ namespace AngleSharp.Browser; using System; using System.Collections.Generic; using System.Net; +using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using AngleSharp.Io; @@ -23,11 +24,20 @@ public sealed class BrowserOptions public string? ProfileDirectory { get; set; } /// - /// Gets or sets the user agent to report. If null, the default of - /// AngleSharp.Io is used. + /// Gets or sets the user agent to report. If null, the + /// is used. /// public string? UserAgent { get; set; } + /// + /// Gets the user agent reported by default, e.g. + /// "Mozilla/5.0 (X11; Linux x86_64) AngleSharp.Browser/0.3". It names the + /// engine instead of claiming to be another browser: sites (e.g. bot + /// protections) check a claim of being Chrome against the way Chrome + /// behaves and refuse a browser that claims it without behaving alike. + /// + public static string DefaultUserAgent { get; } = CreateDefaultUserAgent(); + /// /// Gets the headers added to every request, unless the request sets them /// already (e.g., Accept-Language or DNT). @@ -150,12 +160,30 @@ internal IoOptions CreateIoOptions(IoOptions? profile = null) // like any browser: servers (e.g. CDNs keeping files compressed) may send gzip unasked options.HttpHandler.AutomaticDecompression = DecompressionMethods.All; - if (UserAgent is not null) - { - options.Navigator.UserAgent = UserAgent; - } + options.Navigator.UserAgent = UserAgent ?? DefaultUserAgent; ConfigureIo?.Invoke(options); return options; } + + private static string CreateDefaultUserAgent() + { + var version = typeof(BrowserOptions).Assembly.GetName().Version ?? new Version(0, 0); + var architecture = RuntimeInformation.OSArchitecture switch + { + Architecture.Arm64 => "aarch64", + Architecture.X86 => "i686", + _ => "x86_64", + }; + + // the platform tokens of the other browsers on the same system + var platform = OperatingSystem.IsWindows() + ? (RuntimeInformation.OSArchitecture == Architecture.Arm64 ? "Windows NT 10.0; ARM64" : "Windows NT 10.0; Win64; x64") + : OperatingSystem.IsMacOS() + ? "Macintosh; Intel Mac OS X 10_15_7" + : OperatingSystem.IsAndroid() + ? "Linux; Android 10; K" + : $"X11; Linux {architecture}"; + return $"Mozilla/5.0 ({platform}) AngleSharp.Browser/{version.Major}.{version.Minor}"; + } } diff --git a/src/AngleSharp.Browser/FormControls.cs b/src/AngleSharp.Browser/FormControls.cs index b408a4e..3be1b5a 100644 --- a/src/AngleSharp.Browser/FormControls.cs +++ b/src/AngleSharp.Browser/FormControls.cs @@ -27,7 +27,8 @@ static class FormControls /// /// The control of a label: the one its `for` attribute names, else its first labelable - /// descendant (HTML 4.10.4). AngleSharp only knows the former so far. + /// descendant (HTML 4.10.4). AngleSharp only knows the former before 1.11 (remove this once + /// referenced). /// public static IElement? GetLabeledControl(IHtmlLabelElement label) { diff --git a/src/AngleSharp.Browser/Fullscreen.cs b/src/AngleSharp.Browser/Fullscreen.cs new file mode 100644 index 0000000..1248ee7 --- /dev/null +++ b/src/AngleSharp.Browser/Fullscreen.cs @@ -0,0 +1,228 @@ +namespace AngleSharp.Browser; + +using AngleSharp.Attributes; +using AngleSharp.Dom; +using AngleSharp.Dom.Events; +using AngleSharp.Html.Dom; +using System; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +/// +/// The fullscreen state of the documents of an engine (Fullscreen API): an element shown +/// fullscreen covers the viewport (it matches :fullscreen), and so do the iframes of +/// the documents it is in. The engine shows the page fullscreen meanwhile. +/// +sealed class Fullscreen +{ + private const String PseudoClass = "fullscreen"; + + /// + /// Completes the rules of the user agent for the fullscreen elements (Fullscreen 6, in + /// AngleSharp.Css): without a top layer, the element is above everything else, and without + /// a ::backdrop, it is black behind the element. + /// + public const String DefaultStyle = ":not(:root):fullscreen { z-index: 2147483647 !important; background-color: black }"; + + private static readonly ConditionalWeakTable Elements = new(); + + private readonly Func _hasUserActivation; + private readonly Action _changed; + + public Fullscreen(Func hasUserActivation, Action changed) + { + _hasUserActivation = hasUserActivation; + _changed = changed; + } + + /// + /// Gets the fullscreen element of the document, if any. + /// + public static IElement? GetElement(IDocument document) => + Elements.TryGetValue(document, out var element) ? element : null; + + /// + /// Gets if the documents of the context may show an element fullscreen: not in a sandbox + /// without it, and in an iframe only with allowfullscreen (like its ancestors). + /// + public static Boolean IsEnabled(IDocument document) + { + for (var current = document; current is not null; current = current.Context?.Creator) + { + var context = current.Context; + + if (context is null || context.Security.HasFlag(Sandboxes.Fullscreen)) + { + return false; + } + + if (context.Parent is not null && FindFrame(current)?.HasAttribute(AttributeNames.AllowFullscreen) != true) + { + return false; + } + } + + return true; + } + + /// + /// Shows the element fullscreen, if the page may (a user activation). Requires exclusive access. + /// + public Task Request(IElement element) + { + var document = element.Owner; + + if (document is null || !element.IsConnected() || !IsEnabled(document) || (GetElement(document) is null && !_hasUserActivation())) + { + if (document is not null) + { + Queue(document, () => element.Dispatch(new Event(EventNames.FullscreenError, bubbles: true, cancelable: false, composed: true))); + } + + return Task.FromException(new InvalidOperationException("The element cannot be shown fullscreen.")); + } + + // the element and the frames of its document in the ancestors' documents are fullscreen + for (IElement? current = element; current?.Owner is { } owner; current = FindFrame(owner)) + { + if (GetElement(owner) is var previous && previous != current) + { + previous?.RemovePseudoClass(PseudoClass); + current.SetPseudoClass(PseudoClass); + Elements.AddOrUpdate(owner, current); + var changed = current; + Queue(owner, () => FireChange(changed, owner)); + } + } + + _changed(true); + return Task.CompletedTask; + } + + /// + /// Ends showing an element of the document fullscreen. Requires exclusive access. + /// + public Task Exit(IDocument document) + { + if (GetElement(document) is null) + { + return Task.FromException(new InvalidOperationException("The document has no fullscreen element.")); + } + + ExitAll(document); + return Task.CompletedTask; + } + + /// + /// Ends showing anything fullscreen in the document's top-level browsing context, e.g. for + /// Esc. Requires exclusive access. + /// + public Boolean ExitAll(IDocument? document) + { + var top = document; + + while (top?.Context?.Creator is { } creator) + { + top = creator; + } + + if (top is null || GetElement(top) is null) + { + return false; + } + + for (var current = top; current is not null && GetElement(current) is { } element;) + { + Elements.Remove(current); + element.RemovePseudoClass(PseudoClass); + var owner = current; + Queue(owner, () => FireChange(element, owner)); + current = (element as IHtmlInlineFrameElement)?.ContentDocument; + } + + _changed(false); + return true; + } + + private static void FireChange(IElement element, IDocument document) + { + // an element removed meanwhile does not get it, the document does + IEventTarget target = element.IsConnected() && element.Owner == document ? element : document; + var ev = new Event(EventNames.FullscreenChange, bubbles: true, cancelable: false, composed: true); + target.Dispatch(ev); + } + + private static void Queue(IDocument document, Action action) + { + if (document.Context?.GetService() is { } loop) + { + loop.Enqueue(action); + } + else + { + action(); + } + } + + private static IElement? FindFrame(IDocument document) => + document.Context?.Creator?.QuerySelectorAll("iframe").OfType().FirstOrDefault(frame => frame.ContentDocument == document); +} + +/// +/// The members of the Fullscreen API on elements. +/// +[DomExposed("Element")] +public static class FullscreenElementExtensions +{ + /// + /// Shows the element fullscreen, which needs a user activation (a press or a key). + /// + /// The element to show. + /// The task finishing once it is shown. + [DomName("requestFullscreen")] + public static Task RequestFullscreen(this IElement element) => + element.Owner?.Context?.GetService() is { } fullscreen + ? fullscreen.Request(element) + : Task.FromException(new NotSupportedException("Fullscreen is not supported.")); +} + +/// +/// The members of the Fullscreen API on documents. +/// +[DomExposed("Document")] +public static class FullscreenDocumentExtensions +{ + /// + /// Gets the element shown fullscreen, if any. + /// + [DomName("fullscreenElement")] + [DomAccessor(Accessors.Getter)] + public static IElement? GetFullscreenElement(this IDocument document) => Fullscreen.GetElement(document); + + /// + /// Gets if an element is shown fullscreen. + /// + [DomName("fullscreen")] + [DomAccessor(Accessors.Getter)] + public static Boolean IsFullscreen(this IDocument document) => Fullscreen.GetElement(document) is not null; + + /// + /// Gets if elements of the document may be shown fullscreen. + /// + [DomName("fullscreenEnabled")] + [DomAccessor(Accessors.Getter)] + public static Boolean IsFullscreenEnabled(this IDocument document) => + document.Context?.GetService() is not null && Fullscreen.IsEnabled(document); + + /// + /// Ends showing an element fullscreen. + /// + /// The document. + /// The task finishing once it ended. + [DomName("exitFullscreen")] + public static Task ExitFullscreen(this IDocument document) => + document.Context?.GetService() is { } fullscreen + ? fullscreen.Exit(document) + : Task.FromException(new InvalidOperationException("The document has no fullscreen element.")); +} diff --git a/src/AngleSharp.Browser/PaintWorklets.cs b/src/AngleSharp.Browser/PaintWorklets.cs new file mode 100644 index 0000000..635dac3 --- /dev/null +++ b/src/AngleSharp.Browser/PaintWorklets.cs @@ -0,0 +1,175 @@ +namespace AngleSharp.Browser; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Threading.Tasks; +using AngleSharp.Css.Painting; +using AngleSharp.Css.TypedOm; +using AngleSharp.Dom; +using AngleSharp.Io; +using Jint; +using Jint.Native; +using Jint.Native.Object; +using Jint.Runtime.Interop; + +/// +/// Loads the modules of paint worklets (CSS Painting API, `CSS.paintWorklet.addModule`): each +/// document's worklet runs its modules in a script realm of its own, where `registerPaint` +/// registers the classes painting `paint()` images with AngleSharp.Css's +/// ; once a module ran, the page is laid out again to paint them. +/// +sealed class PaintWorklets(Action changed) : IPaintWorkletModuleLoader +{ + private readonly ConditionalWeakTable _realms = new(); + + public async Task LoadAsync(PaintWorkletGlobalScope scope, Url moduleUrl, CancellationToken cancellationToken) + { + var source = await FetchAsync(scope.Document, moduleUrl, cancellationToken).ConfigureAwait(false); + var realm = _realms.GetValue(scope, static current => new Realm(current)); + + lock (realm) + { + realm.Run(source, moduleUrl.Href); + } + + changed(); + } + + private static async Task FetchAsync(IDocument document, Url url, CancellationToken cancellationToken) + { + var requester = document.Context?.GetServices().FirstOrDefault(m => m.SupportsProtocol(url.Scheme)) ?? + throw new DomException(DomError.Network); + using var response = await requester.RequestAsync(new Request { Address = url, Method = HttpMethod.Get }, cancellationToken).ConfigureAwait(false); + + if (response is null || (int)response.StatusCode is < 200 or >= 300) + { + throw new DomException(DomError.Network); + } + + using var reader = new StreamReader(response.Content); + return await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// The PaintWorkletGlobalScope of a document's worklet as script sees it. + /// + private sealed class Realm + { + private readonly Engine _engine; + private readonly PaintWorkletGlobalScope _scope; + + public Realm(PaintWorkletGlobalScope scope) + { + _scope = scope; + // the members of the DOM objects given to a paint (its context, size and properties) + // are found by their names in script (fillRect for FillRect) + _engine = new Engine(options => options + .SetTypeResolver(new TypeResolver { MemberNameComparer = StringComparer.OrdinalIgnoreCase }) + .SetTypeConverter(engine => new DomTypeConverter(engine)) + .LimitRecursion(256) + .TimeoutInterval(TimeSpan.FromSeconds(5))); + _engine.SetValue("devicePixelRatio", scope.DevicePixelRatio); + _engine.SetValue("registerPaint", new Action(Register)); + } + + public void Run(string source, string url) => _engine.Execute(source, url); + + private void Register(string name, JsValue paintClass) + { + if (!paintClass.IsConstructor()) + { + throw new Jint.Runtime.JavaScriptException(_engine.Intrinsics.TypeError, "The paint definition has to be a class."); + } + + var type = paintClass.AsObject(); + var options = type.Get("contextOptions"); + var definition = new Definition(this, type) + { + InputProperties = ReadStrings(type.Get("inputProperties")), + InputArguments = ReadStrings(type.Get("inputArguments")), + ContextOptions = new PaintRenderingContext2DSettings + { + Alpha = options is not ObjectInstance optionsObject || optionsObject.Get("alpha") is not JsBoolean alpha || alpha.AsBoolean(), + }, + }; + _scope.RegisterPaint(name, definition); + } + + private static string[] ReadStrings(JsValue value) => + value is ObjectInstance list && !value.IsNull() + ? Enumerable.Range(0, (int)Jint.Runtime.TypeConverter.ToLength(list.Get("length"))).Select(i => list.Get(i).ToString()).ToArray() + : []; + + public void Paint(ObjectInstance type, ref ObjectInstance? instance, IPaintRenderingContext2D context, PaintSize size, IStylePropertyMapReadOnly properties, IReadOnlyList arguments) + { + lock (this) + { + // one instance paints all images (a browser may create several) + instance ??= _engine.Construct(type); + var args = _engine.Intrinsics.Array.Construct(arguments.Select(argument => JsValue.FromObject(_engine, argument)).ToArray()); + _engine.Invoke(instance.Get("paint"), instance, [JsValue.FromObject(_engine, context), JsValue.FromObject(_engine, size), JsValue.FromObject(_engine, properties), args]); + } + } + } + + /// + /// Converts the strings of script to the enumerations of the DOM by the names they have + /// there (e.g. "round" for CanvasLineCap.Round), as AngleSharp.Js does. + /// + private sealed class DomTypeConverter(Engine engine) : DefaultTypeConverter(engine) + { + public override object? Convert(object? value, Type type, IFormatProvider formatProvider) => + value is string text && ToEnum(text, type) is { } literal ? literal : base.Convert(value, type, formatProvider); + + public override bool TryConvert(object? value, Type type, IFormatProvider formatProvider, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out object? converted) + { + if (value is string text && ToEnum(text, type) is { } literal) + { + converted = literal; + return true; + } + + return base.TryConvert(value, type, formatProvider, out converted); + } + + private static object? ToEnum(string text, Type type) + { + var enumType = Nullable.GetUnderlyingType(type) ?? type; + + if (!enumType.IsEnum) + { + return null; + } + + foreach (var field in enumType.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)) + { + var name = field.GetCustomAttributes(typeof(AngleSharp.Attributes.DomNameAttribute), false).OfType().FirstOrDefault()?.OfficialName ?? field.Name; + + if (string.Equals(name, text, StringComparison.OrdinalIgnoreCase)) + { + return field.GetValue(null); + } + } + + return null; + } + } + + private sealed class Definition(Realm realm, ObjectInstance type) : IPaintDefinition + { + private ObjectInstance? _instance; + + public IEnumerable InputProperties { get; init; } = []; + + public IEnumerable InputArguments { get; init; } = []; + + public PaintRenderingContext2DSettings ContextOptions { get; init; } = new(); + + public void Paint(IPaintRenderingContext2D context, PaintSize size, IStylePropertyMapReadOnly properties, IReadOnlyList arguments) => + realm.Paint(type, ref _instance, context, size, properties, arguments); + } +} diff --git a/src/Vision/Models/BrowserSettings.cs b/src/Vision/Models/BrowserSettings.cs index 643e803..aa35d23 100644 --- a/src/Vision/Models/BrowserSettings.cs +++ b/src/Vision/Models/BrowserSettings.cs @@ -44,7 +44,7 @@ public sealed record BrowserSettings public string? ProfileDirectory { get; init; } /// - /// Gets the user agent to report; null for the default of AngleSharp. + /// Gets the user agent to report; null for the engine's default (BrowserOptions.DefaultUserAgent). /// public string? UserAgent { get; init; } diff --git a/src/Vision/Pages/settings.html b/src/Vision/Pages/settings.html index 58db9e0..7fcef96 100644 --- a/src/Vision/Pages/settings.html +++ b/src/Vision/Pages/settings.html @@ -227,7 +227,7 @@

Privacy and data

Network

User agent - How the browser introduces itself to sites. Leave empty for the default of AngleSharp. + How the browser introduces itself to sites. Leave empty to name this browser (AngleSharp.Browser). Sites with a bot protection may refuse the Chrome preset, as the browser does not behave like Chrome in every detail.
diff --git a/src/Vision/Views/MainWindow.axaml b/src/Vision/Views/MainWindow.axaml index 811be68..c212fa6 100644 --- a/src/Vision/Views/MainWindow.axaml +++ b/src/Vision/Views/MainWindow.axaml @@ -25,155 +25,155 @@ - - - - - - - - - - - - - - - - - - - + + + + + + + - - - - - - - - - - - - - + + + + + + + + + + + - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + - + + diff --git a/src/Vision/Views/MainWindow.axaml.cs b/src/Vision/Views/MainWindow.axaml.cs index 7f6c668..39a7073 100644 --- a/src/Vision/Views/MainWindow.axaml.cs +++ b/src/Vision/Views/MainWindow.axaml.cs @@ -27,6 +27,8 @@ public partial class MainWindow : Window private readonly DispatcherTimer _holdTimer; private Button? _heldButton; private bool _isHoldHandled; + // the state of the window before the page showed something fullscreen + private WindowState? _stateBeforeFullscreen; public MainWindow() { @@ -175,6 +177,7 @@ protected override void OnDataContextChanged(EventArgs e) if (_viewModel is not null) { _viewModel.PropertyChanged -= OnViewModelPropertyChanged; + _viewModel.Engine.FullscreenChanged -= OnFullscreenChanged; } _viewModel = DataContext as MainViewModel; @@ -182,6 +185,50 @@ protected override void OnDataContextChanged(EventArgs e) if (_viewModel is not null) { _viewModel.PropertyChanged += OnViewModelPropertyChanged; + _viewModel.Engine.FullscreenChanged += OnFullscreenChanged; + } + } + + // raised on the engine's thread + private void OnFullscreenChanged(object? sender, EventArgs e) => + Dispatcher.UIThread.Post(() => ShowFullscreen(_viewModel?.Engine.IsFullscreen == true)); + + /// + /// Shows the window fullscreen with just the page while the page shows something + /// fullscreen, and as before afterwards. + /// + private void ShowFullscreen(bool isFullscreen) + { + if (isFullscreen && _stateBeforeFullscreen is null) + { + _stateBeforeFullscreen = WindowState; + Chrome.IsVisible = false; + ContentGrid.ColumnDefinitions[2].Width = new GridLength(0); + WindowState = WindowState.FullScreen; + } + else if (!isFullscreen && _stateBeforeFullscreen is { } state) + { + _stateBeforeFullscreen = null; + Chrome.IsVisible = true; + WindowState = state; + + if (_viewModel?.IsPanelOpen == true) + { + ContentGrid.ColumnDefinitions[2].Width = new GridLength(_openedWidth); + } + } + } + + protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) + { + base.OnPropertyChanged(change); + + // the user leaving the fullscreen window (e.g. with a key of the platform) ends it for the page as well + if (change.Property == WindowStateProperty && _stateBeforeFullscreen is not null && WindowState != WindowState.FullScreen) + { + _stateBeforeFullscreen = null; + Chrome.IsVisible = true; + _ = _viewModel?.Engine.ExitFullscreenAsync(); } } From b031eeddd39ec72c7fcdca7a171ad8b30025a11a Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Wed, 25 Nov 2026 01:05:46 +0100 Subject: [PATCH 5/6] Updated version --- .../AngleSharp.Browser.csproj | 43 ++++++++++++++++--- src/AngleSharp.Browser/BrowserEngine.cs | 10 ++++- src/Directory.Build.props | 2 +- 3 files changed, 46 insertions(+), 9 deletions(-) diff --git a/src/AngleSharp.Browser/AngleSharp.Browser.csproj b/src/AngleSharp.Browser/AngleSharp.Browser.csproj index b4decaf..47bee97 100644 --- a/src/AngleSharp.Browser/AngleSharp.Browser.csproj +++ b/src/AngleSharp.Browser/AngleSharp.Browser.csproj @@ -7,18 +7,37 @@ html;css;javascript;browser;rendering;headless;anglesharp;angle + + + true + + + + + + + - - - - - - - + + + + + + + @@ -34,4 +53,14 @@ + + + + <_Parameter1>false + + + + <_Parameter1>AngleSharp.Browser.BrowserDom + + diff --git a/src/AngleSharp.Browser/BrowserEngine.cs b/src/AngleSharp.Browser/BrowserEngine.cs index 54305b7..41e597a 100644 --- a/src/AngleSharp.Browser/BrowserEngine.cs +++ b/src/AngleSharp.Browser/BrowserEngine.cs @@ -22,6 +22,8 @@ namespace AngleSharp.Browser; using AngleSharp.Renderer; using AngleSharp.Scripting; using AngleSharp.Renderer.Rendering; +using AngleSharp.Wasm; +using AngleSharp.Xml; /// /// A UI-agnostic browser: it loads documents, paints the active document @@ -187,7 +189,13 @@ private BrowserEngine(BrowserOptions options, BrowserEngine? opener) { config = config .WithConsoleLogger(_ => new BrowserDiagnostics.ConsoleLogger(_diagnostics)) - .WithJs() + .WithJs(DomRegistrations.Combine( + CssDom.Register, + IoDom.Register, + WasmDom.Register, + RendererDom.Register, + XmlDom.Register, + BrowserDom.Register)) // the modules of paint worklets (CSS.paintWorklet.addModule) .With(_ => new PaintWorklets(OnPaintWorkletChanged)); } diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 159616b..d979866 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -1,6 +1,6 @@ - 0.2.0 + 0.3.0 enable latest true From 4d468a5b7b6bbf724b3d145420d5704ed9e43ad2 Mon Sep 17 00:00:00 2001 From: Florian Rappl Date: Wed, 25 Nov 2026 01:34:20 +0100 Subject: [PATCH 6/6] Added temporary upstream DOM --- AGENTS.md | 2 +- src/AngleSharp.Browser/BrowserEngine.cs | 4 +- src/AngleSharp.Browser/UpstreamDom.cs | 69 +++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 src/AngleSharp.Browser/UpstreamDom.cs diff --git a/AGENTS.md b/AGENTS.md index 07a5512..0bcc21f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,7 +34,7 @@ AngleSharp.Browser adds a fully usable (visible) browser based on top of the Ang - `src/AngleSharp.Browser.Tests`: NUnit tests driving the engine headlessly. `src/AngleSharp.Browser.Avalonia.Tests`: NUnit tests of the control and of Vision's panels using Avalonia's headless platform with real Skia rendering. Don't use `Assert.ThrowsAsync` with the engine (it blocks and hangs); use an awaited try/catch. - `build/`: the Fallout build, run via `build.sh`/`build.ps1`, `.github/workflows/ci.yml` calls it. The version comes from the top of `CHANGELOG.md`; a push to `main` publishes a release, one to `devel` a pre-release. - `docs/`: the documentation, published through the doclet in `src/AngleSharp.Browser.Docs`. Keep it in sync with the public API. -- `BrowserEngine` patches a few upstream gaps (User-Agent header, `noscript` style, text documents never completing, timer delays clamped because a zero-delay `setInterval` never yields before AngleSharp 1.9.0, `label.control` not finding wrapped controls, event listener errors reported by an `ErrorEvent` without a type, and `NavigationHistory` reaching the protected `Document.DocumentUri` setter by reflection, as `pushState` has to change the document's address, `LegacyKeyboardEvent.Code` as it knows the key's code by itself from then on, and a field's cursor moved to the end of a value a script set, which AngleSharp does from 1.11); remove them once fixed upstream. +- `BrowserEngine` patches a few upstream gaps (User-Agent header, `noscript` style, text documents never completing, timer delays clamped because a zero-delay `setInterval` never yields before AngleSharp 1.9.0, `label.control` not finding wrapped controls, event listener errors reported by an `ErrorEvent` without a type, and `NavigationHistory` reaching the protected `Document.DocumentUri` setter by reflection, as `pushState` has to change the document's address, `LegacyKeyboardEvent.Code` as it knows the key's code by itself from then on, and a field's cursor moved to the end of a value a script set, which AngleSharp does from 1.11, and `UpstreamDom`, registered after the libraries' generated DOM registrations: the `CssMediaQueryList` of `matchMedia` got Core's `EventTarget` prototype (AngleSharp.Js picks the most derived type in the order of registration), and AngleSharp.Wasm's import/export descriptors weren't registered); remove them once fixed upstream. ## Most Important Commands diff --git a/src/AngleSharp.Browser/BrowserEngine.cs b/src/AngleSharp.Browser/BrowserEngine.cs index 41e597a..58ee782 100644 --- a/src/AngleSharp.Browser/BrowserEngine.cs +++ b/src/AngleSharp.Browser/BrowserEngine.cs @@ -195,7 +195,9 @@ private BrowserEngine(BrowserOptions options, BrowserEngine? opener) WasmDom.Register, RendererDom.Register, XmlDom.Register, - BrowserDom.Register)) + BrowserDom.Register, + // what the generated registrations above miss + UpstreamDom.Register)) // the modules of paint worklets (CSS.paintWorklet.addModule) .With(_ => new PaintWorklets(OnPaintWorkletChanged)); } diff --git a/src/AngleSharp.Browser/UpstreamDom.cs b/src/AngleSharp.Browser/UpstreamDom.cs new file mode 100644 index 0000000..409ded9 --- /dev/null +++ b/src/AngleSharp.Browser/UpstreamDom.cs @@ -0,0 +1,69 @@ +namespace AngleSharp.Browser; + +using System; +using System.Diagnostics.CodeAnalysis; +using AngleSharp.Css.Dom; +using AngleSharp.Dom; +using AngleSharp.Scripting; +using AngleSharp.Wasm.Dom; + +/// +/// Completes the generated DOM registrations of the libraries where they miss what the +/// reflection path exposes. Registered last, see ; remove the +/// parts once fixed upstream. +/// +internal static class UpstreamDom +{ + private const string MediaQueryListType = "AngleSharp.Css.Dom.CssMediaQueryList"; + + public static void Register(DomRegistry registry) + { + RegisterMediaQueryList(registry); + RegisterWasmDescriptors(registry); + } + + // AngleSharp.Js gives an object the prototype of the most derived registered type, walking + // them in the order of registration: Core's EventTarget class comes before Css's + // IMediaQueryList and is never replaced by it, so the object matchMedia returns (a + // CssMediaQueryList, which derives from EventTarget) got EventTarget's prototype, without + // media and matches. Registering the internal type itself, chained to IMediaQueryList, + // gives it the right one (and the shared MediaQueryList interface object). + [UnconditionalSuppressMessage("AOT", "IL3050", Justification = "Instantiated over a reference type, whose shared code always exists.")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The type is kept, as matchMedia creates it.")] + [UnconditionalSuppressMessage("Trimming", "IL2060", Justification = "The generic method only declares the type.")] + private static void RegisterMediaQueryList(DomRegistry registry) + { + var type = typeof(IMediaQueryList).Assembly.GetType(MediaQueryListType); + + if (type is not null && typeof(IMediaQueryList).IsAssignableFrom(type) && type.IsClass) + { + typeof(UpstreamDom) + .GetMethod(nameof(DeclareMediaQueryList), System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)! + .MakeGenericMethod(type) + .Invoke(null, [registry]); + } + } + + private static void DeclareMediaQueryList(DomRegistry registry) + where T : class, IMediaQueryList + { + registry.Type("MediaQueryList").Inherits(); + } + + // AngleSharp.Wasm's generated registration leaves out the descriptors WebAssembly.Module's + // imports and exports give (their members have DOM names, the types none), so they came + // out as empty objects. + private static void RegisterWasmDescriptors(DomRegistry registry) + { + registry.Type("ModuleImportDescriptor") + .WithoutInterfaceObject() + .Property("module", t => t.Module) + .Property("name", t => t.Name) + .Property("kind", t => t.Kind); + + registry.Type("ModuleExportDescriptor") + .WithoutInterfaceObject() + .Property("name", t => t.Name) + .Property("kind", t => t.Kind); + } +}