diff --git a/AGENTS.md b/AGENTS.md index 40f2c67..61a7916 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,17 +10,20 @@ AngleSharp.Browser adds a fully usable (visible) browser based on top of the Ang - `src/AngleSharp.Browser` (NuGet package): the UI-agnostic `BrowserEngine` (navigation, painting, input). Everything configurable lives in `BrowserOptions`. All DOM work is serialized and runs on AngleSharp's event loop, as AngleSharp is not thread-safe. - 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 root with `overflow: hidden` can't be scrolled by the user, but keeps its position. +- 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`). - 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. - 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`); 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. +- `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. - Vision's own UI beyond the toolbar (diagnostics tab, settings, about) is HTML/CSS in `Pages/` (embedded resources), shown by a `BrowserView` with a scripting-free engine. `HtmlPage` subclasses wire the DOM with .NET event handlers via `BrowserEngine.InvokeAsync`; don't add JavaScript there. `BrowserEngine.Diagnostics` collects the current page's requests, errors, console output and frame timings. The side panel of a window shows one page at a time, the diagnostics or the inspector, which share its width (a third of the window, unless the user resized it); `InspectorPage` builds its views on the event loop of the inspected engine and only looks at expanded rows, so its refreshes stay cheap. - `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, pointer events being plain `MouseEvent`s as the `PointerEvent` of AngleSharp is not published yet, 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, and `LegacyKeyboardEvent.Code` as it knows the key's code by itself from then on); remove them once fixed upstream. ## Most Important Commands diff --git a/CHANGELOG.md b/CHANGELOG.md index d8e501e..e1abaf9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,27 @@ +# 0.2.0 + +Released on Wednesday, November 18 2026. + +- Fixed `BrowserView` not passing a modifier key pressed on its own (Control, Shift, Alt, Meta) to the page, e.g. a game firing on Control +- Fixed callers of the engine (e.g. awaiting `PrepareFrameAsync` and rasterizing the frame without a synchronization context) continuing on the event loop, which held up the scripts of the page +- Fixed the pointer not firing `mouseenter`/`mouseleave` (and `pointerenter`/`pointerleave`) and its events having no `relatedTarget` +- Fixed the pointer events of the mouse having no `pointerType`, so that scripts took the mouse for touch (e.g. SmartMenus not opening menus on hover) +- Fixed scripts reading `event` outside of a listener failing, e.g. the carousels of smapiot.com (AngleSharp.Js 1.2.2) +- Fixed pages scrolling a script finds the position of an element on (e.g. smapiot.com) freezing (AngleSharp.Renderer 0.11.4) +- Fixed media changing (e.g. a game playing a sound effect, which rewinds and plays an `audio` element) laying out the whole page, which stalled the frames (e.g. whenever Mario jumps in the Mario 5 demo of demo-full.piral.io); only a page showing `audio controls` is laid out anew +- Improved frames of CSS animations and transitions of the transform, opacity or filter of boxes, and scrolling pages with sticky boxes: the last frame is painted anew instead of the page being laid out (smapiot.com scrolls with about 4 ms instead of 400 ms per frame, AngleSharp.Renderer 0.11.4) +- Added `BrowserOptions.IsTextSelectionEnabled` for selecting the text of pages with the pointer (a double press selects a word, a triple one a paragraph, Shift extends) and Control+A, `PointerDownAsync` with the click count, and `CopySelectionAsync` for the clipboard; `BrowserView` passes the click count and copies with Control+C +- Added animated images (e.g. GIFs), whose frames are shown in turn without a layout of the page +- Added the text cursor over text that can be selected, unless the page asks for another cursor +- Added selecting text to the windows and the panels of `Vision` +- Added `BrowserOptions.SchemeHandlers` for custom URL schemes answered by the host +- Added audio: `audio` elements and `new Audio()` play WAV, MP3, Ogg Vorbis and Ogg Opus (managed decoders, `BrowserOptions.AudioCodecs`) on the host's `BrowserOptions.AudioOutput` (silently without one), audible media once the user interacted with the page (`BrowserOptions.IsAutoplayAllowed`), and stop once their document is left (AngleSharp 1.10.4, AngleSharp.Js 1.2.3); `audio controls` shows a player (play/pause, time, timeline, mute) that the pointer operates, and whose time goes on without a layout of the page (AngleSharp.Renderer 0.11.4); Vision plays the audio on the default device via OpenAL Soft +- Added suggestions of previously visited addresses to the address bar of `Vision`, the most popular first +- Added the `vision:` scheme to `Vision`, showing its own pages (e.g., `vision:settings`) or a list of them +- Added the start page `vision:start` to `Vision` (its new default start page), with the most visited pages, demos and Vision's own pages +- Added `BrowserEngine.History` (the entries with their titles) and `BrowserEngine.GoAsync` for jumping several entries; holding the back or forward button of `Vision` (or right-clicking it) shows the entries to jump to +- Added the requester `vision:requester` to `Vision`, which sends HTTP requests with the requesters of the window and shows their responses, and keeps requests saved under a name per profile (saved from a dialog, listed in a sheet opened from the top-left corner) + # 0.1.0 Released on Monday, November 9 2026. diff --git a/docs/general/02-Engine.md b/docs/general/02-Engine.md index ea5d732..0b885bb 100644 --- a/docs/general/02-Engine.md +++ b/docs/general/02-Engine.md @@ -14,10 +14,12 @@ The `BrowserEngine` represents a browsing context with its history, i.e., what a | `LoadHtmlAsync(html, address)` | Shows the given markup, optionally pretending it came from the given address. | | `ReloadAsync()` | Loads the current address again. | | `GoBackAsync()`, `GoForwardAsync()` | Moves through the history. | +| `GoAsync(delta)` | Jumps several entries back (negative) or forward. | +| `History` | A copy of the entries (address and title) and the index of the current one; `Back` and `Forward` list the entries before and after it, the closest first. | | `Url`, `Title`, `IsLoading` | The state of the current page. | | `CanGoBack`, `CanGoForward` | If there is something to go to. | -The address goes through `BrowserEngine.NormalizeAddress`, so what a user enters in an address bar works: `example.org` turns into `https://example.org`, while rooted paths of existing files turn into `file:` addresses. +The address goes through `BrowserEngine.NormalizeAddress`, so what a user enters in an address bar works: `example.org` turns into `https://example.org`, while rooted paths of existing files turn into `file:` addresses. Addresses of the custom schemes of the engine (`BrowserOptions.SchemeHandlers`) stay as they are. `Url` shows where the engine is going as soon as a navigation starts, like in any browser. A failed navigation does not throw: it raises `Error`, is recorded in the diagnostics, and shows an error page instead. diff --git a/docs/general/03-Rendering.md b/docs/general/03-Rendering.md index 5707830..38cb68f 100644 --- a/docs/general/03-Rendering.md +++ b/docs/general/03-Rendering.md @@ -41,6 +41,8 @@ if (frame is not null) Preparing a frame also refreshes what the engine knows for hit testing. The cursor and links are then looked up without touching the DOM, which keeps pointer moves responsive on busy pages. +Animated images (GIFs and WebPs of several frames) play on their own: when one in view shows its next frame, the engine raises `Invalidated`, and the next frame is the last one rasterized again, without a layout. An image plays from the moment it is first painted and as often as it tells, which is forever for most GIFs. + The first frame of a page shows up early: only what is in the viewport is styled and laid out for it. The engine asks for the next frame right away (it raises `Invalidated`), which lays out the whole page. Until then, the page below the viewport is blank, and the scroll position is not limited to the height of the page. ## Overscan and Scrolling diff --git a/docs/general/04-Input.md b/docs/general/04-Input.md index 829eee5..e1ded6e 100644 --- a/docs/general/04-Input.md +++ b/docs/general/04-Input.md @@ -15,6 +15,7 @@ All positions are in CSS pixels relative to the viewport. | `MovePointer(x, y)` | Moves the pointer without waiting. Moves are coalesced, which is what a UI should use. | | `MovePointerAsync(x, y)` | Moves the pointer and waits until the hover state has been updated. | | `PointerDownAsync(x, y, modifiers)` | Presses the primary button. | +| `PointerDownAsync(x, y, clickCount, modifiers)` | Presses the primary button for the given time in a row, e.g., 2 for a double click. | | `PointerUpAsync(x, y, modifiers)` | Releases the primary button. | | `ClickAsync(x, y, modifiers)` | Presses and releases the primary button. | | `HoveredLink`, `Cursor` | The link below the pointer and the `BrowserCursor` a host should display. | @@ -32,6 +33,26 @@ Holding Control while clicking a link requests a new window, as does a link with await engine.ClickAsync(40, 390, InputModifiers.Control); ``` +## Selecting Text + +With `BrowserOptions.IsTextSelectionEnabled`, the text of a page can be selected as in a browser. It is off by default, as the layouts then also record where their text comes from. + +- Pressing the button and moving the pointer with it held selects the text in between; with Shift, a press extends the selection. +- A second press in a row (`clickCount` 2) selects a word, a third one the paragraph. +- Control+A (or Cmd+A) selects all text of the page, unless a text field has the focus. +- Over text that can be selected, `Cursor` is `BrowserCursor.Text`, unless the page asks for another cursor. +- A page can cancel `mousedown` or `selectstart`, and `user-select: none` keeps text from being selected. Scripts see the selection through `getSelection()`. + +`CopySelectionAsync` fires `copy` and returns the selected text for the clipboard, or an empty text if nothing is selected or the page canceled the event: + +```cs +var engine = new BrowserEngine(new BrowserOptions { IsTextSelectionEnabled = true }); +await engine.LoadHtmlAsync("

Hello world

"); +await engine.PointerDownAsync(30, 20, 2); +await engine.PointerUpAsync(30, 20); +Console.WriteLine(await engine.CopySelectionAsync()); +``` + ## Keyboard 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: diff --git a/docs/general/05-Configuration.md b/docs/general/05-Configuration.md index 34b698d..8c70339 100644 --- a/docs/general/05-Configuration.md +++ b/docs/general/05-Configuration.md @@ -16,11 +16,16 @@ Everything that touches the outside world is configured via `BrowserOptions`, wh | `ColorScheme` | `null` | The answer to `prefers-color-scheme`, e.g., `light` or `dark`. | | `IsScriptingEnabled` | `true` | If JavaScript should be evaluated. | | `ClipboardPlatform` | `null` | The clipboard exposed to pages; `null` means the API is not available. | +| `IsTextSelectionEnabled` | `false` | If the text of pages can be selected with the pointer and Control+A. | | `ViewportWidth`, `ViewportHeight` | 1280, 800 | The initial viewport in CSS pixels. | | `ScreenWidth`, `ScreenHeight` | 1920, 1080 | The screen size reported to media queries. | | `FontSize` | 16 | The default font size in CSS pixels. | | `ConfigureIo` | `null` | A callback customizing the IO options. | | `Configure` | `null` | A callback extending the AngleSharp configuration. | +| `SchemeHandlers` | empty | Handlers answering the requests of custom URL schemes. | +| `AudioOutput` | `null` | Where the audio of pages plays; `null` plays it silently (`SilentAudioOutput`). | +| `AudioCodecs` | WAV, MP3, Ogg Vorbis, Ogg Opus | The audio formats that play, in the order they are tried. | +| `IsAutoplayAllowed` | `false` | If pages may play audible media before the user pressed or typed something. | ```cs var options = new BrowserOptions @@ -69,6 +74,58 @@ var options = new BrowserOptions }; ``` +## Custom Schemes + +`SchemeHandlers` registers URL schemes of the host, e.g., for its own pages. A handler gets the request and answers a response, or `null` if there is nothing at the address. Pages can link to these addresses, and `NavigateAsync` keeps them as they are (`Schemes` lists them; `BrowserEngine.NormalizeAddress(address, schemes)` does the same for an address bar): + +```cs +using System.IO; +using System.Net; +using System.Text; +using AngleSharp.Io; + +var options = new BrowserOptions(); +options.SchemeHandlers["app"] = (request, cancellationToken) => +{ + var response = new DefaultResponse + { + Address = request.Address, + StatusCode = HttpStatusCode.OK, + Content = new MemoryStream(Encoding.UTF8.GetBytes($"

{request.Address.Data}

")), + }; + response.Headers[HeaderNames.ContentType] = "text/html; charset=utf-8"; + return Task.FromResult(response); +}; + +using var engine = new BrowserEngine(options); +await engine.NavigateAsync("app:settings"); +``` + +The handlers are asked before the built-in requesters, so a handler for `http` would take over the network. + +## Audio + +Pages play audio with `audio` elements and `new Audio(src)`, including `play()` (a promise), `pause()`, `currentTime`, `volume`, `muted`, `loop`, `autoplay` and their events (`playing`, `timeupdate`, `ended`, ...). The formats of `AudioCodecs` are decoded with managed code only: WAV (PCM or floats), MP3 (NLayer), Ogg Vorbis (NVorbis) and Ogg Opus (Concentus). Other formats (e.g. AAC in MP4) answer an empty `canPlayType`, so pages offering several `source` elements get one that plays, and fail with an `error` (`MEDIA_ERR_SRC_NOT_SUPPORTED`) otherwise. The engine reads the whole file before it plays. + +Where the audio is heard is up to the host, as it depends on the platform. An `IAudioOutput` opens a stream per media element playing, which pulls the samples (32-bit floats, the channels interleaved) as it plays them; the media's clock advances with what was pulled: + +```cs +sealed class DeviceOutput : IAudioOutput +{ + public IAudioStream Open(AudioFormat format, IAudioSource source) => + new DeviceStream(format, source); // e.g. an OpenAL source fed from source.Read +} + +var options = new BrowserOptions +{ + AudioOutput = new DeviceOutput(), +}; +``` + +Vision plays on the default device via OpenAL Soft (`src/Vision/Audio/OpenAlAudioOutput.cs`, using Silk.NET.OpenAL), which can serve as a starting point. Without an output, the media plays silently in real time, with its events and its end, which is what tests and automation want. Like browsers, audible media only plays once the user pressed or typed something on the page (`play()` rejects with a `NotAllowedError` before); muted media always plays, and `IsAutoplayAllowed` lifts the rule. Media stops once its document is left. + +An `audio` element with the `controls` attribute shows the controls of Chrome (300x54 by default): a play/pause button, the time, a timeline and a mute button. A press on them plays, pauses, mutes or seeks (also while the timeline is dragged); the hit testing is AngleSharp.Renderer's `GetMediaControlAt` and `GetMediaTimelinePosition`. While media plays, the time and the timeline go on in the last frame (rasterized again, like the frames of a GIF) without a layout; only playing, pausing, seeking or a change of the volume lays the page out. One without `controls` is not rendered. + ## Multiple Windows One engine stands for one window. When a page asks for another window (a link with `target="_blank"`, or a link clicked with Control), the engine raises `WindowRequested`. If the request is not marked as handled the page navigates in place, so there is nothing to do if a host only has a single window. diff --git a/docs/general/06-Avalonia.md b/docs/general/06-Avalonia.md index 197f01b..bb5dd49 100644 --- a/docs/general/06-Avalonia.md +++ b/docs/general/06-Avalonia.md @@ -93,7 +93,7 @@ Engine events may be raised on any thread, so they are dispatched here. To open ## Input Handling -The control has to be focused to get keyboard input; clicking it does that. Shortcuts with Control or Alt stay unhandled, so `KeyBinding`s of the window work while the page is focused. Control+V pastes into the focused text field, and the extra mouse buttons go back and forward in the history. +The control has to be focused to get keyboard input; clicking it does that. Shortcuts with Control or Alt stay unhandled, so `KeyBinding`s of the window work while the page is focused. Control+V pastes into the focused text field, Control+C copies the selected text and Control+A selects all of it (with `BrowserOptions.IsTextSelectionEnabled`), and the extra mouse buttons go back and forward in the history. ## Namespace Hint diff --git a/docs/general/07-Vision.md b/docs/general/07-Vision.md index 19d8cf2..47ed878 100644 --- a/docs/general/07-Vision.md +++ b/docs/general/07-Vision.md @@ -18,6 +18,8 @@ dotnet run --project src/Vision -- https://example.org | `--profile ` | The directory to use for cookies, web storage and the HTTP cache. | | `--in-memory` | Persists no browsing data. | +New windows open `vision:start` unless the settings say otherwise: the pages visited most, a few demos and Vision's own pages. All of Vision's pages are listed at `vision:pages`; `vision:requester` sends HTTP requests with the requesters of the window (with its user agent, default headers and cookies) and shows the responses. Requests can be saved there under a name (the button below the response asks for it), and are kept with the profile (`requests.json`); the menu button in the top-left corner opens a sheet with the saved ones. + The profile and the settings are kept in the `Vision` folder of the local application data directory by default. ## What to Look At @@ -28,4 +30,5 @@ The profile and the settings are kept in the `Vision` folder of the local applic | `ViewModels/MainViewModel.cs` | A toolbar and status bar on top of the engine's state and events, including the page's icon. | | `Views/MainWindow.axaml` | Placing `BrowserView` in a window, next to a second one for the diagnostics. | | `Models/BrowserSettings.cs` | Turning user settings into `BrowserOptions`. | -| `Pages/` | The app's own UI (diagnostics, inspector, settings, site information, about) written as HTML and CSS, and wired up with .NET event handlers through `InvokeAsync`, in an engine with scripting disabled. | +| `Audio/OpenAlAudioOutput.cs` | An `IAudioOutput` playing the audio of pages on the default device (OpenAL Soft via Silk.NET), shared by all windows, silent without a device. | +| `Pages/` | The app's own UI (start page, requester, diagnostics, inspector, settings, site information, about) written as HTML and CSS, and wired up with .NET event handlers through `InvokeAsync`, in an engine with scripting disabled. Their text can be selected and copied like the one of pages. | diff --git a/docs/tutorials/01-API.md b/docs/tutorials/01-API.md index 52f5fc4..bf5dc36 100644 --- a/docs/tutorials/01-API.md +++ b/docs/tutorials/01-API.md @@ -10,7 +10,7 @@ The following APIs cover most day-to-day tasks: - `new BrowserEngine(options)` : Creates a browsing context with a history; dispose it when done. -- `NavigateAsync`, `LoadHtmlAsync`, `ReloadAsync`, `GoBackAsync`, `GoForwardAsync` +- `NavigateAsync`, `LoadHtmlAsync`, `ReloadAsync`, `GoBackAsync`, `GoForwardAsync`, `GoAsync` : Changes what is shown. - `InvokeAsync`, `EvaluateScriptAsync` : Runs .NET code against the DOM, or JavaScript in the page. @@ -50,7 +50,8 @@ The following APIs cover most day-to-day tasks: | `NormalizeAddress(address)` | Turns the input of an address bar into an absolute address (static). | | `NavigateAsync(address)` | Loads an address. | | `LoadHtmlAsync(html, address)` | Shows the given source code. | -| `ReloadAsync()`, `GoBackAsync()`, `GoForwardAsync()` | Moves in the history. | +| `ReloadAsync()`, `GoBackAsync()`, `GoForwardAsync()`, `GoAsync(delta)` | Moves in the history. | +| `History` | A copy of the history's entries (address and title) and the index of the current one. | | `Resize(width, height)` | Changes the viewport. | | `PaintAsync()` | Returns a `RenderedImage` with a PNG, or `null`. | | `PrepareFrameAsync()` | Returns a `BrowserFrame`, or `null`. | @@ -58,6 +59,7 @@ The following APIs cover most day-to-day tasks: | `InvokeAsync(action)` | Runs code on the event loop, and returns its value. | | `MovePointer`, `MovePointerAsync`, `PointerDownAsync`, `PointerUpAsync`, `ClickAsync` | Pointer input. | | `KeyDownAsync`, `KeyUpAsync`, `TextInputAsync` | Keyboard input. | +| `CopySelectionAsync()` | Gets the selected text for the clipboard. | | `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. | diff --git a/docs/tutorials/03-Custom-Host.md b/docs/tutorials/03-Custom-Host.md index 257ca01..64261a7 100644 --- a/docs/tutorials/03-Custom-Host.md +++ b/docs/tutorials/03-Custom-Host.md @@ -85,8 +85,9 @@ Translate the events of the framework. All of these are fire-and-forget from the | UI event | Engine call | | --- | --- | | Pointer moved | `MovePointer(x, y)` | -| Primary button pressed / released | `PointerDownAsync` / `PointerUpAsync` | +| Primary button pressed / released | `PointerDownAsync` (with the click count, for selecting words) / `PointerUpAsync` | | Back / forward button pressed | `GoBackAsync` / `GoForwardAsync` | +| Back / forward button held (its menu) | `History.Back` / `History.Forward`, then `GoAsync(delta)` for the entry chosen | | Wheel | `ScrollAsync(-deltaX * distance, -deltaY * distance)` | | Key pressed / released | `KeyDownAsync` / `KeyUpAsync`, with the DOM's name of the key | | Text entered | `TextInputAsync` | @@ -98,6 +99,7 @@ Translate the events of the framework. All of these are fire-and-forget from the What else makes it feel like a browser: - Set `BrowserOptions.ClipboardPlatform` with an implementation of `IClipboardPlatform` from AngleSharp.Io. +- Set `BrowserOptions.IsTextSelectionEnabled`, and put the text of `CopySelectionAsync` on the clipboard for Control+C. - 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`. diff --git a/src/AngleSharp.Browser.Avalonia.Tests/BrowserViewTests.cs b/src/AngleSharp.Browser.Avalonia.Tests/BrowserViewTests.cs index 35b132a..ed43cd2 100644 --- a/src/AngleSharp.Browser.Avalonia.Tests/BrowserViewTests.cs +++ b/src/AngleSharp.Browser.Avalonia.Tests/BrowserViewTests.cs @@ -30,6 +30,23 @@ public async Task SettingTheSourceCreatesAnEngineAndNavigates() window.Close(); } + [AvaloniaTest] + public async Task PressingAModifierOnItsOwnSendsItToThePage() + { + var page = "data:text/html," + Uri.EscapeDataString("Keys"); + var view = new BrowserView { Source = page }; + var window = Show(view); + await WaitUntil(() => view.Engine?.Title == "Keys"); + view.Focus(); + + // a game firing on Control (keyCode 17), like the Spaceshoot sample of Piral + window.KeyPress(Key.LeftCtrl, RawInputModifiers.Control, PhysicalKey.ControlLeft, null); + window.KeyPress(Key.RightShift, RawInputModifiers.Shift, PhysicalKey.ShiftRight, null); + + await WaitUntilAsync(async () => await view.Engine!.EvaluateScriptAsync("window.seen.join()") as string == "Control:17,Shift:16"); + window.Close(); + } + [AvaloniaTest] public void WithoutASourceNoEngineIsCreated() { diff --git a/src/AngleSharp.Browser.Avalonia.Tests/VisionAddressTests.cs b/src/AngleSharp.Browser.Avalonia.Tests/VisionAddressTests.cs new file mode 100644 index 0000000..dc726bf --- /dev/null +++ b/src/AngleSharp.Browser.Avalonia.Tests/VisionAddressTests.cs @@ -0,0 +1,524 @@ +using System; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Threading.Tasks; +using AngleSharp.Dom; +using AngleSharp.Html.Dom; +using Avalonia.Headless.NUnit; +using Avalonia.Threading; +using NUnit.Framework; +using Vision.Models; +using Vision.Pages; +using Vision.ViewModels; + +namespace AngleSharp.Browser.Avalonia.Tests; + +/// +/// The address bar of Vision: its suggestions and the browser's own pages (vision:). +/// +[TestFixture] +public class VisionAddressTests +{ + [Test] + public void SuggestionsAreSortedByPopularityThenBySimilarity() + { + var history = new UrlHistory(); + Visit(history, "https://github.com/AngleSharp/AngleSharp", 1); + Visit(history, "https://github.com/", 3); + Visit(history, "https://gist.github.com/", 3); + Visit(history, "https://example.org/", 9); + + var suggestions = history.Suggest("github.com").Select(m => m.Url).ToArray(); + + // equally popular: the one closer to what was typed comes first + Assert.That(suggestions, Is.EqualTo(new[] { "https://github.com/", "https://gist.github.com/", "https://github.com/AngleSharp/AngleSharp" })); + } + + [Test] + public void SuggestionsMatchTitlesAndLeaveOutBlankPages() + { + var history = new UrlHistory(); + history.Record("https://anglesharp.github.io/#docs", "AngleSharp Documentation"); + history.Record("about:blank"); + history.Record("data:text/html,documentation"); + + var suggestions = history.Suggest("documentation"); + + Assert.That(suggestions.Select(m => m.Url), Is.EqualTo(new[] { "https://anglesharp.github.io/" })); + Assert.That(suggestions[0].Heading, Is.EqualTo("AngleSharp Documentation")); + Assert.That(history.Suggest(" "), Is.Empty); + } + + [Test] + public void TheHistoryIsKeptInItsDirectory() + { + var directory = Directory.CreateTempSubdirectory("vision-history-").FullName; + + try + { + var history = new UrlHistory(directory); + Visit(history, "https://example.org/", 2); + history.SetTitle("https://example.org/", "Example"); + + var loaded = new UrlHistory(directory).Suggest("example"); + + Assert.That(loaded, Has.Count.EqualTo(1)); + Assert.That(loaded[0], Is.EqualTo(new UrlSuggestion("https://example.org/", "Example", 2))); + } + finally + { + Directory.Delete(directory, true); + } + } + + [Test] + public void SimilarityGoesFromNothingToTheSame() + { + Assert.That(UrlHistory.GetSimilarity("github.com", "github.com"), Is.EqualTo(1)); + Assert.That(UrlHistory.GetSimilarity("GitHub.com", "github.com"), Is.EqualTo(1)); + Assert.That(UrlHistory.GetSimilarity("abc", "xyz"), Is.EqualTo(0)); + Assert.That(UrlHistory.GetSimilarity("github", "github.com"), Is.GreaterThan(UrlHistory.GetSimilarity("github", "github.com/AngleSharp"))); + } + + [AvaloniaTest] + public async Task TheArrowKeysChooseTheSuggestionToNavigateTo() + { + var history = new UrlHistory(); + Visit(history, "vision:about", 2); + Visit(history, "vision:settings", 1); + var host = new TestHost(); + using var engine = CreateEngine(host, out var pages); + using var viewModel = new MainViewModel(engine, "about:blank", host, history); + + viewModel.Address = "vision"; + + Assert.That(viewModel.IsSuggesting, Is.True); + Assert.That(viewModel.Suggestions.Select(m => m.Url), Is.EqualTo(new[] { "vision:about", "vision:settings" })); + Assert.That(viewModel.SelectedSuggestionIndex, Is.EqualTo(-1)); + + // down to the second one, up and around back to it + Assert.That(viewModel.MoveSuggestion(1), Is.True); + Assert.That(viewModel.MoveSuggestion(1), Is.True); + Assert.That(viewModel.SelectedSuggestionIndex, Is.EqualTo(1)); + viewModel.MoveSuggestion(1); + Assert.That(viewModel.SelectedSuggestionIndex, Is.EqualTo(-1)); + viewModel.MoveSuggestion(-1); + Assert.That(viewModel.SelectedSuggestionIndex, Is.EqualTo(1)); + + await viewModel.NavigateCommand.ExecuteAsync(null); + + Assert.That(viewModel.IsSuggesting, Is.False); + Assert.That(viewModel.Address, Is.EqualTo("vision:settings")); + Assert.That(engine.Url, Is.EqualTo("vision:settings")); + pages.Dispose(); + } + + [AvaloniaTest] + public async Task TheHistoryButtonsJumpToTheEntriesTheyList() + { + var host = new TestHost(); + using var engine = CreateEngine(host, out var pages); + using var viewModel = new MainViewModel(engine, "about:blank", host); + + await engine.NavigateAsync("vision:about"); + await engine.NavigateAsync("vision:settings"); + await engine.NavigateAsync("vision:start"); + + var back = viewModel.GetHistoryJumps(isBack: true); + Assert.That(back.Select(m => (m.Delta, m.Url)), Is.EqualTo(new[] { (-1, "vision:settings"), (-2, "vision:about") })); + Assert.That(back.All(m => m.Heading.Length > 0), Is.True); + Assert.That(viewModel.GetHistoryJumps(isBack: false), Is.Empty); + + await viewModel.JumpAsync(back[1]); + + Assert.That(engine.Url, Is.EqualTo("vision:about")); + Assert.That(viewModel.GetHistoryJumps(isBack: false).Select(m => (m.Delta, m.Url)), + Is.EqualTo(new[] { (1, "vision:settings"), (2, "vision:start") })); + pages.Dispose(); + } + + [AvaloniaTest] + public async Task WithoutAChosenSuggestionTheTypedAddressIsUsed() + { + var history = new UrlHistory(); + Visit(history, "vision:about", 1); + var host = new TestHost(); + using var engine = CreateEngine(host, out var pages); + using var viewModel = new MainViewModel(engine, "about:blank", host, history); + + viewModel.Address = "vision:pages"; + Assert.That(viewModel.IsSuggesting, Is.False); + viewModel.Address = "vision:"; + Assert.That(viewModel.IsSuggesting, Is.True); + Assert.That(viewModel.CloseSuggestions(), Is.True); + Assert.That(viewModel.MoveSuggestion(1), Is.False); + + await viewModel.NavigateCommand.ExecuteAsync(null); + + Assert.That(engine.Url, Is.EqualTo("vision:")); + pages.Dispose(); + } + + [AvaloniaTest] + public async Task TheSettingsAreAVisionPage() + { + var host = new TestHost(); + using var engine = CreateEngine(host, out var pages); + + await engine.NavigateAsync("vision:settings"); + + await WaitUntil(engine, d => d?.GetElementById("start-page") is IHtmlInputElement { Value: BrowserSettings.DefaultStartPage }); + Assert.That(engine.Title, Is.EqualTo("Settings")); + + // the page is wired up: the button works + await engine.InvokeAsync(d => ((IHtmlElement)d!.GetElementById("reset")!).DoClick()); + await WaitUntil(engine, d => d!.GetElementById("status")!.TextContent.Contains("Defaults restored")); + pages.Dispose(); + } + + [AvaloniaTest] + public async Task AnUnknownVisionPageListsThePagesThereAre() + { + var host = new TestHost(); + using var engine = CreateEngine(host, out var pages); + + await engine.NavigateAsync("vision:nothing"); + + var (notice, links) = await engine.InvokeAsync(d => ( + d!.GetElementById("notice")?.TextContent, + d.QuerySelectorAll("#pages a").Select(m => m.GetAttribute("href")).ToArray())); + Assert.That(notice, Does.Contain("vision:nothing")); + 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 engine.NavigateAsync("vision:pages"); + Assert.That(await engine.InvokeAsync(d => d!.GetElementById("notice")), Is.Null); + pages.Dispose(); + } + + [AvaloniaTest] + public async Task TheStartPageShowsTheMostVisitedPagesDemosAndVisionPages() + { + var history = new UrlHistory(); + Visit(history, "vision:settings", 9); + + for (var i = 1; i <= 7; i++) + { + Visit(history, $"https://example.org/{i}", i); + } + + history.SetTitle("https://example.org/7", "Seven"); + var host = new TestHost(); + using var engine = CreateEngine(host, out var pages, history); + + await engine.NavigateAsync("vision:start"); + + var (visited, demos, vision, heading) = await engine.InvokeAsync(d => ( + d!.QuerySelectorAll("#most-visited a").Select(m => m.GetAttribute("href")).ToArray(), + d.QuerySelectorAll("#demos a").Select(m => m.GetAttribute("href")).ToArray(), + 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(heading, Is.EqualTo("Seven")); + Assert.That(demos, Has.Length.EqualTo(5)); + Assert.That(demos, Does.Contain("https://news.ycombinator.com")); + Assert.That(vision, Is.EqualTo(new[] { "vision:requester", "vision:settings", "vision:about" })); + Assert.That(BrowserSettings.DefaultStartPage, Is.EqualTo("vision:start")); + pages.Dispose(); + } + + [AvaloniaTest] + public async Task TheStartPageWithoutAHistoryTellsWhatWillBeThere() + { + var host = new TestHost(); + using var engine = CreateEngine(host, out var pages); + + await engine.NavigateAsync("vision:start"); + + var empty = await engine.InvokeAsync(d => d!.QuerySelector("#most-visited .empty")?.TextContent); + Assert.That(empty, Does.Contain("visit most")); + pages.Dispose(); + } + + [AvaloniaTest] + public async Task TheRequesterSendsWithTheRequestersOfTheEngine() + { + var host = new TestHost(); + using var engine = CreateEngine(host, out var pages); + + await engine.NavigateAsync("vision:requester"); + await WaitUntil(engine, d => d?.QuerySelectorAll("#requester option").Length > 1); + + // the browser's own pages come from a requester as well + await engine.InvokeAsync(d => + { + ((IHtmlInputElement)d!.GetElementById("url")!).Value = "vision:about"; + ((IHtmlElement)d.GetElementById("send")!).DoClick(); + }); + await WaitUntil(engine, d => d!.GetElementById("response-status")!.TextContent == "200 OK"); + + var (body, headers, requester) = await engine.InvokeAsync(d => ( + d!.GetElementById("body-text")!.TextContent, + d.GetElementById("headers-list")!.TextContent, + d.GetElementById("response-requester")!.TextContent)); + Assert.That(body, Does.Contain("About")); + Assert.That(headers, Does.Contain("text/html")); + Assert.That(requester, Is.EqualTo("Scheme")); + pages.Dispose(); + } + + [AvaloniaTest] + public async Task TheRequesterPostsABodyWithTheDefaultHeaders() + { + using var listener = new HttpListener(); + var port = GetFreePort(); + listener.Prefixes.Add($"http://127.0.0.1:{port}/"); + listener.Start(); + var received = Task.Run(async () => + { + var context = await listener.GetContextAsync(); + using var reader = new StreamReader(context.Request.InputStream); + var request = (context.Request.HttpMethod, Body: await reader.ReadToEndAsync(), Type: context.Request.ContentType, Test: context.Request.Headers["X-Test"]); + context.Response.ContentType = "application/json"; + var answer = System.Text.Encoding.UTF8.GetBytes("{\"ok\":true}"); + await context.Response.OutputStream.WriteAsync(answer); + context.Response.Close(); + return request; + }); + var host = new TestHost(); + var options = new BrowserOptions { ProfileDirectory = null, ViewportWidth = 800, ViewportHeight = 600 }; + options.DefaultHeaders["X-Test"] = "default"; + using var engine = CreateEngine(host, out var pages, options: options); + + await engine.NavigateAsync("vision:requester"); + await WaitUntil(engine, d => d?.QuerySelectorAll("#requester option").Length > 1); + await engine.InvokeAsync(d => + { + ((IHtmlSelectElement)d!.GetElementById("method")!).Value = "Post"; + ((IHtmlInputElement)d.GetElementById("url")!).Value = $"http://127.0.0.1:{port}/echo"; + ((IHtmlTextAreaElement)d.GetElementById("body")!).Value = "{\"name\":\"Vision\"}"; + ((IHtmlElement)d.GetElementById("send")!).DoClick(); + }); + await WaitUntil(engine, d => d!.GetElementById("response-status")!.TextContent == "200 OK"); + + var request = await received; + Assert.That(request.HttpMethod, Is.EqualTo("POST")); + Assert.That(request.Body, Is.EqualTo("{\"name\":\"Vision\"}")); + Assert.That(request.Type, Does.StartWith("application/json")); + Assert.That(request.Test, Is.EqualTo("default")); + // JSON is shown indented, and what was sent includes the default headers + var (body, sent) = await engine.InvokeAsync(d => ( + d!.GetElementById("body-text")!.TextContent, + d.GetElementById("request-headers")!.TextContent)); + Assert.That(body, Does.Contain("\"ok\": true")); + Assert.That(sent, Does.Contain("X-Test")); + pages.Dispose(); + } + + [AvaloniaTest] + public async Task TheRequesterTellsWhatIsWrongWithARequest() + { + var host = new TestHost(); + using var engine = CreateEngine(host, out var pages); + + await engine.NavigateAsync("vision:requester"); + await WaitUntil(engine, d => d?.QuerySelectorAll("#requester option").Length > 1); + await engine.InvokeAsync(d => + { + ((IHtmlTextAreaElement)d!.GetElementById("body")!).Value = "text"; + ((IHtmlElement)d.GetElementById("send")!).DoClick(); + }); + + var status = await engine.InvokeAsync(d => d!.GetElementById("status")!.TextContent); + Assert.That(status, Does.Contain("GET request has no body")); + pages.Dispose(); + } + + [AvaloniaTest] + public async Task TheRequesterSavesRestoresAndDeletesRequests() + { + var host = new TestHost(); + var saved = new SavedRequests(); + using var engine = CreateEngine(host, out var pages, requests: saved); + + await engine.NavigateAsync("vision:requester"); + await WaitUntil(engine, d => d?.QuerySelectorAll("#requester option").Length > 1); + Assert.That(await engine.InvokeAsync(d => d!.QuerySelector("#saved .none")), Is.Not.Null); + + // the button below the response asks for a name, the method and address by default + await engine.InvokeAsync(d => + { + ((IHtmlSelectElement)d!.GetElementById("method")!).Value = "Post"; + ((IHtmlInputElement)d.GetElementById("url")!).Value = "https://example.org/api/items"; + ((IHtmlTextAreaElement)d.GetElementById("body")!).Value = "{}"; + ((IHtmlElement)d.GetElementById("save")!).DoClick(); + }); + // the click is dispatched after this + await WaitUntil(engine, d => d!.GetElementById("modal")!.ClassList.Contains("open")); + Assert.That(await engine.InvokeAsync(d => ((IHtmlInputElement)d!.GetElementById("name")!).Value), Is.EqualTo("POST example.org/api/items")); + await engine.InvokeAsync(d => ((IHtmlElement)d!.GetElementById("save-confirm")!).DoClick()); + await WaitUntil(engine, d => d!.QuerySelectorAll("#saved .item").Length == 1 && !d.GetElementById("modal")!.ClassList.Contains("open")); + Assert.That(await engine.InvokeAsync(d => d!.GetElementById("menu-count")!.TextContent), Is.EqualTo("1")); + + // cancelling saves nothing + await engine.InvokeAsync(d => ((IHtmlElement)d!.GetElementById("save")!).DoClick()); + await WaitUntil(engine, d => d!.GetElementById("modal")!.ClassList.Contains("open")); + await engine.InvokeAsync(d => ((IHtmlElement)d!.GetElementById("save-cancel")!).DoClick()); + await WaitUntil(engine, d => !d!.GetElementById("modal")!.ClassList.Contains("open")); + + await engine.InvokeAsync(d => ((IHtmlElement)d!.GetElementById("save")!).DoClick()); + await WaitUntil(engine, d => d!.GetElementById("modal")!.ClassList.Contains("open")); + await engine.InvokeAsync(d => + { + ((IHtmlInputElement)d!.GetElementById("name")!).Value = "Items"; + ((IHtmlElement)d.GetElementById("save-confirm")!).DoClick(); + }); + await WaitUntil(engine, d => d!.QuerySelectorAll("#saved .item").Length == 2); + Assert.That(saved.All.Select(m => m.Name), Is.EqualTo(new[] { "Items", "POST example.org/api/items" })); + Assert.That(saved.Find("items")!.Body, Is.EqualTo("{}")); + + // the saved requests are in the sheet the menu button opens + await engine.InvokeAsync(d => ((IHtmlElement)d!.GetElementById("menu")!).DoClick()); + await WaitUntil(engine, d => d!.GetElementById("sheet")!.ClassList.Contains("open")); + + // what the form shows is replaced by the saved request, which closes the sheet + await engine.InvokeAsync(d => + { + ((IHtmlSelectElement)d!.GetElementById("method")!).Value = "Get"; + ((IHtmlInputElement)d.GetElementById("url")!).Value = "https://other.org/"; + ((IHtmlTextAreaElement)d.GetElementById("body")!).Value = string.Empty; + ((IHtmlElement)d.QuerySelector("#saved .item[data-name='Items'] .name")!).DoClick(); + }); + await WaitUntil(engine, d => d!.QuerySelector("#saved .item.active") is not null); + var (method, url, body, active, methodClass) = await engine.InvokeAsync(d => ( + ((IHtmlSelectElement)d!.GetElementById("method")!).Value, + ((IHtmlInputElement)d.GetElementById("url")!).Value, + ((IHtmlTextAreaElement)d.GetElementById("body")!).Value, + d.QuerySelector("#saved .item.active")?.GetAttribute("data-name"), + d.GetElementById("method")!.ClassName)); + Assert.That((method, url, body, active), Is.EqualTo(("Post", "https://example.org/api/items", "{}", "Items"))); + Assert.That(methodClass, Does.Contain("post")); + Assert.That(await engine.InvokeAsync(d => d!.GetElementById("sheet")!.ClassList.Contains("open")), Is.False); + + await engine.InvokeAsync(d => ((IHtmlElement)d!.QuerySelector("#saved .item[data-name='Items'] .remove")!).DoClick()); + await WaitUntil(engine, d => d!.QuerySelectorAll("#saved .item").Length == 1); + Assert.That(saved.Find("Items"), Is.Null); + pages.Dispose(); + } + + [Test] + public void SavedRequestsAreKeptInTheirDirectory() + { + var directory = Directory.CreateTempSubdirectory("vision-requests-").FullName; + + try + { + var requests = new SavedRequests(directory); + requests.Save(new SavedRequest("First", "Get", "https://example.org/", "Accept: */*", string.Empty, null, true)); + requests.Save(new SavedRequest("Second", "Post", "https://example.org/", string.Empty, "x", "HttpClient", false)); + requests.Save(new SavedRequest("first", "Delete", "https://example.org/1", string.Empty, string.Empty, null, true)); + + var loaded = new SavedRequests(directory).All; + + // saving a name again replaces the request, the most recent first + Assert.That(loaded.Select(m => (m.Name, m.Method)), Is.EqualTo(new[] { ("first", "Delete"), ("Second", "Post") })); + Assert.That(loaded[1].Requester, Is.EqualTo("HttpClient")); + } + finally + { + Directory.Delete(directory, true); + } + } + + [TestCase("vision:settings", "settings")] + [TestCase("vision://About/", "about")] + [TestCase("vision:settings?x=1#y", "settings")] + [TestCase("vision:", "")] + public void TheNameOfAVisionPageComesFromItsAddress(string url, string name) + { + Assert.That(VisionPages.GetName(url), Is.EqualTo(name)); + } + + private static void Visit(UrlHistory history, string url, int times) + { + for (var i = 0; i < times; i++) + { + history.Record(url); + } + } + + private static BrowserEngine CreateEngine(IBrowserHost host, out VisionPages pages, UrlHistory? history = null, BrowserOptions? options = null, SavedRequests? requests = null) + { + options ??= new BrowserOptions { ProfileDirectory = null, ViewportWidth = 800, ViewportHeight = 600 }; + pages = new VisionPages(host, history, requests); + options.SchemeHandlers[VisionPages.Scheme] = pages.HandleAsync; + var engine = new BrowserEngine(options); + pages.Attach(engine); + return engine; + } + + private static int GetFreePort() + { + var socket = new TcpListener(IPAddress.Loopback, 0); + socket.Start(); + var port = ((IPEndPoint)socket.LocalEndpoint).Port; + socket.Stop(); + return port; + } + + private static async Task WaitUntil(BrowserEngine engine, Func<IDocument?, bool> condition) + { + var deadline = DateTime.UtcNow.AddSeconds(10); + + while (!await engine.InvokeAsync(condition)) + { + Assert.That(DateTime.UtcNow, Is.LessThan(deadline), "Condition was not met in time."); + Dispatcher.UIThread.RunJobs(); + await Task.Delay(20); + } + } + + private sealed class TestHost : IBrowserHost + { + // like the application, whose theme is an Avalonia property + public string ColorScheme + { + get + { + Dispatcher.UIThread.VerifyAccess(); + return "light"; + } + } + + public string StartPage => "about:blank"; + + public event EventHandler? ColorSchemeChanged + { + add { } + remove { } + } + + public HtmlPage CreateSettingsPage(Action close) => new SettingsPage(ColorScheme, new BrowserSettings(), _ => null, close); + + public void OpenWindow(string? address, BrowserEngine? opener) + { + } + + public void OpenSettings() + { + } + + public void OpenAbout(BrowserEngine owner) + { + } + + public void OpenSiteInfo(BrowserEngine owner) + { + } + } +} diff --git a/src/AngleSharp.Browser.Avalonia.Tests/VisionPanelTests.cs b/src/AngleSharp.Browser.Avalonia.Tests/VisionPanelTests.cs index f714982..3af1d46 100644 --- a/src/AngleSharp.Browser.Avalonia.Tests/VisionPanelTests.cs +++ b/src/AngleSharp.Browser.Avalonia.Tests/VisionPanelTests.cs @@ -51,6 +51,24 @@ public async Task TheInspectorShowsTheCurrentDom() await WaitUntil(page, d => Tree(d).Contains("article")); } + [AvaloniaTest] + public async Task TheTextOfAPanelCanBeSelectedButNotItsTabs() + { + await _target.LoadHtmlAsync(Page); + using var page = new InspectorPage("light", _target); + await page.LoadAsync(); + await WaitUntil(page, d => FindRow(d, "h1") is not null); + await page.Engine.PrepareFrameAsync(); + await page.Engine.PrepareFrameAsync(); + + await page.Engine.KeyDownAsync("a", InputModifiers.Control); + var all = await page.Engine.CopySelectionAsync(); + var tabs = await page.Engine.InvokeAsync(d => d!.QuerySelector(".tab")!.TextContent.Trim()); + + Assert.That(all, Does.Contain("h1")); + Assert.That(all, Does.Not.Contain(tabs)); + } + [AvaloniaTest] public async Task SelectingAnElementShowsItsAttributesRulesAndComputedStyle() { @@ -215,6 +233,20 @@ public async Task TheSiteInformationShowsTheCertificateAndItsChain() Assert.That(text, Does.Contain("(in 29 days)").Or.Contain("(in 30 days)")); } + [AvaloniaTest] + public async Task TheAboutPageShowsTheVisionLogo() + { + using var page = new AboutPage("light", () => { }); + await page.LoadAsync(); + await WaitUntil(page, d => d!.QuerySelector<IHtmlImageElement>(".logo img") is { IsCompleted: true }); + + var logo = await page.Engine.InvokeAsync(d => d!.QuerySelector<IHtmlImageElement>(".logo img")!); + + // a vector, so it stays sharp at any scale + Assert.That(logo.Source, Does.StartWith("data:image/svg+xml;")); + Assert.That(logo.AlternativeText, Is.EqualTo("Vision logo")); + } + private static string Tree(IDocument? document) => document!.GetElementById("tree")!.TextContent; private static IElement? FindRow(IDocument? document, string tag) diff --git a/src/AngleSharp.Browser.Avalonia/BrowserView.cs b/src/AngleSharp.Browser.Avalonia/BrowserView.cs index e7dc88b..613e968 100644 --- a/src/AngleSharp.Browser.Avalonia/BrowserView.cs +++ b/src/AngleSharp.Browser.Avalonia/BrowserView.cs @@ -67,8 +67,21 @@ public sealed class BrowserView : Control [Key.PageDown] = "PageDown", [Key.Home] = "Home", [Key.End] = "End", + [Key.Insert] = "Insert", + [Key.LeftCtrl] = "Control", + [Key.RightCtrl] = "Control", + [Key.LeftShift] = "Shift", + [Key.RightShift] = "Shift", + [Key.LeftAlt] = "Alt", + [Key.RightAlt] = "Alt", + [Key.LWin] = "Meta", + [Key.RWin] = "Meta", }; + // pressing a modifier on its own is a key of the page (e.g. Control firing in a game), while + // the window still gets it for its shortcuts + private static bool IsModifierKey(string key) => key is "Control" or "Shift" or "Alt" or "Meta"; + private readonly Cursor _arrowCursor = new(StandardCursorType.Arrow); private readonly Cursor _handCursor = new(StandardCursorType.Hand); private readonly Cursor _textCursor = new(StandardCursorType.Ibeam); @@ -262,7 +275,7 @@ protected override void OnPointerPressed(PointerPressedEventArgs e) { case PointerUpdateKind.LeftButtonPressed: Focus(); - Observe(_engine?.PointerDownAsync(point.Position.X, point.Position.Y, GetModifiers(e.KeyModifiers))); + Observe(_engine?.PointerDownAsync(point.Position.X, point.Position.Y, e.ClickCount, GetModifiers(e.KeyModifiers))); e.Handled = true; break; case PointerUpdateKind.XButton1Pressed: @@ -321,11 +334,22 @@ protected override async void OnKeyDown(KeyEventArgs e) e.Handled = true; await PasteAsync(engine); } + else if (e.Key == Key.C && e.KeyModifiers.HasFlag(KeyModifiers.Control)) + { + e.Handled = true; + await CopyAsync(engine); + } + else if (e.Key == Key.A && e.KeyModifiers.HasFlag(KeyModifiers.Control)) + { + // the page sees the shortcut, and selects all of its text unless it cancels it + e.Handled = true; + Observe(engine.KeyDownAsync("a", GetModifiers(e.KeyModifiers))); + } else if (SpecialKeys.TryGetValue(e.Key, out var key) || !e.KeyModifiers.HasFlag(KeyModifiers.Control) && !e.KeyModifiers.HasFlag(KeyModifiers.Alt)) { // shortcuts with control or alt are left to the window; keys producing // characters stay unhandled, as Avalonia only raises TextInput for those - e.Handled = key is not null && key != " "; + e.Handled = key is not null && key != " " && !IsModifierKey(key); Observe(engine.KeyDownAsync(key ?? e.KeySymbol ?? e.Key.ToString(), GetModifiers(e.KeyModifiers))); } } @@ -463,6 +487,16 @@ private void SyncSource(BrowserEngine engine) } } + private async Task CopyAsync(BrowserEngine engine) + { + var text = await engine.CopySelectionAsync(); + + if (text.Length > 0 && TopLevel.GetTopLevel(this)?.Clipboard is { } clipboard) + { + await clipboard.SetTextAsync(text); + } + } + private async Task PasteAsync(BrowserEngine engine) { var clipboard = TopLevel.GetTopLevel(this)?.Clipboard; diff --git a/src/AngleSharp.Browser.Docs/package.json b/src/AngleSharp.Browser.Docs/package.json index 89e662a..5af8122 100644 --- a/src/AngleSharp.Browser.Docs/package.json +++ b/src/AngleSharp.Browser.Docs/package.json @@ -1,6 +1,6 @@ { "name": "@anglesharp/browser", - "version": "0.1.0", + "version": "0.2.0", "preview": true, "description": "The doclet for the AngleSharp.Browser documentation.", "keywords": [ diff --git a/src/AngleSharp.Browser.Tests/AngleSharp.Browser.Tests.csproj b/src/AngleSharp.Browser.Tests/AngleSharp.Browser.Tests.csproj index 44b109e..b5479b5 100644 --- a/src/AngleSharp.Browser.Tests/AngleSharp.Browser.Tests.csproj +++ b/src/AngleSharp.Browser.Tests/AngleSharp.Browser.Tests.csproj @@ -10,6 +10,11 @@ <PackageReference Include="NUnit3TestAdapter" Version="5.2.0" /> </ItemGroup> + <ItemGroup> + <!-- tones of a quarter second, made with ffmpeg (sine, 440 Hz) --> + <None Include="Media\**" CopyToOutputDirectory="PreserveNewest" /> + </ItemGroup> + <ItemGroup> <ProjectReference Include="..\AngleSharp.Browser\AngleSharp.Browser.csproj" /> </ItemGroup> diff --git a/src/AngleSharp.Browser.Tests/AudioTests.cs b/src/AngleSharp.Browser.Tests/AudioTests.cs new file mode 100644 index 0000000..8ab1019 --- /dev/null +++ b/src/AngleSharp.Browser.Tests/AudioTests.cs @@ -0,0 +1,505 @@ +namespace AngleSharp.Browser.Tests; + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using AngleSharp.Html.Dom; +using AngleSharp.Io; +using NUnit.Framework; + +/// <summary> +/// Audio: the decoders, the media elements of pages, where they play and what may play. +/// </summary> +[TestFixture] +public class AudioTests +{ + private const string Address = "https://example.com/"; + private const double ToneDuration = 0.25; + + [TestCase("tone.wav", 22050, 1)] + [TestCase("tone.mp3", 22050, 1)] + [TestCase("tone.ogg", 22050, 1)] + [TestCase("tone.opus", 48000, 2)] + public void CodecsDecodeTheirFormat(string name, int sampleRate, int channels) + { + var data = File.ReadAllBytes(GetMediaPath(name)); + var codecs = AudioCodecs.CreateDefault().Where(m => m.CanDecode(data)).ToArray(); + + Assert.That(codecs, Has.Length.EqualTo(1)); + + using var decoder = codecs[0].Open(new MemoryStream(data)); + var samples = ReadAll(decoder); + var seconds = (double)samples.Length / decoder.Channels / decoder.SampleRate; + + Assert.That(decoder.SampleRate, Is.EqualTo(sampleRate)); + Assert.That(decoder.Channels, Is.EqualTo(channels)); + Assert.That(decoder.Duration?.TotalSeconds, Is.EqualTo(ToneDuration).Within(0.08)); + // encoders pad the start and the end a bit (MP3 to whole frames of 1152 samples) + Assert.That(seconds, Is.EqualTo(ToneDuration).Within(0.08)); + Assert.That(samples.Max(Math.Abs), Is.GreaterThan(0.08f)); + + // seeking back gives the samples again + Assert.That(decoder.Seek(TimeSpan.Zero), Is.True); + Assert.That(ReadAll(decoder).Length, Is.EqualTo(samples.Length).Within(samples.Length / 10)); + } + + [Test] + public void WavCodecDecodesTheSampleFormats() + { + foreach (var (bits, isFloat) in new[] { (8, false), (16, false), (24, false), (32, false), (32, true) }) + { + var data = CreateWav(8000, 1, 0.1, bits, isFloat, 0.5); + using var decoder = AudioCodecs.Wav.Open(new MemoryStream(data)); + var samples = ReadAll(decoder); + + Assert.That(samples, Has.Length.EqualTo(800), $"{bits} bits"); + Assert.That(samples[0], Is.EqualTo(0.5f).Within(0.01f), $"{bits} bits"); + } + } + + [Test] + public async Task CanPlayTypeAnswersByTheCodecs() + { + using var engine = CreateEngine(); + await engine.LoadHtmlAsync("<title>Audio", Address); + + var answers = await engine.EvaluateScriptAsync(""" + ['audio/mpeg', 'audio/wav', 'audio/ogg; codecs="vorbis"', 'audio/ogg; codecs=opus', 'audio/mp4', 'audio/ogg; codecs=flac', 'video/mp4'] + .map(function (type) { return new Audio().canPlayType(type); }).join(',') + """); + + Assert.That(answers, Is.EqualTo("maybe,maybe,maybe,maybe,,,")); + } + + [TestCase("tone.wav")] + [TestCase("tone.mp3")] + [TestCase("tone.ogg")] + [TestCase("tone.opus")] + public async Task ScriptsPlayAudioToItsEnd(string name) + { + var output = new RecordingOutput(); + using var engine = CreateEngine(output, allowAutoplay: true); + await engine.LoadHtmlAsync("Audio", Address); + + await engine.EvaluateScriptAsync($$""" + window.events = []; + var audio = new Audio('app:{{name}}'); + ['play', 'playing', 'pause', 'ended', 'loadedmetadata', 'canplaythrough'].forEach(function (type) { + audio.addEventListener(type, function () { events.push(type); }); + }); + audio.play().then(function () { events.push('resolved'); }); + """); + await Eventually(async () => (string?)await engine.EvaluateScriptAsync("events.join(',')") is { } events && events.EndsWith("ended")); + + // the resource of the scheme is there at once, so it may be ready before the play event + var events = ((string?)await engine.EvaluateScriptAsync("events.join(',')"))!.Split(','); + Assert.That(events, Is.EquivalentTo(new[] { "play", "loadedmetadata", "canplaythrough", "playing", "resolved", "pause", "ended" })); + Assert.That(events[^5..], Is.EqualTo(new[] { "play", "playing", "resolved", "pause", "ended" }).Or.EqualTo(new[] { "canplaythrough", "playing", "resolved", "pause", "ended" })); + Assert.That(Array.IndexOf(events, "play"), Is.LessThan(Array.IndexOf(events, "playing"))); + Assert.That(await engine.EvaluateScriptAsync("audio.paused && audio.ended"), Is.EqualTo(true)); + // TODO: MP3 keeps the delay and padding of its encoder, which the LAME header tells + Assert.That((double)(await engine.EvaluateScriptAsync("audio.currentTime"))!, Is.EqualTo(ToneDuration).Within(0.08)); + Assert.That(output.Peak, Is.GreaterThan(0.08f)); + Assert.That(output.OpenStreams, Is.EqualTo(0)); + } + + [Test] + public async Task VolumeAndMutedScaleTheSamples() + { + var output = new RecordingOutput(); + using var engine = CreateEngine(output, allowAutoplay: true); + await engine.LoadHtmlAsync("Audio", Address); + + await engine.EvaluateScriptAsync("var audio = new Audio('app:tone.wav'); audio.volume = 0.25; audio.onended = function () { document.title = 'ended'; }; audio.play();"); + await Eventually(() => engine.Title == "ended"); + + // the tone peaks at 1/8 + Assert.That(output.Peak, Is.EqualTo(0.125f / 4).Within(0.005f)); + Assert.That(output.Formats, Is.EqualTo(new[] { new AudioFormat(22050, 1) })); + + output.Reset(); + await engine.EvaluateScriptAsync("audio.muted = true; document.title = ''; audio.play();"); + await Eventually(() => engine.Title == "ended"); + + Assert.That(output.Peak, Is.EqualTo(0f)); + } + + [Test] + public async Task AudibleMediaWaitsForTheUserToInteract() + { + using var engine = CreateEngine(); + await engine.LoadHtmlAsync("Audio
", Address); + + await engine.EvaluateScriptAsync(""" + var audio = new Audio('app:tone.wav'); + audio.oncanplaythrough = function () { + audio.play().then(function () { document.title = 'played'; }, function (e) { document.title = e.name; }); + }; + """); + await Eventually(() => engine.Title == "NotAllowedError"); + + Assert.That(await engine.EvaluateScriptAsync("audio.paused"), Is.EqualTo(true)); + + // muted media plays anyway + await engine.EvaluateScriptAsync("var muted = new Audio('app:tone.wav'); muted.muted = true; muted.play().then(function () { document.title = 'muted'; });"); + await Eventually(() => engine.Title == "muted"); + + // a press activates the page + await engine.PointerDownAsync(10, 10); + await engine.PointerUpAsync(10, 10); + await engine.EvaluateScriptAsync("audio.play().then(function () { document.title = 'played'; });"); + await Eventually(() => engine.Title == "played"); + } + + [Test] + public async Task AutoplayElementsOfTheDocumentPlay() + { + var output = new RecordingOutput(); + using var engine = CreateEngine(output, allowAutoplay: true); + await engine.LoadHtmlAsync("Audio", Address); + + await Eventually(() => output.OpenStreams == 1); + + var audio = await engine.InvokeAsync(document => (IHtmlAudioElement)document!.QuerySelector("audio")!); + Assert.That(await engine.InvokeAsync(_ => audio.IsPaused), Is.False); + } + + [Test] + public async Task MediaStopsOnceItsDocumentIsLeft() + { + var output = new RecordingOutput(); + using var engine = CreateEngine(output, allowAutoplay: true); + await engine.LoadHtmlAsync("Audio", Address); + + await engine.EvaluateScriptAsync("var audio = new Audio('app:long.wav'); audio.play();"); + await Eventually(() => output.OpenStreams == 1); + + await engine.LoadHtmlAsync("Other", Address + "other"); + await Eventually(() => output.OpenStreams == 0); + } + + [Test] + public async Task LoopingMediaPlaysAgain() + { + var output = new RecordingOutput(); + using var engine = CreateEngine(output, allowAutoplay: true); + await engine.LoadHtmlAsync("Audio", Address); + + await engine.EvaluateScriptAsync("var audio = new Audio('app:tone.wav'); audio.loop = true; audio.play();"); + await Eventually(() => output.Formats.Count >= 2); + + Assert.That(await engine.EvaluateScriptAsync("audio.paused"), Is.EqualTo(false)); + await engine.EvaluateScriptAsync("audio.pause()"); + await Eventually(() => output.OpenStreams == 0); + } + + [Test] + public async Task UnsupportedAudioGivesAnError() + { + using var engine = CreateEngine(allowAutoplay: true); + await engine.LoadHtmlAsync("Audio", Address); + + await engine.EvaluateScriptAsync(""" + var audio = new Audio('app:tone.m4a'); + audio.onerror = function () { document.title = 'error ' + audio.error.code; }; + audio.play().catch(function (e) { window.rejection = e.name; }); + """); + await Eventually(() => engine.Title == "error 4"); + + Assert.That(await engine.EvaluateScriptAsync("window.rejection"), Is.EqualTo("NotSupportedError")); + } + + [Test] + public async Task ControlsPlayPauseAndMute() + { + var output = new RecordingOutput(); + using var engine = CreateEngine(output); + await LoadControlsAsync(engine); + + // the play button (a press also lets the page play) + await engine.ClickAsync(28, 27); + await Eventually(() => output.OpenStreams == 1); + Assert.That(await engine.EvaluateScriptAsync("audio.paused"), Is.EqualTo(false)); + + // the mute button, then the pause button + await engine.ClickAsync(272, 27); + Assert.That(await engine.EvaluateScriptAsync("audio.muted"), Is.EqualTo(true)); + await engine.ClickAsync(28, 27); + await Eventually(() => output.OpenStreams == 0); + Assert.That(await engine.EvaluateScriptAsync("audio.paused"), Is.EqualTo(true)); + Assert.That(await engine.EvaluateScriptAsync("events.join(',')"), Is.EqualTo("play,playing,volumechange,pause")); + } + + [Test] + public async Task ControlsSeekWhileTheTimelineIsDragged() + { + using var engine = CreateEngine(); + await LoadControlsAsync(engine); + + // from the start of the timeline to its end, along a pixel row of it + await engine.PointerDownAsync(150, 27); + var pressed = (double)(await engine.EvaluateScriptAsync("audio.currentTime"))!; + engine.MovePointer(299, 27); + await Eventually(async () => (double)(await engine.EvaluateScriptAsync("audio.currentTime"))! == 30); + await engine.PointerUpAsync(299, 27); + + Assert.That(pressed, Is.GreaterThan(0).And.LessThan(30)); + // released, the pointer moves without seeking + engine.MovePointer(150, 27); + await engine.EvaluateScriptAsync("0"); + Assert.That(await engine.EvaluateScriptAsync("audio.currentTime"), Is.EqualTo(30)); + } + + [Test] + public async Task PlayingControlsMoveOnWithoutALayout() + { + using var engine = CreateEngine(allowAutoplay: true); + await LoadControlsAsync(engine); + await engine.EvaluateScriptAsync("audio.play()"); + await Eventually(async () => await engine.EvaluateScriptAsync("audio.paused") is false); + + // the same frame rasterized later shows the time gone on + var frame = (await engine.PrepareFrameAsync())!; + var before = frame.Rasterize().Data.ToArray(); + await Task.Delay(1200); + var after = frame.Rasterize().Data; + + Assert.That(after.SequenceEqual(before), Is.False); + } + + [Test] + public async Task MediaWithoutControlsPlaysWithoutALayout() + { + using var engine = CreateEngine(allowAutoplay: true); + await engine.LoadHtmlAsync("Audio

A game playing its sounds

", Address); + (await engine.PrepareFrameAsync())!.Rasterize(); + + // like a game rewinding and playing its sound effects + await engine.EvaluateScriptAsync(""" + var audio = new Audio('app:tone.wav'), plays = 0; + audio.onended = function () { if (++plays < 2) { audio.currentTime = 0; audio.play(); } else { document.title = 'done'; } }; + audio.play(); + """); + // (running a script lays out anew, the title doesn't) + (await engine.PrepareFrameAsync())!.Rasterize(); + var start = engine.Diagnostics.Frames.Count; + var watch = Stopwatch.StartNew(); + + while (engine.Title != "done" && watch.ElapsedMilliseconds < 5000) + { + (await engine.PrepareFrameAsync())?.Rasterize(); + await Task.Delay(20); + } + + var kinds = engine.Diagnostics.Frames.Skip(start).Select(frame => frame.Kind).ToList(); + Assert.That(engine.Title, Is.EqualTo("done")); + Assert.That(kinds, Is.Not.Empty); + Assert.That(kinds, Has.None.EqualTo(FrameKind.Layout), string.Join(", ", kinds)); + } + + // controls at the top left (300x54), of a media of 30 seconds whose events are recorded + private static async Task LoadControlsAsync(BrowserEngine engine) + { + await engine.LoadHtmlAsync("Audio", Address); + await engine.EvaluateScriptAsync(""" + var audio = document.querySelector('audio'), events = []; + ['play', 'playing', 'pause', 'volumechange'].forEach(function (name) { + audio.addEventListener(name, function () { events.push(name); }); + }); + """); + await Eventually(async () => await engine.EvaluateScriptAsync("audio.duration") is 30.0); + await engine.PrepareFrameAsync(); + } + + private static BrowserEngine CreateEngine(IAudioOutput? output = null, bool allowAutoplay = false) + { + var options = new BrowserOptions + { + ProfileDirectory = null, + ViewportWidth = 800, + ViewportHeight = 600, + AudioOutput = output, + IsAutoplayAllowed = allowAutoplay, + }; + options.SchemeHandlers["app"] = (request, _) => + { + // the name is all after the scheme (app:tone.wav) + var name = request.Address.Href["app:".Length..]; + var (type, content) = name switch + { + "long.wav" => ("audio/wav", CreateWav(8000, 1, 30, 16, false, 0.1)), + "tone.m4a" => ("audio/mp4", new byte[64]), + _ => (Path.GetExtension(name) switch + { + ".wav" => "audio/wav", + ".mp3" => "audio/mpeg", + _ => "audio/ogg", + }, File.ReadAllBytes(GetMediaPath(name))), + }; + var response = new DefaultResponse + { + Address = request.Address, + StatusCode = System.Net.HttpStatusCode.OK, + Content = new MemoryStream(content), + }; + response.Headers[HeaderNames.ContentType] = type; + return Task.FromResult(response); + }; + return new BrowserEngine(options); + } + + private static string GetMediaPath(string name) => Path.Combine(TestContext.CurrentContext.TestDirectory, "Media", name); + + private static float[] ReadAll(IAudioDecoder decoder) + { + var samples = new List(); + var buffer = new float[1024 * decoder.Channels]; + int count; + + while ((count = decoder.Read(buffer)) > 0) + { + samples.AddRange(buffer.Take(count)); + } + + return [.. samples]; + } + + private static byte[] CreateWav(int sampleRate, int channels, double seconds, int bits, bool isFloat, double value) + { + var frames = (int)(sampleRate * seconds); + var blockAlign = channels * bits / 8; + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write("RIFF"u8); + writer.Write(36 + frames * blockAlign); + writer.Write("WAVEfmt "u8); + writer.Write(16); + writer.Write((short)(isFloat ? 3 : 1)); + writer.Write((short)channels); + writer.Write(sampleRate); + writer.Write(sampleRate * blockAlign); + writer.Write((short)blockAlign); + writer.Write((short)bits); + writer.Write("data"u8); + writer.Write(frames * blockAlign); + + for (var i = 0; i < frames * channels; i++) + { + switch (bits) + { + case 8: + writer.Write((byte)(128 + value * 128)); + break; + case 16: + writer.Write((short)(value * 32768)); + break; + case 24: + var sample = (int)(value * 8388608); + writer.Write((byte)sample); + writer.Write((byte)(sample >> 8)); + writer.Write((byte)(sample >> 16)); + break; + default: + if (isFloat) + { + writer.Write((float)value); + } + else + { + writer.Write((int)(value * 2147483648)); + } + + break; + } + } + + writer.Flush(); + return stream.ToArray(); + } + + private static async Task Eventually(Func condition) => await Eventually(() => Task.FromResult(condition())); + + private static async Task Eventually(Func> condition) + { + var watch = Stopwatch.StartNew(); + + while (!await condition()) + { + if (watch.Elapsed > TimeSpan.FromSeconds(10)) + { + Assert.Fail("Condition was not met in time."); + } + + await Task.Delay(20); + } + } + + /// + /// Plays silently (in real time), but records the formats and the loudest sample. + /// + private sealed class RecordingOutput : IAudioOutput + { + private readonly SilentAudioOutput _silent = new(); + private readonly ConcurrentQueue _formats = new(); + private int _openStreams; + private float _peak; + + public IReadOnlyCollection Formats => [.. _formats]; + + public int OpenStreams => Volatile.Read(ref _openStreams); + + public float Peak => Volatile.Read(ref _peak); + + public void Reset() + { + _formats.Clear(); + Volatile.Write(ref _peak, 0f); + } + + public IAudioStream Open(AudioFormat format, IAudioSource source) + { + _formats.Enqueue(format); + Interlocked.Increment(ref _openStreams); + return new Stream(this, _silent.Open(format, new Source(this, source))); + } + + private sealed class Source(RecordingOutput output, IAudioSource source) : IAudioSource + { + public void Read(Span buffer) + { + source.Read(buffer); + + foreach (var sample in buffer) + { + if (Math.Abs(sample) > output._peak) + { + Volatile.Write(ref output._peak, Math.Abs(sample)); + } + } + } + } + + private sealed class Stream(RecordingOutput output, IAudioStream stream) : IAudioStream + { + private int _isDisposed; + + public void Start() => stream.Start(); + + public void Stop() => stream.Stop(); + + public void Dispose() + { + if (Interlocked.Exchange(ref _isDisposed, 1) == 0) + { + stream.Dispose(); + Interlocked.Decrement(ref output._openStreams); + } + } + } + } +} diff --git a/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs b/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs index fa98bea..b89a3b6 100644 --- a/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs +++ b/src/AngleSharp.Browser.Tests/BrowserEngineTests.cs @@ -44,6 +44,47 @@ public void NormalizeAddressCompletesUserInput(string input, string expected) Assert.That(BrowserEngine.NormalizeAddress(input), Is.EqualTo(expected)); } + [TestCase("app:settings", "app:settings")] + [TestCase("APP://settings/", "APP://settings/")] + [TestCase("localhost:8080", "https://localhost:8080")] + [TestCase("other:settings", "https://other:settings")] + public void NormalizeAddressKeepsCustomSchemes(string input, string expected) + { + Assert.That(BrowserEngine.NormalizeAddress(input, ["app"]), Is.EqualTo(expected)); + } + + [Test] + public async Task CustomSchemesAreAnsweredByTheirHandlers() + { + var requested = new List(); + var options = new BrowserOptions { ProfileDirectory = null }; + options.SchemeHandlers["app"] = (request, _) => + { + requested.Add(request.Address.Href); + var response = new DefaultResponse + { + Address = request.Address, + StatusCode = System.Net.HttpStatusCode.OK, + Content = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("Own")), + }; + response.Headers[HeaderNames.ContentType] = "text/html; charset=utf-8"; + return Task.FromResult(response); + }; + using var engine = new BrowserEngine(options); + + await engine.NavigateAsync("app:start"); + + Assert.That(engine.Schemes, Is.EqualTo(new[] { "app" })); + Assert.That(engine.Url, Is.EqualTo("app:start")); + Assert.That(engine.Title, Is.EqualTo("Own")); + + // links of the scheme go to the handler as well + await engine.InvokeAsync(d => ((IHtmlElement)d!.GetElementById("next")!).DoClick()); + await Eventually(() => engine.Url == "app:next" && !engine.IsLoading); + + Assert.That(requested, Is.EqualTo(new[] { "app:start", "app:next" })); + } + private async Task<(IDocument Nested, IHtmlInlineFrameElement Frame)> LoadFrameAsync(string frameHtml, string pageStyle = "") { var srcdoc = System.Net.WebUtility.HtmlEncode(frameHtml); @@ -2027,6 +2068,33 @@ public async Task WindowsShareTheProfileButNotTheHistory() Assert.That(_engine.Url, Is.EqualTo("https://example.com/first")); } + [Test] + public async Task HistoryListsItsEntriesAndJumpsSeveralSteps() + { + var first = new Uri(WritePage("first.html", "First")).AbsoluteUri; + var second = new Uri(WritePage("second.html", "Second")).AbsoluteUri; + var third = new Uri(WritePage("third.html", "Third")).AbsoluteUri; + await _engine.NavigateAsync(first); + await _engine.NavigateAsync(second); + await _engine.NavigateAsync(third); + + var history = _engine.History; + Assert.That(history.Index, Is.EqualTo(2)); + Assert.That(history.Entries.Select(m => (m.Url, m.Title)), Is.EqualTo(new[] { (first, "First"), (second, "Second"), (third, "Third") })); + Assert.That(history.Back.Select(m => m.Title), Is.EqualTo(new[] { "Second", "First" })); + Assert.That(history.Forward, Is.Empty); + + await _engine.GoAsync(-2); + + Assert.That(_engine.Title, Is.EqualTo("First")); + Assert.That(_engine.History.Forward.Select(m => m.Title), Is.EqualTo(new[] { "Second", "Third" })); + + await _engine.GoAsync(2); + + Assert.That(_engine.Title, Is.EqualTo("Third")); + Assert.That(_engine.CanGoForward, Is.False); + } + [Test] public async Task WindowCanBeOpenedAfterRequestsWereMade() { @@ -2106,6 +2174,151 @@ await _engine.LoadHtmlAsync(""" Assert.That(watch.ElapsedMilliseconds, Is.LessThan(1000)); } + [Test] + public async Task AnimatedTransformsNeedNoLayoutsOfThePage() + { + await _engine.LoadHtmlAsync(""" +

text

+ """); + await _engine.PrepareFrameAsync(); + await _engine.PrepareFrameAsync(); + var start = _engine.Diagnostics.Frames.Count; + var pixels = new HashSet<(byte, byte, byte)>(); + + for (var i = 0; i < 8; i++) + { + await Task.Delay(40); + pixels.Add(PixelOf((await _engine.PrepareFrameAsync())!, 58, 42)); + } + + var kinds = _engine.Diagnostics.Frames.Skip(start).Select(frame => frame.Kind).ToList(); + Assert.That(kinds, Has.Count.GreaterThanOrEqualTo(8)); + // the frames of the animation are the last one painted under the new transform + Assert.That(kinds.Count(kind => kind == FrameKind.Layout), Is.LessThanOrEqualTo(1), string.Join(", ", kinds)); + Assert.That(pixels, Has.Count.GreaterThan(1)); + } + + [Test] + public async Task AnimatedGifAsksForFramesShowingItsNextImages() + { + // 1x1 frames, red for 100 ms, then blue for 1 s, looping + byte[] gif = + [ + .. "GIF89a"u8.ToArray(), 1, 0, 1, 0, 0x80, 0, 0, 255, 0, 0, 0, 0, 255, + 0x21, 0xFF, 0x0B, .. "NETSCAPE2.0"u8.ToArray(), 3, 1, 0, 0, 0, + 0x21, 0xF9, 4, 0, 10, 0, 0, 0, 0x2C, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 0x44, 1, 0, + 0x21, 0xF9, 4, 0, 100, 0, 0, 0, 0x2C, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 0x4C, 1, 0, + 0x3B, + ]; + await _engine.LoadHtmlAsync($""); + await Eventually(() => _engine.Document?.QuerySelector("img") is IHtmlImageElement { IsCompleted: true }); + await _engine.PrepareFrameAsync(); + await _engine.PrepareFrameAsync(); + var invalidations = 0; + _engine.Invalidated += (_, _) => invalidations++; + var colors = new HashSet<(byte, byte, byte)>(); + var watch = Stopwatch.StartNew(); + + while (colors.Count < 2 && watch.ElapsedMilliseconds < 6000) + { + colors.Add(PixelOf((await _engine.PrepareFrameAsync())!, 20, 20)); + await Task.Delay(30); + } + + Assert.That(colors, Does.Contain(((byte)255, (byte)0, (byte)0)).And.Contain(((byte)0, (byte)0, (byte)255))); + Assert.That(invalidations, Is.GreaterThan(0)); + // the next images of the GIF need no layout + Assert.That(_engine.Diagnostics.Frames.TakeLast(3).Select(frame => frame.Kind), Has.None.EqualTo(FrameKind.Layout)); + } + + private const string SelectablePage = "

hello world again

second line

"; + + [Test] + public async Task TextCannotBeSelectedUnlessEnabled() + { + await _engine.LoadHtmlAsync(SelectablePage); + await _engine.PrepareFrameAsync(); + + await _engine.PointerDownAsync(2, 10, 2); + await _engine.PointerUpAsync(2, 10); + + Assert.That(await _engine.CopySelectionAsync(), Is.Empty); + } + + [Test] + public async Task DraggingSelectsTextWhenEnabled() + { + using var engine = new BrowserEngine(new BrowserOptions { ViewportWidth = 800, ViewportHeight = 600, IsTextSelectionEnabled = true }); + await engine.LoadHtmlAsync(SelectablePage); + await engine.PrepareFrameAsync(); + + await engine.PointerDownAsync(1, 10); + await engine.MovePointerAsync(400, 35); + await engine.PointerUpAsync(400, 35); + + Assert.That(await engine.CopySelectionAsync(), Is.EqualTo("hello world again\n\nsecond line")); + } + + [Test] + public async Task TextShowsTheTextCursorWhenItCanBeSelected() + { + using var engine = new BrowserEngine(new BrowserOptions { ViewportWidth = 800, ViewportHeight = 600, IsTextSelectionEnabled = true }); + await engine.LoadHtmlAsync(SelectablePage + "

arrow

"); + await engine.PrepareFrameAsync(); + await engine.PrepareFrameAsync(); + + await engine.MovePointerAsync(20, 10); + var overText = engine.Cursor; + await engine.MovePointerAsync(700, 10); + var besideText = engine.Cursor; + await engine.MovePointerAsync(20, 60); + var overDefault = engine.Cursor; + await _engine.LoadHtmlAsync(SelectablePage); + await _engine.PrepareFrameAsync(); + await _engine.MovePointerAsync(20, 10); + + Assert.That(overText, Is.EqualTo(BrowserCursor.Text)); + Assert.That(besideText, Is.EqualTo(BrowserCursor.Default)); + Assert.That(overDefault, Is.EqualTo(BrowserCursor.Default)); + Assert.That(_engine.Cursor, Is.EqualTo(BrowserCursor.Default)); + } + + [Test] + public async Task DoublePressSelectsAWordAndCtrlASelectsAll() + { + using var engine = new BrowserEngine(new BrowserOptions { ViewportWidth = 800, ViewportHeight = 600, IsTextSelectionEnabled = true }); + await engine.LoadHtmlAsync(SelectablePage); + await engine.PrepareFrameAsync(); + + await engine.PointerDownAsync(80, 10, 2); + await engine.PointerUpAsync(80, 10); + var word = await engine.CopySelectionAsync(); + await engine.KeyDownAsync("a", InputModifiers.Control); + var all = await engine.CopySelectionAsync(); + + Assert.That(word, Is.EqualTo("world")); + Assert.That(all, Does.Contain("hello world again").And.Contain("second line")); + } + + [Test] + public async Task CopyingCanBeCanceledByThePage() + { + using var engine = new BrowserEngine(new BrowserOptions { ViewportWidth = 800, ViewportHeight = 600, IsTextSelectionEnabled = true }); + await engine.LoadHtmlAsync(SelectablePage); + await engine.PrepareFrameAsync(); + await engine.InvokeAsync(document => document!.AddEventListener("copy", (_, e) => e.Cancel())); + + await engine.KeyDownAsync("a", InputModifiers.Control); + + Assert.That(await engine.CopySelectionAsync(), Is.Empty); + } + private string WritePage(string name, string html) { var path = Path.Combine(_directory, name); diff --git a/src/AngleSharp.Browser.Tests/JavaScriptTests.cs b/src/AngleSharp.Browser.Tests/JavaScriptTests.cs index 0a1e0d9..7036111 100644 --- a/src/AngleSharp.Browser.Tests/JavaScriptTests.cs +++ b/src/AngleSharp.Browser.Tests/JavaScriptTests.cs @@ -38,6 +38,23 @@ public async Task EvaluatingScriptsReturnsTheirValue() Assert.That(await _engine.EvaluateScriptAsync("document.title"), Is.EqualTo("Scripts")); } + [Test] + public async Task CallersDoNotContinueOnTheEventLoop() + { + await _engine.LoadHtmlAsync("

Frames

", Address); + var loopThread = await _engine.InvokeAsync(_ => Environment.CurrentManagedThreadId); + + // what a caller does with a frame (e.g. rasterizing it) would hold up the scripts there + var frame = await _engine.PrepareFrameAsync(); + + Assert.That(frame, Is.Not.Null); + Assert.That(Environment.CurrentManagedThreadId, Is.Not.EqualTo(loopThread)); + + await _engine.EvaluateScriptAsync("1"); + + Assert.That(Environment.CurrentManagedThreadId, Is.Not.EqualTo(loopThread)); + } + [Test] public async Task EvaluatingScriptsWithoutScriptingReturnsNothing() { @@ -247,6 +264,53 @@ await _engine.LoadHtmlAsync(""" Assert.That(seen, Does.EndWith("pointerdown:21,mousedown:21,pointerup:21,mouseup:21,click:21")); } + [Test] + public async Task HoverFiresEnterAndLeaveWithTheRelatedTargetAndPointerType() + { + await _engine.LoadHtmlAsync(""" +
+ + """, Address); + await _engine.PrepareFrameAsync(); + + await _engine.MovePointerAsync(400, 400); + await _engine.MovePointerAsync(150, 150); + await _engine.MovePointerAsync(50, 50); + await _engine.MovePointerAsync(400, 400); + + Assert.That(await _engine.EvaluateScriptAsync("window.seen.join()"), Is.EqualTo( + "pointerover@a + + """, Address); + await _engine.PrepareFrameAsync(); + + await _engine.MovePointerAsync(50, 50); + await _engine.KeyDownAsync("a"); + + Assert.That(await _engine.EvaluateScriptAsync("window.seen.join()"), Is.EqualTo("window:5,key:BODY")); + } + [Test] public async Task KeysTellTheirLegacyNamesAndCode() { @@ -265,6 +329,25 @@ await _engine.LoadHtmlAsync(""" Assert.That(await _engine.EvaluateScriptAsync("window.seen.join()"), Is.EqualTo("Enter:Enter:13:13,a:KeyA:65:65")); } + [Test] + public async Task ModifierKeysPressedOnTheirOwnReachThePage() + { + // a game firing on Control (keyCode 17), like the Spaceshoot sample of Piral + await _engine.LoadHtmlAsync(""" + + """, Address); + + await _engine.KeyDownAsync("Control", InputModifiers.Control); + await _engine.KeyDownAsync("Shift", InputModifiers.Shift); + await _engine.KeyDownAsync("Alt", InputModifiers.Alt); + await _engine.KeyDownAsync("Meta", InputModifiers.Meta); + + Assert.That(await _engine.EvaluateScriptAsync("window.seen.join()"), Is.EqualTo("Control:17,Shift:16,Alt:18,Meta:91")); + } + [Test] public async Task PushStateChangesTheAddressOfTheDocument() { diff --git a/src/AngleSharp.Browser.Tests/Media/tone.mp3 b/src/AngleSharp.Browser.Tests/Media/tone.mp3 new file mode 100644 index 0000000..81947dd Binary files /dev/null and b/src/AngleSharp.Browser.Tests/Media/tone.mp3 differ diff --git a/src/AngleSharp.Browser.Tests/Media/tone.ogg b/src/AngleSharp.Browser.Tests/Media/tone.ogg new file mode 100644 index 0000000..6c03d16 Binary files /dev/null and b/src/AngleSharp.Browser.Tests/Media/tone.ogg differ diff --git a/src/AngleSharp.Browser.Tests/Media/tone.opus b/src/AngleSharp.Browser.Tests/Media/tone.opus new file mode 100644 index 0000000..7a19641 Binary files /dev/null and b/src/AngleSharp.Browser.Tests/Media/tone.opus differ diff --git a/src/AngleSharp.Browser.Tests/Media/tone.wav b/src/AngleSharp.Browser.Tests/Media/tone.wav new file mode 100644 index 0000000..86e36fe Binary files /dev/null and b/src/AngleSharp.Browser.Tests/Media/tone.wav differ diff --git a/src/AngleSharp.Browser/AngleSharp.Browser.csproj b/src/AngleSharp.Browser/AngleSharp.Browser.csproj index cc96add..177b591 100644 --- a/src/AngleSharp.Browser/AngleSharp.Browser.csproj +++ b/src/AngleSharp.Browser/AngleSharp.Browser.csproj @@ -12,18 +12,26 @@ - - - - - + + + + + - + + + + + + + + + - - + + diff --git a/src/AngleSharp.Browser/AudioCodecs.cs b/src/AngleSharp.Browser/AudioCodecs.cs new file mode 100644 index 0000000..d37503b --- /dev/null +++ b/src/AngleSharp.Browser/AudioCodecs.cs @@ -0,0 +1,461 @@ +namespace AngleSharp.Browser; + +using System; +using System.Buffers.Binary; +using System.Collections.Generic; +using System.IO; +using System.Text; +using Concentus; +using Concentus.Oggfile; +using NLayer; +using NVorbis; + +/// +/// A format of audio the engine plays; see . +/// +public interface IAudioCodec +{ + /// + /// Gets the content types (without parameters) of the format, e.g. "audio/mpeg". + /// + IReadOnlyCollection ContentTypes { get; } + + /// + /// Gets the names of the codecs it decodes, as in the codecs parameter of a content type + /// (e.g. "vorbis" of "audio/ogg; codecs=vorbis"). + /// + IReadOnlyCollection CodecNames { get; } + + /// + /// Checks if the data starting with the given bytes (at least the first 64, unless the + /// data is shorter) is of the format. + /// + /// The first bytes of the data. + /// True if the codec decodes the data. + bool CanDecode(ReadOnlySpan header); + + /// + /// Opens a decoder for the data, which owns the (seekable) stream. + /// + /// The data of the format. + /// The decoder. + IAudioDecoder Open(Stream stream); +} + +/// +/// The decoder of an , giving the samples as 32-bit floats from -1 to +/// 1, the channels interleaved. +/// +public interface IAudioDecoder : IDisposable +{ + /// + /// Gets the samples per second of every channel. + /// + int SampleRate { get; } + + /// + /// Gets the number of channels. + /// + int Channels { get; } + + /// + /// Gets the duration, if known. + /// + TimeSpan? Duration { get; } + + /// + /// Decodes the next samples into the buffer, whose length is a multiple of the channels. + /// + /// The buffer to fill. + /// The number of samples decoded, fewer than asked for only at the end. + int Read(Span buffer); + + /// + /// Moves to the given position. + /// + /// The position from the start. + /// True if the decoder moved there. + bool Seek(TimeSpan position); +} + +/// +/// The audio formats of the engine, which are decoded with managed code only. +/// +public static class AudioCodecs +{ + /// + /// Gets the codec of WAV files (PCM of 8, 16, 24 or 32 bits, or 32-bit floats). + /// + public static IAudioCodec Wav { get; } = new WavCodec(); + + /// + /// Gets the codec of MP3 files (MPEG audio, decoded by NLayer). + /// + public static IAudioCodec Mp3 { get; } = new Mp3Codec(); + + /// + /// Gets the codec of Ogg Vorbis files (decoded by NVorbis). + /// + public static IAudioCodec Vorbis { get; } = new VorbisCodec(); + + /// + /// Gets the codec of Ogg Opus files (decoded by Concentus). + /// + public static IAudioCodec Opus { get; } = new OpusCodec(); + + /// + /// Creates the list of all codecs of the engine. + /// + /// The codecs, in the order they are tried. + public static List CreateDefault() => [Wav, Mp3, Vorbis, Opus]; + + private static bool StartsWith(ReadOnlySpan data, string text) => + data.Length >= text.Length && data[..text.Length].SequenceEqual(Encoding.ASCII.GetBytes(text)); + + private static bool IsOgg(ReadOnlySpan header, string codecSignature) => + StartsWith(header, "OggS") && header.IndexOf(Encoding.ASCII.GetBytes(codecSignature)) >= 0; + + private sealed class WavCodec : IAudioCodec + { + public IReadOnlyCollection ContentTypes { get; } = ["audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave", "audio/x-pn-wav"]; + + public IReadOnlyCollection CodecNames { get; } = ["1", "3"]; + + public bool CanDecode(ReadOnlySpan header) => + header.Length >= 12 && StartsWith(header, "RIFF") && StartsWith(header[8..], "WAVE"); + + public IAudioDecoder Open(Stream stream) => new WavDecoder(stream); + } + + private sealed class Mp3Codec : IAudioCodec + { + public IReadOnlyCollection ContentTypes { get; } = ["audio/mpeg", "audio/mp3", "audio/mpeg3", "audio/x-mpeg", "audio/x-mp3"]; + + public IReadOnlyCollection CodecNames { get; } = ["mp3", "mp4a.6b", "mp4a.69", "mp4a.40.34"]; + + // an ID3 tag or the sync of an MPEG audio frame (AAC's ADTS has layer 0) + public bool CanDecode(ReadOnlySpan header) => + StartsWith(header, "ID3") || header.Length >= 2 && header[0] == 0xFF && (header[1] & 0xE0) == 0xE0 && (header[1] & 0x06) != 0; + + public IAudioDecoder Open(Stream stream) => new Mp3Decoder(stream); + } + + private sealed class VorbisCodec : IAudioCodec + { + public IReadOnlyCollection ContentTypes { get; } = ["audio/ogg", "application/ogg", "audio/vorbis"]; + + public IReadOnlyCollection CodecNames { get; } = ["vorbis"]; + + public bool CanDecode(ReadOnlySpan header) => IsOgg(header, "\u0001vorbis"); + + public IAudioDecoder Open(Stream stream) => new VorbisDecoder(stream); + } + + private sealed class OpusCodec : IAudioCodec + { + public IReadOnlyCollection ContentTypes { get; } = ["audio/ogg", "application/ogg", "audio/opus"]; + + public IReadOnlyCollection CodecNames { get; } = ["opus"]; + + public bool CanDecode(ReadOnlySpan header) => IsOgg(header, "OpusHead"); + + public IAudioDecoder Open(Stream stream) => new OpusDecoder(stream); + } + + private sealed class WavDecoder : IAudioDecoder + { + private const int Pcm = 1; + private const int Float = 3; + private const int Extensible = 0xFFFE; + + private readonly Stream _stream; + private readonly int _format; + private readonly int _bits; + private readonly int _blockAlign; + private readonly long _dataStart; + private readonly long _dataLength; + private byte[] _buffer = []; + private long _position; + + public WavDecoder(Stream stream) + { + _stream = stream; + var reader = new BinaryReader(stream, Encoding.ASCII, leaveOpen: true); + stream.Position = 12; + var hasFormat = false; + + while (stream.Position + 8 <= stream.Length) + { + var id = Encoding.ASCII.GetString(reader.ReadBytes(4)); + var size = reader.ReadUInt32(); + var next = stream.Position + size + (size & 1); + + if (id == "fmt ") + { + _format = reader.ReadUInt16(); + Channels = reader.ReadUInt16(); + SampleRate = (int)reader.ReadUInt32(); + reader.ReadUInt32(); + _blockAlign = reader.ReadUInt16(); + _bits = reader.ReadUInt16(); + + if (_format == Extensible && size >= 26) + { + reader.ReadUInt16(); + reader.ReadUInt16(); + reader.ReadUInt32(); + // the sub format's GUID starts with the format's code + _format = reader.ReadUInt16(); + } + + hasFormat = true; + } + else if (id == "data") + { + _dataStart = stream.Position; + _dataLength = Math.Min(size, stream.Length - _dataStart); + break; + } + + stream.Position = next; + } + + var isSupported = _format == Pcm && _bits is 8 or 16 or 24 or 32 || _format == Float && _bits == 32; + + if (!hasFormat || _dataStart == 0 || !isSupported || Channels <= 0 || SampleRate <= 0 || _blockAlign != Channels * _bits / 8) + { + throw new InvalidDataException("The WAV file has no supported format."); + } + } + + public int SampleRate { get; } + + public int Channels { get; } + + public TimeSpan? Duration => TimeSpan.FromSeconds((double)(_dataLength / _blockAlign) / SampleRate); + + public int Read(Span buffer) + { + var bytesPerSample = _bits / 8; + var frames = (int)Math.Min(buffer.Length / Channels, (_dataLength - _position) / _blockAlign); + var length = frames * _blockAlign; + + if (frames <= 0) + { + return 0; + } + + if (_buffer.Length < length) + { + _buffer = new byte[length]; + } + + _stream.Position = _dataStart + _position; + _stream.ReadExactly(_buffer, 0, length); + _position += length; + var data = _buffer.AsSpan(0, length); + var count = frames * Channels; + + for (var i = 0; i < count; i++) + { + var sample = data.Slice(i * bytesPerSample, bytesPerSample); + buffer[i] = _format == Float ? BinaryPrimitives.ReadSingleLittleEndian(sample) : _bits switch + { + 8 => (sample[0] - 128) / 128f, + 16 => BinaryPrimitives.ReadInt16LittleEndian(sample) / 32768f, + 24 => (sample[0] | sample[1] << 8 | (sbyte)sample[2] << 16) / 8388608f, + _ => BinaryPrimitives.ReadInt32LittleEndian(sample) / 2147483648f, + }; + } + + return count; + } + + public bool Seek(TimeSpan position) + { + var frame = (long)(Math.Max(0, position.TotalSeconds) * SampleRate); + _position = Math.Min(frame * _blockAlign, _dataLength / _blockAlign * _blockAlign); + return true; + } + + public void Dispose() => _stream.Dispose(); + } + + private sealed class Mp3Decoder(Stream stream) : IAudioDecoder + { + private readonly MpegFile _file = new(stream); + + public int SampleRate => _file.SampleRate; + + public int Channels => _file.Channels; + + public TimeSpan? Duration => _file.Duration > TimeSpan.Zero ? _file.Duration : null; + + public int Read(Span buffer) => ReadFully(buffer, _file.ReadSamples); + + public bool Seek(TimeSpan position) + { + if (!_file.CanSeek) + { + return false; + } + + _file.Time = position; + return true; + } + + public void Dispose() + { + _file.Dispose(); + stream.Dispose(); + } + } + + private sealed class VorbisDecoder(Stream stream) : IAudioDecoder + { + private readonly VorbisReader _reader = new(stream, closeOnDispose: true); + + public int SampleRate => _reader.SampleRate; + + public int Channels => _reader.Channels; + + public TimeSpan? Duration => _reader.TotalTime > TimeSpan.Zero ? _reader.TotalTime : null; + + public int Read(Span buffer) => ReadFully(buffer, _reader.ReadSamples); + + public bool Seek(TimeSpan position) + { + _reader.SeekTo(position, SeekOrigin.Begin); + return true; + } + + public void Dispose() => _reader.Dispose(); + } + + private sealed class OpusDecoder : IAudioDecoder + { + // Opus always decodes at 48 kHz + private const int Rate = 48000; + + private readonly Stream _stream; + private OpusOggReadStream _reader; + private short[] _pending = []; + private int _offset; + + public OpusDecoder(Stream stream) + { + _stream = stream; + Channels = ReadChannels(stream); + _reader = OpenReader(); + Duration = _reader.TotalTime > TimeSpan.Zero ? _reader.TotalTime : null; + } + + public int SampleRate => Rate; + + public int Channels { get; } + + public TimeSpan? Duration { get; } + + public int Read(Span buffer) + { + var count = 0; + + while (count < buffer.Length && Fill()) + { + var length = Math.Min(buffer.Length - count, _pending.Length - _offset); + + for (var i = 0; i < length; i++) + { + buffer[count + i] = _pending[_offset + i] / 32768f; + } + + count += length; + _offset += length; + } + + return count; + } + + // the reader of Concentus has no packets after seeking back, so it starts over and + // decodes up to the position (which is cheap for Opus) + public bool Seek(TimeSpan position) + { + _reader = OpenReader(); + _pending = []; + _offset = 0; + var skip = (long)(Math.Max(0, position.TotalSeconds) * Rate) * Channels; + + while (skip > 0 && Fill()) + { + var length = (int)Math.Min(skip, _pending.Length - _offset); + _offset += length; + skip -= length; + } + + return true; + } + + public void Dispose() => _stream.Dispose(); + + private OpusOggReadStream OpenReader() + { + _stream.Position = 0; + return new OpusOggReadStream(OpusCodecFactory.CreateDecoder(Rate, Channels), _stream); + } + + // makes sure there are pending samples, unless at the end + private bool Fill() + { + while (_offset >= _pending.Length) + { + if (!_reader.HasNextPacket || _reader.DecodeNextPacket() is not { } packet) + { + return false; + } + + _pending = packet; + _offset = 0; + } + + return true; + } + + // the channels are in the identification header, the first packet (RFC 7845, 5.1) + private static int ReadChannels(Stream stream) + { + var header = new byte[Math.Min(stream.Length, 512)]; + stream.Position = 0; + stream.ReadExactly(header); + var index = header.AsSpan().IndexOf("OpusHead"u8); + + if (index < 0 || index + 9 >= header.Length || header[index + 9] is 0 or > 2) + { + throw new InvalidDataException("The Ogg Opus file has no supported channels."); + } + + return header[index + 9]; + } + } + + private delegate int SampleReader(Span buffer); + + // decoders may give fewer samples than asked for before the end (e.g. at a frame's end) + private static int ReadFully(Span buffer, SampleReader read) + { + var count = 0; + + while (count < buffer.Length) + { + var length = read(buffer[count..]); + + if (length <= 0) + { + break; + } + + count += length; + } + + return count; + } +} diff --git a/src/AngleSharp.Browser/AudioOutput.cs b/src/AngleSharp.Browser/AudioOutput.cs new file mode 100644 index 0000000..8174b6b --- /dev/null +++ b/src/AngleSharp.Browser/AudioOutput.cs @@ -0,0 +1,59 @@ +namespace AngleSharp.Browser; + +using System; + +/// +/// The format of the samples an audio stream plays: 32-bit floats from -1 to 1, the samples +/// of the channels interleaved (e.g. left, right, left, ...). +/// +/// The samples per second of every channel, e.g. 44100. +/// The number of channels, e.g. 2 for stereo. +public readonly record struct AudioFormat(int SampleRate, int Channels); + +/// +/// Where the audio of the pages plays, e.g. the platform's audio device; see +/// . The engine opens a stream for every media element +/// playing, which the output pulls the samples of. +/// +public interface IAudioOutput +{ + /// + /// Opens a stream, which pulls its samples from the source once started (on a thread of + /// the output's choice). The engine disposes the stream once the media stops. + /// + /// The format of the samples. + /// The source to pull the samples from. + /// The stream, which is stopped. + IAudioStream Open(AudioFormat format, IAudioSource source); +} + +/// +/// A stream of an . +/// +public interface IAudioStream : IDisposable +{ + /// + /// Starts pulling (and playing) the samples of the source. + /// + void Start(); + + /// + /// Stops pulling the samples, without waiting for those pulled to have played. + /// + void Stop(); +} + +/// +/// The samples of a stream, which the engine provides. +/// +public interface IAudioSource +{ + /// + /// Fills the buffer with the next samples (interleaved, in the stream's format). The + /// source always fills the whole buffer, with silence where there is nothing to play. + /// The media's clock advances by what the output pulls, so an output pulls about at the + /// pace it plays. + /// + /// The buffer to fill; its length is a multiple of the channels. + void Read(Span buffer); +} diff --git a/src/AngleSharp.Browser/AudioPlayback.cs b/src/AngleSharp.Browser/AudioPlayback.cs new file mode 100644 index 0000000..190823d --- /dev/null +++ b/src/AngleSharp.Browser/AudioPlayback.cs @@ -0,0 +1,303 @@ +namespace AngleSharp.Browser; + +using System; +using System.Threading; +using AngleSharp.Dom; +using AngleSharp.Dom.Events; +using AngleSharp.Media.Dom; + +/// +/// The controller of an audio resource: it decodes the samples as the output pulls them, so +/// its clock is what the output played. Its events are raised on the event loop of its +/// document; the element fires those of the state it changes itself (play, pause, ...). +/// +sealed class AudioPlayback : IMediaController, IAudioSource +{ + private static readonly TimeSpan TimeUpdateInterval = TimeSpan.FromMilliseconds(250); + + private readonly Lock _gate = new(); + private readonly MediaHost _host; + private readonly IBrowsingContext _context; + private readonly IAudioDecoder _decoder; + private readonly int _channels; + private readonly int _sampleRate; + private IAudioStream? _stream; + private Timer? _timeUpdates; + private MediaControllerPlaybackState _state; + private long _frames; + private double _volume = 1.0; + private bool _isMuted; + private bool _isDisposed; + + public AudioPlayback(MediaHost host, IBrowsingContext context, IAudioDecoder decoder) + { + _host = host; + _context = context; + _decoder = decoder; + _channels = decoder.Channels; + _sampleRate = decoder.SampleRate; + Document = context.Active; + } + + /// + /// Gets the document the media plays for. + /// + public IDocument? Document { get; } + + /// + /// Gets the browsing context of the document. + /// + public IBrowsingContext Context => _context; + + public ITimeRanges? BufferedTime => Seekable; + + public ITimeRanges? SeekableTime => Seekable; + + public ITimeRanges? PlayedTime => new TimeRanges(0, CurrentTime); + + public double Duration => _decoder.Duration?.TotalSeconds ?? double.NaN; + + public double CurrentTime + { + get + { + lock (_gate) + { + return (double)_frames / _sampleRate; + } + } + set + { + lock (_gate) + { + var time = Math.Max(0, double.IsNaN(Duration) ? value : Math.Min(value, Duration)); + + if (_decoder.Seek(TimeSpan.FromSeconds(time))) + { + _frames = (long)(time * _sampleRate); + + if (_state == MediaControllerPlaybackState.Ended) + { + _state = MediaControllerPlaybackState.Waiting; + } + } + } + + _host.OnChanged(); + } + } + + public double DefaultPlaybackRate { get; set; } = 1.0; + + // TODO: other rates than 1 (the samples would need to be resampled) + public double PlaybackRate { get; set; } = 1.0; + + public double Volume + { + get => _volume; + set + { + _volume = Math.Clamp(value, 0.0, 1.0); + _host.OnChanged(); + } + } + + public bool IsMuted + { + get => _isMuted; + set + { + _isMuted = value; + _host.OnChanged(); + } + } + + public bool IsPaused => _state != MediaControllerPlaybackState.Playing; + + public MediaReadyState ReadyState => MediaReadyState.EnoughData; + + public MediaControllerPlaybackState PlaybackState => _state; + + public bool IsPlaying => _state == MediaControllerPlaybackState.Playing; + + private TimeRanges? Seekable => double.IsNaN(Duration) ? null : new TimeRanges(0, Duration); + + // the element announces what the playback has from the start (all of its data) +#pragma warning disable CS0067 + public event DomEventHandler? Emptied; + public event DomEventHandler? LoadedMetadata; + public event DomEventHandler? LoadedData; + public event DomEventHandler? CanPlay; + public event DomEventHandler? CanPlayThrough; + public event DomEventHandler? Ended; + public event DomEventHandler? Waiting; + public event DomEventHandler? DurationChanged; + public event DomEventHandler? TimeUpdated; + public event DomEventHandler? Paused; + public event DomEventHandler? Played; + public event DomEventHandler? Playing; + public event DomEventHandler? RateChanged; + public event DomEventHandler? VolumeChanged; +#pragma warning restore CS0067 + + public void Play() + { + IAudioStream? stream; + + lock (_gate) + { + if (_isDisposed) + { + throw new DomException(DomError.InvalidState); + } + + if (_state == MediaControllerPlaybackState.Playing) + { + return; + } + + if (!_host.MayPlay(this)) + { + throw new DomException("NotAllowedError"); + } + + if (_state == MediaControllerPlaybackState.Ended) + { + _decoder.Seek(TimeSpan.Zero); + _frames = 0; + } + + _state = MediaControllerPlaybackState.Playing; + stream = _stream = _host.Output.Open(new AudioFormat(_sampleRate, _channels), this); + _timeUpdates = new Timer(_ => Raise(TimeUpdated, EventNames.TimeUpdate), null, TimeUpdateInterval, TimeUpdateInterval); + } + + _host.OnPlaying(this); + // outside of the lock: an output may pull right away (on another thread) + stream.Start(); + _host.OnChanged(); + Raise(Playing, EventNames.Playing); + } + + public void Pause() => Halt(MediaControllerPlaybackState.Waiting); + + /// + /// Stops the media for the engine (e.g. as its document went away), which the element + /// hears as a pause. + /// + public void Stop() + { + if (Halt(MediaControllerPlaybackState.Waiting)) + { + Raise(Paused, EventNames.Pause); + } + } + + /// + /// Stops the media for good and frees its decoder. + /// + public void Dispose() + { + Halt(MediaControllerPlaybackState.Waiting); + + lock (_gate) + { + if (!_isDisposed) + { + _isDisposed = true; + _decoder.Dispose(); + } + } + } + + public void Read(Span buffer) + { + var hasEnded = false; + + lock (_gate) + { + var count = 0; + + if (_state == MediaControllerPlaybackState.Playing && !_isDisposed) + { + count = _decoder.Read(buffer); + count -= count % _channels; + var gain = _isMuted ? 0f : (float)_volume; + + if (gain != 1f) + { + for (var i = 0; i < count; i++) + { + buffer[i] *= gain; + } + } + + _frames += count / _channels; + hasEnded = count < buffer.Length; + } + + buffer[count..].Clear(); + } + + if (hasEnded) + { + // not on the output's thread, which the stream is stopped from + ThreadPool.QueueUserWorkItem(_ => + { + if (Halt(MediaControllerPlaybackState.Ended)) + { + Raise(TimeUpdated, EventNames.TimeUpdate); + Raise(Ended, EventNames.Ended); + } + }); + } + } + + /// + /// Stops playing (if it does) and goes to the given state. + /// + private bool Halt(MediaControllerPlaybackState state) + { + IAudioStream? stream; + Timer? timeUpdates; + + lock (_gate) + { + if (_state != MediaControllerPlaybackState.Playing) + { + return false; + } + + _state = state; + stream = _stream; + timeUpdates = _timeUpdates; + _stream = null; + _timeUpdates = null; + } + + // outside of the lock, as an output may wait for a pull in progress + timeUpdates?.Dispose(); + stream?.Stop(); + stream?.Dispose(); + _host.OnHalted(this); + _host.OnChanged(); + return true; + } + + private void Raise(DomEventHandler? handler, string name) + { + if (handler is not null) + { + _context.GetService().Enqueue(() => handler.Invoke(this, new Event(name))); + } + } + + private sealed class TimeRanges(double start, double end) : ITimeRanges + { + public int Length => end > start ? 1 : 0; + + public double Start(int index) => index == 0 && Length > 0 ? start : throw new DomException(DomError.IndexSizeError); + + public double End(int index) => index == 0 && Length > 0 ? end : throw new DomException(DomError.IndexSizeError); + } +} diff --git a/src/AngleSharp.Browser/AudioResourceService.cs b/src/AngleSharp.Browser/AudioResourceService.cs new file mode 100644 index 0000000..adf7686 --- /dev/null +++ b/src/AngleSharp.Browser/AudioResourceService.cs @@ -0,0 +1,43 @@ +namespace AngleSharp.Browser; + +using System; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using AngleSharp.Dom; +using AngleSharp.Io; +using AngleSharp.Media; +using AngleSharp.Media.Dom; + +/// +/// Turns the responses of audio elements into their playbacks. The whole response is read +/// first, which the decoders then seek in. +/// +sealed class AudioResourceService(MediaHost host, IBrowsingContext context) : IResourceService +{ + private const int HeaderLength = 512; + + public bool SupportsType(string mimeType) => host.CanPlayType(mimeType); + + public async Task CreateAsync(IResponse response, CancellationToken cancel) + { + var data = new MemoryStream(); + await response.Content.CopyToAsync(data, cancel).ConfigureAwait(false); + var header = new ReadOnlyMemory(data.GetBuffer(), 0, (int)Math.Min(data.Length, HeaderLength)); + var codec = host.Codecs.FirstOrDefault(m => m.CanDecode(header.Span)) ?? + throw new NotSupportedException("The audio is of no supported format."); + data.Position = 0; + var decoder = codec.Open(data); + var playback = new AudioPlayback(host, context, decoder); + host.Add(playback); + return new AudioInfo(response.Address, playback); + } + + private sealed class AudioInfo(Url source, IMediaController controller) : IAudioInfo + { + public Url Source { get; set; } = source; + + public IMediaController Controller { get; } = controller; + } +} diff --git a/src/AngleSharp.Browser/BrowserEngine.Frames.cs b/src/AngleSharp.Browser/BrowserEngine.Frames.cs index 54a6e75..ee983b1 100644 --- a/src/AngleSharp.Browser/BrowserEngine.Frames.cs +++ b/src/AngleSharp.Browser/BrowserEngine.Frames.cs @@ -117,6 +117,7 @@ public bool HasPaintedDocument } var document = _document!; + SyncMediaChanges(document); var version = Volatile.Read(ref _layoutVersion); var time = DateTimeOffset.Now; var start = Stopwatch.GetTimestamp(); @@ -187,12 +188,18 @@ public bool HasPaintedDocument } _isLastFrameAnimating = frame.IsAnimating; + ScheduleImageFrame(frame); - // the first frame of a page tells if it scrolls as a whole, then it gets an overscan - if (frame.IsAnimating || (frame is { IsScrollShiftable: true, OverscanTop: 0 } && ViewportHeight > 1)) + // the first frame of a page tells if it scrolls as a whole, then it gets an overscan; an + // animation may only paint differently in the next frame (see TryReuseLastFrame) + if (frame is { IsScrollShiftable: true, OverscanTop: 0 } && ViewportHeight > 1) { Invalidate(); } + else if (frame.IsAnimating) + { + Invalidate(isMutation: true); + } // the list of an open dropdown is on top of the frame var shown = RefreshSelectPopup() is { } popup ? frame.WithOverlay(popup.Overlay) : frame; @@ -200,6 +207,33 @@ public bool HasPaintedDocument return new BrowserFrame(shown, raster => OnFramePainted(document, new FrameTiming(time, kind, layout, raster) { Metrics = metrics })); } + /// + /// 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 + /// shows the frame its time has come to, which needs no layout. + /// + private void ScheduleImageFrame(RenderedFrame frame) + { + var next = frame.GetTimeToNextImageFrame(); + + try + { + // a little later than due, to be sure the image shows the next frame + _imageFrameTimer.Change(next is { } delay ? delay + TimeSpan.FromMilliseconds(2) : Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); + } + catch (ObjectDisposedException) + { + } + } + + private void OnImageFrameDue(object? state) + { + if (!_isDisposed) + { + Invalidate(isMutation: true); + } + } + /// /// The last frame brought up to date without a layout of the whole document, if the changes /// allow it (see IDomHarness.UpdateFrame): it is the same frame when they did @@ -211,8 +245,28 @@ public bool HasPaintedDocument { metrics = RenderMetrics.None; - if (_lastFrame is not { } last || !ReferenceEquals(last.Document, document) || last.Width != ViewportWidth || last.Height != ViewportHeight || - _harness.UpdateFrame() is not { } frame) + if (_lastFrame is not { } last || !ReferenceEquals(last.Document, document) || last.Width != ViewportWidth || last.Height != ViewportHeight) + { + return null; + } + + // the time goes on for what animates, which the harness brings the frame to if it can + if (_isLastFrameAnimating) + { + // advancing raises PaintInvalidated, which is this very frame + _isPainting = true; + + try + { + AdvanceClock(); + } + finally + { + _isPainting = false; + } + } + + if (_harness.UpdateFrame() is not { } frame) { return null; } @@ -334,6 +388,8 @@ private static Dictionary CreatePointerInfos(HitTestMap m "text" => BrowserCursor.Text, _ when info.Href is not null => BrowserCursor.Pointer, _ when info.IsTextEntry => BrowserCursor.Text, + // the I-beam over text that can be selected, unless the page asks for another cursor + "auto" or "" when _options.IsTextSelectionEnabled && ReferenceEquals(hit.Element.Owner, frame.Document) && frame.Frame.HasTextAt(x, frameY) => BrowserCursor.Text, _ => BrowserCursor.Default, }; return new PointerTarget(hit.Element, info.Href, cursor, hit.IsInScrollContainer || info.IsListBox); diff --git a/src/AngleSharp.Browser/BrowserEngine.Input.cs b/src/AngleSharp.Browser/BrowserEngine.Input.cs index b10c152..b0f3916 100644 --- a/src/AngleSharp.Browser/BrowserEngine.Input.cs +++ b/src/AngleSharp.Browser/BrowserEngine.Input.cs @@ -72,6 +72,11 @@ partial class BrowserEngine private bool _isPointerWorkerRunning; private int _hitTestVersion = -1; private IElement? _hovered; + + /// + /// The hovered element and its ancestors when it got hovered, the outermost first. + /// + private List _hoverChain = []; private IElement? _pressed; // where the selection of the focused list box was last changed from, and what is active in it private IElement? _listBoxAnchor; @@ -150,9 +155,23 @@ public Task MovePointerAsync(double x, double y, CancellationToken cancellationT /// The held modifier keys. /// The token to cancel waiting for the engine. public Task PointerDownAsync(double x, double y, InputModifiers modifiers = InputModifiers.None, CancellationToken cancellationToken = default) => + PointerDownAsync(x, y, 1, modifiers, cancellationToken); + + /// + /// Presses the primary pointer button at the given viewport position, the given time in a + /// row (e.g., 2 for the second press of a double click, which selects a word). + /// + /// The horizontal position in CSS pixels. + /// The vertical position in CSS pixels. + /// The number of successive presses, at least 1. + /// The held modifier keys. + /// The token to cancel waiting for the engine. + public Task PointerDownAsync(double x, double y, int clickCount, InputModifiers modifiers = InputModifiers.None, CancellationToken cancellationToken = default) => RunExclusiveAsync(() => { var popup = _selectPopup; + // a press is the user activating the page (e.g. letting it play audio) + _media.HasUserActivation = true; // a press on the popup is for the popup alone, one elsewhere closes it if (popup is not null && popup.View.Contains(x, y)) @@ -184,6 +203,13 @@ public Task PointerDownAsync(double x, double y, InputModifiers modifiers = Inpu // a press on the select that is open just closed it ShowSelectPopup((IHtmlSelectElement)target); } + else if (PressMediaControls(target, x, y)) + { + } + else if (!IsDropdown(target)) + { + BeginTextSelection(hit, x, y, Math.Max(1, clickCount), modifiers); + } } } else if (hit is not null) @@ -191,6 +217,11 @@ public Task PointerDownAsync(double x, double y, InputModifiers modifiers = Inpu // something disabled takes no events, but a press on it still moves the focus UpdateFocus(hit); } + else + { + // a press next to the page removes the selection + BeginTextSelection(null, x, y, 1, InputModifiers.None); + } }, cancellationToken); /// @@ -221,6 +252,8 @@ public async Task PointerUpAsync(double x, double y, InputModifiers modifiers = return null; } + EndTextSelection(); + _seekingMedia = null; var target = ResolveListBoxTarget(HitTest(x, y), x, y); var pressed = _pressed; _pressed = null; @@ -343,7 +376,12 @@ public async Task ScrollAsync(double deltaX, double deltaY, CancellationToken ca /// The token to cancel waiting for the engine. public async Task KeyDownAsync(string key, InputModifiers modifiers = InputModifiers.None, CancellationToken cancellationToken = default) { - var navigation = await RunExclusiveAsync(() => HandleKeyDown(key, modifiers), cancellationToken).ConfigureAwait(false); + var navigation = await RunExclusiveAsync(() => + { + // like a press, other than Escape (HTML 6.4.3) + _media.HasUserActivation |= key != "Escape"; + return HandleKeyDown(key, modifiers); + }, cancellationToken).ConfigureAwait(false); if (navigation is not null) { @@ -445,22 +483,26 @@ private void UpdateHover(double x, double y, bool isMove = true) if (element != previous) { - if (previous is not null && IsInPage(previous.Owner)) - { - Fire(previous, CreateMouseEvent(previous, "pointerout", x, y, InputModifiers.None)); - Fire(previous, CreateMouseEvent(previous, "mouseout", x, y, InputModifiers.None)); - } - - if (element is not null) - { - Fire(element, CreateMouseEvent(element, "pointerover", x, y, InputModifiers.None)); - Fire(element, CreateMouseEvent(element, "mouseover", x, y, InputModifiers.None)); - } - + var left = previous is not null && IsInPage(previous.Owner) ? previous : null; + var chain = GetHoverChain(element); + // the boundary events of pointers come first, then the ones of the mouse (as in Chromium) + FireBoundaryEvents("pointer", left, element, chain, x, y); + FireBoundaryEvents("mouse", left, element, chain, x, y); _hovered = element; + _hoverChain = chain; KeepAnimating(InteractionDuration); } + if (isMove && _selecting is not null) + { + ExtendTextSelection(x, y); + } + + if (isMove) + { + SeekMedia(x); + } + if (element is not null && isMove) { Fire(element, CreateMouseEvent(element, "pointermove", x, y, InputModifiers.None)); @@ -849,6 +891,9 @@ private void ScrollToFragment(IDocument document, string fragment) switch (key) { + case "a" or "A" when !isTextEntry && (modifiers.HasFlag(InputModifiers.Control) || modifiers.HasFlag(InputModifiers.Meta)): + SelectAllText(); + return null; case "Tab": MoveFocus(modifiers.HasFlag(InputModifiers.Shift) ? -1 : 1); return null; @@ -1111,26 +1156,99 @@ private void FireChange(IElement element) Fire(element, new Event("change", true, false)); } - private MouseEvent CreateMouseEvent(IElement target, string type, double x, double y, InputModifiers modifiers) + /// + /// Gets the elements the pointer is over: the element and its ancestors, the outermost first. + /// + private static List GetHoverChain(IElement? element) + { + var chain = new List(); + + for (; element is not null; element = element.ParentElement) + { + chain.Add(element); + } + + chain.Reverse(); + return chain; + } + + /// + /// Fires the out and leave events for the element the pointer left, then the over and enter + /// events for the one it is over now, of the given kind ("pointer" or "mouse"). The enter + /// and leave events don't bubble and only reach the elements the pointer entered or left. + /// + private void FireBoundaryEvents(string kind, IElement? left, IElement? entered, List chain, double x, double y) + { + if (left is not null) + { + Fire(left, CreateMouseEvent(left, kind + "out", x, y, InputModifiers.None, entered)); + + for (var i = _hoverChain.Count - 1; i >= 0; i--) + { + var ancestor = _hoverChain[i]; + + if (!chain.Contains(ancestor) && IsInPage(ancestor.Owner) && ancestor.IsConnected()) + { + Fire(ancestor, CreateMouseEvent(ancestor, kind + "leave", x, y, InputModifiers.None, entered, bubbles: false)); + } + } + } + + if (entered is not null) + { + Fire(entered, CreateMouseEvent(entered, kind + "over", x, y, InputModifiers.None, left)); + + foreach (var ancestor in chain) + { + if (!_hoverChain.Contains(ancestor)) + { + Fire(ancestor, CreateMouseEvent(ancestor, kind + "enter", x, y, InputModifiers.None, left, bubbles: false)); + } + } + } + } + + private MouseEvent CreateMouseEvent(IElement target, string type, double x, double y, InputModifiers modifiers, IEventTarget? relatedTarget = null, bool bubbles = true) { var (clientX, clientY) = ToClient(target, x, y); - return CreateMouseEvent(target.Owner?.DefaultView ?? _document?.DefaultView, type, x, y, clientX, clientY, modifiers); + return CreateMouseEvent(target.Owner?.DefaultView ?? _document?.DefaultView, type, x, y, clientX, clientY, modifiers, relatedTarget, bubbles); } - private static MouseEvent CreateMouseEvent(IWindow? view, string type, double x, double y, double clientX, double clientY, InputModifiers modifiers) => new( - type, - bubbles: true, - cancelable: true, - view: view, - detail: 1, - screenX: (int)x, - screenY: (int)y, - clientX: (int)clientX, - clientY: (int)clientY, - ctrlKey: modifiers.HasFlag(InputModifiers.Control), - altKey: modifiers.HasFlag(InputModifiers.Alt), - shiftKey: modifiers.HasFlag(InputModifiers.Shift), - metaKey: modifiers.HasFlag(InputModifiers.Meta)); + private static MouseEvent CreateMouseEvent(IWindow? view, string type, double x, double y, double clientX, double clientY, InputModifiers modifiers, IEventTarget? relatedTarget = null, bool bubbles = true) => + // the pointer events of the mouse are the ones of the primary pointer, which scripts tell + // from touch by their type (e.g. SmartMenus only opens menus on hover for a mouse) + type.StartsWith("pointer", StringComparison.Ordinal) ? new PointerEvent( + type, + bubbles: bubbles, + // like in browsers, the enter and leave events can't be canceled + cancelable: bubbles, + view: view, + screenX: (int)x, + screenY: (int)y, + clientX: (int)clientX, + clientY: (int)clientY, + ctrlKey: modifiers.HasFlag(InputModifiers.Control), + altKey: modifiers.HasFlag(InputModifiers.Alt), + shiftKey: modifiers.HasFlag(InputModifiers.Shift), + metaKey: modifiers.HasFlag(InputModifiers.Meta), + relatedTarget: relatedTarget, + pointerId: 1, + pointerType: "mouse", + isPrimary: true) : new MouseEvent( + type, + bubbles: bubbles, + cancelable: bubbles, + view: view, + detail: 1, + screenX: (int)x, + screenY: (int)y, + clientX: (int)clientX, + clientY: (int)clientY, + ctrlKey: modifiers.HasFlag(InputModifiers.Control), + altKey: modifiers.HasFlag(InputModifiers.Alt), + shiftKey: modifiers.HasFlag(InputModifiers.Shift), + metaKey: modifiers.HasFlag(InputModifiers.Meta), + relatedTarget: relatedTarget); private KeyboardEvent CreateKeyboardEvent(string type, string key, InputModifiers modifiers) => new LegacyKeyboardEvent( type, diff --git a/src/AngleSharp.Browser/BrowserEngine.Media.cs b/src/AngleSharp.Browser/BrowserEngine.Media.cs new file mode 100644 index 0000000..6f2b68e --- /dev/null +++ b/src/AngleSharp.Browser/BrowserEngine.Media.cs @@ -0,0 +1,106 @@ +namespace AngleSharp.Browser; + +using System.Linq; +using System.Threading.Tasks; +using AngleSharp.Dom; +using AngleSharp.Html.Dom; + +/// +/// The controls the renderer paints for media (`audio[controls]`): a press on the play button +/// plays or pauses, one on the mute button mutes, and the timeline seeks while it is dragged. +/// +partial class BrowserEngine +{ + // the media whose timeline is dragged while the button is held + private IHtmlMediaElement? _seekingMedia; + // if a media changed what its controls would show since the last frame + private volatile bool _hasMediaChanged; + + /// + /// Acts on a press on the controls of a media element, if it was one. Requires exclusive access. + /// + private bool PressMediaControls(IElement? target, double x, double y) + { + if (target is not IHtmlMediaElement media || !media.HasMediaControls()) + { + return false; + } + + var (left, top) = ToClient(media, x, y); + + switch (media.GetMediaControlAt(left, top)) + { + case MediaControlPart.PlayPause when media.IsPaused || media.IsEnded: + // a page may not play it (e.g. no source), which its promise tells the page alone + media.PlayAsync().ContinueWith(task => task.Exception, TaskContinuationOptions.OnlyOnFaulted); + break; + case MediaControlPart.PlayPause: + media.Pause(); + break; + case MediaControlPart.Mute: + media.IsMuted = !media.IsMuted; + break; + case MediaControlPart.Timeline: + _seekingMedia = media; + SeekMedia(x); + break; + } + + // the controls show the state of the element, which changed without a mutation + Invalidate(); + return true; + } + + /// + /// Seeks the media whose timeline is dragged to the position of the pointer. Requires exclusive access. + /// + private void SeekMedia(double x) + { + if (_seekingMedia is not { } media) + { + return; + } + + var duration = media.Duration; + + if (media.Owner is null || !double.IsFinite(duration) || media.GetMediaTimelinePosition(ToClient(media, x, 0).X) is not { } position) + { + return; + } + + media.CurrentTime = position * duration; + Invalidate(); + } + + // the media changed what its controls show (it may be on another thread); only the + // controls show it, so a page without them (e.g. a game playing its sounds) keeps its frame + private void OnMediaChanged() + { + if (!_isDisposed) + { + _hasMediaChanged = true; + Invalidate(isMutation: true); + } + } + + /// + /// Lays out the next frame anew if a media changed since the last one and the page (or one + /// of its iframes) shows the controls of a media. Requires exclusive access. + /// + private void SyncMediaChanges(IDocument document) + { + if (_hasMediaChanged) + { + _hasMediaChanged = false; + + if (ShowsMediaControls(document)) + { + _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.Selection.cs b/src/AngleSharp.Browser/BrowserEngine.Selection.cs new file mode 100644 index 0000000..94a8065 --- /dev/null +++ b/src/AngleSharp.Browser/BrowserEngine.Selection.cs @@ -0,0 +1,118 @@ +namespace AngleSharp.Browser; + +using System.Threading; +using System.Threading.Tasks; +using AngleSharp.Dom; +using AngleSharp.Dom.Events; +using AngleSharp.Renderer; + +/// +/// Selecting text with the pointer (see ): the +/// harness of the document pressed in selects, and shows the selection without a layout. +/// +partial class BrowserEngine +{ + // the harness selecting text while the button is held, and the document it shows + private (IDomHarness Harness, IDocument Document)? _selecting; + + /// + /// Fires copy at the focused element and gets the selected text as it is shown, e.g., + /// for Ctrl+C. Gets an empty text if nothing is selected or the page canceled copying. + /// + /// The token to cancel waiting for the engine. + public Task CopySelectionAsync(CancellationToken cancellationToken = default) => + RunExclusiveAsync(() => + { + if (!_options.IsTextSelectionEnabled || FocusedDocument is not { Context: { } context } document) + { + return string.Empty; + } + + var text = GetHarness(document, context).SelectedText; + + if (text.Length == 0 || GetKeyboardTarget() is not IElement target || + !Fire(target, new Event("copy", bubbles: true, cancelable: true))) + { + return string.Empty; + } + + return text; + }, cancellationToken); + + /// + /// Starts selecting at the position, after a press whose mousedown wasn't canceled, in + /// the document of what was hit there. Requires exclusive access. + /// + private void BeginTextSelection(IElement? hit, double x, double y, int clickCount, InputModifiers modifiers) + { + _selecting = null; + + if (!_options.IsTextSelectionEnabled || (hit?.Owner ?? _document) is not { Context: { } context } document) + { + return; + } + + var harness = GetHarness(document, context); + var (clientX, clientY) = ToSelectionClient(hit, x, y); + + if (harness.BeginTextSelection(clientX, clientY, clickCount, modifiers.HasFlag(InputModifiers.Shift))) + { + _selecting = (harness, document); + } + } + + /// + /// Extends the selection to the position, while the button is held. Requires exclusive access. + /// + private void ExtendTextSelection(double x, double y) + { + if (_selecting is not { } selecting || !IsInPage(selecting.Document)) + { + _selecting = null; + return; + } + + var (clientX, clientY) = ToSelectionClient(selecting.Document.DocumentElement, x, y); + selecting.Harness.ExtendTextSelection(clientX, clientY); + } + + /// + /// Ends selecting, as the button was released. Requires exclusive access. + /// + private void EndTextSelection() + { + _selecting?.Harness.EndTextSelection(); + _selecting = null; + } + + /// + /// Selects all text of the focused document, e.g., for Ctrl+A. Requires exclusive access. + /// + private void SelectAllText() + { + if (_options.IsTextSelectionEnabled && FocusedDocument is { Context: { } context } document) + { + GetHarness(document, context).SelectAllText(); + } + } + + private IDomHarness GetHarness(IDocument document, IBrowsingContext context) + { + if (ReferenceEquals(document, _document)) + { + return _harness; + } + + // the harness of an iframe's document is the renderer's, which selects by default + var harness = context.GetDomHarness(); + harness.IsTextSelectionEnabled = _options.IsTextSelectionEnabled; + return harness; + } + + /// + /// The position in the viewport of the element's document as its harness sees it: the page + /// may be shown scrolled ahead of the DOM. + /// + private (double X, double Y) ToSelectionClient(IElement? element, double x, double y) => + ToClient(element, x, y + ScrollPosition - ScrollTop); +} diff --git a/src/AngleSharp.Browser/BrowserEngine.cs b/src/AngleSharp.Browser/BrowserEngine.cs index cf2e866..1db302e 100644 --- a/src/AngleSharp.Browser/BrowserEngine.cs +++ b/src/AngleSharp.Browser/BrowserEngine.cs @@ -18,6 +18,7 @@ namespace AngleSharp.Browser; using AngleSharp.Io; using AngleSharp.Io.Cookie; using AngleSharp.Js; +using AngleSharp.Media; using AngleSharp.Renderer; using AngleSharp.Scripting; using AngleSharp.Renderer.Rendering; @@ -68,7 +69,11 @@ function clamp(name, min) { private readonly SemaphoreSlim _gate = new(1, 1); private readonly NavigationHistory _history = new(); private readonly BrowserDiagnostics _diagnostics = new(); + private readonly MediaHost _media; private readonly Timer _heartbeat; + // the next frame of an animated image shown (see ScheduleImageFrame) + private readonly Timer _imageFrameTimer; + private readonly string[] _schemes; private MutationObserver? _observer; private IDocument? _document; private IEventLoop? _eventLoop; @@ -102,6 +107,8 @@ public BrowserEngine(BrowserOptions? options = null) private BrowserEngine(BrowserOptions options, BrowserEngine? opener) { _options = options; + _media = new MediaHost(options); + _media.Changed += OnMediaChanged; _device = new DefaultRenderDevice { @@ -141,7 +148,9 @@ private BrowserEngine(BrowserOptions options, BrowserEngine? opener) .WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true, - }); + }) + // audio plays on the host's output (see BrowserOptions.AudioOutput) + .With>(context => new AudioResourceService(_media, context)); if (options.IsScriptingEnabled) { @@ -166,6 +175,14 @@ private BrowserEngine(BrowserOptions options, BrowserEngine? opener) _history.TraversalRequested += delta => _ = Task.Run(() => TraverseAsync(delta, CancellationToken.None)); _history.Changed += OnStateChanged; + // the host's own schemes come first, as the requesters are asked in order + _schemes = [.. options.SchemeHandlers.Keys]; + + if (_schemes.Length > 0) + { + config = config.With(new SchemeRequester(options.SchemeHandlers)); + } + if (options.Configure is not null) { config = options.Configure(config); @@ -226,9 +243,11 @@ private BrowserEngine(BrowserOptions options, BrowserEngine? opener) } }); _harness = _context.GetDomHarness(); + _harness.IsTextSelectionEnabled = options.IsTextSelectionEnabled; _loop = _context.GetService(); _harness.PaintInvalidated += OnPaintInvalidated; _heartbeat = new Timer(OnHeartbeat, null, HeartbeatInterval, HeartbeatInterval); + _imageFrameTimer = new Timer(OnImageFrameDue); } /// @@ -318,6 +337,17 @@ public bool CanGoForward get => _history.CanGoForward; } + /// + /// Gets a copy of the history: its entries (oldest first) and the index of the current one, + /// e.g., for a menu of the back and forward buttons. + /// + public BrowserHistory History => _history.GetSnapshot(); + + /// + /// Gets the custom schemes the engine answers; see . + /// + public IReadOnlyList Schemes => _schemes; + /// /// Gets the width of the viewport in CSS pixels. /// @@ -338,7 +368,16 @@ public bool CanGoForward /// /// The address as entered by the user. /// The address to navigate to. - public static string NormalizeAddress(string? address) + public static string NormalizeAddress(string? address) => NormalizeAddress(address, []); + + /// + /// Turns user input from an address bar into an absolute address, which keeps addresses + /// of the given custom schemes (see ) as they are. + /// + /// The address as entered by the user. + /// The custom schemes, e.g., "app" for "app:settings". + /// The address to navigate to. + public static string NormalizeAddress(string? address, IEnumerable schemes) { var trimmed = address?.Trim() ?? string.Empty; @@ -347,6 +386,13 @@ public static string NormalizeAddress(string? address) return "about:blank"; } + var colon = trimmed.IndexOf(':'); + + if (colon > 0 && schemes.Contains(trimmed[..colon], StringComparer.OrdinalIgnoreCase)) + { + return trimmed; + } + if (Path.IsPathRooted(trimmed) && File.Exists(trimmed)) { return new Uri(trimmed).AbsoluteUri; @@ -365,10 +411,10 @@ public static string NormalizeAddress(string? address) /// /// Navigates to the given address. /// - /// The address to load; see . + /// The address to load; see . /// The token to cancel loading. public Task NavigateAsync(string address, CancellationToken cancellationToken = default) => - LoadAsync(NormalizeAddress(address), false, cancellationToken); + LoadAsync(NormalizeAddress(address, _schemes), false, cancellationToken); /// /// Loads the given HTML source as a document. @@ -403,6 +449,14 @@ public Task GoBackAsync(CancellationToken cancellationToken = default) => public Task GoForwardAsync(CancellationToken cancellationToken = default) => TraverseAsync(1, cancellationToken); + /// + /// Navigates to the entry in the history the given number of steps away, if any. + /// + /// The number of steps: negative ones go back, positive ones forward. + /// The token to cancel loading. + public Task GoAsync(int delta, CancellationToken cancellationToken = default) => + TraverseAsync(delta, cancellationToken); + /// /// Changes the size of the viewport. /// @@ -502,6 +556,7 @@ public void Dispose() { _isDisposed = true; _heartbeat.Dispose(); + _imageFrameTimer.Dispose(); lock (_scrollLock) { @@ -511,6 +566,8 @@ public void Dispose() _harness.PaintInvalidated -= OnPaintInvalidated; _observer?.Disconnect(); + _media.Changed -= OnMediaChanged; + _media.StopAll(); _context.Dispose(); } } @@ -680,12 +737,17 @@ private void SyncActiveDocument() _observer = null; _document = active; _hovered = null; + _hoverChain = []; _pressed = null; + _seekingMedia = null; _focusedFrameDocument = null; _hoveredFrames.Clear(); _pointerFrame = null; _wasReadyForLayout = false; ResetScrollPosition(); + // the media of the previous document stops, and a new one has to be activated anew + _media.HasUserActivation = false; + _media.StopDetached(); if (active is not null) { @@ -702,6 +764,7 @@ private void SyncActiveDocument() if (active is not null && active.ReadyState != DocumentReadyState.Loading && (active.Title ?? string.Empty) != _title) { _title = active.Title ?? string.Empty; + _history.SetTitle(active, _title); OnStateChanged(); } @@ -728,6 +791,8 @@ private async Task RunExclusiveAsync(Func action, CancellationToken can /// private async Task RunEnteredAsync(Func action, CancellationToken cancellationToken) { + T result; + try { // AngleSharp is not thread-safe; the event loop serializes the work with scripts. A task @@ -745,19 +810,22 @@ private async Task RunEnteredAsync(Func action, CancellationToken cance return default!; } }); - var result = await task.ConfigureAwait(false); + result = await task.ConfigureAwait(false); if (error is not null) { ExceptionDispatchInfo.Throw(error); } - - return result; } finally { _gate.Release(); } + + // this runs on the event loop, which the caller is not to continue on: what it does with + // the result (e.g. rasterizing a frame) would hold up the scripts + await Task.Yield(); + return result; } private Task RunExclusiveAsync(Action action, CancellationToken cancellationToken = default) => @@ -790,8 +858,8 @@ private void OnHeartbeat(object? state) if (Environment.TickCount64 < Volatile.Read(ref _animateUntil)) { - // the last frame is checked for changes, it is laid out anew only if it animates - Invalidate(isMutation: !_isLastFrameAnimating); + // the last frame is checked for changes (also of its animations, see TryReuseLastFrame) + Invalidate(isMutation: true); } } diff --git a/src/AngleSharp.Browser/BrowserHistory.cs b/src/AngleSharp.Browser/BrowserHistory.cs new file mode 100644 index 0000000..9c06a1d --- /dev/null +++ b/src/AngleSharp.Browser/BrowserHistory.cs @@ -0,0 +1,54 @@ +namespace AngleSharp.Browser; + +using System.Collections.Generic; + +/// +/// A copy of the session history of an engine (see ). +/// +/// The entries, the oldest first. +/// The index of the current entry, or -1 if there is none. +public sealed record BrowserHistory(IReadOnlyList Entries, int Index) +{ + /// + /// Gets the entries before the current one, the closest first (one step back, two, ...). + /// + public IReadOnlyList Back + { + get + { + var back = new List(); + + for (var i = Index - 1; i >= 0; i--) + { + back.Add(Entries[i]); + } + + return back; + } + } + + /// + /// Gets the entries after the current one, the closest first (one step forward, two, ...). + /// + public IReadOnlyList Forward + { + get + { + var forward = new List(); + + for (var i = Index + 1; i < Entries.Count; i++) + { + forward.Add(Entries[i]); + } + + return forward; + } + } +} + +/// +/// An entry of the session history. +/// +/// The address of the entry. +/// The title of its document, or empty if it has none (yet). +public sealed record BrowserHistoryEntry(string Url, string Title); diff --git a/src/AngleSharp.Browser/BrowserOptions.cs b/src/AngleSharp.Browser/BrowserOptions.cs index 7591dc7..e2e2485 100644 --- a/src/AngleSharp.Browser/BrowserOptions.cs +++ b/src/AngleSharp.Browser/BrowserOptions.cs @@ -3,6 +3,8 @@ namespace AngleSharp.Browser; using System; using System.Collections.Generic; using System.Net; +using System.Threading; +using System.Threading.Tasks; using AngleSharp.Io; using AngleSharp.Io.Dom; using AngleSharp.Io.ServiceWorkerApi; @@ -49,6 +51,32 @@ public sealed class BrowserOptions /// public IClipboardPlatform? ClipboardPlatform { get; set; } + /// + /// Gets or sets if the text of pages can be selected with the pointer (dragging, a double + /// press for a word, a triple one for a paragraph, Shift to extend) and with Ctrl+A. Off by + /// default, as the layouts then also record where their text comes from. + /// + public bool IsTextSelectionEnabled { get; set; } + + /// + /// Gets or sets where the audio of the pages plays (e.g. an adapter of the platform's audio + /// device). If null, it plays silently: media advances in real time, with its events, but + /// isn't heard (). + /// + public IAudioOutput? AudioOutput { get; set; } + + /// + /// Gets the audio formats that play, in the order they are tried; by default those of + /// (WAV, MP3, Ogg Vorbis and Ogg Opus). + /// + public IList AudioCodecs { get; } = Browser.AudioCodecs.CreateDefault(); + + /// + /// Gets or sets if pages may play audible media before the user interacted with them (a + /// press or a key). Off by default, like in browsers; muted media always plays. + /// + public bool IsAutoplayAllowed { get; set; } + /// /// Gets or sets the initial viewport width in CSS pixels. /// @@ -87,6 +115,14 @@ public sealed class BrowserOptions /// public Func? Configure { get; set; } + /// + /// Gets the handlers of custom URL schemes by their name (without the colon), e.g., "app" + /// answering the requests of "app:settings". A handler answers null if there is nothing at + /// the address. Addresses of these schemes are navigated to as entered. + /// + public IDictionary>> SchemeHandlers { get; } = + new Dictionary>>(StringComparer.OrdinalIgnoreCase); + /// /// Creates the IO options of an engine. Another window of a profile shares its data, but /// gets an HTTP handler of its own: a handler cannot be configured anymore once it has sent diff --git a/src/AngleSharp.Browser/LegacyKeyboardEvent.cs b/src/AngleSharp.Browser/LegacyKeyboardEvent.cs index 7cc2618..020d29c 100644 --- a/src/AngleSharp.Browser/LegacyKeyboardEvent.cs +++ b/src/AngleSharp.Browser/LegacyKeyboardEvent.cs @@ -88,7 +88,9 @@ public LegacyKeyboardEvent(string type, IWindow? view, string key, string modifi "ArrowUp" => 38, "ArrowRight" => 39, "ArrowDown" => 40, + "Insert" => 45, "Delete" => 46, + "Meta" => 91, "," => 188, "-" => 189, "." => 190, @@ -102,6 +104,8 @@ public LegacyKeyboardEvent(string type, IWindow? view, string key, string modifi " " => "Space", "Enter" or "Tab" or "Escape" or "Backspace" or "Delete" or "Home" or "End" or "PageUp" or "PageDown" or "Insert" or "ArrowUp" or "ArrowDown" or "ArrowLeft" or "ArrowRight" => key, + // the view can't tell the left modifier from the right one + "Shift" or "Control" or "Alt" or "Meta" => key + "Left", { Length: 1 } when char.IsAsciiLetter(key[0]) => "Key" + char.ToUpperInvariant(key[0]), { Length: 1 } when char.IsAsciiDigit(key[0]) => "Digit" + key, _ => key.Length > 1 && key[0] == 'F' && key[1..].All(char.IsDigit) ? key : string.Empty, diff --git a/src/AngleSharp.Browser/MediaHost.cs b/src/AngleSharp.Browser/MediaHost.cs new file mode 100644 index 0000000..f370de1 --- /dev/null +++ b/src/AngleSharp.Browser/MediaHost.cs @@ -0,0 +1,142 @@ +namespace AngleSharp.Browser; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +/// +/// The media of an engine: where it plays, what may play (the autoplay policy) and which +/// media there is, so the engine stops the media of documents that went away. +/// +sealed class MediaHost(BrowserOptions options) +{ + private readonly Lock _gate = new(); + // all media of the documents, weakly, as pages create (and drop) media freely + private readonly List> _media = []; + // the media playing, which nothing else may hold on to + private readonly HashSet _playing = []; + private volatile bool _hasUserActivation; + + public IAudioOutput Output { get; } = options.AudioOutput ?? new SilentAudioOutput(); + + public IReadOnlyList Codecs { get; } = [.. options.AudioCodecs]; + + /// + /// Gets or sets if the user interacted with the current page (a press or a key), which + /// lets it play audible media (HTML 6.4.3, sticky activation). + /// + public bool HasUserActivation + { + get => _hasUserActivation; + set => _hasUserActivation = value; + } + + /// + /// Gets the media playing. + /// + public int PlayingCount + { + get + { + lock (_gate) + { + return _playing.Count; + } + } + } + + /// + /// Raised when a media changed what its controls show other than its time going on (e.g. it + /// was paused, seeked or muted), from any thread. + /// + public event Action? Changed; + + public void OnChanged() => Changed?.Invoke(); + + public bool MayPlay(AudioPlayback playback) => + options.IsAutoplayAllowed || _hasUserActivation || playback.IsMuted || playback.Volume == 0; + + /// + /// Checks if a content type (with its codecs parameter, if any) plays. + /// + public bool CanPlayType(string type) + { + var parameters = type.Split(';'); + var essence = parameters[0].Trim(); + + // a response of no audio type (e.g. served as a download) is told by its data + if (essence.Length == 0 || essence.Equals("application/octet-stream", StringComparison.OrdinalIgnoreCase) || essence.Equals("binary/octet-stream", StringComparison.OrdinalIgnoreCase)) + { + return parameters.Length == 1 && Codecs.Count > 0; + } + + var codecs = Codecs.Where(m => m.ContentTypes.Contains(essence, StringComparer.OrdinalIgnoreCase)).ToArray(); + var names = parameters.Skip(1) + .Select(m => m.Split('=', 2)) + .Where(m => m.Length == 2 && m[0].Trim().Equals("codecs", StringComparison.OrdinalIgnoreCase)) + .SelectMany(m => m[1].Trim().Trim('"').Split(',')) + .Select(m => m.Trim()) + .Where(m => m.Length > 0); + return codecs.Length > 0 && names.All(name => codecs.Any(codec => codec.CodecNames.Contains(name, StringComparer.OrdinalIgnoreCase))); + } + + public void Add(AudioPlayback playback) + { + lock (_gate) + { + _media.RemoveAll(m => !m.TryGetTarget(out _)); + _media.Add(new WeakReference(playback)); + } + } + + public void OnPlaying(AudioPlayback playback) + { + lock (_gate) + { + _playing.Add(playback); + } + } + + public void OnHalted(AudioPlayback playback) + { + lock (_gate) + { + _playing.Remove(playback); + } + } + + /// + /// Stops the media of documents that are no longer shown in their browsing context. + /// + public void StopDetached() => Stop(playback => !ReferenceEquals(playback.Context.Active, playback.Document)); + + /// + /// Stops all media, e.g. once the engine is disposed. + /// + public void StopAll() => Stop(_ => true); + + private void Stop(Func predicate) + { + var stopped = new List(); + + lock (_gate) + { + foreach (var reference in _media) + { + if (reference.TryGetTarget(out var playback) && predicate(playback)) + { + stopped.Add(playback); + } + } + + _media.RemoveAll(m => !m.TryGetTarget(out var playback) || stopped.Contains(playback)); + } + + foreach (var playback in stopped) + { + playback.Stop(); + playback.Dispose(); + } + } +} diff --git a/src/AngleSharp.Browser/NavigationHistory.cs b/src/AngleSharp.Browser/NavigationHistory.cs index 983efde..05f9b40 100644 --- a/src/AngleSharp.Browser/NavigationHistory.cs +++ b/src/AngleSharp.Browser/NavigationHistory.cs @@ -2,6 +2,7 @@ namespace AngleSharp.Browser; using System; using System.Collections.Generic; +using System.Linq; using AngleSharp.Browser.Dom; using AngleSharp.Dom; using System.Reflection; @@ -20,7 +21,13 @@ sealed class NavigationHistory : IHistory /// /// One entry: its address, its document (once known) and the state a script gave it. /// - public sealed record Entry(string Url, IDocument? Document, object? State); + public sealed record Entry(string Url, IDocument? Document, object? State) + { + /// + /// Gets the title of the document, once it has one. + /// + public string Title { get; init; } = string.Empty; + } /// /// Raised when a script asks to move through the history (back, forward, go). @@ -112,6 +119,31 @@ public void Push(string url, IDocument document) } } + /// + /// Gives the current entry the title of its (displayed) document. + /// + public void SetTitle(IDocument document, string title) + { + lock (_entries) + { + if (_index >= 0 && ReferenceEquals(_entries[_index].Document, document)) + { + _entries[_index] = _entries[_index] with { Title = title }; + } + } + } + + /// + /// A copy of the entries and the index of the current one. + /// + public BrowserHistory GetSnapshot() + { + lock (_entries) + { + return new BrowserHistory([.. _entries.Select(m => new BrowserHistoryEntry(m.Url, m.Title))], _index); + } + } + public int Length { get { lock (_entries) return _entries.Count; } @@ -155,7 +187,7 @@ public void PushState(object data, string? title, string? url = null) } var current = _entries[_index]; - Add(new Entry(ResolveUrl(current, url), current.Document, data)); + Add(new Entry(ResolveUrl(current, url), current.Document, data) { Title = current.Title }); SetDocumentUrl(_entries[_index]); } diff --git a/src/AngleSharp.Browser/SchemeRequester.cs b/src/AngleSharp.Browser/SchemeRequester.cs new file mode 100644 index 0000000..30c7929 --- /dev/null +++ b/src/AngleSharp.Browser/SchemeRequester.cs @@ -0,0 +1,24 @@ +namespace AngleSharp.Browser; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using AngleSharp.Io; + +/// +/// Answers the requests of the custom schemes registered in +/// . +/// +internal sealed class SchemeRequester(IDictionary>> handlers) : BaseRequester +{ + // a snapshot: the options may change once the engine has been created + private readonly Dictionary>> _handlers = new(handlers, StringComparer.OrdinalIgnoreCase); + + public IEnumerable Schemes => _handlers.Keys; + + public override bool SupportsProtocol(string protocol) => _handlers.ContainsKey(protocol); + + protected override Task PerformRequestAsync(Request request, CancellationToken cancel) => + _handlers.TryGetValue(request.Address.Scheme, out var handler) ? handler(request, cancel) : Task.FromResult(null); +} diff --git a/src/AngleSharp.Browser/SilentAudioOutput.cs b/src/AngleSharp.Browser/SilentAudioOutput.cs new file mode 100644 index 0000000..fa9fb93 --- /dev/null +++ b/src/AngleSharp.Browser/SilentAudioOutput.cs @@ -0,0 +1,81 @@ +namespace AngleSharp.Browser; + +using System; +using System.Diagnostics; +using System.Threading; + +/// +/// The audio output without a device: it pulls the samples in real time and drops them, so +/// media plays (with its time advancing, events and its end) without being heard. The engine +/// uses it unless gives another one. +/// +public sealed class SilentAudioOutput : IAudioOutput +{ + private static readonly TimeSpan Interval = TimeSpan.FromMilliseconds(20); + + /// + public IAudioStream Open(AudioFormat format, IAudioSource source) => new SilentStream(format, source); + + private sealed class SilentStream(AudioFormat format, IAudioSource source) : IAudioStream + { + private readonly Lock _gate = new(); + private readonly Stopwatch _clock = new(); + private float[] _buffer = []; + private Timer? _timer; + private long _frames; + + public void Start() + { + lock (_gate) + { + if (_timer is null) + { + _frames = 0; + _clock.Restart(); + _timer = new Timer(_ => Pull(), null, Interval, Interval); + } + } + } + + public void Stop() + { + lock (_gate) + { + _timer?.Dispose(); + _timer = null; + _clock.Stop(); + } + } + + public void Dispose() => Stop(); + + private void Pull() + { + lock (_gate) + { + if (_timer is null) + { + return; + } + + // what played since the start, so the clock doesn't drift with the timer + var due = (long)(_clock.Elapsed.TotalSeconds * format.SampleRate) - _frames; + + if (due <= 0) + { + return; + } + + var length = (int)Math.Min(due, format.SampleRate) * format.Channels; + + if (_buffer.Length < length) + { + _buffer = new float[length]; + } + + source.Read(_buffer.AsSpan(0, length)); + _frames += length / format.Channels; + } + } + } +} diff --git a/src/Directory.Build.props b/src/Directory.Build.props index a738e6c..159616b 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -1,6 +1,6 @@ - 0.1.0 + 0.2.0 enable latest true diff --git a/src/Vision/App.axaml b/src/Vision/App.axaml index 0dbddfb..f323db6 100644 --- a/src/Vision/App.axaml +++ b/src/Vision/App.axaml @@ -168,6 +168,42 @@ + + + + + + + + + + + + +
+
+

Vision pages

+

The browser's own pages, which are available at addresses starting with vision:.

+
+ {{notice}} +
{{pages}}
+
+ + diff --git a/src/Vision/Pages/requester.html b/src/Vision/Pages/requester.html new file mode 100644 index 0000000..d2ca282 --- /dev/null +++ b/src/Vision/Pages/requester.html @@ -0,0 +1,751 @@ + + + + +Requester + + + +
+
+ +
{ }
+
+

Requester

+

Send requests with the requesters of this window, which add its user agent and default headers like they do for pages.

+
+
+ +
+
+
+ + + +
+
+ Requester + + +
+
+
+ Headers + One "Name: value" per line. + +
+
+ Body + UTF-8. Without a Content-Type, JSON if it starts with { or [. + +
+
+
+
+ +
+
+ No response yet + Send a request to see its status, headers and body here. +
+ +
+ +
+ + +
+
+
+ +
+
+
Saved requests 0 + +
+
+
+ + + + diff --git a/src/Vision/Pages/start.html b/src/Vision/Pages/start.html new file mode 100644 index 0000000..230419a --- /dev/null +++ b/src/Vision/Pages/start.html @@ -0,0 +1,144 @@ + + + + +Start + + + +
+
+

Vision

+

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

+
+ +
+

Most visited

+
{{most-visited}}
+
+ +
+

Demos

+
{{demos}}
+
+ +
+

Vision

+
{{pages}}
+
+
+ + diff --git a/src/Vision/ViewModels/IBrowserHost.cs b/src/Vision/ViewModels/IBrowserHost.cs index c055947..63fa807 100644 --- a/src/Vision/ViewModels/IBrowserHost.cs +++ b/src/Vision/ViewModels/IBrowserHost.cs @@ -2,6 +2,7 @@ namespace Vision.ViewModels; using System; using AngleSharp.Browser; +using Vision.Pages; /// /// What a browser window needs from the application: other windows and the shared settings. @@ -18,6 +19,11 @@ public interface IBrowserHost /// event EventHandler? ColorSchemeChanged; + /// + /// Gets the page new windows start with. + /// + string StartPage { get; } + /// /// Opens a browser window, which shares the profile of the given engine, if possible. /// @@ -25,6 +31,11 @@ public interface IBrowserHost void OpenSettings(); + /// + /// Creates the settings page, which applies the settings of the browser. + /// + HtmlPage CreateSettingsPage(Action close); + void OpenAbout(BrowserEngine owner); /// diff --git a/src/Vision/ViewModels/MainViewModel.cs b/src/Vision/ViewModels/MainViewModel.cs index 037cebb..66fa1b9 100644 --- a/src/Vision/ViewModels/MainViewModel.cs +++ b/src/Vision/ViewModels/MainViewModel.cs @@ -10,24 +10,32 @@ namespace Vision.ViewModels; using Avalonia.Media.Imaging; using Avalonia.Threading; using System.Diagnostics; +using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; +using Vision.Models; using Vision.Pages; public partial class MainViewModel : ViewModelBase, IDisposable { private const string ApplicationName = "Vision"; + private const int SuggestionCount = 8; private readonly IBrowserHost _host; + private readonly UrlHistory _history; + private string? _recordedUrl; + private bool _isShowingAddress; private HtmlPage? _panel; private string? _lastUrl; private int _isErrorCheckPending; private string? _iconUrl; private CancellationTokenSource? _iconLoading; - public MainViewModel(BrowserEngine engine, string startAddress, IBrowserHost host) + public MainViewModel(BrowserEngine engine, string startAddress, IBrowserHost host, UrlHistory? history = null) { Engine = engine; - Address = startAddress; + _history = history ?? new UrlHistory(); + ShowAddress(startAddress); _host = host; engine.ColorScheme = host.ColorScheme; engine.StateChanged += (_, _) => Dispatcher.UIThread.Post(UpdateState); @@ -98,6 +106,23 @@ public MainViewModel(BrowserEngine engine, string startAddress, IBrowserHost hos [ObservableProperty] public partial BrowserEngine? PanelEngine { get; set; } + /// + /// Gets the addresses visited before, which match what is typed into the address bar. + /// + public ObservableCollection Suggestions { get; } = []; + + /// + /// Gets if the address bar shows its suggestions. + /// + [ObservableProperty] + public partial bool IsSuggesting { get; set; } + + /// + /// Gets the index of the suggestion chosen with the arrow keys, or -1 for what is typed. + /// + [ObservableProperty] + public partial int SelectedSuggestionIndex { get; set; } = -1; + public bool HasStatus => Status.Length > 0; /// @@ -113,19 +138,127 @@ public void Dispose() ClosePanel(); } + /// + /// Moves the selection through the suggestions (from what is typed to the first one, and + /// back), if they are shown. + /// + /// If the suggestions handled the move. + public bool MoveSuggestion(int delta) + { + if (!IsSuggesting || Suggestions.Count == 0) + { + return false; + } + + // -1 is what has been typed, which sits above the first suggestion + var count = Suggestions.Count + 1; + SelectedSuggestionIndex = ((SelectedSuggestionIndex + 1 + delta) % count + count) % count - 1; + return true; + } + + /// + /// Hides the suggestions. + /// + /// If they were shown. + public bool CloseSuggestions() + { + var wasSuggesting = IsSuggesting; + IsSuggesting = false; + SelectedSuggestionIndex = -1; + Suggestions.Clear(); + return wasSuggesting; + } + + /// + /// Navigates to the given suggestion, e.g., when it was clicked. + /// + public Task NavigateToAsync(UrlSuggestion suggestion) + { + CloseSuggestions(); + ShowAddress(suggestion.Url); + return Engine.NavigateAsync(suggestion.Url); + } + + /// + /// Navigates to the chosen suggestion, else to what has been typed. + /// [RelayCommand] private Task NavigateAsync() { - Address = BrowserEngine.NormalizeAddress(Address); + if (IsSuggesting && SelectedSuggestionIndex >= 0 && SelectedSuggestionIndex < Suggestions.Count) + { + return NavigateToAsync(Suggestions[SelectedSuggestionIndex]); + } + + CloseSuggestions(); + ShowAddress(BrowserEngine.NormalizeAddress(Address, Engine.Schemes)); return Engine.NavigateAsync(Address); } + partial void OnAddressChanged(string value) + { + // only what the user types is looked up + if (!_isShowingAddress) + { + UpdateSuggestions(value); + } + } + + private void UpdateSuggestions(string text) + { + var suggestions = _history.Suggest(text, SuggestionCount); + SelectedSuggestionIndex = -1; + Suggestions.Clear(); + + foreach (var suggestion in suggestions) + { + Suggestions.Add(suggestion); + } + + IsSuggesting = Suggestions.Count > 0; + } + + /// + /// Shows an address in the address bar, which is not looked up like a typed one. + /// + private void ShowAddress(string address) + { + _isShowingAddress = true; + + try + { + Address = address; + } + finally + { + _isShowingAddress = false; + } + } + [RelayCommand(CanExecute = nameof(CanGoBack))] private Task GoBackAsync() => Engine.GoBackAsync(); [RelayCommand(CanExecute = nameof(CanGoForward))] private Task GoForwardAsync() => Engine.GoForwardAsync(); + /// + /// Gets the entries of the history the back (or forward) button can jump to, the closest + /// first, which its menu shows when it is held down. + /// + /// If the entries before the current one are wanted, else the ones after it. + public IReadOnlyList GetHistoryJumps(bool isBack) + { + var history = Engine.History; + var entries = isBack ? history.Back : history.Forward; + var sign = isBack ? -1 : 1; + return [.. entries.Select((entry, i) => new HistoryJump(sign * (i + 1), entry.Url, entry.Title))]; + } + + /// + /// Jumps to an entry of the history, e.g., one chosen in the menu of the back button. + /// + public Task JumpAsync(HistoryJump jump) => Engine.GoAsync(jump.Delta); + [RelayCommand] private Task ReloadAsync() => Engine.ReloadAsync(); @@ -215,12 +348,17 @@ private void UpdateState() if (Engine.Url is string url && url != "about:blank" && url != _lastUrl) { _lastUrl = url; - Address = url; + CloseSuggestions(); + ShowAddress(url); } + RecordVisit(); + var isSecure = Engine.Url?.StartsWith("https:", StringComparison.OrdinalIgnoreCase) ?? false; IsSecure = isSecure; - SiteInfo = isSecure ? "Connection is secure" : "Connection is not secure"; + SiteInfo = isSecure ? "Connection is secure" + : Engine.Url?.StartsWith($"{VisionPages.Scheme}:", StringComparison.OrdinalIgnoreCase) ?? false ? "Vision's own page" + : "Connection is not secure"; WindowTitle = string.IsNullOrWhiteSpace(Engine.Title) ? ApplicationName : $"{Engine.Title} - {ApplicationName}"; if (Engine.IconUrl != _iconUrl) @@ -236,6 +374,28 @@ private void UpdateState() UpdateStatus(); } + /// + /// Counts the visit of a page once it has loaded (also of an address a script pushed), and + /// keeps its title, which the suggestions show. + /// + private void RecordVisit() + { + if (Engine.IsLoading || Engine.Url is not string url) + { + return; + } + + if (url != _recordedUrl) + { + _recordedUrl = url; + _history.Record(url, Engine.Title); + } + else + { + _history.SetTitle(url, Engine.Title); + } + } + /// /// Loads the icon of the current page, which replaces the one of the previous page. /// @@ -274,3 +434,17 @@ private void UpdateStatus() Status = Engine.HoveredLink ?? (IsLoading ? $"Loading {Address}" : string.Empty); } } + +/// +/// An entry of the history the back or forward button jumps to. +/// +/// The steps to the entry: negative ones go back, positive ones forward. +/// The address of the entry. +/// The title of its page, or empty. +public sealed record HistoryJump(int Delta, string Url, string Title) +{ + /// + /// Gets what the menu shows: the title, else the address. + /// + public string Heading => Title.Length > 0 ? Title : Url; +} diff --git a/src/Vision/Views/MainWindow.axaml b/src/Vision/Views/MainWindow.axaml index 692fdaf..811be68 100644 --- a/src/Vision/Views/MainWindow.axaml +++ b/src/Vision/Views/MainWindow.axaml @@ -1,6 +1,7 @@ @@ -50,7 +53,7 @@ - + + private void ShowHistoryMenu(Button button) + { + if (_viewModel is not { } viewModel) + { + return; + } + + var jumps = viewModel.GetHistoryJumps(button == BackButton); + + if (jumps.Count == 0) + { + return; + } + + var menu = new MenuFlyout { Placement = PlacementMode.BottomEdgeAlignedLeft }; + + foreach (var jump in jumps) + { + var item = new MenuItem { Header = jump.Heading, MaxWidth = 420 }; + ToolTip.SetTip(item, jump.Url); + item.Click += (_, _) => _ = viewModel.JumpAsync(jump); + menu.Items.Add(item); + } + + menu.ShowAt(button); + } + + private void OnAddressKeyDown(object? sender, KeyEventArgs e) + { + if (_viewModel is { } viewModel && e.KeyModifiers == KeyModifiers.None) + { + e.Handled = e.Key switch + { + Key.Down => viewModel.MoveSuggestion(1), + Key.Up => viewModel.MoveSuggestion(-1), + Key.Escape => viewModel.CloseSuggestions(), + _ => false, + }; + } + } + + private void OnAddressLostFocus(object? sender, RoutedEventArgs e) + { + // a click on a suggestion comes first + Dispatcher.UIThread.Post(() => + { + if (!AddressBox.IsFocused) + { + _viewModel?.CloseSuggestions(); + } + }, DispatcherPriority.Background); + } + + private void OnSuggestionPressed(object? sender, PointerPressedEventArgs e) + { + if (_viewModel is { } viewModel && e.GetCurrentPoint(SuggestionList).Properties.IsLeftButtonPressed && + (e.Source as Visual)?.FindAncestorOfType(includeSelf: true)?.DataContext is UrlSuggestion suggestion) + { + e.Handled = true; + _ = viewModel.NavigateToAsync(suggestion); + } } protected override void OnDataContextChanged(EventArgs e) diff --git a/src/Vision/Vision.csproj b/src/Vision/Vision.csproj index 5c5e3c1..517d038 100644 --- a/src/Vision/Vision.csproj +++ b/src/Vision/Vision.csproj @@ -3,6 +3,8 @@ WinExe net10.0 false + + true app.manifest Assets\vision.ico - + @@ -36,6 +38,9 @@ All + + +