Browser vuoto: correzioni dopo la revisione (#52)

La revisione di c49df4c ha trovato alcuni punti deboli. Si correggono qui.

- Fuori vista la pagina torna al 100%. Lo zoom calcolato per uno schermo
  piccolo restava anche per le sessioni del motore, e le pagine vedevano un
  devicePixelRatio diverso (regola 4). Il rapporto si ricalcola solo quando
  la finestra viene sullo schermo.
- Pulsante nella barra delle applicazioni. WPF lo cambia nascondendo la
  finestra e mostrandola di nuovo (verificato con un aggancio a
  WM_WINDOWPOSCHANGED). Ora il pulsante cambia solo mentre la finestra è
  fuori vista. Sullo schermo la finestra chiede di ridisegnarsi
  (RedrawWindow), senza nulla che la pagina veda. Una prova con WebView2
  vero controlla che la finestra non si nasconda mai sullo schermo.
- Ridotta a icona troppo a lungo, la finestra si ripristina coperta (DWM) e
  senza prendere il fuoco, e si sposta fuori vista prima di scoprirsi. Prima
  ricompariva per un attimo dove stava. Spostare la posizione di ripristino
  non basta: Windows la riporta su uno schermo (provato).
- Dopo un riavvio del processo GPU i bordi della pagina cambiano davvero: un
  pixel in meno, poi quelli veri. Gli stessi bordi di nuovo potevano non
  servire a nulla.
- «Pagina iniziale», sulla barra di Windows e nella vista remota, passa da
  BrowserConnectionService.OpenStartPageAsync. Aspetta la fine della
  sessione del motore e il turno della pagina, come l'apertura dal riposo,
  e agisce solo mentre Alberto guida.
- Vista remota.
  - Dopo un riavvio dei fotogrammi la vista aspetta il primo fotogramma per
    mezzo secondo prima dell'immagine ferma: Chromium lo manda solo dopo la
    risposta allo start, e prima quasi ogni riavvio costava una cattura.
  - L'immagine ferma si scarta se nel frattempo arriva un fotogramma vero.
  - Il silenzio si conta dall'avvio.
  - Un riavvio del browser durante la chiusura non lascia eccezioni non
    osservate.
- Un POST vuoto senza Content-Length (a pezzi, HTTP/2) non dà più 400 su
  begin, cancel e browser/show (ApiHttp.OptionalBodyAsync).
- La pagina Browser toglie ?accesso=1 dall'indirizzo. Ricaricarla riapriva
  la pagina di accesso.
- RemoteViewFramesTests aspetta fino a 20 s invece di 5. Controlla che
  l'immagine arrivi, non quanto in fretta; il tempo va nell'uscita della
  prova.

Aggiornati PROTOCOLLO.md, la guida (Primo collegamento, Installazione
Windows) e docs/decisioni.md con le righe di #52.

Prove nuove:
- AFrameSoonAfterARestartNeedsNoStillPicture
- PaginaInizialeWaitsForThePageTurnAndActsOnlyWhileAlbertoIsAtTheBrowser
- ABodyWithoutALengthIsReadAndAnEmptyOneIsNoBody
- nella prova della finestra vera: nessun nascondere sullo schermo e pagina
  al 100% fuori vista

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-16 13:28:08 +01:00
1 parent c49df4ca7b
commit 654076d280
25 files changed
+505 -86

No files matched your search

+36
View File
@@ -206,6 +206,42 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>
/// «Pagina iniziale» of the window's bar and of the remote view (issue #52): Alberto's own navigation (rule 7) to
/// <see cref="StartPageUrl"/>, as when he takes the browser from the rest page — after the engine's session ended and
/// with the page's turn, so that no step of a session or of the profile search has its page swapped under it. Only
/// while he is at the browser: otherwise the page is the engine's and nothing happens.
/// </summary>
public async Task OpenStartPageAsync(CancellationToken ct)
{
if (!_browser.IsAvailable)
{
return;
}
await _commands.WaitAsync(ct).ConfigureAwait(false);
try
{
if (!_browser.UserIsDriving)
{
return;
}
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
using var turn = await TakePageAsync(ct).ConfigureAwait(false);
var target = StartPageUrl;
var what = target == _loginUrl ? "pagina di accesso" : "pagina iniziale del sito";
var result = await _browser.Cdp.NavigateAsync(target, ct).ConfigureAwait(false);
_log.Info("collegamento", result.Succeeded
? $"«Pagina iniziale»: {what} aperta."
: $"«Pagina iniziale»: {what} non aperta (errore di rete del browser).");
}
finally
{
_commands.Release();
}
}
public async Task ReleaseAsync(CancellationToken ct)
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
+2 -2
View File
@@ -245,8 +245,8 @@ public sealed class FebeApp : IAsyncDisposable
}
// Browser, connection, engine. The engine loop starts only once the browser is up.
// The start page (issue #52) is the connection's, which exists only after the browser: read when asked.
var context = new FebePlatformContext(o, data, Database, Clock, Log, Tracker, () => Connection?.StartPageUrl ?? o.LoginUrl);
// «Pagina iniziale» (issue #52) is the connection's, which exists only after the browser: looked up when pressed.
var context = new FebePlatformContext(o, data, Database, Clock, Log, Tracker, ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask);
var browser = await _platform.CreateBrowserAsync(context, ct).ConfigureAwait(false);
Browser = browser;
var connection = new BrowserConnectionService(browser, Database, Tracker, Clock, Log, o.LoginUrl, HomeUrl(o.Site.BaseUrl), o.Site.SessionCookie);
+5 -8
View File
@@ -55,15 +55,12 @@ public interface IFebePlatform
/// <param name="Clock">The clock of the engine.</param>
/// <param name="Log">The log.</param>
/// <param name="Tracker">When Alberto last used the browser: the desktop window marks it when he uses and closes it.</param>
/// <param name="StartPage">
/// Where «Pagina iniziale» of the browser window goes (issue #52): the site's home when connected, the login page
/// otherwise. Null: the login page.
/// <param name="OpenStartPage">
/// What «Pagina iniziale» of the browser window does (issue #52): the connection opens the site's home when connected,
/// the login page otherwise, once the engine's session ended and with the page's turn
/// (<c>BrowserConnectionService.OpenStartPageAsync</c>). Null: the button does nothing.
/// </param>
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func<string>? StartPage = null)
{
/// <summary>The start page now (<see cref="StartPage"/>, or the login page).</summary>
public string CurrentStartPage() => StartPage?.Invoke() ?? Options.LoginUrl;
}
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func<CancellationToken, Task>? OpenStartPage = null);
/// <summary>Options of the shared composition, filled by each shell from its own configuration.</summary>
public sealed record FebeAppOptions
@@ -22,7 +22,8 @@ public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, in
/// lost acknowledgement stops the frames for good, and a change of renderer (another site, the rest page, a crash) may
/// leave the screencast on the old one. After <see cref="Silence"/> without frames — measured from the start, from the
/// last frame or from the last change of document of the main frame — the screencast is stopped and started again (a
/// new screencast session), and one still picture of the page is sent when the start brings no frame. Each restart
/// new screencast session), and one still picture of the page is sent when no frame came within
/// <see cref="FirstFrameWait"/> of the start (Chromium sends the first frame only after answering the start). Each restart
/// doubles the wait, up to <see cref="LongestSilence"/>: a page that does not move (Chromium sends nothing then) costs
/// one restart every so often, not one every two seconds. Frames that flow again (<see cref="FlowingFrames"/> after a
/// restart) or a new document bring the wait back to <see cref="Silence"/>.
@@ -38,6 +39,9 @@ public sealed record ScreencastWatchdog(TimeSpan Silence, TimeSpan Tick, TimeSpa
/// </summary>
public const int FlowingFrames = 3;
/// <summary>How long a restart waits for its first frame before it sends a still picture instead.</summary>
public static readonly TimeSpan FirstFrameWait = TimeSpan.FromMilliseconds(500);
/// <summary>About two seconds, looked at four times a second, at most half a minute between restarts.</summary>
public static ScreencastWatchdog Default { get; } = new(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(250), TimeSpan.FromSeconds(30));
}
@@ -118,6 +122,7 @@ public sealed class ScreencastSession : IAsyncDisposable
private bool _restartWanted;
private bool _silent;
private DateTimeOffset _silentSince;
private TaskCompletionSource? _nextFrame;
/// <param name="cdp">The page session.</param>
/// <param name="log">Where starts, restarts and silences are noted (never parameters or frames).</param>
@@ -338,9 +343,11 @@ public sealed class ScreencastSession : IAsyncDisposable
private void OnReconnected(object? sender, EventArgs e) =>
_ = Task.Run(async () =>
{
var ct = _lifetime.Token;
// Read inside the try: a browser restart that races the dispose finds the source disposed.
var ct = CancellationToken.None;
try
{
ct = _lifetime.Token;
await _starts.WaitAsync(ct).ConfigureAwait(false);
try
{
@@ -412,10 +419,16 @@ public sealed class ScreencastSession : IAsyncDisposable
}
}
/// <summary>Stop and start again (a new screencast session), then one still picture when no frame came.</summary>
/// <summary>
/// Stop and start again (a new screencast session), then one still picture when no frame came within
/// <see cref="ScreencastWatchdog.FirstFrameWait"/>. The silence counts from the start; the wait for the next restart
/// doubles here, before the start, so that frames flowing meanwhile bring it back to the short one.
/// </summary>
private async Task RestartAsync(ScreencastWatchdog watchdog, TimeSpan silence, bool afterLoad, CancellationToken ct)
{
await _starts.WaitAsync(ct).ConfigureAwait(false);
var started = false;
TaskCompletionSource? nextFrame = null;
try
{
bool first;
@@ -427,6 +440,11 @@ public sealed class ScreencastSession : IAsyncDisposable
_silent = true;
_silentSince = _clock.Now - silence;
}
_restartWanted = false;
_framesSinceRestart = 0;
var longer = _silenceLimit + _silenceLimit;
_silenceLimit = longer < watchdog.LongestSilence ? longer : watchdog.LongestSilence;
}
var seconds = Math.Max(1, (int)Math.Round(silence.TotalSeconds)).ToString(CultureInfo.InvariantCulture);
@@ -443,7 +461,6 @@ public sealed class ScreencastSession : IAsyncDisposable
_log.Debug(line);
}
var before = FramesReceived;
try
{
await _cdp.SendAsync("Page.stopScreencast", null, ct).ConfigureAwait(false);
@@ -453,9 +470,22 @@ public sealed class ScreencastSession : IAsyncDisposable
// Nothing was running on the browser side: the start below is what matters.
}
// Ready before the start: its first frame may come as soon as Chromium has answered.
nextFrame = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
lock (_watch)
{
_nextFrame = nextFrame;
}
await SendStartAsync(ct).ConfigureAwait(false);
lock (_watch)
{
_watchFrom = _clock.Now;
}
started = true;
Interlocked.Increment(ref _restarts);
if (FramesReceived == before)
if (!await FrameWithinAsync(nextFrame.Task, ScreencastWatchdog.FirstFrameWait, ct).ConfigureAwait(false))
{
await SendStillAsync(ct).ConfigureAwait(false);
}
@@ -469,29 +499,65 @@ public sealed class ScreencastSession : IAsyncDisposable
{
lock (_watch)
{
_watchFrom = _clock.Now;
_restartWanted = false;
_framesSinceRestart = 0;
var longer = _silenceLimit + _silenceLimit;
_silenceLimit = longer < watchdog.LongestSilence ? longer : watchdog.LongestSilence;
if (!started)
{
_watchFrom = _clock.Now; // a failed restart: the next one after a whole silence, not at the next look
}
if (ReferenceEquals(_nextFrame, nextFrame))
{
_nextFrame = null;
}
}
_starts.Release();
}
}
/// <summary>True when <paramref name="frame"/> completes within <paramref name="wait"/> (on the clock).</summary>
private async Task<bool> FrameWithinAsync(Task frame, TimeSpan wait, CancellationToken ct)
{
if (frame.IsCompleted)
{
return true;
}
using var stopWaiting = CancellationTokenSource.CreateLinkedTokenSource(ct);
var delay = _clock.Delay(wait, stopWaiting.Token);
await Task.WhenAny(frame, delay).ConfigureAwait(false);
// Asked of the frame itself, not of which task woke the wait: both may be done by now, and a frame is a frame.
if (frame.IsCompleted)
{
// The pause ends here (a clock that moves only when asked keeps no sleeper behind).
await stopWaiting.CancelAsync().ConfigureAwait(false);
return true;
}
await delay.ConfigureAwait(false); // cancelled with ct: the restart ends there
return false;
}
/// <summary>
/// One picture of the page as it is (<c>Page.captureScreenshot</c>, already allowed for the preview): a page that
/// does not repaint shows something, and the pointer can be placed on it.
/// </summary>
private async Task SendStillAsync(CancellationToken ct)
{
var before = FramesReceived;
var jpeg = await PagePreview.CaptureAsync(_cdp, Math.Clamp((_options ?? new ScreencastOptions()).Quality, 0, 100), ct).ConfigureAwait(false);
if (jpeg.Length == 0 || Volatile.Read(ref _stopped) == 1)
{
return;
}
if (FramesReceived != before)
{
// A real frame came during the capture: it is newer and carries the page's scroll and zoom.
_log.Debug("Vista remota: immagine ferma scartata, è arrivato un fotogramma.");
return;
}
var last = LastFrame;
double width;
double height;
@@ -577,6 +643,8 @@ public sealed class ScreencastSession : IAsyncDisposable
{
_lastFrameAt = _clock.Now;
_restartWanted = false;
_nextFrame?.TrySetResult();
_nextFrame = null;
if (++_framesSinceRestart >= ScreencastWatchdog.FlowingFrames && _options?.Watchdog is { } watchdog)
{
// The page moves: frames flow, and a silence from now on is worth a quick restart again.
+55 -12
View File
@@ -4,6 +4,7 @@ using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
using Febe.Desktop.Native;
namespace Febe.Desktop.Browser;
@@ -17,10 +18,16 @@ namespace Febe.Desktop.Browser;
/// <remarks>
/// <para>
/// Issue #52. On screen it has a button in the taskbar, so that minimising it does not make it vanish; minimised it
/// keeps Alberto at the wheel, but never for long (S2): after <see cref="MinimizedLimit"/> it is restored and put out of
/// view as if he had closed it. When the page and its bar do not fit in the work area of the screen (a small screen, a
/// large text scale) the window shrinks to fit and the page is shown zoomed out (<see cref="Fit"/>), always with the
/// same size in CSS pixels. While the page is the empty rest page the bar says so.
/// keeps Alberto at the wheel, but never for long (S2): after <see cref="MinimizedLimit"/> it is put out of view as if
/// he had closed it, restored there without coming on screen. When the page and its bar do not fit in the work area of
/// the screen (a small screen, a large text scale) the window shrinks to fit and the page is shown zoomed out
/// (<see cref="Fit"/>), always with the same size in CSS pixels; out of view the page is at 100% again, so that the
/// engine's pages always see the same browser. While the page is the empty rest page the bar says so.
/// </para>
/// <para>
/// WPF changes the taskbar button of a shown window by hiding it and showing it again (seen in WM_WINDOWPOSCHANGED:
/// SWP_HIDEWINDOW, then SWP_SHOWWINDOW). The button is therefore changed only while the window is out of view: before it
/// comes on screen, after it left.
/// </para>
/// </remarks>
internal sealed class BrowserWindow : Window
@@ -183,6 +190,8 @@ internal sealed class BrowserWindow : Window
{
var area = SystemParameters.WorkArea;
FitTo(area);
// Still out of view: the hide and show with which WPF adds the button happen where nobody sees them.
ShowInTaskbar = true;
var width = ActualWidth > 0 ? ActualWidth : PageWidth * Fit;
var height = ActualHeight > 0 ? ActualHeight : (PageHeight * Fit) + BarHeight;
@@ -192,19 +201,42 @@ internal sealed class BrowserWindow : Window
/// <summary>
/// Parks the window just right of every screen: open, «visible» for Windows and for WebView2, out of Alberto's view
/// (S2), without its taskbar button. Never <c>Hide()</c>, never left minimised.
/// (S2), without its taskbar button and with the page at 100% (<see cref="Fit"/> 1). Never <c>Hide()</c>, never
/// left minimised: a minimised window is restored without taking the focus and cloaked meanwhile, because Windows
/// restores it where it was on screen (a restore position off every screen is moved back onto one).
/// </summary>
public void MoveOffScreen()
{
_minimized.Stop();
if (WindowState == WindowState.Minimized)
var restoring = WindowState == WindowState.Minimized;
var cloaked = restoring && Cloak(true);
try
{
WindowState = WindowState.Normal;
if (restoring)
{
Win32.ShowWindow(Handle, Win32.SwShowNoActivate);
if (WindowState == WindowState.Minimized)
{
WindowState = WindowState.Normal;
}
}
Left = SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth + 64;
Top = SystemParameters.VirtualScreenTop;
// Out of view first: the hide and show with which WPF removes the button happen where nobody sees them.
ShowInTaskbar = false;
}
finally
{
if (cloaked)
{
Cloak(false);
}
}
ShowInTaskbar = false;
Left = SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth + 64;
Top = SystemParameters.VirtualScreenTop;
// The engine's pages see the browser as it is, at 100%, whatever the size of Alberto's screen (rule 4).
SetFit(1);
}
/// <summary>Lets the window really close (Febe is stopping).</summary>
@@ -250,7 +282,7 @@ internal sealed class BrowserWindow : Window
_minimized.Stop();
if (WindowState == WindowState.Minimized)
{
WindowState = WindowState.Normal;
// Restored out of view by the owner (MoveOffScreen), never first on screen where it was.
DoneRequested?.Invoke(this, EventArgs.Empty);
}
}
@@ -260,7 +292,11 @@ internal sealed class BrowserWindow : Window
// The frame of the window (title bar and borders) around the page and its bar.
var frame = SystemParameters.WindowNonClientFrameThickness;
var resize = SystemParameters.WindowResizeBorderThickness;
var fit = FitFor(area.Width, area.Height, PageWidth, PageHeight, frame.Left + frame.Right + resize.Left + resize.Right, frame.Top + frame.Bottom + resize.Top + resize.Bottom);
SetFit(FitFor(area.Width, area.Height, PageWidth, PageHeight, frame.Left + frame.Right + resize.Left + resize.Right, frame.Top + frame.Bottom + resize.Top + resize.Bottom));
}
private void SetFit(double fit)
{
if (Math.Abs(fit - Fit) < 0.001)
{
return;
@@ -273,6 +309,13 @@ internal sealed class BrowserWindow : Window
PageAreaChanged?.Invoke(this, EventArgs.Empty);
}
/// <summary>Cloaks or uncloaks the window (DWM); false when DWM refused.</summary>
private bool Cloak(bool on)
{
var value = on ? 1 : 0;
return Win32.DwmSetWindowAttribute(Handle, Win32.DwmCloak, ref value, sizeof(int)) == 0;
}
private static Button BarButton(string text, string tip) => new()
{
Content = text,
+1 -1
View File
@@ -52,7 +52,7 @@ internal sealed class WebView2Browser : IFebeBrowser
_options = new BrowserOptions(ProfileDirectory, settings.Width, settings.Height);
Host = new WebView2Host(
ui,
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.CurrentStartPage),
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage),
context.Log);
Host.BrowserProcessFailed += (_, _) => RequestRestart(null);
}
+82 -8
View File
@@ -9,6 +9,7 @@ using Febe.Browser.Hosting;
using Febe.Browser.WebView2;
using Febe.Core.Abstractions;
using Febe.Desktop.Core;
using Febe.Desktop.Native;
using Microsoft.Web.WebView2.Core;
namespace Febe.Desktop.Browser;
@@ -18,8 +19,11 @@ namespace Febe.Desktop.Browser;
/// <param name="AdditionalBrowserArguments">The switches of S2 (<see cref="BrowserArguments.ForWebView2"/>).</param>
/// <param name="Icon">The icon of the window.</param>
/// <param name="MarkUsed">Called when Alberto uses the browser and when he is done with it («Riprendi»).</param>
/// <param name="StartPage">Where «Pagina iniziale» goes: the site's home when connected, the login page otherwise (issue #52).</param>
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func<string>? StartPage = null);
/// <param name="OpenStartPage">
/// What «Pagina iniziale» does (issue #52): the connection opens the site's home when connected, the login page otherwise,
/// once the engine's session ended and with the page's turn. Null: the button does nothing.
/// </param>
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func<CancellationToken, Task>? OpenStartPage = null);
/// <summary>What the host does when a process of WebView2 fails (issue #52).</summary>
internal enum ProcessFailureResponse
@@ -33,7 +37,7 @@ internal enum ProcessFailureResponse
/// <summary>The page crashed (or hangs while nobody looks): back to the rest page (spec §6.1).</summary>
Rest,
/// <summary>The GPU process restarted: the bounds are given again, or the window may stay blank or black.</summary>
/// <summary>The GPU process restarted: the page is resized by a pixel and back, or the window may stay blank or black.</summary>
Redraw,
}
@@ -179,8 +183,10 @@ internal sealed class WebView2Host : IBrowserHost
// The lease first: once the window is on screen the engine must be still, whatever happens to the focus.
TakeLease();
// On screen, perhaps shrunk to fit it: WebView2 gets its bounds again and learns where its window is now.
// On screen, perhaps shrunk to fit it: WebView2 gets its bounds again and learns where its window is now, and paints
// again (WPF hid and showed the window, out of view, to give it its taskbar button).
UpdateBounds();
Repaint();
try
{
_controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
@@ -345,7 +351,7 @@ internal sealed class WebView2Host : IBrowserHost
window.DoneRequested += (_, _) => Done();
window.BackRequested += (_, _) => UserNavigation(core => core.GoBack(), core => core.CanGoBack);
window.ReloadRequested += (_, _) => UserNavigation(core => core.Reload(), _ => true);
window.HomeRequested += (_, _) => UserNavigation(core => core.Navigate(_settings.StartPage!()), _ => _settings.StartPage is not null);
window.HomeRequested += (_, _) => OpenStartPage();
window.DpiChanged += (_, _) => UpdateBounds();
window.PageAreaChanged += (_, _) => UpdateBounds();
@@ -508,9 +514,10 @@ internal sealed class WebView2Host : IBrowserHost
break;
case ProcessFailureResponse.Redraw:
// A windowed WebView can stay blank or black after the GPU process restarted until its bounds change:
// they are given again (never IsVisible = false, S2), once this handler has returned.
_ = _ui.InvokeAsync(UpdateBounds, DispatcherPriority.Background);
// A windowed WebView can stay blank or black after the GPU process restarted until its size changes: the
// same bounds again may be no change at all, so one pixel less and then the real ones (never
// IsVisible = false, S2), once this handler has returned.
_ = _ui.InvokeAsync(Redraw, DispatcherPriority.Background);
break;
default:
if (kind == CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
@@ -576,6 +583,73 @@ internal sealed class WebView2Host : IBrowserHost
}
}
/// <summary>
/// «Pagina iniziale»: Alberto's own navigation (rule 7), done by the connection, which first waits for the engine's
/// session to end and takes the page's turn (issue #52).
/// </summary>
private void OpenStartPage()
{
if (_settings.OpenStartPage is not { } open || _core is null)
{
return;
}
TakeLease();
_ = OpenStartPageQuietlyAsync(open);
}
private async Task OpenStartPageQuietlyAsync(Func<CancellationToken, Task> open)
{
try
{
await open(CancellationToken.None).ConfigureAwait(true);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Warn("browser", $"«Pagina iniziale» non aperta ({ex.GetType().Name}).");
}
}
/// <summary>After a GPU restart: a real change of size (one pixel less), then the real bounds and a repaint.</summary>
private void Redraw()
{
if (_controller is not { } controller || _window is not { } window)
{
return;
}
try
{
var bounds = window.PageBounds;
if (bounds.Height > 1)
{
controller.Bounds = bounds with { Height = bounds.Height - 1 };
}
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
{
// The browser process is gone: the next start sizes the new WebView.
return;
}
_ = _ui.InvokeAsync(
() =>
{
UpdateBounds();
Repaint();
},
DispatcherPriority.Background);
}
/// <summary>Asks the window and WebView2's child windows to paint again; nothing the page can see changes.</summary>
private void Repaint()
{
if (_window is { } window)
{
Win32.RedrawWindow(window.Handle, IntPtr.Zero, IntPtr.Zero, Win32.RdwInvalidate | Win32.RdwAllChildren | Win32.RdwUpdateNow);
}
}
private void UpdateBounds()
{
if (_controller is not { } controller || _window is not { } window)
+15
View File
@@ -66,6 +66,21 @@ internal static class Win32
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsIconic(IntPtr window);
public const uint RdwInvalidate = 0x0001;
public const uint RdwAllChildren = 0x0080;
public const uint RdwUpdateNow = 0x0100;
/// <summary>DWMWA_CLOAK: the window stays shown for Windows but DWM does not put it on screen.</summary>
public const int DwmCloak = 13;
/// <summary>Asks a window and its children (WebView2's own) to paint again, without changing anything else.</summary>
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool RedrawWindow(IntPtr window, IntPtr updateRect, IntPtr updateRegion, uint flags);
[DllImport("dwmapi.dll")]
public static extern int DwmSetWindowAttribute(IntPtr window, int attribute, ref int value, int size);
[DllImport("user32.dll")]
public static extern IntPtr SetCursor(IntPtr cursor);
+24 -13
View File
@@ -25,7 +25,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
private readonly IClock _clock;
private readonly IClock _browserClock;
private readonly FebeLog _log;
private readonly Func<string>? _startPage;
private readonly Func<CancellationToken, Task>? _openStartPage;
private readonly Lock _gate = new();
private readonly SemaphoreSlim _opening = new(1, 1);
private BrowserRemoteViewConnection? _current;
@@ -39,15 +39,18 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
/// Time for the waits on the browser itself and for the frames' watchdog; null: the wall clock, because the browser
/// commits a navigation and paints in real time whatever clock the engine runs on (the tests compress it).
/// </param>
/// <param name="startPage">Where «Pagina iniziale» goes (issue #52); null: the button does nothing.</param>
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func<string>? startPage = null)
/// <param name="openStartPage">
/// What «Pagina iniziale» does (issue #52): the connection opens the start page once the engine's session ended and
/// with the page's turn; null: the button does nothing.
/// </param>
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func<CancellationToken, Task>? openStartPage = null)
{
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_log = log ?? throw new ArgumentNullException(nameof(log));
_browserClock = browserClock ?? new SystemClock(clock.LocalZone);
_startPage = startPage;
_openStartPage = openStartPage;
}
/// <summary>
@@ -93,7 +96,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
}
var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock, _log.ForBrowser("vista"), _startPage, Watchdog);
var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock, _log.ForBrowser("vista"), _openStartPage, Watchdog);
try
{
await connection.StartAsync(_browser.WindowWidth, _browser.WindowHeight, ct).ConfigureAwait(false);
@@ -177,7 +180,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
private readonly BrowserUseTracker _tracker;
private readonly IClock _clock;
private readonly RemoteViewSession _session;
private readonly Func<string>? _startPage;
private readonly Func<CancellationToken, Task>? _openStartPage;
private readonly ScreencastWatchdog? _watchdog;
private readonly Lock _gate = new();
private readonly Queue<RemoteViewMeta> _meta = new();
@@ -196,13 +199,13 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
private int _disposed;
private bool _used;
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock, IBrowserLog log, Func<string>? startPage, ScreencastWatchdog? watchdog)
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock, IBrowserLog log, Func<CancellationToken, Task>? openStartPage, ScreencastWatchdog? watchdog)
{
_owner = owner;
_browser = browser;
_tracker = tracker;
_clock = clock;
_startPage = startPage;
_openStartPage = openStartPage;
_watchdog = watchdog;
// A real log (issue #52): the starts, restarts and silences of the frames reach the registro.
@@ -316,14 +319,22 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
public async Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct)
{
MarkUsed();
if (action == RemoteViewNavigation.Home)
{
// Alberto's own navigation (rule 7), done by the connection: like the start page opened from the rest page,
// it waits for the engine's session to end and takes the page's turn first.
if (_openStartPage is { } open)
{
await open(ct).ConfigureAwait(false);
}
return;
}
string? target;
lock (_gate)
{
if (action == RemoteViewNavigation.Home)
{
target = _startPage?.Invoke();
}
else if (action == RemoteViewNavigation.Back)
if (action == RemoteViewNavigation.Back)
{
// Back never lands on the empty rest page (issue #52): it skips it, and with nothing before it stays.
var previous = _history.Count - 2;
+1 -1
View File
@@ -53,7 +53,7 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(app);
RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log, startPage: () => app.Connection?.StartPageUrl ?? app.Options.LoginUrl);
RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log, openStartPage: ct => app.Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask);
services.AddSingleton<IRemoteViewHost>(RemoteView);
}
+35
View File
@@ -2,6 +2,7 @@ using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using Febe.Core.Storage;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;
namespace Febe.Web.Api;
@@ -86,6 +87,40 @@ public static class ApiHttp
}
}
/// <summary>
/// Reads an optional JSON body: <paramref name="empty"/> when there is none — no length and nothing to read, as an
/// empty POST may come chunked or over HTTP/2 — and the body otherwise (a 400 when it is not readable).
/// </summary>
public static async Task<T> OptionalBodyAsync<T>(HttpContext context, JsonTypeInfo<T> type, T empty)
{
ArgumentNullException.ThrowIfNull(context);
var request = context.Request;
if (request.ContentLength == 0)
{
return empty;
}
if (request.ContentLength is null)
{
if (context.Features.Get<IHttpRequestBodyDetectionFeature>() is { CanHaveBody: false })
{
return empty;
}
// A body without a declared length may still be empty: one byte tells, then it is read from the start.
request.EnableBuffering();
var probe = new byte[1];
if (await request.Body.ReadAsync(probe, context.RequestAborted).ConfigureAwait(false) == 0)
{
return empty;
}
request.Body.Position = 0;
}
return await BodyAsync(context, type).ConfigureAwait(false);
}
/// <summary>A JSON answer with its source-generated metadata.</summary>
public static IResult Json<T>(T value, JsonTypeInfo<T> type, int status = StatusCodes.Status200OK) =>
Results.Json(value, type, statusCode: status);
+2 -6
View File
@@ -22,9 +22,7 @@ public static class ConnectionApi
endpoints.MapPost("/api/connection/begin", async (HttpContext context, IConnectionService connection, CancellationToken ct) =>
{
var body = context.Request.ContentLength is null or > 0
? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest).ConfigureAwait(false)
: new BeginDrivingRequest(false);
var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest, new BeginDrivingRequest(false)).ConfigureAwait(false);
await connection.BeginUserDrivingAsync(body.OpenLogin, ct).ConfigureAwait(false);
return Results.NoContent();
});
@@ -41,9 +39,7 @@ public static class ConnectionApi
// own: leaving a page of Febe leaves it as it is, on screen until Alberto closes it (issue #52).
endpoints.MapPost("/api/connection/cancel", async (HttpContext context, IConnectionService connection, IBrowserWindow window, CancellationToken ct) =>
{
var body = context.Request.ContentLength is null or > 0
? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CancelDrivingRequest).ConfigureAwait(false)
: new CancelDrivingRequest(false);
var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.CancelDrivingRequest, new CancelDrivingRequest(false)).ConfigureAwait(false);
if (body.PageLeft && window.IsSeparateWindow)
{
await connection.ReleaseAsync(ct).ConfigureAwait(false);
+1 -3
View File
@@ -65,9 +65,7 @@ public static class EngineApi
throw new BadRequestException("Qui il browser di Febe si usa dalla pagina Browser.");
}
var body = context.Request.ContentLength is null or > 0
? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest).ConfigureAwait(false)
: new BeginDrivingRequest(false);
var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest, new BeginDrivingRequest(false)).ConfigureAwait(false);
await connection.ShowBrowserAsync(body.OpenLogin, ct).ConfigureAwait(false);
tracker.MarkUsed(clock.Now);
return ApiHttp.Message("Il browser di Febe è in primo piano.");
+7 -4
View File
@@ -15,8 +15,10 @@ Lo usano due parti scritte in parallelo: non cambiarlo senza aggiornare entrambe
| `POST /api/browser/show` | corpo facoltativo `{ openLogin: bool }` → `{ message }`. Solo Windows: porta in primo piano la finestra «Browser di Febe»; come `begin` apre la pagina di accesso (`openLogin`) o, se era a riposo, la pagina iniziale |
**Pagina iniziale** (issue #52): la home del sito se Febe è collegato e non scollegato da Instagram, altrimenti la
pagina di accesso. Aprirla dal riposo è un'azione di Alberto, sotto il suo permesso di guida (`UserIsDriving`), non
del motore: Febe aspetta che la sessione del motore finisca, prende la pagina e solo dopo naviga. La striscia rossa
pagina di accesso. Aprirla, dal riposo o con il pulsante «Pagina iniziale» (barra della finestra di Windows, vista
remota), è un'azione di Alberto, sotto il suo permesso di guida (`UserIsDriving`), non del motore: Febe aspetta che la
sessione del motore finisca, prende il turno della pagina (un passo della ricerca dei profili finisce prima) e solo
dopo naviga. «Indietro», «Ricarica» e i clic nella pagina invece agiscono subito, come nel browser. La striscia rossa
di una disconnessione apre il browser con `openLogin: true` (in Docker la pagina Browser con `?accesso=1`).
In modalità dimostrativa la scena `scollegato` dà `notConnected`, la scena `fermo` dà `verificationRequired`.
@@ -42,8 +44,9 @@ Dal server al browser di Alberto:
I fotogrammi non devono fermarsi in silenzio (issue #52). Il server li riavvia (`Page.stopScreencast` e
`Page.startScreencast`) quando una pagina nuova si è caricata (`Page.loadEventFired`) senza che ne sia arrivato
uno, e quando non ne arrivano da circa 2 s; l'attesa raddoppia a ogni riavvio senza esito, fino a 30 s, e torna a
2 s quando i fotogrammi scorrono di nuovo o cambia la pagina. Se dopo un riavvio non arriva nulla, manda un'immagine
ferma della pagina (`Page.captureScreenshot`) come messaggio binario come gli altri. Avvii, riavvii e silenzi vanno
2 s quando i fotogrammi scorrono di nuovo o cambia la pagina. Se entro mezzo secondo dal riavvio non arriva nessun
fotogramma, manda un'immagine ferma della pagina (`Page.captureScreenshot`) come messaggio binario come gli altri;
se durante la cattura arriva un fotogramma vero, l'immagine ferma non si manda. Avvii, riavvii e silenzi vanno
nel registro (livello Info, categoria `vista`), senza indirizzi né contenuti. L'interfaccia, se dopo 8 s
dall'apertura non ha ancora un fotogramma, mostra «Nessuna immagine dal browser» con «Riprova», che riapre la vista.
Sul riposo (`about:blank`) la barra dice «Il browser è a riposo su una pagina vuota» invece dell'indirizzo.
+4 -2
View File
@@ -3,12 +3,12 @@
// engine is still; «Ho finito» lets «Riprendi» become active after a verification. Leaving the page without «Ho finito»
// (another page, a reload, closing the tab) gives the browser back, like «Annulla» (on Windows the window stays as it
// is until Alberto closes it). A browser at rest opens its start page; «?accesso=1» (the red strip of a disconnection)
// opens the login page.
// opens the login page, once: the parameter leaves the address straight away.
import { api } from '../core/api.js';
import { caps } from '../core/context.js';
import { h, icon, fill } from '../core/dom.js';
import { navigate } from '../core/shell.js';
import { navigate, setQuery } from '../core/shell.js';
import { t } from '../core/text.js';
import { toast } from '../core/ui.js';
import { drivingLease, finishDriving, passwordNote, windowPanel } from './connection.js';
@@ -28,6 +28,8 @@ export default {
const lease = drivingLease(page);
const login = new URLSearchParams(location.search).get('accesso') === '1';
lease.begin(login);
// Asked once: a reload of the page, or the tab restored later, must not open the login page again.
if (login) setQuery({ accesso: null });
const message = h('div', { 'aria-live': 'polite' });
const done = async () => {
const result = await finishDriving();