Browser mai bianco né muto: pagina iniziale, finestra che resta, fotogrammi che ripartono (#52)

Il browser di Febe a volte era bianco o non mostrava nulla. Le cause erano
diverse e si correggono insieme.

- Pagina iniziale. Se il browser è a riposo su about:blank e Alberto lo apre
  («Usa il browser», «Apri il browser»), Febe lo porta sulla home del sito
  quando è collegato, altrimenti sulla pagina di accesso. È un'azione di
  Alberto, sotto il suo permesso di guida, non del motore: Febe aspetta che
  la sessione finisca e prende il turno della pagina.
  Il nuovo pulsante «Pagina iniziale» sta nella barra della finestra di
  Windows e nella vista remota. Su about:blank la barra dice «Il browser è a
  riposo su una pagina vuota». «Indietro» non torna più sulla pagina di
  riposo.
- Disconnessione. «Apri il browser» nella striscia rossa apre la pagina di
  accesso. Con --accesso-di-prova il primo controllo all'avvio non segnala
  più una disconnessione finta.
- Windows: la finestra resta.
  - Lasciare una pagina di Febe non nasconde più la finestra «Browser di
    Febe» e non la rimette a riposo: finisce solo il permesso tenuto dalla
    pagina (cancel con pageLeft, IConnectionService.ReleaseAsync).
  - Sullo schermo la finestra ha il suo pulsante nella barra delle
    applicazioni, così ridurla a icona non la fa sparire. Dopo 2 minuti
    ridotta a icona torna fuori vista (S2).
  - Se lo schermo è troppo piccolo, la finestra si restringe all'area di
    lavoro e la pagina si rimpicciolisce con ZoomFactor, con le stesse misure
    CSS.
  - I bordi della pagina si riapplicano, con NotifyParentWindowPositionChanged,
    quando la finestra si mostra, si sposta o riparte il processo GPU.
  - Una pagina che non risponde mentre Alberto guida resta com'è.
  - IBrowserWindow.ShowAsync lascia il posto a
    IConnectionService.ShowBrowserAsync.
- Docker: fotogrammi che ripartono. La vista remota ha un watchdog. Riavvia
  i fotogrammi dopo una pagina nuova caricata senza fotogrammi e dopo circa
  2 s di silenzio. L'attesa raddoppia fino a 30 s finché la pagina resta
  ferma. Se il riavvio non porta nulla, la vista riceve un'immagine ferma
  (Page.captureScreenshot, già fra i comandi ammessi).
  RemoteViewSession ha ora un registro vero: avvii, riavvii e silenzi vanno
  a livello Info, categoria «vista», senza indirizzi.
  Se dopo 8 s non arriva nessuna immagine, l'interfaccia mostra «Nessuna
  immagine dal browser» con «Riprova».

Nessun comando CDP nuovo e nessuna dipendenza nuova. Aggiornati PROTOCOLLO.md
e la guida (Primo collegamento, Attività e arresti, Installazione Windows,
Problemi comuni).

Prove nuove:
- ScreencastWatchdogTests, RemoteViewFramesTests (Chromium vero, solo CI
  Linux)
- Home e Indietro in RemoteViewStartTests
- RemoteViewSocketTests
- ConnectionApiTests
- BrowserStartPageTests
- BrowserWindowDecisionTests e BrowserWindowTests (WebView2 vero)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-16 12:51:12 +01:00
1 parent 65c0c4470e
commit c49df4ca7b
49 files changed
+2056 -177

No files matched your search

+2 -1
View File
@@ -101,7 +101,8 @@ riprendere: lascia Febe in pausa.
## Che cosa fare dopo una disconnessione
1. «Apri il browser»: la pagina mostra l'accesso di Instagram.
1. «Apri il browser» nella striscia rossa: il browser apre la pagina di accesso di Instagram (anche se era a riposo
sulla pagina vuota).
2. Accedi a mano (nome utente, password, eventuale codice), aspetta la pagina iniziale, «Ho finito».
3. «Riprendi». Anche qui riparte l'avvio graduale.
+7
View File
@@ -19,6 +19,13 @@
automatica sono spenti.
- Ciò che scrivi nella finestra del browser va direttamente alla pagina di Instagram: Febe non riceve la password.
Mentre usi il browser il motore resta fermo; quando hai finito chiudi la finestra (o «Ho finito»): torna fuori vista.
Lasciare la pagina di Febe da cui l'hai aperta non la chiude: resta sullo schermo finché non la chiudi tu.
- Sullo schermo la finestra ha il suo pulsante nella barra delle applicazioni, così ridurla a icona non la fa sparire.
Ridotta a icona però non può restare a lungo (S2): dopo due minuti Febe la rimette fuori vista, come se l'avessi
chiusa. Se lo schermo è troppo piccolo per la pagina e la sua barra, la finestra si restringe e mostra la pagina
rimpicciolita, sempre della stessa misura per Instagram. Nella barra in basso: «Indietro», «Ricarica», «Pagina
iniziale» (la home di Instagram se sei collegato, altrimenti la pagina di accesso) e l'indirizzo; sulla pagina
vuota di riposo la barra dice «Il browser è a riposo su una pagina vuota».
- Funzioni di Windows offerte all'interfaccia: scelta di una cartella, «Mostra nella cartella», indirizzi aperti nel
tuo browser predefinito (mai nel browser di Febe), notifiche di Windows, avvio con il computer.
+14 -4
View File
@@ -64,10 +64,20 @@ Poi aggiungi gli account da seguire: [Account e impostazioni](Account-e-impostaz
## Usare il browser a mano
Da collegato, **«Usa il browser»** apre il browser di Febe (in Docker la pagina «Browser», con la vista remota e i
comandi «Indietro» e «Ricarica»; su Windows la finestra). Serve per controllare qualcosa a mano. Mentre lo usi il
motore resta fermo; quando hai finito premi «Ho finito». Se lasci la pagina Browser, o la pagina Collegamento mentre
accedi, senza premere «Ho finito» (un'altra pagina, la scheda chiusa o ricaricata), vale come «Annulla»: il browser
torna sulla pagina vuota e il motore può lavorare di nuovo.
comandi «Indietro», «Ricarica» e «Pagina iniziale»; su Windows la finestra, con gli stessi tre pulsanti nella barra in
basso). Serve per controllare qualcosa a mano. Mentre lo usi il motore resta fermo; quando hai finito premi «Ho finito».
Quando Febe non lo usa, il browser resta **a riposo su una pagina vuota**. Se lo apri mentre è a riposo, Febe apre per
te la **pagina iniziale**: la home di Instagram se sei collegato, la pagina di accesso se non lo sei (o se Instagram ti
ha scollegato). Se invece c'è già una pagina (per esempio quella di una verifica), la lascia com'è. «Pagina iniziale»
ci torna quando vuoi; se la barra dice «Il browser è a riposo su una pagina vuota», premilo.
Se lasci la pagina Browser, o la pagina Collegamento mentre accedi, senza premere «Ho finito» (un'altra pagina, la
scheda chiusa o ricaricata):
- **in Docker** vale come «Annulla»: il browser torna sulla pagina vuota e il motore può lavorare di nuovo;
- **su Windows** la finestra «Browser di Febe» resta com'è, sullo schermo e con la sua pagina, finché non la chiudi (o
premi «Ho finito»); finché è sullo schermo il motore resta fermo.
## Scollegarsi
+2
View File
@@ -26,6 +26,8 @@ dati.
| Che cosa vedi | Che cosa fare |
|---|---|
| La vista remota è lenta o non risponde | La vista è un'immagine della pagina inviata dal server: aspetta qualche secondo dopo ogni clic. Se dice «La vista remota non risponde», premi «Riprova»; se si apre in un'altra finestra, la precedente si chiude da sola (una vista alla volta) |
| La vista remota dice «Nessuna immagine dal browser» | La vista è aperta ma la pagina non arriva. Febe riavvia da solo l'invio delle immagini quando si fermano; premi «Riprova». Se resta così, guarda il registro (categoria «vista»: avvii, riavvii e silenzi) e riferisci il caso |
| Il browser è bianco, o la barra dice «Il browser è a riposo su una pagina vuota» | È la pagina vuota su cui Febe lascia il browser quando non lo usa: premi «Pagina iniziale» (la home di Instagram se sei collegato, altrimenti la pagina di accesso) |
| «Ho finito» dice che l'accesso non è riuscito | Nella pagina deve comparire la tua pagina iniziale di Instagram, non il modulo di accesso: completa l'accesso, poi di nuovo «Ho finito» |
| Dopo un riavvio Febe chiede di nuovo l'accesso | Non dovrebbe: la sessione è nel profilo del browser in `/dati/browser`. Controlla che `/dati` sia un volume persistente e non sia stato cancellato; riferisci il caso (è la voce S3 di [Ipotesi da verificare](Ipotesi-da-verificare)) |
+129 -22
View File
@@ -17,9 +17,10 @@ namespace Febe.App;
/// means that the session cookie exists in the browser profile: only its existence is checked
/// (<c>Network.getCookies</c>, names only), never its value. Opening the login page is Alberto's action, not the
/// engine's (rule 7, last sentence): it happens only while he holds the «driving» lease and the engine is still.
/// On Windows the browser is the window «Browser di Febe»: «Accedi» and «Portalo in primo piano» bring it to the front,
/// «Ho finito» and «Annulla» put it back out of view, «Scollega» closes it before deleting the profile. In Docker
/// showing and hiding do nothing (the remote view shows the browser).
/// On Windows the browser is the window «Browser di Febe»: «Accedi», «Apri il browser» and «Portalo in primo piano»
/// bring it to the front, «Ho finito» and «Annulla» put it back out of view, «Scollega» closes it before deleting the
/// profile; leaving a page of Febe leaves it as it is. In Docker showing and hiding do nothing (the remote view shows
/// the browser).
/// </summary>
/// <remarks>
/// <para>
@@ -29,6 +30,11 @@ namespace Febe.App;
/// must not stay still for ever.
/// </para>
/// <para>
/// Alberto never meets the empty rest page (issue #52): when he takes the browser while it rests there, his own first
/// navigation (rule 7, like the login page) opens <see cref="StartPageUrl"/> — the site's home when connected, the login
/// page when not connected or after a disconnection.
/// </para>
/// <para>
/// A session cookie that disappears outside a session (or is missing at start-up after a connection) is a disconnection
/// (spec §7.6): reported to the breaker as the recipes would, so that it is an incident with its alert and only
/// «Riprendi» restarts the engine. Not when Alberto himself is at the browser, nor after his «Scollega».
@@ -54,6 +60,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
private readonly IClock _clock;
private readonly FebeLog _log;
private readonly string _loginUrl;
private readonly string _homeUrl;
private readonly SessionCookieOptions _cookie;
private readonly SemaphoreSlim _commands = new(1, 1);
private readonly Lock _gate = new();
@@ -65,7 +72,15 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
private bool? _disconnectedByUser;
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
public BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog log, string loginUrl, SessionCookieOptions cookie)
/// <param name="browser">The browser of Febe.</param>
/// <param name="storage">The database (first connection, «Scollega»).</param>
/// <param name="tracker">When Alberto last used the browser.</param>
/// <param name="clock">The composition's clock.</param>
/// <param name="log">Febe's log.</param>
/// <param name="loginUrl">The page «Accedi a Instagram» opens.</param>
/// <param name="homeUrl">The site's home, the start page once connected.</param>
/// <param name="cookie">The session cookie looked for (its name only).</param>
public BrowserConnectionService(IFebeBrowser browser, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, FebeLog log, string loginUrl, string homeUrl, SessionCookieOptions cookie)
{
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
@@ -73,6 +88,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_log = log ?? throw new ArgumentNullException(nameof(log));
_loginUrl = loginUrl ?? throw new ArgumentNullException(nameof(loginUrl));
_homeUrl = homeUrl ?? throw new ArgumentNullException(nameof(homeUrl));
_cookie = cookie ?? throw new ArgumentNullException(nameof(cookie));
}
@@ -91,6 +107,14 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>
/// Where the browser goes when Alberto takes it from the rest page or presses «Pagina iniziale» (issue #52): the
/// site's home when the session is there, the login page when it is not (or not known yet) and after a disconnection
/// (spec §7.6), when Instagram's home would only send him there.
/// </summary>
public string StartPageUrl =>
IsConnected == true && _engine?.Services.Breaker.State.Status != BreakerStatus.Disconnected ? _homeUrl : _loginUrl;
/// <summary>
/// Hook for the readers (hypothesis H10): when the data of the page tell which account is connected, the composition
/// marks it as «Tu» (<see cref="Account.IsMine"/>); the status shows that account. Raised after every change of the
@@ -150,21 +174,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
_tracker.MarkUsed(_clock.Now);
if (openLogin)
{
// The engine ends its session when the lease starts; wait for it before taking the page. A search step
// in progress (issue #37) stops at its next check of the lease: the login page waits for its turn.
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
using var turn = await TakePageAsync(ct).ConfigureAwait(false);
var result = await _browser.Cdp.NavigateAsync(_loginUrl, ct).ConfigureAwait(false);
_log.Info("collegamento", result.Succeeded
? "Alberto usa il browser: pagina di accesso aperta."
: "Alberto usa il browser: la pagina di accesso non si è aperta (errore di rete del browser).");
}
else
{
_log.Info("collegamento", "Alberto usa il browser.");
}
await OpenForAlbertoAsync(openLogin, ct).ConfigureAwait(false);
// Windows: the window «Browser di Febe» comes to the front (Docker: nothing, the remote view shows it).
await ShowQuietlyAsync(ct).ConfigureAwait(false);
@@ -175,6 +185,43 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
public async Task ShowBrowserAsync(bool openLogin, CancellationToken ct)
{
EnsureBrowser();
await _commands.WaitAsync(ct).ConfigureAwait(false);
// Alberto's hold while his page opens: the window takes its own lease when it comes on screen, and holds the
// engine still for as long as it stays there (closing it ends it, as before).
var hold = _browser.UserDriving.Begin();
try
{
_tracker.MarkUsed(_clock.Now);
await OpenForAlbertoAsync(openLogin, ct).ConfigureAwait(false);
await _browser.ShowToUserAsync(ct).ConfigureAwait(false);
}
finally
{
hold.Dispose();
_commands.Release();
}
}
public async Task ReleaseAsync(CancellationToken ct)
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
try
{
if (ReleaseLease())
{
_log.Info("collegamento", "Pagina di Febe lasciata: la finestra del browser resta com'è finché non la chiudi.");
}
}
finally
{
_commands.Release();
}
}
public async Task<FinishResult> FinishAsync(CancellationToken ct)
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
@@ -305,16 +352,18 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// <summary>
/// Looks at the cookie now (outside the cache) and records the change. Used at start-up, by the background loop
/// and after the test site's automatic login. A session that went away (or is missing at start-up after a
/// connection) while Alberto is not at the browser is reported to the breaker as a disconnection (spec §7.6).
/// connection) while Alberto is not at the browser is reported to the breaker as a disconnection (spec §7.6) —
/// unless <paramref name="mayReport"/> is false: the first look of a start with the test site's automatic login,
/// which is about to open the session itself (issue #52: a false disconnection at every development start).
/// </summary>
public async Task<bool?> RefreshAsync(CancellationToken ct)
public async Task<bool?> RefreshAsync(CancellationToken ct, bool mayReport = true)
{
if (!_browser.IsAvailable)
{
return IsConnected;
}
var connected = await CheckAsync(force: true, mayReport: true, ct).ConfigureAwait(false);
var connected = await CheckAsync(force: true, mayReport, ct).ConfigureAwait(false);
if (connected == true)
{
await MarkConnectedAsync(ct).ConfigureAwait(false);
@@ -528,6 +577,64 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
return true;
}
/// <summary>
/// Alberto's own first navigation (rule 7: not an engine action, no Governor), under his lease: the login page when
/// asked for, and the start page when the browser rests on the empty page (issue #52). Any other page stays as it is
/// — the one he was using, or the verification page of a stop.
/// </summary>
private async Task OpenForAlbertoAsync(bool openLogin, CancellationToken ct)
{
if (!openLogin && !IsRest(await FullUrlAsync(ct).ConfigureAwait(false)))
{
_log.Info("collegamento", "Alberto usa il browser.");
return;
}
// The engine ends its session when the lease starts; wait for it before taking the page. A search step in
// progress (issue #37) stops at its next check of the lease: Alberto's page waits for its turn.
await WaitForSessionEndAsync(ct).ConfigureAwait(false);
using var turn = await TakePageAsync(ct).ConfigureAwait(false);
string target;
string what;
if (openLogin)
{
target = _loginUrl;
what = "pagina di accesso";
}
else if (IsRest(await FullUrlAsync(ct).ConfigureAwait(false)))
{
target = StartPageUrl;
what = target == _loginUrl ? "era a riposo, pagina di accesso" : "era a riposo, pagina iniziale del sito";
}
else
{
// The session that just ended left its page: his to look at.
_log.Info("collegamento", "Alberto usa il browser.");
return;
}
var result = await _browser.Cdp.NavigateAsync(target, ct).ConfigureAwait(false);
_log.Info("collegamento", result.Succeeded
? $"Alberto usa il browser: {what} aperta."
: $"Alberto usa il browser: {what} non aperta (errore di rete del browser).");
}
/// <summary>The empty rest page (or no document at all): never what Alberto should be shown.</summary>
private static bool IsRest(string? url) => url is "" or CdpPageExtensions.RestUrl;
/// <summary>The address of the main frame, in full (never logged); null when the browser does not answer.</summary>
private async Task<string?> FullUrlAsync(CancellationToken ct)
{
try
{
return await _browser.Cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException or KeyNotFoundException or InvalidOperationException)
{
return null;
}
}
private async Task WaitForSessionEndAsync(CancellationToken ct)
{
if (_engine is not { } engine)
+11 -3
View File
@@ -245,9 +245,11 @@ public sealed class FebeApp : IAsyncDisposable
}
// Browser, connection, engine. The engine loop starts only once the browser is up.
var browser = await _platform.CreateBrowserAsync(new FebePlatformContext(o, data, Database, Clock, Log, Tracker), ct).ConfigureAwait(false);
// 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);
var browser = await _platform.CreateBrowserAsync(context, ct).ConfigureAwait(false);
Browser = browser;
var connection = new BrowserConnectionService(browser, Database, Tracker, Clock, Log, o.LoginUrl, o.Site.SessionCookie);
var connection = new BrowserConnectionService(browser, Database, Tracker, Clock, Log, o.LoginUrl, HomeUrl(o.Site.BaseUrl), o.Site.SessionCookie);
Connection = connection;
var engineOptions = o.FirstSessionDelay is { } delay
? EngineOptions.Default with { StartupDelayMin = delay, StartupDelayMax = delay }
@@ -458,7 +460,9 @@ public sealed class FebeApp : IAsyncDisposable
services.Events.Notified += WakeDownloads;
OnStop(() => services.Events.Notified -= WakeDownloads);
await Connection!.RefreshAsync(ct).ConfigureAwait(false);
// With the test site's automatic login the first look reports nothing: the session it may not find yet is
// the one the login below opens (issue #52), not a disconnection.
await Connection!.RefreshAsync(ct, mayReport: !o.TestSiteAutoLogin).ConfigureAwait(false);
if (o.TestSiteAutoLogin && Connection.IsConnected != true)
{
await TestSiteLoginAsync(ct).ConfigureAwait(false);
@@ -514,6 +518,10 @@ public sealed class FebeApp : IAsyncDisposable
}
}
/// <summary>The site's home page as the browser writes it (with its final slash), for «Pagina iniziale».</summary>
private static string HomeUrl(string baseUrl) =>
Uri.TryCreate(baseUrl, UriKind.Absolute, out var home) ? home.AbsoluteUri : baseUrl;
/// <summary>
/// Development with the test site only (<c>--accesso-di-prova</c>): what Alberto does by hand on Instagram — open
/// the site once, so that its session cookie exists — then back to the rest page.
+3 -2
View File
@@ -101,7 +101,8 @@ public sealed partial class FebeLog : IDisposable
}
/// <summary>The adapter for the browser layer (it logs only CDP command names, states and counts).</summary>
public IBrowserLog ForBrowser() => new DelegateBrowserLog((level, message, exception) => Write(
/// <param name="category">The category of the lines (the remote view writes as «vista»).</param>
public IBrowserLog ForBrowser(string category = "browser") => new DelegateBrowserLog((level, message, exception) => Write(
level switch
{
BrowserLogLevel.Error => LogLevel.Error,
@@ -109,7 +110,7 @@ public sealed partial class FebeLog : IDisposable
BrowserLogLevel.Information => LogLevel.Information,
_ => LogLevel.Debug,
},
"browser",
category,
message,
exception));
+9 -1
View File
@@ -55,7 +55,15 @@ 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>
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker);
/// <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>
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;
}
/// <summary>Options of the shared composition, filled by each shell from its own configuration.</summary>
public sealed record FebeAppOptions
+4
View File
@@ -47,6 +47,10 @@ public sealed class ProblemConnectionService(IReadOnlyList<ConfigurationProblem>
public Task CancelAsync(CancellationToken ct) => Task.CompletedTask;
public Task ShowBrowserAsync(bool openLogin, CancellationToken ct) => throw Refused();
public Task ReleaseAsync(CancellationToken ct) => Task.CompletedTask;
public Task DisconnectAsync(CancellationToken ct) => throw Refused();
private Febe.Web.Api.BadRequestException Refused() =>
@@ -66,7 +66,7 @@ public sealed class RemoteViewSession : IAsyncDisposable
/// <param name="cdp">The page session.</param>
/// <param name="gate">Where the «Alberto is driving» lease is taken.</param>
/// <param name="log">Where opening and closing are noted (never keys).</param>
/// <param name="log">Where the frames' starts, restarts and silences are noted (never keys).</param>
/// <param name="clock">Wall-clock time for the screencast's start attempts; null: the system clock.</param>
public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null, IClock? clock = null)
{
@@ -100,7 +100,8 @@ public sealed class RemoteViewSession : IAsyncDisposable
throw;
}
_log.Info("Vista remota aperta: il motore resta fermo finché Alberto usa il browser.");
// The host notes the opening in its own words; here only for whoever uses the session alone.
_log.Debug("Vista remota aperta: il motore resta fermo finché Alberto usa il browser.");
}
public async Task MouseAsync(RemoteMouseEvent e, CancellationToken ct = default)
@@ -198,7 +199,7 @@ public sealed class RemoteViewSession : IAsyncDisposable
_buttons = 0;
}
_log.Info("Vista remota chiusa.");
_log.Debug("Vista remota chiusa.");
}
public async ValueTask DisposeAsync()
+394 -27
View File
@@ -1,3 +1,4 @@
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Nodes;
@@ -13,7 +14,33 @@ namespace Febe.Browser.RemoteView;
/// <param name="MaxWidth">Largest frame width in pixels.</param>
/// <param name="MaxHeight">Largest frame height in pixels.</param>
/// <param name="EveryNthFrame">Send one frame out of this many.</param>
public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, int MaxHeight = 900, int EveryNthFrame = 1);
/// <param name="Watchdog">How missing frames are noticed and the frames started again; null: never (issue #52).</param>
public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, int MaxHeight = 900, int EveryNthFrame = 1, ScreencastWatchdog? Watchdog = null);
/// <summary>
/// When the remote view starts its frames again (issue #52): Chromium sends a frame only when the page repaints, a
/// 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
/// 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"/>.
/// </summary>
/// <param name="Silence">Time without frames before the first restart.</param>
/// <param name="Tick">How often the watchdog looks.</param>
/// <param name="LongestSilence">The longest wait between two restarts without frames.</param>
public sealed record ScreencastWatchdog(TimeSpan Silence, TimeSpan Tick, TimeSpan LongestSilence)
{
/// <summary>
/// Frames after a restart that show the page is moving: a start alone brings one frame even on a still page, which
/// says that the screencast works, not that it keeps going.
/// </summary>
public const int FlowingFrames = 3;
/// <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));
}
/// <summary>One frame of the remote view.</summary>
/// <param name="Jpeg">The image.</param>
@@ -24,6 +51,7 @@ public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, in
/// <param name="ScrollOffsetX">Horizontal scroll position.</param>
/// <param name="ScrollOffsetY">Vertical scroll position.</param>
/// <param name="Timestamp">Browser timestamp (seconds), when given.</param>
/// <param name="Still">True for a still picture (<c>Page.captureScreenshot</c>) sent because no frame came.</param>
public sealed record ScreencastFrame(
byte[] Jpeg,
double DeviceWidth,
@@ -32,7 +60,8 @@ public sealed record ScreencastFrame(
double OffsetTop,
double ScrollOffsetX,
double ScrollOffsetY,
double? Timestamp);
double? Timestamp,
bool Still = false);
/// <summary>
/// The remote view's video (spec §4.1, §11): <c>Page.startScreencast</c> in JPEG, every frame acknowledged with
@@ -40,9 +69,16 @@ public sealed record ScreencastFrame(
/// <see cref="ReadFramesAsync"/> (only the latest ones are kept when the reader is slow) and <see cref="FrameReceived"/>.
/// </summary>
/// <remarks>
/// <para>
/// A view opened while the page changes document (the rest page after a session, the login page opened together with
/// the view) can meet the moment in which Chromium refuses the start with «Not attached to an active page»: the start
/// is sent again, a few times, for at most <see cref="InactivePageBudget"/>. Any other failure is reported at once.
/// </para>
/// <para>
/// With a <see cref="ScreencastWatchdog"/> the frames are started again when they stop coming (issue #52): after a
/// silence, and when the main frame finished loading a new document (<c>Page.loadEventFired</c>) without a frame. Every
/// restart, the start after a browser restart and the stop run one at a time, so the stop is never followed by a start.
/// </para>
/// </remarks>
public sealed class ScreencastSession : IAsyncDisposable
{
@@ -60,15 +96,32 @@ public sealed class ScreencastSession : IAsyncDisposable
private readonly Channel<int> _acks = Channel.CreateUnbounded<int>(new UnboundedChannelOptions { SingleReader = true });
private readonly CancellationTokenSource _lifetime = new();
// Starts after the first one (watchdog, browser restart) and the stop: one at a time.
private readonly SemaphoreSlim _starts = new(1, 1);
private readonly Lock _watch = new();
private readonly List<IDisposable> _pageEvents = [];
private IDisposable? _subscription;
private Task? _ackPump;
private Task? _watchdog;
private ScreencastOptions? _options;
private int _stopped;
private long _framesReceived;
private long _restarts;
// Guarded by _watch: when silence is measured from, how long it may last, and what the page did meanwhile.
private DateTimeOffset _lastFrameAt;
private DateTimeOffset _watchFrom;
private TimeSpan _silenceLimit;
private long _framesAtNavigation;
private int _framesSinceRestart;
private bool _restartWanted;
private bool _silent;
private DateTimeOffset _silentSince;
/// <param name="cdp">The page session.</param>
/// <param name="log">Where the start and stop are noted (never parameters or frames).</param>
/// <param name="clock">Wall-clock time for the pauses between start attempts; null: the system clock.</param>
/// <param name="log">Where starts, restarts and silences are noted (never parameters or frames).</param>
/// <param name="clock">Wall-clock time for the pauses between start attempts and the watchdog; null: the system clock.</param>
public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null, IClock? clock = null)
{
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
@@ -79,11 +132,15 @@ public sealed class ScreencastSession : IAsyncDisposable
/// <summary>Raised on the browser event thread for every frame: handlers must be quick.</summary>
public event EventHandler<ScreencastFrame>? FrameReceived;
/// <summary>The last frame received, for mapping input coordinates.</summary>
/// <summary>The last frame received (or still picture sent), for mapping input coordinates.</summary>
public ScreencastFrame? LastFrame { get; private set; }
/// <summary>Frames of the screencast received so far (still pictures not counted).</summary>
public long FramesReceived => Interlocked.Read(ref _framesReceived);
/// <summary>How many times the watchdog started the frames again.</summary>
public long Restarts => Interlocked.Read(ref _restarts);
public async Task StartAsync(ScreencastOptions? options = null, CancellationToken ct = default)
{
if (_subscription is not null)
@@ -100,7 +157,20 @@ public sealed class ScreencastSession : IAsyncDisposable
_ackPump = Task.Run(() => AckPumpAsync(_lifetime.Token), CancellationToken.None);
await SendStartAsync(ct).ConfigureAwait(false);
_log.Debug("Vista remota avviata.");
if (_options.Watchdog is { } watchdog)
{
lock (_watch)
{
_watchFrom = _clock.Now;
_silenceLimit = watchdog.Silence;
}
_pageEvents.Add(_cdp.On("Page.frameNavigated", OnFrameNavigated));
_pageEvents.Add(_cdp.On("Page.loadEventFired", OnLoadEventFired));
_watchdog = Task.Run(() => WatchAsync(watchdog, _lifetime.Token), CancellationToken.None);
}
_log.Info("Vista remota: fotogrammi avviati.");
}
/// <summary>Frames as they arrive; the oldest are dropped if the reader falls behind. Ends when the session stops.</summary>
@@ -124,31 +194,44 @@ public sealed class ScreencastSession : IAsyncDisposable
events.Reconnected -= OnReconnected;
}
if (_subscription is not null)
foreach (var subscription in _pageEvents)
{
_subscription.Dispose();
try
subscription.Dispose();
}
// The watchdog and any start under way end first: no start may follow the stop below.
await _lifetime.CancelAsync().ConfigureAwait(false);
if (_watchdog is not null)
{
await Quietly(_watchdog).ConfigureAwait(false);
}
await _starts.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
if (_subscription is not null)
{
await _cdp.SendAsync("Page.stopScreencast", null, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException)
{
// The browser is gone: nothing to stop.
_subscription.Dispose();
try
{
await _cdp.SendAsync("Page.stopScreencast", null, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException)
{
// The browser is gone: nothing to stop.
}
}
}
finally
{
_starts.Release();
}
_frames.Writer.TryComplete();
_acks.Writer.TryComplete();
await _lifetime.CancelAsync().ConfigureAwait(false);
if (_ackPump is not null)
{
try
{
await _ackPump.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
await Quietly(_ackPump).ConfigureAwait(false);
}
_log.Debug("Vista remota fermata.");
@@ -158,6 +241,55 @@ public sealed class ScreencastSession : IAsyncDisposable
{
await StopAsync().ConfigureAwait(false);
_lifetime.Dispose();
_starts.Dispose();
}
/// <summary>The width and height written in a JPEG's frame header (SOFn), or null when the data has none.</summary>
internal static (int Width, int Height)? JpegSize(ReadOnlySpan<byte> jpeg)
{
if (jpeg.Length < 4 || jpeg[0] != 0xFF || jpeg[1] != 0xD8)
{
return null;
}
var i = 2;
while (i + 3 < jpeg.Length)
{
if (jpeg[i] != 0xFF)
{
return null;
}
var marker = jpeg[i + 1];
if (marker == 0xFF)
{
i++;
continue;
}
var length = (jpeg[i + 2] << 8) | jpeg[i + 3];
var isFrame = marker is >= 0xC0 and <= 0xCF && marker is not (0xC4 or 0xC8 or 0xCC);
if (isFrame)
{
if (i + 8 >= jpeg.Length)
{
return null;
}
var height = (jpeg[i + 5] << 8) | jpeg[i + 6];
var width = (jpeg[i + 7] << 8) | jpeg[i + 8];
return width > 0 && height > 0 ? (width, height) : null;
}
if (length < 2)
{
return null;
}
i += 2 + length;
}
return null;
}
private async Task SendStartAsync(CancellationToken ct)
@@ -182,7 +314,7 @@ public sealed class ScreencastSession : IAsyncDisposable
ct).ConfigureAwait(false);
if (attempt > 1)
{
_log.Debug($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(System.Globalization.CultureInfo.InvariantCulture)}, dopo un cambio di pagina.");
_log.Info($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(CultureInfo.InvariantCulture)}, dopo un cambio di pagina.");
}
return;
@@ -206,16 +338,213 @@ public sealed class ScreencastSession : IAsyncDisposable
private void OnReconnected(object? sender, EventArgs e) =>
_ = Task.Run(async () =>
{
var ct = _lifetime.Token;
try
{
await SendStartAsync(_lifetime.Token).ConfigureAwait(false);
await _starts.WaitAsync(ct).ConfigureAwait(false);
try
{
if (Volatile.Read(ref _stopped) == 0)
{
await SendStartAsync(ct).ConfigureAwait(false);
_log.Info("Vista remota: fotogrammi avviati di nuovo dopo il riavvio del browser.");
}
}
finally
{
_starts.Release();
}
lock (_watch)
{
_watchFrom = _clock.Now;
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
catch (ObjectDisposedException)
{
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Warn("Vista remota: non è ripartita dopo il riavvio del browser.", ex);
}
});
/// <summary>
/// The watchdog: every <see cref="ScreencastWatchdog.Tick"/> it looks how long no frame came; past the allowed
/// silence (or when a new document loaded without frames) it starts the frames again.
/// </summary>
private async Task WatchAsync(ScreencastWatchdog watchdog, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await _clock.Delay(watchdog.Tick, ct).ConfigureAwait(false);
bool due;
bool afterLoad;
TimeSpan silence;
lock (_watch)
{
var now = _clock.Now;
var since = _lastFrameAt > _watchFrom ? _lastFrameAt : _watchFrom;
silence = now - since;
afterLoad = _restartWanted;
due = afterLoad || silence >= _silenceLimit;
}
if (due && Volatile.Read(ref _stopped) == 0)
{
await RestartAsync(watchdog, silence, afterLoad, ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Never the end of the watchdog: the next look tries again.
_log.Debug($"Vista remota: controllo dei fotogrammi non riuscito ({ex.GetType().Name}).");
}
}
}
/// <summary>Stop and start again (a new screencast session), then one still picture when no frame came.</summary>
private async Task RestartAsync(ScreencastWatchdog watchdog, TimeSpan silence, bool afterLoad, CancellationToken ct)
{
await _starts.WaitAsync(ct).ConfigureAwait(false);
try
{
bool first;
lock (_watch)
{
first = !_silent;
if (first)
{
_silent = true;
_silentSince = _clock.Now - silence;
}
}
var seconds = Math.Max(1, (int)Math.Round(silence.TotalSeconds)).ToString(CultureInfo.InvariantCulture);
var why = afterLoad
? "pagina nuova caricata senza fotogrammi"
: $"nessun fotogramma da {seconds} s";
var line = $"Vista remota: {why}, riavvio dei fotogrammi.";
if (first)
{
_log.Info(line);
}
else
{
_log.Debug(line);
}
var before = FramesReceived;
try
{
await _cdp.SendAsync("Page.stopScreencast", null, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is CdpCommandException or TimeoutException)
{
// Nothing was running on the browser side: the start below is what matters.
}
await SendStartAsync(ct).ConfigureAwait(false);
Interlocked.Increment(ref _restarts);
if (FramesReceived == before)
{
await SendStillAsync(ct).ConfigureAwait(false);
}
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
// The browser is restarting or the page is between two documents for longer than the budget: next time.
_log.Debug($"Vista remota: riavvio dei fotogrammi non riuscito ({ex.GetType().Name}).");
}
finally
{
lock (_watch)
{
_watchFrom = _clock.Now;
_restartWanted = false;
_framesSinceRestart = 0;
var longer = _silenceLimit + _silenceLimit;
_silenceLimit = longer < watchdog.LongestSilence ? longer : watchdog.LongestSilence;
}
_starts.Release();
}
}
/// <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 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;
}
var last = LastFrame;
double width;
double height;
if (last is { DeviceWidth: > 0, DeviceHeight: > 0 })
{
width = last.DeviceWidth;
height = last.DeviceHeight;
}
else if (JpegSize(jpeg) is { } size)
{
// Docker's browser draws at one device pixel per CSS pixel.
width = size.Width;
height = size.Height;
}
else
{
var o = _options ?? new ScreencastOptions();
width = o.MaxWidth;
height = o.MaxHeight;
}
Deliver(new ScreencastFrame(jpeg, width, height, 1, 0, 0, 0, null, Still: true));
_log.Debug("Vista remota: immagine ferma della pagina inviata.");
}
private void OnFrameNavigated(JsonElement e)
{
if (!e.TryGetProperty("frame", out var frame) || frame.TryGetProperty("parentId", out _))
{
return;
}
// A new document in the main frame (perhaps in another renderer): the silence counts from here, short again.
lock (_watch)
{
_watchFrom = _clock.Now;
_framesAtNavigation = FramesReceived;
_silenceLimit = _options?.Watchdog?.Silence ?? _silenceLimit;
_silent = false;
}
}
private void OnLoadEventFired(JsonElement e)
{
lock (_watch)
{
if (FramesReceived == _framesAtNavigation)
{
_restartWanted = true; // loaded and still no frame of it: the next look starts them again
}
}
}
private void OnFrame(JsonElement p)
{
if (!p.TryGetProperty("sessionId", out var sid) || !sid.TryGetInt32(out var sessionId))
@@ -242,8 +571,35 @@ public sealed class ScreencastSession : IAsyncDisposable
Read(meta, "scrollOffsetY"),
meta.ValueKind == JsonValueKind.Object && meta.TryGetProperty("timestamp", out var ts) && ts.TryGetDouble(out var t) ? t : null);
LastFrame = frame;
Interlocked.Increment(ref _framesReceived);
TimeSpan? resumedAfter = null;
lock (_watch)
{
_lastFrameAt = _clock.Now;
_restartWanted = false;
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.
_silenceLimit = watchdog.Silence;
if (_silent)
{
_silent = false;
resumedAfter = _lastFrameAt - _silentSince;
}
}
}
if (resumedAfter is { } after)
{
_log.Info($"Vista remota: fotogrammi di nuovo in arrivo, dopo {Math.Max(1, (int)Math.Round(after.TotalSeconds)).ToString(CultureInfo.InvariantCulture)} s di silenzio.");
}
Deliver(frame);
}
private void Deliver(ScreencastFrame frame)
{
LastFrame = frame;
_frames.Writer.TryWrite(frame);
FrameReceived?.Invoke(this, frame);
}
@@ -258,11 +614,22 @@ public sealed class ScreencastSession : IAsyncDisposable
}
catch (Exception ex) when (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
// A lost ack only pauses frames until the next start.
// A lost ack pauses the frames: the watchdog, when there is one, starts them again after the silence.
}
}
}
private static async Task Quietly(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
private static double Read(JsonElement meta, string name, double fallback = 0) =>
meta.ValueKind == JsonValueKind.Object && meta.TryGetProperty(name, out var v) && v.TryGetDouble(out var d) ? d : fallback;
}
+6 -21
View File
@@ -152,7 +152,7 @@ public sealed class DesktopPlatform : IFebePlatform
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(app);
services.AddSingleton(_shell.Native);
services.AddSingleton<IBrowserWindow>(new DesktopBrowserWindow(() => app.Browser));
services.AddSingleton<IBrowserWindow>(new DesktopBrowserWindow());
services.AddSingleton<IDataFolderChange>(new DesktopDataFolderChange(_locations, app.Options.DataFolder, _dataFolderFixed));
}
@@ -200,29 +200,14 @@ public sealed class DesktopPlatform : IFebePlatform
}
/// <summary>
/// «Apri il browser» on Windows (spec §10.3): brings the window «Browser di Febe» to the front. While it is in front
/// Alberto is driving and the engine is still; closing the window ends it.
/// The browser of Windows is the window «Browser di Febe» (spec §10.3): «Apri il browser» brings it to the front through
/// the connection (<c>IConnectionService.ShowBrowserAsync</c>, which opens the start page when it was at rest). While
/// it is on screen Alberto is driving and the engine is still; closing the window ends it, leaving a page of Febe does
/// not (issue #52).
/// </summary>
public sealed class DesktopBrowserWindow(Func<IFebeBrowser?> browser) : IBrowserWindow
public sealed class DesktopBrowserWindow : IBrowserWindow
{
public bool IsSeparateWindow => true;
public async Task ShowAsync(CancellationToken ct)
{
if (browser() is not { } current)
{
throw new BadRequestException("Il browser di Febe non è in funzione in questo momento.");
}
if (!current.IsAvailable)
{
throw new BadRequestException(current.LastError is { } error
? "Il browser di Febe non è in funzione: " + error
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
}
await current.ShowToUserAsync(ct).ConfigureAwait(false);
}
}
/// <summary>
+132 -18
View File
@@ -3,21 +3,40 @@ using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
namespace Febe.Desktop.Browser;
/// <summary>
/// The window «Browser di Febe» (spec §4.1, §12): the page of Instagram at a fixed size, always the same, and below it a
/// thin bar with «Indietro», «Ricarica» and the address without its query string. WebView2 draws into the upper area
/// (as a child window, or as a DirectComposition visual for S2). When Alberto does not use it the window stays open
/// but out of view, never hidden nor minimised: WebView2 would stop painting (S2). Closing it only puts it out of view.
/// thin bar with «Indietro», «Ricarica», «Pagina iniziale» and the address without its query string. WebView2 draws
/// into the upper area (as a child window, or as a DirectComposition visual for S2). When Alberto does not use it the
/// window stays open but out of view, never hidden: WebView2 would stop painting (S2). Closing it only puts it out of
/// view.
/// </summary>
/// <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.
/// </para>
/// </remarks>
internal sealed class BrowserWindow : Window
{
/// <summary>Height of the bar under the page, in device-independent pixels.</summary>
public const double BarHeight = 40;
/// <summary>The smallest zoom the page is shown at when the screen is small.</summary>
public const double SmallestFit = 0.4;
/// <summary>What the bar says while the page is the empty rest page.</summary>
public const string RestNotice = "Il browser è a riposo su una pagina vuota: premi «Pagina iniziale».";
private readonly TextBlock _address;
private readonly Border _page;
private readonly DispatcherTimer _minimized;
private bool _allowClose;
public BrowserWindow(int pageWidth, int pageHeight, ImageSource? icon)
@@ -31,8 +50,9 @@ internal sealed class BrowserWindow : Window
WindowStartupLocation = WindowStartupLocation.Manual;
ShowActivated = false;
// No taskbar button: out of view the window must not be reachable by accident (a click on a button that shows
// Out of view no taskbar button: the window must not be reachable by accident (a click on a button that shows
// nothing). It comes to the front from the interface: «Apri il browser», «Portalo in primo piano», the login.
// On screen it has one (MoveOnScreen), so a minimised window can be brought back.
ShowInTaskbar = false;
Background = new SolidColorBrush(Color.FromRgb(0xF4, 0xF5, 0xF7));
@@ -40,6 +60,8 @@ internal sealed class BrowserWindow : Window
back.Click += (_, _) => BackRequested?.Invoke(this, EventArgs.Empty);
var reload = BarButton("Ricarica", "Ricarica la pagina");
reload.Click += (_, _) => ReloadRequested?.Invoke(this, EventArgs.Empty);
var home = BarButton("Pagina iniziale", "Apre la pagina iniziale del sito, o la pagina di accesso se non sei collegato");
home.Click += (_, _) => HomeRequested?.Invoke(this, EventArgs.Empty);
_address = new TextBlock
{
VerticalAlignment = VerticalAlignment.Center,
@@ -57,24 +79,30 @@ internal sealed class BrowserWindow : Window
Foreground = new SolidColorBrush(Color.FromRgb(0x5B, 0x63, 0x6E)),
FontFamily = new FontFamily("Segoe UI"),
FontSize = 12,
TextTrimming = TextTrimming.CharacterEllipsis,
};
var bar = new DockPanel { Height = BarHeight, LastChildFill = true, Background = new SolidColorBrush(Color.FromRgb(0xFF, 0xFF, 0xFF)) };
DockPanel.SetDock(back, Dock.Left);
DockPanel.SetDock(reload, Dock.Left);
DockPanel.SetDock(home, Dock.Left);
DockPanel.SetDock(hint, Dock.Right);
bar.Children.Add(back);
bar.Children.Add(reload);
bar.Children.Add(home);
bar.Children.Add(hint);
bar.Children.Add(_address);
// The page area: WebView2 covers it (its bounds are computed from PageWidth/PageHeight and the DPI).
var page = new Border { Width = pageWidth, Height = pageHeight, Background = Brushes.White };
// The page area: WebView2 covers it (its bounds are computed from PageWidth/PageHeight, the fit and the DPI).
_page = new Border { Width = pageWidth, Height = pageHeight, Background = Brushes.White };
var layout = new DockPanel { LastChildFill = true };
DockPanel.SetDock(bar, Dock.Bottom);
layout.Children.Add(bar);
layout.Children.Add(page);
layout.Children.Add(_page);
Content = layout;
_minimized = new DispatcherTimer(DispatcherPriority.Normal, Dispatcher);
_minimized.Tick += (_, _) => MinimizedTooLong();
}
/// <summary>Width of the page in device-independent pixels (CSS pixels of the page at zoom 100%).</summary>
@@ -82,15 +110,30 @@ internal sealed class BrowserWindow : Window
public int PageHeight { get; }
/// <summary>
/// The zoom the page is shown at: 1, or less when the page and its bar do not fit in the work area of the screen.
/// The page keeps its size in CSS pixels whatever the fit (the host zooms WebView2 out by the same factor).
/// </summary>
public double Fit { get; private set; } = 1;
/// <summary>How long the window may stay minimised before it is put out of view as «ho finito» (S2).</summary>
public TimeSpan MinimizedLimit { get; set; } = TimeSpan.FromMinutes(2);
/// <summary>Raised by «Indietro».</summary>
public event EventHandler? BackRequested;
/// <summary>Raised by «Ricarica».</summary>
public event EventHandler? ReloadRequested;
/// <summary>Raised when Alberto closes or minimises the window: the owner puts it out of view.</summary>
/// <summary>Raised by «Pagina iniziale».</summary>
public event EventHandler? HomeRequested;
/// <summary>Raised when Alberto closes the window, or leaves it minimised too long: the owner puts it out of view.</summary>
public event EventHandler? DoneRequested;
/// <summary>Raised when the page area changed size (a new fit): the owner sizes WebView2 again.</summary>
public event EventHandler? PageAreaChanged;
/// <summary>The window handle (created on first use).</summary>
public IntPtr Handle => new WindowInteropHelper(this).EnsureHandle();
@@ -98,32 +141,68 @@ internal sealed class BrowserWindow : Window
public double Scale => VisualTreeHelper.GetDpi(this).DpiScaleX;
/// <summary>Where WebView2 draws, in physical pixels of the client area.</summary>
public System.Drawing.Rectangle PageBounds => new(0, 0, (int)Math.Round(PageWidth * Scale), (int)Math.Round(PageHeight * Scale));
public System.Drawing.Rectangle PageBounds => new(0, 0, (int)Math.Round(PageWidth * Fit * Scale), (int)Math.Round(PageHeight * Fit * Scale));
/// <summary>True while the window is on a screen, false while it is parked out of view.</summary>
public bool IsOnScreen =>
Left < SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth
&& Left + ActualWidth > SystemParameters.VirtualScreenLeft;
/// <summary>Shows the address of the page, without query string or fragment (they may carry tokens).</summary>
public void ShowAddress(string? address) => _address.Text = address ?? string.Empty;
/// <summary>The text the bar shows now (the address, or <see cref="RestNotice"/>).</summary>
public string AddressText => _address.Text;
/// <summary>Centres the window on the work area of the primary screen.</summary>
/// <summary>
/// The zoom at which a page of <paramref name="pageWidth"/>×<paramref name="pageHeight"/> plus its bar and the
/// window's frame fits in an area of <paramref name="areaWidth"/>×<paramref name="areaHeight"/> (all in
/// device-independent pixels): 1 when it fits, never below <see cref="SmallestFit"/>.
/// </summary>
public static double FitFor(double areaWidth, double areaHeight, double pageWidth, double pageHeight, double frameWidth, double frameHeight)
{
if (pageWidth <= 0 || pageHeight <= 0)
{
return 1;
}
var byWidth = (areaWidth - frameWidth) / pageWidth;
var byHeight = (areaHeight - frameHeight - BarHeight) / pageHeight;
var fit = Math.Min(1, Math.Min(byWidth, byHeight));
return Math.Max(SmallestFit, Math.Floor(fit * 100) / 100);
}
/// <summary>
/// Shows the address of the page, without query string or fragment (they may carry tokens); on the empty rest page,
/// <see cref="RestNotice"/>.
/// </summary>
public void ShowAddress(string? address) =>
_address.Text = address is null or "" or "about:blank" ? RestNotice : address;
/// <summary>
/// Centres the window on the work area of the primary screen, shrunk to fit it when needed, with its taskbar button.
/// </summary>
public void MoveOnScreen()
{
var area = SystemParameters.WorkArea;
var width = ActualWidth > 0 ? ActualWidth : PageWidth;
var height = ActualHeight > 0 ? ActualHeight : PageHeight + BarHeight;
FitTo(area);
ShowInTaskbar = true;
var width = ActualWidth > 0 ? ActualWidth : PageWidth * Fit;
var height = ActualHeight > 0 ? ActualHeight : (PageHeight * Fit) + BarHeight;
Left = area.Left + Math.Max(0, (area.Width - width) / 2);
Top = area.Top + Math.Max(0, (area.Height - height) / 2);
}
/// <summary>
/// Parks the window just right of every screen: open, «visible» for Windows and for WebView2, out of Alberto's view
/// (S2). Never <c>Hide()</c> and never minimised.
/// (S2), without its taskbar button. Never <c>Hide()</c>, never left minimised.
/// </summary>
public void MoveOffScreen()
{
_minimized.Stop();
if (WindowState == WindowState.Minimized)
{
WindowState = WindowState.Normal;
}
ShowInTaskbar = false;
Left = SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth + 64;
Top = SystemParameters.VirtualScreenTop;
}
@@ -132,6 +211,7 @@ internal sealed class BrowserWindow : Window
public void CloseForGood()
{
_allowClose = true;
_minimized.Stop();
Close();
}
@@ -151,14 +231,48 @@ internal sealed class BrowserWindow : Window
{
if (WindowState == WindowState.Minimized)
{
// A minimised window stops painting (S2): back to normal, out of view.
WindowState = WindowState.Normal;
DoneRequested?.Invoke(this, EventArgs.Empty);
// Minimised Alberto still has it (its taskbar button brings it back), but WebView2 stops painting (S2):
// left there too long it counts as closed.
_minimized.Interval = MinimizedLimit;
_minimized.Stop();
_minimized.Start();
}
else
{
_minimized.Stop();
}
base.OnStateChanged(e);
}
private void MinimizedTooLong()
{
_minimized.Stop();
if (WindowState == WindowState.Minimized)
{
WindowState = WindowState.Normal;
DoneRequested?.Invoke(this, EventArgs.Empty);
}
}
private void FitTo(Rect area)
{
// 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);
if (Math.Abs(fit - Fit) < 0.001)
{
return;
}
Fit = fit;
_page.Width = PageWidth * fit;
_page.Height = PageHeight * fit;
UpdateLayout();
PageAreaChanged?.Invoke(this, EventArgs.Empty);
}
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)),
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.CurrentStartPage),
context.Log);
Host.BrowserProcessFailed += (_, _) => RequestRestart(null);
}
+101 -19
View File
@@ -18,7 +18,24 @@ 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>
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed);
/// <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);
/// <summary>What the host does when a process of WebView2 fails (issue #52).</summary>
internal enum ProcessFailureResponse
{
/// <summary>Nothing: WebView2 recovers by itself (an unresponsive page while Alberto looks at it, a helper process).</summary>
None,
/// <summary>The whole browser is gone: the owner starts it again.</summary>
Restart,
/// <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>
Redraw,
}
/// <summary>
/// The browser host of the Windows edition (spec §5, §6.1, §12): WebView2 in the window «Browser di Febe», with its own
@@ -36,6 +53,9 @@ internal sealed record WebView2HostOptions(BrowserHosting Hosting, string Additi
/// «Ho finito»; using and closing it marks the browser as used for «Riprendi».</item>
/// <item>Stopping closes the WebView and waits for its browser process to exit, so the session is on disk (S3);
/// <see cref="RestartAsync"/> («Scollega») does the same before deleting the profile.</item>
/// <item>Issue #52: the bounds (and the zoom of a window shrunk to fit the screen) are given again, and WebView2 told of
/// the window's new place, whenever the window moves on or off screen and after the GPU process restarted; a page that
/// hangs while Alberto looks at it is left to recover instead of being replaced by the rest page.</item>
/// <item>Threads: every WebView2 object (environment, controller, <c>CoreWebView2</c>, its settings and DevTools
/// receivers) and the window are touched only on the UI thread, through its dispatcher; WebView2 throws on any other
/// thread. Callers on other threads (the composition, the engine) get only plain values captured on the UI thread
@@ -147,12 +167,20 @@ internal sealed class WebView2Host : IBrowserHost
}
window.MoveOnScreen();
if (window.WindowState == System.Windows.WindowState.Minimized)
{
window.WindowState = System.Windows.WindowState.Normal;
}
window.Activate();
window.Topmost = true;
window.Topmost = false;
// 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.
UpdateBounds();
try
{
_controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
@@ -169,9 +197,24 @@ internal sealed class WebView2Host : IBrowserHost
{
_window?.MoveOffScreen();
ReleaseLease();
NotifyPositionChanged();
return Task.CompletedTask;
});
/// <summary>
/// What a failed process of WebView2 asks of the host (issue #52). A page that does not answer while Alberto is at
/// the window is his to wait for (WebView2 recovers, or he reloads): replacing it with the rest page would turn it
/// white under his eyes. Nobody looking, it goes to rest as a crashed page does.
/// </summary>
internal static ProcessFailureResponse ResponseTo(CoreWebView2ProcessFailedKind kind, bool userIsDriving) => kind switch
{
CoreWebView2ProcessFailedKind.BrowserProcessExited => ProcessFailureResponse.Restart,
CoreWebView2ProcessFailedKind.RenderProcessExited => ProcessFailureResponse.Rest,
CoreWebView2ProcessFailedKind.RenderProcessUnresponsive => userIsDriving ? ProcessFailureResponse.None : ProcessFailureResponse.Rest,
CoreWebView2ProcessFailedKind.GpuProcessExited => ProcessFailureResponse.Redraw,
_ => ProcessFailureResponse.None,
};
/// <summary>
/// Closes the WebView, waits for its browser process to exit (the profile is free and written), runs
/// <paramref name="whileStopped"/> — «Scollega» deletes the profile there — and starts it again. <see cref="Cdp"/>
@@ -302,7 +345,14 @@ 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.DpiChanged += (_, _) => UpdateBounds();
window.PageAreaChanged += (_, _) => UpdateBounds();
// The raw controller does not follow its parent by itself: popups (lists of a <select>, menus, suggestions)
// would open where the window was, out of view.
window.LocationChanged += (_, _) => NotifyPositionChanged();
window.ShowAddress(null);
_window = window;
}
@@ -336,6 +386,7 @@ internal sealed class WebView2Host : IBrowserHost
controller.BoundsMode = CoreWebView2BoundsMode.UseRawPixels;
controller.Bounds = _window.PageBounds;
controller.ZoomFactor = _window.Fit;
// WebView2 stops painting when IsVisible is false (S2): it stays true for the whole life of the browser.
controller.IsVisible = true;
@@ -436,24 +487,38 @@ internal sealed class WebView2Host : IBrowserHost
return;
}
if (kind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
switch (ResponseTo(kind, UserIsDriving))
{
// The whole browser is gone: commands fail from now on, and the owner starts it again (same profile), as
// the supervisor does with Chromium — once this handler has returned (threading model of WebView2).
_session.Detach();
_ = _ui.InvokeAsync(() => BrowserProcessFailed?.Invoke(this, EventArgs.Empty), DispatcherPriority.Background);
}
else if (kind is CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
{
// The page crashed: back to the rest page (spec §6.1); a running recipe ends on its own errors.
try
{
(sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl);
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
{
// The browser went with the page: its own ProcessFailed follows.
}
case ProcessFailureResponse.Restart:
// The whole browser is gone: commands fail from now on, and the owner starts it again (same profile), as
// the supervisor does with Chromium — once this handler has returned (threading model of WebView2).
_session.Detach();
_ = _ui.InvokeAsync(() => BrowserProcessFailed?.Invoke(this, EventArgs.Empty), DispatcherPriority.Background);
break;
case ProcessFailureResponse.Rest:
// The page crashed: back to the rest page (spec §6.1); a running recipe ends on its own errors.
try
{
(sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl);
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
{
// The browser went with the page: its own ProcessFailed follows.
}
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);
break;
default:
if (kind == CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
{
_log.Info("browser", "WebView2: la pagina non risponde mentre usi il browser; Febe la lascia com'è (Ricarica, se non si riprende).");
}
break;
}
}
@@ -481,11 +546,12 @@ internal sealed class WebView2Host : IBrowserHost
TakeLease();
}
/// <summary>Alberto closed or minimised the window: done, out of view.</summary>
/// <summary>Alberto closed the window (or left it minimised too long): done, out of view.</summary>
private void Done()
{
_window?.MoveOffScreen();
ReleaseLease();
NotifyPositionChanged();
}
private void UserNavigation(Action<CoreWebView2> action, Func<CoreWebView2, bool> allowed)
@@ -520,6 +586,10 @@ internal sealed class WebView2Host : IBrowserHost
try
{
controller.Bounds = window.PageBounds;
// Shrunk to fit a small screen, the page is zoomed out by as much: its size in CSS pixels stays the same.
controller.ZoomFactor = window.Fit;
controller.NotifyParentWindowPositionChanged();
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
{
@@ -527,6 +597,18 @@ internal sealed class WebView2Host : IBrowserHost
}
}
private void NotifyPositionChanged()
{
try
{
_controller?.NotifyParentWindowPositionChanged();
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
{
// The browser process is gone: the next start places the new WebView.
}
}
private void TakeLease()
{
if (_lease is null)
+39 -10
View File
@@ -2,6 +2,7 @@ using System.Runtime.CompilerServices;
using System.Text.Json;
using Febe.App;
using Febe.Browser.Cdp;
using Febe.Browser.Diagnostics;
using Febe.Browser.Gestures;
using Febe.Browser.RemoteView;
using Febe.Core.Abstractions;
@@ -24,6 +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 Lock _gate = new();
private readonly SemaphoreSlim _opening = new(1, 1);
private BrowserRemoteViewConnection? _current;
@@ -34,18 +36,26 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
/// <param name="clock">The composition's clock (the time of that note).</param>
/// <param name="log">Febe's log.</param>
/// <param name="browserClock">
/// Time for the waits on the browser itself; null: the wall clock, because the browser commits a navigation in real
/// time whatever clock the engine runs on (the tests compress it).
/// 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>
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null)
/// <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)
{
_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;
}
/// <summary>
/// How an open view notices that frames stopped coming and starts them again (issue #52); null: never (tests whose
/// clock moves only when asked).
/// </summary>
public ScreencastWatchdog? Watchdog { get; set; } = ScreencastWatchdog.Default;
public async Task<IRemoteViewConnection> OpenAsync(CancellationToken ct)
{
if (!_browser.IsAvailable)
@@ -83,7 +93,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
}
var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock);
var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock, _log.ForBrowser("vista"), _startPage, Watchdog);
try
{
await connection.StartAsync(_browser.WindowWidth, _browser.WindowHeight, ct).ConfigureAwait(false);
@@ -167,6 +177,8 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
private readonly BrowserUseTracker _tracker;
private readonly IClock _clock;
private readonly RemoteViewSession _session;
private readonly Func<string>? _startPage;
private readonly ScreencastWatchdog? _watchdog;
private readonly Lock _gate = new();
private readonly Queue<RemoteViewMeta> _meta = new();
private readonly SemaphoreSlim _signal = new(0, int.MaxValue);
@@ -184,13 +196,17 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
private int _disposed;
private bool _used;
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock)
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock, IBrowserLog log, Func<string>? startPage, ScreencastWatchdog? watchdog)
{
_owner = owner;
_browser = browser;
_tracker = tracker;
_clock = clock;
_session = new RemoteViewSession(browser.Cdp, browser.UserDriving, clock: browserClock);
_startPage = startPage;
_watchdog = watchdog;
// A real log (issue #52): the starts, restarts and silences of the frames reach the registro.
_session = new RemoteViewSession(browser.Cdp, browser.UserDriving, log, browserClock);
}
public RemoteViewEnd? Ended { get; private set; }
@@ -216,7 +232,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
_signal.Release();
_session.Screencast.FrameReceived += OnFrame;
await _session.StartAsync(new ScreencastOptions(Quality: 70, MaxWidth: width, MaxHeight: height), ct).ConfigureAwait(false);
await _session.StartAsync(new ScreencastOptions(Quality: 70, MaxWidth: width, MaxHeight: height, Watchdog: _watchdog), ct).ConfigureAwait(false);
}
public async IAsyncEnumerable<RemoteViewOutput> ReadAsync([EnumeratorCancellation] CancellationToken ct)
@@ -303,14 +319,25 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
string? target;
lock (_gate)
{
if (action == RemoteViewNavigation.Back)
if (action == RemoteViewNavigation.Home)
{
if (_history.Count < 2)
target = _startPage?.Invoke();
}
else 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;
while (previous >= 0 && IsRest(_history[previous]))
{
previous--;
}
if (previous < 0)
{
return;
}
_history.RemoveAt(_history.Count - 1);
_history.RemoveRange(previous + 1, _history.Count - previous - 1);
target = _history[^1];
}
else
@@ -452,6 +479,8 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
/// <summary>The address without query string or fragment (they may carry tokens).</summary>
internal static string WithoutQuery(string url) => Addresses.WithoutQuery(url);
private static bool IsRest(string url) => url is "" or CdpPageExtensions.RestUrl;
}
/// <summary>Turns the DOM key of the page into what <c>Input.dispatchKeyEvent</c> needs (virtual key codes).</summary>
+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);
RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log, startPage: () => app.Connection?.StartPageUrl ?? app.Options.LoginUrl);
services.AddSingleton<IRemoteViewHost>(RemoteView);
}
+16 -2
View File
@@ -1,6 +1,7 @@
using Febe.Core.Abstractions;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Febe.Web.Native;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
@@ -36,9 +37,22 @@ public static class ConnectionApi
return ApiHttp.Json(new FinishDto(result.Connected, result.Message), FebeJsonContext.Default.FinishDto);
});
endpoints.MapPost("/api/connection/cancel", async (IConnectionService connection, CancellationToken ct) =>
// «Annulla», or a page left without either button ({ pageLeft: true }). On Windows the browser is a window of its
// 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) =>
{
await connection.CancelAsync(ct).ConfigureAwait(false);
var body = context.Request.ContentLength is null or > 0
? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CancelDrivingRequest).ConfigureAwait(false)
: new CancelDrivingRequest(false);
if (body.PageLeft && window.IsSeparateWindow)
{
await connection.ReleaseAsync(ct).ConfigureAwait(false);
}
else
{
await connection.CancelAsync(ct).ConfigureAwait(false);
}
return Results.NoContent();
});
+7 -3
View File
@@ -56,15 +56,19 @@ public static class EngineApi
FebeJsonContext.Default.ResumeDto);
});
// «Apri il browser» on Windows: the window of the browser comes to the front.
endpoints.MapPost("/api/browser/show", async (IBrowserWindow browser, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
// «Apri il browser» on Windows: the window of the browser comes to the front, on the start page when it was at rest
// and on the login page with { openLogin: true } (the red strip of a disconnection; issue #52).
endpoints.MapPost("/api/browser/show", async (HttpContext context, IBrowserWindow browser, IConnectionService connection, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
{
if (!browser.IsSeparateWindow)
{
throw new BadRequestException("Qui il browser di Febe si usa dalla pagina Browser.");
}
await browser.ShowAsync(ct).ConfigureAwait(false);
var body = context.Request.ContentLength is null or > 0
? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest).ConfigureAwait(false)
: new BeginDrivingRequest(false);
await connection.ShowBrowserAsync(body.OpenLogin, ct).ConfigureAwait(false);
tracker.MarkUsed(clock.Now);
return ApiHttp.Message("Il browser di Febe è in primo piano.");
});
+1
View File
@@ -49,6 +49,7 @@ namespace Febe.Web.Api;
[JsonSerializable(typeof(Library.LibraryChange))]
[JsonSerializable(typeof(ConnectionStatusDto))]
[JsonSerializable(typeof(BeginDrivingRequest))]
[JsonSerializable(typeof(CancelDrivingRequest))]
[JsonSerializable(typeof(FinishDto))]
[JsonSerializable(typeof(IncidentListDto))]
[JsonSerializable(typeof(AlertListDto))]
+6
View File
@@ -11,6 +11,12 @@ public sealed record ConnectionStatusDto(string State, string? Username, string?
/// <summary><c>POST /api/connection/begin</c>.</summary>
public sealed record BeginDrivingRequest(bool OpenLogin);
/// <summary>
/// «Annulla», or the page that held the browser was left (<paramref name="PageLeft"/>): on Windows the window then
/// stays as it is (issue #52).
/// </summary>
public sealed record CancelDrivingRequest(bool PageLeft);
/// <summary><c>POST /api/connection/finish</c>.</summary>
public sealed record FinishDto(bool Connected, string Message);
@@ -55,6 +55,21 @@ public interface IConnectionService
/// <summary>«Annulla»: ends user driving and puts the browser on the empty rest page.</summary>
Task CancelAsync(CancellationToken ct);
/// <summary>
/// «Apri il browser» on Windows (spec §10.3, issue #52): the window comes to the front and holds the engine still
/// while it is on screen. A browser resting on the empty page first opens the start page (the site's home when
/// connected, the login page otherwise); with <paramref name="openLogin"/> the login page in any case (the red strip
/// of a disconnection).
/// </summary>
Task ShowBrowserAsync(bool openLogin, CancellationToken ct);
/// <summary>
/// The Febe page that took the browser was left (another page, a reload, the tab closed) while the browser is a
/// window of its own (Windows, issue #52): only the page's hold ends. The window stays as it is, on screen and with
/// its page, until Alberto closes it or presses «Ho finito».
/// </summary>
Task ReleaseAsync(CancellationToken ct);
/// <summary>«Scollega» (after confirmation in the UI): stops the engine and deletes the browser profile.</summary>
Task DisconnectAsync(CancellationToken ct);
}
+25 -6
View File
@@ -8,16 +8,25 @@ Lo usano due parti scritte in parallelo: non cambiarlo senza aggiornare entrambe
| Endpoint | Corpo e risposta |
|---|---|
| `GET /api/connection` | `{ state: "notConnected"\|"connected"\|"verificationRequired"\|"browserUnavailable", username, displayName, userIsDriving, currentUrl }` |
| `POST /api/connection/begin` | `{ openLogin: bool }` → 204. Alberto usa il browser; con `openLogin` il browser carica la pagina di accesso vera |
| `POST /api/connection/begin` | `{ openLogin: bool }` → 204. Alberto usa il browser; con `openLogin` il browser carica la pagina di accesso vera; senza, se il browser è a riposo (`about:blank`) apre la pagina iniziale (sotto) |
| `POST /api/connection/finish` | → `{ connected: bool, message }` («Ho finito») |
| `POST /api/connection/cancel` | → 204 («Annulla») |
| `POST /api/connection/cancel` | corpo facoltativo `{ pageLeft: bool }` → 204 («Annulla»; con `pageLeft` la pagina è stata lasciata, sotto) |
| `POST /api/connection/disconnect` | → 204 («Scollega», dopo la conferma nell'interfaccia) |
| `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
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`.
L'interfaccia manda `cancel` anche quando Alberto lascia la pagina Browser, o la pagina Collegamento mentre accede,
senza «Ho finito» né «Annulla»: un'altra pagina, la scheda chiusa o ricaricata (`fetch` con `keepalive`, che porta
l'`Origin` dell'interfaccia). Dopo un «Ho finito» riuscito la pagina chiude la vista remota e non manda un nuovo `begin`.
L'interfaccia manda `cancel` con `{ "pageLeft": true }` anche quando Alberto lascia la pagina Browser, o la pagina
Collegamento mentre accede, senza «Ho finito» né «Annulla»: un'altra pagina, la scheda chiusa o ricaricata (`fetch`
con `keepalive`, che porta l'`Origin` dell'interfaccia). In Docker vale come «Annulla» (il browser torna a riposo).
Su Windows, dove il browser è una finestra a parte, finisce solo il permesso tenuto dalla pagina: la finestra resta
com'è, sullo schermo e con la sua pagina, finché Alberto non la chiude (e finché è sullo schermo il motore resta
fermo). Dopo un «Ho finito» riuscito la pagina chiude la vista remota e non manda un nuovo `begin`.
## Vista remota (`/api/vista`, solo veste Docker)
@@ -30,13 +39,23 @@ Dal server al browser di Alberto:
all'apertura e a ogni cambio di indirizzo o dimensione (l'indirizzo senza parametri di ricerca);
- messaggi binari: un fotogramma JPEG ciascuno (da `Page.startScreencast`), da disegnare su un `<canvas>`.
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
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.
Dal browser di Alberto al server, solo messaggi di testo JSON:
- `{ "type": "mouse", "action": "move"|"down"|"up"|"wheel", "x": 0..1, "y": 0..1, "button": "left"|"right"|"middle", "deltaX": n, "deltaY": n, "clickCount": n }`
con coordinate relative al fotogramma;
- `{ "type": "key", "action": "down"|"up"|"char", "key": "a", "code": "KeyA", "text": "a", "modifiers": n }`
(i tasti non si registrano mai, né sul server né nel browser di Alberto);
- `{ "type": "navigate", "action": "back"|"reload" }`.
- `{ "type": "navigate", "action": "back"|"reload"|"home" }`: «Indietro» (salta la pagina di riposo), «Ricarica»,
«Pagina iniziale» (la pagina iniziale descritta sopra).
## Problemi di configurazione
+6
View File
@@ -114,6 +114,12 @@ public enum RemoteViewNavigation
/// <summary>Reload the current page.</summary>
Reload,
/// <summary>
/// «Pagina iniziale» (issue #52): the site's home when connected, the login page when not connected or after a
/// disconnection. Alberto's own navigation while he drives (rule 7), like the other two.
/// </summary>
Home,
}
/// <summary>The browser is not available (starting, restarting, missing, or Febe stopped by a configuration problem).</summary>
@@ -321,6 +321,7 @@ public static class RemoteViewSocket
{
"back" => RemoteViewNavigation.Back,
"reload" => RemoteViewNavigation.Reload,
"home" => RemoteViewNavigation.Home,
_ => null,
};
@@ -19,5 +19,9 @@ public sealed class UnavailableConnectionService : IConnectionService
public Task CancelAsync(CancellationToken ct) => Task.CompletedTask;
public Task ShowBrowserAsync(bool openLogin, CancellationToken ct) => throw new BadRequestException(Message);
public Task ReleaseAsync(CancellationToken ct) => Task.CompletedTask;
public Task DisconnectAsync(CancellationToken ct) => throw new BadRequestException(Message);
}
-2
View File
@@ -385,8 +385,6 @@ public sealed class DemoShell(IHttpContextAccessor accessor, string root) : INat
public Task<bool> GetAutostartAsync(CancellationToken ct) => Task.FromResult(true);
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
public Task ShowAsync(CancellationToken ct) => Task.CompletedTask;
}
/// <summary>Files of the demo: the shared sample pictures. Videos have only their cover.</summary>
+4
View File
@@ -57,6 +57,10 @@ public sealed class DemoConnectionService(IHttpContextAccessor accessor, DemoWor
public Task CancelAsync(CancellationToken ct) => Task.CompletedTask;
public Task ShowBrowserAsync(bool openLogin, CancellationToken ct) => Task.CompletedTask;
public Task ReleaseAsync(CancellationToken ct) => Task.CompletedTask;
public Task DisconnectAsync(CancellationToken ct) =>
throw new BadRequestException("Dimostrazione: Febe non si scollega davvero. Nella versione vera ferma il motore e cancella il profilo del browser con la sessione.");
}
+4 -6
View File
@@ -75,17 +75,15 @@ public sealed class BrowserShell : INativeShell
/// </summary>
public interface IBrowserWindow
{
/// <summary>True when the browser is a window of its own (Windows): «Apri il browser» calls <see cref="ShowAsync"/>.</summary>
/// <summary>
/// True when the browser is a window of its own (Windows): «Apri il browser» asks the connection to bring it to the
/// front (<c>IConnectionService.ShowBrowserAsync</c>), and leaving a Febe page leaves the window as it is.
/// </summary>
bool IsSeparateWindow { get; }
/// <summary>Brings the browser window to the front (Windows). The engine stays still while Alberto uses it.</summary>
Task ShowAsync(CancellationToken ct);
}
/// <summary>No browser window (Docker uses the Browser page; the demo has no browser).</summary>
public sealed class NoBrowserWindow : IBrowserWindow
{
public bool IsSeparateWindow => false;
public Task ShowAsync(CancellationToken ct) => Task.CompletedTask;
}
+16
View File
@@ -0,0 +1,16 @@
<!-- @license lucide-static v1.56.0 - ISC -->
<svg
class="lucide lucide-house"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8" />
<path d="M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
</svg>

After

Width:  |  Height:  |  Size: 459 B

+11 -5
View File
@@ -248,7 +248,9 @@ function renderBanner(frame, state) {
}
},
}, icon('rotate-cw'), t('arresto.riprendi'));
const open = h('button.btn.primo', { type: 'button', onclick: openBrowser }, icon('app-window'), t('arresto.apriBrowser'));
// After a disconnection the browser opens on the login page (issue #52); after a verification it stays as it is.
const disconnected = Boolean(state.connection && state.connection.state === 'disconnected');
const open = h('button.btn.primo', { type: 'button', onclick: () => openBrowser({ login: disconnected }) }, icon('app-window'), t('arresto.apriBrowser'));
const box = h(`div.arresto${isError ? '' : '.ambra'}`, { role: 'alert' },
icon(isError ? 'octagon-alert' : 'triangle-alert', 'l'),
h('div.testo', h('b', banner.title), h('span', banner.message)),
@@ -257,18 +259,22 @@ function renderBanner(frame, state) {
fill(frame.bannerSlot, box);
}
/** «Apri il browser»: on Windows the window comes to the front; in Docker the Browser page with the remote view. */
export async function openBrowser() {
/**
* «Apri il browser»: on Windows the window comes to the front; in Docker the Browser page with the remote view. A
* browser at rest opens its start page; with login (the red strip of a disconnection) the login page.
*/
export async function openBrowser({ login = false } = {}) {
const openLogin = login === true;
if (caps().browserWindow) {
try {
const result = await api('/api/browser/show', { method: 'POST' });
const result = await api('/api/browser/show', { method: 'POST', body: { openLogin } });
toast(result.message);
refreshEngine();
} catch (error) {
showError(error);
}
} else {
navigate('/browser');
navigate(openLogin ? '/browser?accesso=1' : '/browser');
}
}
+1 -1
View File
@@ -99,7 +99,7 @@ function drawActions(page, state) {
}, icon('pause'), h('span.testo-btn', t('attivita.pausa')));
page.actions(
first,
h('button.btn', { type: 'button', onclick: openBrowser, 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))),
h('button.btn', { type: 'button', onclick: () => openBrowser(), 'aria-label': t('attivita.apriBrowser') }, icon('app-window'), h('span.testo-btn', t('attivita.apriBrowser'))),
diagnosticsButton(),
);
}
+6 -3
View File
@@ -1,7 +1,9 @@
// Browser (spec §10.3 «Apri il browser»; mockup 10 without the steps column): in Docker the remote view of the
// server's browser and «Ho finito»; on Windows the browser is its own window. While Alberto uses the browser the
// 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».
// (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.
import { api } from '../core/api.js';
import { caps } from '../core/context.js';
@@ -24,7 +26,8 @@ export default {
}
if (page.signal.aborted) return;
const lease = drivingLease(page);
lease.begin(false);
const login = new URLSearchParams(location.search).get('accesso') === '1';
lease.begin(login);
const message = h('div', { 'aria-live': 'polite' });
const done = async () => {
const result = await finishDriving();
@@ -40,7 +43,7 @@ export default {
h('div.destra', h('button.btn.primo.grande', { type: 'button', onclick: done }, t('impostazioni.collegamento.hoFinito')))));
fill(page.body, h('div.pagina-browser',
message,
windows ? windowPanel() : remoteView(page, { url: status && status.currentUrl, login: status && status.state === 'notConnected' }).element,
windows ? windowPanel() : remoteView(page, { url: status && status.currentUrl, login: login || (status && status.state === 'notConnected') }).element,
passwordNote(windows)));
},
};
+4 -3
View File
@@ -40,15 +40,16 @@ export async function beginDriving(openLogin) {
/**
* The browser as a page uses it (spec §4.1, §10.3: the engine is still only while Alberto uses the browser). begin()
* takes it; «Ho finito», «Annulla» and «Scollega» give it back on the server, and the page calls settled(). Leaving the
* page in any other way — another page, a reload, closing the tab — counts as «Annulla»: the browser goes back to the
* empty page and the engine may work again.
* page in any other way — another page, a reload, closing the tab — gives it back too: in Docker like «Annulla» (the
* browser goes back to the empty page and the engine may work again); on Windows the window «Browser di Febe» stays as
* it is, on screen until Alberto closes it (issue #52), and only the page's hold ends.
*/
export function drivingLease(page) {
let held = false;
const release = (keepalive) => {
if (!held) return;
held = false;
releasing = api('/api/connection/cancel', { method: 'POST', keepalive }).then(() => {}, () => {});
releasing = api('/api/connection/cancel', { method: 'POST', body: { pageLeft: true }, keepalive }).then(() => {}, () => {});
};
const onHide = () => release(true);
window.addEventListener('pagehide', onHide);
+50 -3
View File
@@ -11,6 +11,14 @@ import { label } from '../core/ui.js';
const BUTTONS = ['left', 'middle', 'right'];
const MAC = /Mac|iPhone|iPad/.test(navigator.platform || '');
/** How long the view waits for the first image before saying that none comes (issue #52). */
const FIRST_FRAME_WAIT = 8000;
/** The empty page the browser rests on: the bar says so instead of showing an address. */
function isRest(url) {
return !url || url === 'about:blank';
}
function altGraph(e) {
return Boolean(e.getModifierState && e.getModifierState('AltGraph'));
}
@@ -44,8 +52,9 @@ export function remoteView(page, { url = null, login = false } = {}) {
const address = h('span.dati');
const back = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('browser.indietro'), title: t('browser.indietro'), onclick: () => send({ type: 'navigate', action: 'back' }) }, icon('arrow-left'));
const reload = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('browser.ricarica'), title: t('browser.ricarica'), onclick: () => send({ type: 'navigate', action: 'reload' }) }, icon('rotate-cw'));
const home = h('button.btn.nudo.solo', { type: 'button', 'aria-label': t('browser.paginaIniziale'), title: t('browser.paginaInizialeAiuto'), onclick: () => send({ type: 'navigate', action: 'home' }) }, icon('house'));
const bar = h('div.vista-barra',
back, reload,
back, reload, home,
h('div.vista-indirizzo', { 'aria-label': t('browser.indirizzo') }, icon('lock', 's'), address),
label(t('browser.vista')));
const canvas = h('canvas.vista-schermo', { tabindex: '0', 'aria-label': t('browser.schermo'), hidden: true, width: '1280', height: '900' });
@@ -56,10 +65,14 @@ export function remoteView(page, { url = null, login = false } = {}) {
let socket = null;
let closed = false;
let frames = 0;
// Each connection has its number: what a replaced socket still says is ignored.
let generation = 0;
let waiting = null;
function showAddress(value) {
if (!value) {
address.replaceChildren();
if (isRest(value)) {
// Never a white area without a word (issue #52): the bar says the browser is resting, «Pagina iniziale» leaves.
fill(address, h('span.muto', t('browser.aRiposo')));
return;
}
const clean = String(value).replace(/^https?:\/\//, '');
@@ -85,16 +98,41 @@ export function remoteView(page, { url = null, login = false } = {}) {
status.hidden = false;
}
/** No image from the browser after a while (the view is open): said plainly, with «Riprova». */
function noImage() {
canvas.hidden = true;
fill(status, h('div.vista-segnaposto',
icon('image', 'l'),
h('p', t('browser.nessunaImmagine')),
h('button.btn', { type: 'button', onclick: connect }, icon('refresh-cw', 's'), t('browser.riprova'))));
status.hidden = false;
}
function send(message) {
if (socket && socket.readyState === 1) socket.send(JSON.stringify(message));
}
function stopWaiting() {
if (waiting) clearTimeout(waiting);
waiting = null;
}
function connect() {
if (closed) return;
if (caps().demo) {
placeholder();
return;
}
generation += 1;
const mine = generation;
stopWaiting();
if (socket) {
// «Riprova» on an open view: the old socket goes, its close says nothing.
const old = socket;
socket = null;
old.close();
}
frames = 0;
fill(status, h('div.vista-segnaposto', icon('hourglass', 'l'), h('p', t('browser.collegamento'))));
status.hidden = false;
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
@@ -104,8 +142,13 @@ export function remoteView(page, { url = null, login = false } = {}) {
failure();
return;
}
waiting = setTimeout(() => {
waiting = null;
if (mine === generation && !closed && frames === 0) noImage();
}, FIRST_FRAME_WAIT);
socket.binaryType = 'blob';
socket.addEventListener('message', async (e) => {
if (mine !== generation) return;
if (typeof e.data === 'string') {
try {
const meta = JSON.parse(e.data);
@@ -127,6 +170,7 @@ export function remoteView(page, { url = null, login = false } = {}) {
bitmap.close();
frames += 1;
if (frames === 1) {
stopWaiting();
canvas.hidden = false;
status.hidden = true;
}
@@ -135,6 +179,8 @@ export function remoteView(page, { url = null, login = false } = {}) {
}
});
socket.addEventListener('close', () => {
if (mine !== generation) return;
stopWaiting();
socket = null;
if (!closed) failure();
});
@@ -220,6 +266,7 @@ export function remoteView(page, { url = null, login = false } = {}) {
function close() {
closed = true;
stopWaiting();
document.removeEventListener('paste', onPaste);
window.removeEventListener('blur', releaseAll);
if (socket) socket.close();
+4
View File
@@ -832,6 +832,10 @@
"segnapostoAccesso": "Qui compare la vera pagina di accesso di Instagram, caricata dal sito. Febe non la ridisegna e non la imita.",
"indietro": "Indietro",
"ricarica": "Ricarica",
"paginaIniziale": "Pagina iniziale",
"paginaInizialeAiuto": "Pagina iniziale: la home del sito se sei collegato, altrimenti la pagina di accesso",
"aRiposo": "Il browser è a riposo su una pagina vuota: premi «Pagina iniziale».",
"nessunaImmagine": "Nessuna immagine dal browser: la vista è aperta, ma la pagina non arriva. Premi «Riprova»; se resta così, guarda il registro.",
"indirizzo": "Indirizzo della pagina",
"collegamento": "Collegamento alla vista remota…",
"nonRisponde": "La vista remota non risponde: il browser di Febe non è raggiungibile in questo momento.",
@@ -0,0 +1,183 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using Febe.Browser.Cdp;
using Febe.Desktop.Browser;
using Febe.SitoDiProva;
using Febe.Tests.Windows.Support;
using Microsoft.Web.WebView2.Core;
namespace Febe.Tests.Windows;
/// <summary>
/// The decisions of the window «Browser di Febe» that need no browser (Gitea issue #52): what a failed process of
/// WebView2 asks of the host, and how much a page is shrunk to fit a small screen.
/// </summary>
[TestClass]
public sealed class BrowserWindowDecisionTests
{
[TestMethod]
public void AFailedProcessIsAnsweredByWhatItBroke()
{
Assert.AreEqual(ProcessFailureResponse.Restart, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.BrowserProcessExited, userIsDriving: false));
Assert.AreEqual(ProcessFailureResponse.Restart, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.BrowserProcessExited, userIsDriving: true));
Assert.AreEqual(ProcessFailureResponse.Rest, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.RenderProcessExited, userIsDriving: true), "a crashed page is gone anyway");
Assert.AreEqual(ProcessFailureResponse.Rest, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.RenderProcessUnresponsive, userIsDriving: false));
Assert.AreEqual(ProcessFailureResponse.None, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.RenderProcessUnresponsive, userIsDriving: true), "never white under Alberto's eyes");
Assert.AreEqual(ProcessFailureResponse.Redraw, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.GpuProcessExited, userIsDriving: false));
Assert.AreEqual(ProcessFailureResponse.Redraw, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.GpuProcessExited, userIsDriving: true));
Assert.AreEqual(ProcessFailureResponse.None, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.UtilityProcessExited, userIsDriving: false));
Assert.AreEqual(ProcessFailureResponse.None, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.FrameRenderProcessExited, userIsDriving: true));
}
[TestMethod]
public void APageThatDoesNotFitIsShrunkButNeverBelowTheSmallestFit()
{
// 1280×900 and its bar, in a frame of 16×39.
Assert.AreEqual(1, BrowserWindow.FitFor(1920, 1040, 1280, 900, 16, 39), "a full HD screen: as it is");
Assert.AreEqual(0.72, BrowserWindow.FitFor(1366, 728, 1280, 900, 16, 39), 1e-9, "a small laptop: by the height");
Assert.AreEqual(0.78, BrowserWindow.FitFor(1024, 1200, 1280, 900, 16, 39), 1e-9, "a narrow screen: by the width");
Assert.AreEqual(BrowserWindow.SmallestFit, BrowserWindow.FitFor(400, 300, 1280, 900, 16, 39));
Assert.AreEqual(1, BrowserWindow.FitFor(1366, 728, 0, 0, 16, 39), "no page size: nothing to fit");
}
}
/// <summary>
/// The window «Browser di Febe» on a real Windows (Gitea issue #52): on screen it has its taskbar button and says when
/// the page is the empty rest page, «Pagina iniziale» opens the start page, and a minimised window keeps Alberto at the
/// wheel until it has been minimised too long. The window comes on screen for a moment.
/// </summary>
[TestClass]
public sealed class BrowserWindowTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireWebView2() => WebView2Runtime.Require();
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task OnScreenTheWindowHasItsTaskbarButtonAndSaysWhenItRests()
{
var ct = TestContext.CancellationToken;
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
var start = site.Url("/benvenuto");
await using var bed = await BrowserBed.CreateAsync("finestra-pagina-iniziale", startPage: () => start);
await bed.StartAsync(ct);
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar), "out of view, no taskbar button");
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
Assert.IsTrue(await bed.OnUiAsync(() => window.IsOnScreen));
Assert.IsTrue(await bed.OnUiAsync(() => window.ShowInTaskbar), "on screen, a taskbar button");
Assert.AreEqual(BrowserWindow.RestNotice, await bed.OnUiAsync(() => window.AddressText), "the empty page says what it is");
Assert.IsGreaterThan(0, await bed.OnUiAsync(() => window.Fit));
// «Pagina iniziale»: Alberto's own navigation, to the start page the composition gives.
await bed.OnUiAsync(() =>
{
Button(window, "Pagina iniziale").RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
return true;
});
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (await bed.OnUiAsync(() => window.AddressText) != start)
{
Assert.IsLessThan(deadline, DateTime.UtcNow, "la pagina iniziale nella barra: " + bed.Lines.Text);
await Task.Delay(100, ct);
}
Assert.AreEqual(start, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct);
Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar), "out of view again, no taskbar button");
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task AMinimisedWindowKeepsAlbertoAtTheWheelUntilItIsMinimisedTooLong()
{
var ct = TestContext.CancellationToken;
await using var bed = await BrowserBed.CreateAsync("finestra-ridotta");
await bed.StartAsync(ct);
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
await bed.OnUiAsync(() => window.MinimizedLimit = TimeSpan.FromSeconds(1));
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
await bed.OnUiAsync(() => window.WindowState = WindowState.Minimized);
Assert.IsTrue(bed.Browser.UserIsDriving, "minimised is not «ho finito»: its taskbar button brings it back");
Assert.IsTrue(await bed.OnUiAsync(() => window.ShowInTaskbar));
// Left there: restored and put out of view, as if closed (S2: never minimised for long).
await bed.WaitUntilAsync(() => !bed.Browser.UserIsDriving, TimeSpan.FromSeconds(15), "la fine della guida dopo la finestra ridotta a icona", ct);
Assert.AreEqual(WindowState.Normal, await bed.OnUiAsync(() => window.WindowState));
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar));
// Brought back before the limit, it stays Alberto's.
await bed.OnUiAsync(() => window.MinimizedLimit = TimeSpan.FromMinutes(2));
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
await bed.OnUiAsync(() => window.WindowState = WindowState.Minimized);
await bed.OnUiAsync(() => window.WindowState = WindowState.Normal);
await Task.Delay(1500, ct);
Assert.IsTrue(bed.Browser.UserIsDriving);
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct);
}
[TestMethod]
[Timeout(240_000, CooperativeCancellation = true)]
public async Task LeavingThePageOfFebeLeavesTheWindowOnScreenWithItsPage()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopBed.StartAsync("finestra-resta", autoLogin: false, ct);
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
var connection = bed.App.Connection!;
var browser = bed.Browser;
var window = await bed.Ui.InvokeAsync(() => browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
// «Usa il browser» on the rest page, not connected: the login page of the test site, never a white window.
await connection.BeginUserDrivingAsync(openLogin: false, ct);
var opened = (await connection.GetStatusAsync(ct)).CurrentUrl;
StringAssert.StartsWith(opened, bed.Site.Url("/benvenuto"));
Assert.IsTrue(await bed.Ui.InvokeAsync(() => window.IsOnScreen));
// The page of Febe goes (another page, the tab closed): the window stays, with its page and the engine still.
await connection.ReleaseAsync(ct);
await Task.Delay(1500, ct);
Assert.IsTrue(await bed.Ui.InvokeAsync(() => window.IsOnScreen), "still on screen");
Assert.IsTrue(browser.UserIsDriving, "the window on screen holds the engine");
Assert.AreEqual(opened, (await connection.GetStatusAsync(ct)).CurrentUrl, "its page as it was");
Assert.IsTrue(bed.Lines.Any("Pagina di Febe lasciata: la finestra del browser resta com'è finché non la chiudi."), bed.Lines.Text);
// Closed with its X: out of view, the engine may work again.
await bed.Ui.InvokeAsync(() =>
{
window.Close();
return true;
});
await bed.WaitUntilAsync(() => Task.FromResult(!browser.UserIsDriving), TimeSpan.FromSeconds(10), "la fine della guida dopo la chiusura", ct);
Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen));
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
}
private static Button Button(DependencyObject root, string text) =>
FindOrNull(root, text) ?? throw new AssertFailedException($"Nessun pulsante «{text}» nella finestra.");
private static Button? FindOrNull(DependencyObject root, string text)
{
foreach (var child in LogicalTreeHelper.GetChildren(root).OfType<DependencyObject>())
{
if (child is Button { Content: string content } button && content == text)
{
return button;
}
if (FindOrNull(child, text) is { } found)
{
return found;
}
}
return null;
}
}
@@ -42,7 +42,10 @@ internal sealed class BrowserBed : IAsyncDisposable
public WebView2Browser Browser { get; }
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window)
/// <param name="name">Prefix of the temporary folder.</param>
/// <param name="hosting">How WebView2 draws (S2).</param>
/// <param name="startPage">Where «Pagina iniziale» goes; null: the login page of the options.</param>
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func<string>? startPage = null)
{
var folder = new TestFolder(name);
var ui = await UiThread.StartAsync();
@@ -53,7 +56,7 @@ internal sealed class BrowserBed : IAsyncDisposable
var database = await FebeDatabase.OpenAsync(data.Root);
var options = new FebeAppOptions { DataFolder = data.Root, LibraryFolder = folder.Combine("libreria") };
var tracker = new BrowserUseTracker();
var context = new FebePlatformContext(options, data, database, clock, log, tracker);
var context = new FebePlatformContext(options, data, database, clock, log, tracker, startPage);
var settings = new WebView2BrowserSettings(data.BrowserProfile, 1280, 900, hosting, BrowserArguments.ForWebView2());
// Built off the UI thread, as DesktopPlatform.CreateBrowserAsync does after its awaits.
@@ -64,7 +64,8 @@ public sealed class RemoteViewDuringNavigationTests
var notes = new ConcurrentQueue<string>();
var log = new DelegateBrowserLog((level, message, _) =>
{
if (level == BrowserLogLevel.Debug)
// The retry note is written at Info since issue #52 (it reaches the registro).
if (level is BrowserLogLevel.Debug or BrowserLogLevel.Information)
{
notes.Enqueue(message);
}
@@ -0,0 +1,130 @@
using System.Diagnostics;
using Febe.Browser.Cdp;
using Febe.Browser.RemoteView;
using Febe.Tests.Browser.TestSupport;
namespace Febe.Tests.Browser;
/// <summary>
/// The remote view that stayed white (Gitea issue #52), on a real Chromium on Xvfb and the local test site: a page that
/// does not move still shows itself, and the frames keep coming when the page changes renderer (another site, the rest
/// page and back). Only in the Linux CI; never Instagram.
/// </summary>
[TestClass]
[DoNotParallelize]
public sealed class RemoteViewFramesTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireBrowser()
{
if (RealBrowser.UnavailableReason() is { } reason)
{
Assert.Inconclusive(reason);
}
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task AStillPageAndTheRestPageShowAPictureWithinFiveSeconds()
{
var ct = TestContext.CancellationToken;
await using var browser = await RealBrowser.StartAsync();
var cdp = browser.Cdp;
var opened = await cdp.NavigateAsync(browser.Site.Url("/accesso"), ct);
Assert.IsTrue(opened.Succeeded, opened.ErrorText);
await cdp.WaitForLoadAsync(new Febe.Core.Abstractions.SystemClock(), TimeSpan.FromSeconds(15), ct);
var view = new RemoteViewSession(cdp, browser.Host.UserDriving);
try
{
await view.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900, Watchdog: ScreencastWatchdog.Default), ct);
Assert.IsTrue(await PictureAfterAsync(view.Screencast, null, TimeSpan.FromSeconds(5), ct), "a picture of the login page");
var last = view.Screencast.LastFrame;
var rest = await cdp.RestAsync(ct);
Assert.IsTrue(rest.Succeeded, rest.ErrorText);
Assert.IsTrue(await PictureAfterAsync(view.Screencast, last, TimeSpan.FromSeconds(5), ct), "a picture of the rest page too");
}
finally
{
await view.DisposeAsync();
}
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task FramesKeepComingWhenThePageChangesRenderer()
{
var ct = TestContext.CancellationToken;
await using var browser = await RealBrowser.StartAsync();
var cdp = browser.Cdp;
var first = await cdp.NavigateAsync(browser.Site.Url("/animata"), ct);
Assert.IsTrue(first.Succeeded, first.ErrorText);
var view = new RemoteViewSession(cdp, browser.Host.UserDriving);
try
{
await view.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900, Watchdog: ScreencastWatchdog.Default), ct);
Assert.IsTrue(await FramesAfterAsync(view.Screencast, ct), "frames of the animated page");
foreach (var (address, moving) in new[]
{
(browser.Site.LocalhostUrl("/animata"), true),
("about:blank", false),
(browser.Site.Url("/animata"), true),
})
{
var last = view.Screencast.LastFrame;
var watch = Stopwatch.StartNew();
var navigated = await cdp.NavigateAsync(address, ct);
Assert.IsTrue(navigated.Succeeded, $"{address}: {navigated.ErrorText}");
var shown = moving
? await FramesAfterAsync(view.Screencast, ct)
: await PictureAfterAsync(view.Screencast, last, TimeSpan.FromSeconds(5), ct);
TestContext.WriteLine($"{address}: {(shown ? "immagini" : "niente")} dopo {watch.ElapsedMilliseconds} ms, riavvii {view.Screencast.Restarts}.");
Assert.IsTrue(shown, $"{address}: the view is not white");
}
}
finally
{
await view.DisposeAsync();
}
}
/// <summary>A frame or a still picture other than <paramref name="last"/>, within <paramref name="timeout"/>.</summary>
private static async Task<bool> PictureAfterAsync(ScreencastSession screencast, ScreencastFrame? last, TimeSpan timeout, CancellationToken ct)
{
var deadline = Stopwatch.StartNew();
while (deadline.Elapsed < timeout)
{
if (screencast.LastFrame is { Jpeg: [0xFF, 0xD8, ..] } frame && !ReferenceEquals(frame, last))
{
return true;
}
await Task.Delay(50, ct);
}
return false;
}
/// <summary>A few real frames of the screencast (not still pictures) after now, within ten seconds.</summary>
private static async Task<bool> FramesAfterAsync(ScreencastSession screencast, CancellationToken ct)
{
var before = screencast.FramesReceived;
var deadline = Stopwatch.StartNew();
while (deadline.Elapsed < TimeSpan.FromSeconds(10))
{
if (screencast.FramesReceived >= before + 3)
{
return true;
}
await Task.Delay(50, ct);
}
return false;
}
}
@@ -0,0 +1,336 @@
using System.Collections.Concurrent;
using System.Text.Json.Nodes;
using Febe.Browser.Cdp;
using Febe.Browser.Diagnostics;
using Febe.Browser.RemoteView;
using Febe.Core.Abstractions;
using Febe.Tests.Browser.TestSupport;
namespace Febe.Tests.Browser;
/// <summary>
/// The frames' watchdog of the remote view (Gitea issue #52), without a browser: a lost acknowledgement, a page that
/// does not repaint and a new document loaded without frames must never leave the view white and silent. The clock
/// moves only when the test says so, one look of the watchdog at a time.
/// </summary>
[TestClass]
public sealed class ScreencastWatchdogTests
{
private static readonly ScreencastWatchdog Watchdog = new(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(250), TimeSpan.FromSeconds(30));
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task ALostAcknowledgementIsFollowedByARestartAndTheFramesComeBack()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(lostAcks: true);
await bed.StartAsync(ct);
bed.Frame();
Assert.AreEqual(1, bed.Starts);
// The ack was lost: Chromium sends nothing more. Two seconds later the frames are started again.
await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct);
Assert.AreEqual(1, bed.Session.Restarts);
Assert.AreEqual(2, bed.Starts, "a new screencast session");
var methods = bed.Cdp.Sent.Select(c => c.Method).Where(m => m is "Page.stopScreencast" or "Page.startScreencast").ToList();
CollectionAssert.AreEqual(new[] { "Page.startScreencast", "Page.stopScreencast", "Page.startScreencast" }, methods);
Assert.IsTrue(bed.Info.Contains("Vista remota: nessun fotogramma da 2 s, riavvio dei fotogrammi."), bed.AllLines);
// Frames flow again: said once, at Info.
for (var i = 0; i < ScreencastWatchdog.FlowingFrames; i++)
{
bed.Frame();
}
Assert.IsTrue(bed.Info.Any(l => l.StartsWith("Vista remota: fotogrammi di nuovo in arrivo, dopo ", StringComparison.Ordinal)), bed.AllLines);
Assert.AreEqual(1 + ScreencastWatchdog.FlowingFrames, bed.Session.FramesReceived);
// The stop is the last word: no start after it.
await bed.Session.StopAsync(ct);
Assert.AreEqual("Page.stopScreencast", bed.Cdp.Sent.Last(c => c.Method.Contains("Screencast", StringComparison.Ordinal) && c.Method != "Page.screencastFrameAck").Method);
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task APageThatNeverSendsAFrameGetsAStillPictureOfItself()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(screenshot: Jpeg(800, 600));
await bed.StartAsync(ct);
await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct);
var still = bed.Session.LastFrame;
Assert.IsNotNull(still, "something to show");
Assert.IsTrue(still.Still);
Assert.AreEqual(800, still.DeviceWidth, "the size written in the picture");
Assert.AreEqual(600, still.DeviceHeight);
Assert.AreEqual(0, bed.Session.FramesReceived, "a still picture is not a frame of the screencast");
Assert.AreEqual(1, bed.Cdp.Sent.Count(c => c.Method == "Page.captureScreenshot"));
using var read = CancellationTokenSource.CreateLinkedTokenSource(ct);
read.CancelAfter(TimeSpan.FromSeconds(5));
await foreach (var frame in bed.Session.ReadFramesAsync(read.Token))
{
Assert.IsTrue(frame.Still, "the reader gets it like any frame");
break;
}
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task ANewDocumentLoadedWithoutFramesStartsThemAgainAtTheNextLook()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed();
await bed.StartAsync(ct);
bed.Frame();
// A frame of a page inside the page changes nothing; the main frame does.
bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F2", ["parentId"] = "F1", ["url"] = "http://127.0.0.1/pubblicita" } });
bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "http://127.0.0.1/animata" } });
bed.Cdp.Raise("Page.loadEventFired", new JsonObject { ["timestamp"] = 1.0 });
await bed.StepAsync(Watchdog.Tick, ct);
Assert.AreEqual(1, bed.Session.Restarts, "no two seconds of white after a new page");
Assert.IsTrue(bed.Info.Contains("Vista remota: pagina nuova caricata senza fotogrammi, riavvio dei fotogrammi."), bed.AllLines);
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task ANewDocumentWhoseFramesArriveIsLeftAlone()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed();
await bed.StartAsync(ct);
bed.Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "http://127.0.0.1/animata" } });
bed.Frame();
bed.Cdp.Raise("Page.loadEventFired", new JsonObject { ["timestamp"] = 1.0 });
for (var i = 0; i < 6; i++)
{
await bed.StepAsync(Watchdog.Tick, ct);
bed.Frame();
}
Assert.AreEqual(0, bed.Session.Restarts);
Assert.AreEqual(1, bed.Starts);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task AStillPageCostsFewerAndFewerRestartsAndOneLineInTheRegistro()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(screenshot: Jpeg(1280, 900));
await bed.StartAsync(ct);
// Thirty seconds of a page that does not move: restarts after 2, 4, 8 and 16 more seconds, not fifteen.
await bed.StepAsync(TimeSpan.FromSeconds(30.25), ct);
Assert.AreEqual(4, bed.Session.Restarts, bed.AllLines);
Assert.AreEqual(1, bed.Info.Count(l => l.Contains("riavvio dei fotogrammi", StringComparison.Ordinal)), "one line for the whole silence, the others at Debug");
Assert.IsFalse(bed.AllLines.Contains("http", StringComparison.Ordinal), "no addresses in the registro");
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task WithoutAWatchdogNothingIsStartedAgain()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(noWatchdog: true);
await bed.StartAsync(ct);
Assert.AreEqual(0, bed.Clock.Waiting, "nobody watches");
bed.Clock.Advance(TimeSpan.FromMinutes(1));
Assert.AreEqual(1, bed.Starts);
Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.captureScreenshot"));
}
[TestMethod]
public void TheSizeOfAJpegIsReadFromItsFrameHeader()
{
Assert.AreEqual((800, 600), ScreencastSession.JpegSize(Jpeg(800, 600)));
Assert.AreEqual((1280, 900), ScreencastSession.JpegSize(Jpeg(1280, 900, progressive: true)));
Assert.IsNull(ScreencastSession.JpegSize([0xFF, 0xD8, 0xFF, 0xD9]), "no frame header");
Assert.IsNull(ScreencastSession.JpegSize([0x89, 0x50, 0x4E, 0x47]), "not a JPEG");
Assert.IsNull(ScreencastSession.JpegSize([]));
Assert.IsNull(ScreencastSession.JpegSize([0xFF, 0xD8, 0xFF, 0xC0, 0x00, 0x11, 0x08]), "cut short");
}
/// <summary>A minimal JPEG header: SOI, an APP0 segment, then a SOF0 (or SOF2) with the size.</summary>
private static byte[] Jpeg(int width, int height, bool progressive = false) =>
[
0xFF, 0xD8,
0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46, 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00,
0xFF, progressive ? (byte)0xC2 : (byte)0xC0, 0x00, 0x11, 0x08,
(byte)(height >> 8), (byte)height, (byte)(width >> 8), (byte)width,
0x03, 0x01, 0x22, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01,
0xFF, 0xD9,
];
/// <summary>A screencast over a fake page and a clock that moves only when stepped.</summary>
private sealed class Bed : IAsyncDisposable
{
private readonly ConcurrentQueue<(BrowserLogLevel Level, string Message)> _lines = new();
private readonly ScreencastWatchdog? _watchdog;
private int _starts;
private int _frameSession;
public Bed(bool lostAcks = false, byte[]? screenshot = null, bool noWatchdog = false)
{
_watchdog = noWatchdog ? null : Watchdog;
Clock = new SteppingClock();
Cdp = new FakeCdpSession(Clock)
{
Responder = (method, _) =>
{
switch (method)
{
case "Page.startScreencast":
Interlocked.Increment(ref _starts);
return null;
case "Page.screencastFrameAck" when lostAcks:
throw new CdpCommandException(method, CdpCommandException.ServerErrorCode, "Session is not attached");
case "Page.captureScreenshot":
return screenshot is null ? null : new JsonObject { ["data"] = Convert.ToBase64String(screenshot) };
default:
return null;
}
},
};
Session = new ScreencastSession(Cdp, new DelegateBrowserLog((level, message, _) => _lines.Enqueue((level, message))), Clock);
}
public SteppingClock Clock { get; }
public FakeCdpSession Cdp { get; }
public ScreencastSession Session { get; }
public int Starts => Volatile.Read(ref _starts);
public List<string> Info => [.. _lines.Where(l => l.Level == BrowserLogLevel.Information).Select(l => l.Message)];
public string AllLines => string.Join('\n', _lines.Select(l => $"{l.Level} {l.Message}"));
public async Task StartAsync(CancellationToken ct)
{
await Session.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900, Watchdog: _watchdog), ct);
if (_watchdog is not null)
{
await Clock.WaitForSleeperAsync(ct);
}
}
/// <summary>A frame of the screencast, as Chromium sends it.</summary>
public void Frame() => Cdp.Raise("Page.screencastFrame", new JsonObject
{
["sessionId"] = Interlocked.Increment(ref _frameSession),
["data"] = Convert.ToBase64String(Jpeg(1280, 900)),
["metadata"] = new JsonObject { ["deviceWidth"] = 1280, ["deviceHeight"] = 900, ["pageScaleFactor"] = 1 },
});
/// <summary>Moves the clock by <paramref name="time"/>, one look of the watchdog at a time.</summary>
public async Task StepAsync(TimeSpan time, CancellationToken ct)
{
var tick = (_watchdog ?? Watchdog).Tick;
for (var moved = TimeSpan.Zero; moved < time; moved += tick)
{
Clock.Advance(tick);
await Clock.WaitForSleeperAsync(ct);
}
}
public async ValueTask DisposeAsync() => await Session.DisposeAsync();
}
/// <summary>A clock whose delays end only when the test moves it past them.</summary>
private sealed class SteppingClock : IClock
{
private readonly Lock _gate = new();
private readonly List<(DateTimeOffset Due, TaskCompletionSource Done)> _sleepers = [];
private DateTimeOffset _now = new(2026, 11, 16, 9, 0, 0, TimeSpan.Zero);
public DateTimeOffset Now
{
get
{
lock (_gate)
{
return _now;
}
}
}
public TimeZoneInfo LocalZone => TimeZoneInfo.Utc;
public int Waiting
{
get
{
lock (_gate)
{
return _sleepers.Count;
}
}
}
public Task Delay(TimeSpan time, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
if (time <= TimeSpan.Zero)
{
return Task.CompletedTask;
}
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
lock (_gate)
{
_sleepers.Add((_now + time, done));
}
ct.Register(() =>
{
lock (_gate)
{
_sleepers.RemoveAll(s => s.Done == done);
}
done.TrySetCanceled(ct);
});
return done.Task;
}
public void Advance(TimeSpan time)
{
List<TaskCompletionSource> due;
lock (_gate)
{
_now += time;
due = [.. _sleepers.Where(s => s.Due <= _now).Select(s => s.Done)];
_sleepers.RemoveAll(s => s.Due <= _now);
}
foreach (var done in due)
{
done.TrySetResult();
}
}
/// <summary>Waits (in real time) until someone sleeps on the clock again: the watchdog finished its look.</summary>
public async Task WaitForSleeperAsync(CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
while (Waiting == 0)
{
await Task.Delay(1, timeout.Token);
}
}
}
}
@@ -44,6 +44,9 @@ public sealed class LocalTestSite : IDisposable
public string Url(string path) => $"http://{SiteHost}{path}";
/// <summary>The same site under the name «localhost»: another site for Chromium, so another renderer.</summary>
public string LocalhostUrl(string path) => $"http://localhost:{SitePort}{path}";
public string CdnUrl(string path) => $"http://{CdnHost}{path}";
public static int FreePort()
@@ -0,0 +1,196 @@
using System.Net;
using Febe.Core.Abstractions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Desktop;
/// <summary>
/// The browser that showed nothing (Gitea issue #52), in the shared composition with the fake window «Browser di Febe»:
/// opened from the empty rest page it goes to a page of its own, «Apri il browser» of a disconnection opens the login,
/// leaving a page of Febe leaves the window as it is, and the test site's automatic login raises no false alarm.
/// Never Instagram: the fake browser answers by itself.
/// </summary>
[TestClass]
public sealed class BrowserStartPageTests
{
private const string Login = "https://www.instagram.com/accounts/login/";
private const string Home = "https://www.instagram.com/";
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task UsaIlBrowserFromTheRestPageOpensTheLoginOrTheHomeAndAnyOtherPageStays()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
Assert.AreEqual("about:blank", browser.FakeCdp.Url);
// Not connected: never a white window, the login page.
await BeginAsync(bed, openLogin: false);
Assert.AreEqual(Login, browser.FakeCdp.Url);
Assert.AreEqual(1, browser.Shown, "the window came to the front");
browser.FakeCdp.LoggedIn = true;
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean());
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo «Ho finito»");
// Connected: the site's home.
await BeginAsync(bed, openLogin: false);
Assert.AreEqual(Home, browser.FakeCdp.Url);
// A page he opened stays as it is.
browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/");
var navigations = Navigations(browser);
await BeginAsync(bed, openLogin: false);
Assert.AreEqual("https://www.instagram.com/marta.prova/", browser.FakeCdp.Url);
Assert.AreEqual(navigations, Navigations(browser), "no navigation of his page");
var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection");
Assert.IsTrue(status.GetProperty("userIsDriving").GetBoolean());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ApriIlBrowserBringsTheWindowWithItsStartPageAndTheLoginAfterADisconnection()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
// Connected, at rest: «Apri il browser» (Attività) opens the home, the window in front.
await LoginAsync(bed);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo «Ho finito»");
var shown = browser.Shown;
var result = await bed.JsonAsync(HttpMethod.Post, "/api/browser/show");
StringAssert.Contains(result.GetProperty("message").GetString(), "primo piano");
Assert.AreEqual(Home, browser.FakeCdp.Url);
Assert.AreEqual(shown + 1, browser.Shown);
Assert.IsTrue(browser.UserIsDriving, "the window on screen holds the engine still");
// Closed with its X: out of view, the engine puts the page to rest.
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo la chiusura");
// The session goes while nobody looks: a disconnection. The red strip's «Apri il browser» asks for the login.
browser.FakeCdp.LoggedIn = false;
await bed.App.Connection!.RefreshAsync(ct);
var breaker = bed.App.Engine!.Services.Breaker;
await breaker.FlushAsync();
Assert.AreEqual(BreakerStatus.Disconnected, breaker.State.Status);
Assert.AreEqual(Login, bed.App.Connection.StartPageUrl, "disconnected: the start page is the login");
using (var show = await bed.SendAsync(HttpMethod.Post, "/api/browser/show", """{"openLogin":true}"""))
{
Assert.AreEqual(HttpStatusCode.OK, show.StatusCode, await show.Content.ReadAsStringAsync(ct));
}
Assert.AreEqual(Login, browser.FakeCdp.Url);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task LeavingThePageOfFebeLeavesTheWindowOnScreenButAnnullaPutsItAway()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var browser = bed.Browser!;
await LoginAsync(bed);
await DesktopTestBed.WaitUntilAsync(() => browser.FakeCdp.Url == "about:blank", TimeSpan.FromSeconds(10), "la pagina di riposo dopo «Ho finito»");
await BeginAsync(bed, openLogin: false);
Assert.AreEqual(Home, browser.FakeCdp.Url);
var hidden = browser.Hidden;
// Another page of Febe, the tab closed or reloaded: the page's hold ends, the window stays where it is.
using (var left = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel", """{"pageLeft":true}"""))
{
Assert.AreEqual(HttpStatusCode.NoContent, left.StatusCode);
}
await Task.Delay(TimeSpan.FromSeconds(1), ct);
Assert.AreEqual(hidden, browser.Hidden, "not put out of view");
Assert.AreEqual(Home, browser.FakeCdp.Url, "not put to rest");
Assert.IsTrue(browser.UserIsDriving, "on screen, the window still holds the engine");
Assert.IsTrue(bed.App.Engine!.Services.Runtime.UserIsDriving);
// «Annulla» from the page is still «Annulla»: out of view and at rest.
await BeginAsync(bed, openLogin: false);
using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel"))
{
Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode);
}
Assert.AreEqual(hidden + 1, browser.Hidden);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo «Annulla»");
Assert.AreEqual("about:blank", browser.FakeCdp.Url);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task HoFinitoWithoutTheLoginSaysTheSessionIsNotThere()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync();
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
await BeginAsync(bed, openLogin: true);
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsFalse(finish.GetProperty("connected").GetBoolean());
StringAssert.Contains(finish.GetProperty("message").GetString(), "non trova la sessione");
}
[TestMethod]
[Timeout(90_000, CooperativeCancellation = true)]
public async Task TheTestSitesAutomaticLoginIsNoDisconnectionAtTheNextStart()
{
var ct = TestContext.CancellationToken;
const string site = "http://127.0.0.1:8481";
string[] args = ["--sito-di-prova", site, "--accesso-di-prova"];
using var temp = new TempFolder("accesso-di-prova");
var locations = new MemoryLocationStore();
FakeDesktopShell Shell() => new() { OnCreated = b => b.FakeCdp.LogsInOnVisit = site };
await using (var bed = await DesktopTestBed.StartAsync(args, Shell(), temp, locations))
{
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
Assert.IsTrue(bed.App.Connection!.IsConnected, "logged in by the automatic login");
await bed.StopAsync();
}
// The next start: the new browser has no session yet (the test site forgot it); the automatic login opens it again.
await using (var bed = await DesktopTestBed.StartAsync(args, Shell(), temp, locations))
{
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
var breaker = bed.App.Engine!.Services.Breaker;
await breaker.FlushAsync();
Assert.IsTrue(bed.App.Connection!.IsConnected);
Assert.AreEqual(BreakerStatus.Closed, breaker.State.Status, "not a disconnection: the session the login was about to open");
Assert.IsEmpty(await bed.App.Database.Incidents.ListOpenAsync(ct));
await bed.StopAsync();
}
}
private static int Navigations(FakeBrowser browser) => browser.FakeCdp.Methods.Count(m => m == "Page.navigate");
private static async Task BeginAsync(DesktopTestBed bed, bool openLogin)
{
using var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", openLogin ? """{"openLogin":true}""" : """{"openLogin":false}""");
Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode);
}
private static async Task LoginAsync(DesktopTestBed bed)
{
await BeginAsync(bed, openLogin: true);
bed.Browser!.FakeCdp.LoggedIn = true;
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean(), finish.GetProperty("message").GetString());
}
}
@@ -28,11 +28,15 @@ internal sealed class FakeDesktopShell : IDesktopShell
public ConcurrentQueue<string> ProcessWindows { get; } = new();
/// <summary>Called with each browser as it is created, before Febe uses it (to set up the fake page).</summary>
public Action<FakeBrowser>? OnCreated { get; set; }
public string? WebView2Version() => RuntimeVersion;
public IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context)
{
var browser = new FakeBrowser(settings.ProfileDirectory, settings.Width, settings.Height, context);
OnCreated?.Invoke(browser);
Created.Enqueue((settings, browser));
return browser;
}
@@ -225,6 +229,12 @@ internal sealed class FakeCdp : ICdpSession
public bool LoggedIn { get; set; }
/// <summary>
/// Like the test site, which sets its session cookie on any visit: a navigation to an address starting with this
/// logs in, and the page reports itself loaded. Null: only the test logs in.
/// </summary>
public string? LogsInOnVisit { get; set; }
public string Url { get; private set; } = "about:blank";
public ConcurrentQueue<string> Methods { get; } = new();
@@ -244,7 +254,9 @@ internal sealed class FakeCdp : ICdpSession
{
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = Url } } },
"Page.navigate" => Navigate(parameters),
"Network.getCookies" => new JsonObject { ["cookies"] = LoggedIn ? new JsonArray(new JsonObject { ["name"] = "sessionid" }) : new JsonArray() },
// The session cookie of Instagram, and the test site's one.
"Network.getCookies" => new JsonObject { ["cookies"] = LoggedIn ? new JsonArray(new JsonObject { ["name"] = "sessionid" }, new JsonObject { ["name"] = "sessione_prova" }) : new JsonArray() },
"Runtime.evaluate" when LogsInOnVisit is not null => new JsonObject { ["result"] = new JsonObject { ["type"] = "string", ["value"] = "complete" } },
_ => new JsonObject(),
};
return Task.FromResult(JsonDocument.Parse(result.ToJsonString()).RootElement.Clone());
@@ -276,6 +288,11 @@ internal sealed class FakeCdp : ICdpSession
var url = (parameters as JsonObject)?["url"]?.GetValue<string>();
if (url is not null)
{
if (LogsInOnVisit is { } site && url.StartsWith(site, StringComparison.Ordinal))
{
LoggedIn = true;
}
Navigated(url);
}
@@ -177,6 +177,17 @@ public sealed class RemoteViewSocketTests
Assert.AreEqual("about:blank", BrowserRemoteViewConnection.WithoutQuery("about:blank"));
}
[TestMethod]
public void TheThreeButtonsOfTheBarAreNavigations()
{
static object? Parse(string json) => RemoteViewSocket.Parse(Encoding.UTF8.GetBytes(json));
Assert.AreEqual(RemoteViewNavigation.Back, Parse("""{"type":"navigate","action":"back"}"""));
Assert.AreEqual(RemoteViewNavigation.Reload, Parse("""{"type":"navigate","action":"reload"}"""));
Assert.AreEqual(RemoteViewNavigation.Home, Parse("""{"type":"navigate","action":"home"}"""), "«Pagina iniziale» (issue #52)");
Assert.IsNull(Parse("""{"type":"navigate","action":"https://example.com/"}"""), "never an address from the page");
}
private static Task<WebTestServer> StartAsync(FakeRemoteViewHost host) =>
WebTestServer.StartAsync(
new FebeWebOptions { Edition = FebeEdition.Docker, Access = AccessMode.Password, Password = Password },
@@ -132,6 +132,65 @@ public sealed class RemoteViewStartTests
}
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task PaginaInizialeOpensTheStartPageOfTheMoment()
{
var ct = TestContext.CancellationToken;
var start = "http://127.0.0.1:8481/benvenuto";
await using var bed = new Bed(_ => null, () => start);
var view = await bed.Host.OpenAsync(ct);
await view.NavigateAsync(RemoteViewNavigation.Home, ct);
Assert.AreEqual(start, bed.LastNavigation, "not connected: the login page");
// Connected meanwhile: the same button opens the site's home.
start = "http://127.0.0.1:8481/";
await view.NavigateAsync(RemoteViewNavigation.Home, ct);
Assert.AreEqual(start, bed.LastNavigation);
Assert.AreEqual(2, bed.Cdp.Sent.Count(c => c.Method == "Page.navigate"), "Alberto's own navigations, one per press");
await view.DisposeAsync();
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task WithoutAStartPageTheButtonDoesNothing()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(_ => null);
var view = await bed.Host.OpenAsync(ct);
await view.NavigateAsync(RemoteViewNavigation.Home, ct);
Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.navigate"));
await view.DisposeAsync();
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task IndietroNeverLandsOnTheEmptyRestPage()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(_ => null);
var view = await bed.Host.OpenAsync(ct);
// The view opened on the rest page; then a page, the rest page again (a session of the engine), another page.
bed.Navigated("http://127.0.0.1:8481/profilo/marta.prova/");
bed.Navigated("about:blank");
bed.Navigated("http://127.0.0.1:8481/esplora/");
await view.NavigateAsync(RemoteViewNavigation.Back, ct);
Assert.AreEqual("http://127.0.0.1:8481/profilo/marta.prova/", bed.LastNavigation, "the rest page in between is skipped");
// Before that only the rest page: «Indietro» stays where it is instead of turning the view white.
bed.Cdp.ClearSent();
await view.NavigateAsync(RemoteViewNavigation.Back, ct);
Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.navigate"));
await view.DisposeAsync();
}
private static CdpCommandException InactivePage() =>
new("Page.startScreencast", CdpCommandException.ServerErrorCode, CdpCommandException.InactivePageMessage);
@@ -170,7 +229,8 @@ public sealed class RemoteViewStartTests
private int _starts;
/// <param name="startFailure">For the n-th start (from 1), the exception the browser answers with; null: started.</param>
public Bed(Func<int, Exception?> startFailure)
/// <param name="startPage">Where «Pagina iniziale» goes; null: nowhere.</param>
public Bed(Func<int, Exception?> startFailure, Func<string>? startPage = null)
{
Clock = new VirtualClock();
_start = Clock.Now;
@@ -196,7 +256,11 @@ public sealed class RemoteViewStartTests
};
Browser = new PageBrowser(Cdp);
_log = new FebeLog(null, null, Clock);
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock);
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, startPage: startPage)
{
// The virtual clock moves only in the pauses: a watchdog on it would never wait.
Watchdog = null,
};
}
public VirtualClock Clock { get; }
@@ -209,6 +273,13 @@ public sealed class RemoteViewStartTests
public int Starts => Volatile.Read(ref _starts);
/// <summary>The address of the last <c>Page.navigate</c>.</summary>
public string? LastNavigation => Cdp.Sent.LastOrDefault(c => c.Method == "Page.navigate")?.Parameters?["url"]?.GetValue<string>();
/// <summary>The main frame committed a new document.</summary>
public void Navigated(string url) =>
Cdp.Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = url } });
/// <summary>Time spent in the host's pauses (the virtual clock moves only there).</summary>
public TimeSpan Elapsed => Clock.Now - _start;
@@ -227,12 +227,15 @@ public sealed partial class ServerEndToEndTests
TimeSpan.FromSeconds(60),
"il motore di nuovo in funzione, in attesa del collegamento");
// «Ho finito» without having logged in: Febe says it does not find the session.
// «Usa il browser» on the rest page, not connected (issue #52): never the white page, the login page. (The test
// site sets its session on any visit, so «Ho finito» without a login is proved with the fake browser of
// BrowserStartPageTests.)
await connection.BeginUserDrivingAsync(openLogin: false, ct);
Assert.IsTrue(server.Browser.UserIsDriving);
var finish = await connection.FinishAsync(ct);
Assert.IsFalse(finish.Connected);
StringAssert.Contains(finish.Message, "non trova la sessione");
var opened = (await connection.GetStatusAsync(ct)).CurrentUrl;
Assert.IsNotNull(opened);
StringAssert.Contains(opened, "/benvenuto", "the login page of the test site");
await connection.CancelAsync(ct);
Assert.IsFalse(server.Browser.UserIsDriving);
// «Annulla» ends the driving and leaves the browser on the rest page.
@@ -62,6 +62,38 @@ public sealed class ConnectionApiTests
CollectionAssert.AreEqual(new[] { "begin:True", "finish", "cancel", "disconnect" }, connection.Calls);
}
[TestMethod]
public async Task LeavingThePageIsAnnullaInDockerAndOnlyTheEndOfTheHoldOnWindows()
{
// Docker: the remote view is the page, leaving it gives the browser back to rest.
var docker = new RecordingConnection();
await using (var server = await Part2.StartAsync(services: s => s.AddSingleton<IConnectionService>(docker)))
{
var (status, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel", new { pageLeft = true });
Assert.AreEqual(HttpStatusCode.NoContent, status);
var (showStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show");
Assert.AreEqual(HttpStatusCode.BadRequest, showStatus, "in Docker the browser is the Browser page");
}
CollectionAssert.AreEqual(new[] { "cancel" }, docker.Calls);
// Windows (issue #52): the window stays as it is; «Annulla» is still «Annulla»; «Apri il browser» says which page.
var windows = new RecordingConnection();
await using (var server = await Part2.StartAsync(services: s => s
.AddSingleton<IConnectionService>(windows)
.AddSingleton<Febe.Web.Native.IBrowserWindow>(new SeparateWindow())))
{
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel", new { pageLeft = true });
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel");
var (shown, message) = await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show");
Assert.AreEqual(HttpStatusCode.OK, shown);
StringAssert.Contains(message.Str("message"), "primo piano");
await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show", new { openLogin = true });
}
CollectionAssert.AreEqual(new[] { "release", "cancel", "show:False", "show:True" }, windows.Calls);
}
[TestMethod]
public async Task CommandsFromAnotherPageAreRefused()
{
@@ -99,4 +131,10 @@ public sealed class ConnectionApiTests
Assert.AreEqual(problem.Message, listed[0].Str("message"));
Assert.AreEqual(problem.Remedy, listed[0].Str("remedy"));
}
/// <summary>The browser as a window of its own, as on Windows.</summary>
private sealed class SeparateWindow : Febe.Web.Native.IBrowserWindow
{
public bool IsSeparateWindow => true;
}
}
@@ -109,6 +109,20 @@ internal sealed class RecordingConnection : IConnectionService
return Task.CompletedTask;
}
public Task ShowBrowserAsync(bool openLogin, CancellationToken ct)
{
Record("show:" + openLogin);
Status = Status with { UserIsDriving = true };
return Task.CompletedTask;
}
public Task ReleaseAsync(CancellationToken ct)
{
Record("release");
Status = Status with { UserIsDriving = false };
return Task.CompletedTask;
}
public Task DisconnectAsync(CancellationToken ct)
{
Record("disconnect");