diff --git a/docs/decisioni.md b/docs/decisioni.md index 015b575..fee79d0 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -350,3 +350,17 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-15 | Nella finestra, l'indirizzo di un post, di un reel, di una storia o di un'altra pagina di Instagram non diventa un nome (`p`, `reel`, `stories`…): stesso elenco di `UsernameParser.ReservedPaths` | Incollare `instagram.com/p/…` offriva «Aggiungi @p per nome utente» | | 2026-11-15 | Il mockup 04 è superato da #37: il riferimento è la schermata `docs/schermate/04-aggiungi-account.png` finché Alberto non ne fornisce uno nuovo (domanda Q9) | Non esiste il sorgente del mockup nel repository; la schermata segue gli elementi del foglio di stile (mockup 13) | | 2026-11-15 | Risposte di Alberto sulla ricerca dei profili (#37): il controllo del fuoco con `Runtime.evaluate` in sola lettura è ammesso e scritto in §6.1 (N1); i turni cadono a ogni ricetta e prima di ogni apertura di pagina, non dentro il visualizzatore né fra le raffiche di scorrimento (N2); l'ascolto di `Network.requestWillBeSent`, solo per l'indirizzo, è ammesso e scritto in §6.1; le foto dei profili seguiti non si scaricano per ora | Domande poste ad Alberto il 15 novembre 2026 alla fine del disegno; tutte con la risposta consigliata | +| 2026-11-16 | Vista remota: watchdog dei fotogrammi facoltativo (`ScreencastOptions.Watchdog`, default dell'host 2 s / 250 ms / 30 s), con riavvio stop+start dopo silenzio o `loadEventFired` senza fotogrammi e attesa che raddoppia fino a 30 s; immagine ferma con `Page.captureScreenshot` se il riavvio non porta nulla | Un ack perso o un cambio di renderer lasciavano la vista bianca per sempre; il raddoppio evita un riavvio ogni 2 s sulle pagine ferme. Nessun comando CDP nuovo | +| 2026-11-16 | Dopo un riavvio dei fotogrammi la vista aspetta il primo fotogramma per mezzo secondo (`ScreencastWatchdog.FirstFrameWait`, sull'orologio) prima di mandare l'immagine ferma, e la scarta se durante la cattura arriva un fotogramma vero; il silenzio si conta dall'avvio e l'attesa raddoppia prima dell'avvio | Chromium manda il primo fotogramma solo dopo aver risposto a `Page.startScreencast`: il controllo subito dopo la risposta mandava una cattura a quasi ogni riavvio, e l'immagine ferma poteva sostituire un fotogramma più recente | +| 2026-11-16 | Finestra «Browser di Febe» troppo grande per lo schermo: si restringe all'area di lavoro e la pagina si mostra con `ZoomFactor` uguale al rapporto (minimo 0,4) | La pagina tiene le stesse misure CSS (1280×900) per Instagram e per le ricette | +| 2026-11-16 | Fuori vista la finestra torna sempre a `Fit` 1 (pagina e `ZoomFactor` al 100%); il rapporto si ricalcola solo quando viene sullo schermo | Su uno schermo piccolo il rapporto restava per le sessioni del motore: le pagine vedevano un `devicePixelRatio` e media query diversi, un browser diverso da quello di sempre (regola 4) | +| 2026-11-16 | Su Windows lasciare una pagina di Febe non nasconde né mette a riposo la finestra del browser (cancel con `pageLeft` → `IConnectionService.ReleaseAsync`); resta finché Alberto non la chiude o preme «Ho finito» | La finestra spariva sotto gli occhi di Alberto quando cambiava pagina in Febe | +| 2026-11-16 | Finestra ridotta a icona: non vale più come «ho finito»; ha il pulsante nella barra delle applicazioni e dopo 2 minuti torna fuori vista | Ridurla la faceva sparire; S2 vieta di lasciarla ridotta a lungo | +| 2026-11-16 | Il pulsante della barra delle applicazioni cambia solo mentre la finestra è fuori vista (aggiunto prima di portarla sullo schermo, tolto dopo averla spostata); sullo schermo la finestra chiede di ridisegnarsi (`RedrawWindow` con i figli, niente che la pagina veda) | WPF cambia `ShowInTaskbar` di una finestra mostrata nascondendola e mostrandola di nuovo (visto con un aggancio a `WM_WINDOWPOSCHANGED`: `SWP_HIDEWINDOW`, poi `SWP_SHOWWINDOW`); S2 vieta di nasconderla sotto gli occhi di Alberto. `ITaskbarList` avrebbe evitato il nascondere, ma il suo comportamento con la finestra fuori vista non si può provare qui | +| 2026-11-16 | Ridotta a icona troppo a lungo, la finestra si ripristina coperta (`DWMWA_CLOAK`) e senza fuoco (`SW_SHOWNOACTIVATE`), si sposta fuori vista e solo allora si scopre | Windows ripristina una finestra dove stava sullo schermo: spostare prima la posizione di ripristino non basta, Windows la riporta su uno schermo (provato); senza copertura la finestra appariva e prendeva il fuoco per un attimo | +| 2026-11-16 | Dopo un riavvio del processo GPU la finestra riceve bordi di un pixel più bassi e poi quelli veri, e una richiesta di ridisegno | Gli stessi bordi di nuovo possono non essere un cambiamento per WebView2; il ridisegno senza cambio di misura non è provato con un arresto vero della GPU | +| 2026-11-16 | «Pagina iniziale» della finestra di Windows e della vista remota passa da `BrowserConnectionService.OpenStartPageAsync`: aspetta la fine della sessione del motore e il turno della pagina, e agisce solo mentre Alberto guida | Come l'apertura dal riposo: un passo di una sessione che finisce o della ricerca dei profili (#37) non deve trovarsi la pagina cambiata a metà | +| 2026-11-16 | I corpi facoltativi delle richieste (`begin`, `cancel`, `browser/show`) si leggono con `ApiHttp.OptionalBodyAsync`: senza lunghezza dichiarata, un byte dice se il corpo c'è | Un POST vuoto a pezzi (o in HTTP/2) arriva senza `Content-Length` e finiva in 400 «Richiesta non leggibile» | +| 2026-11-16 | La pagina Browser toglie `?accesso=1` dall'indirizzo appena l'ha usato | Ricaricare la pagina, o riaprire la scheda, riapriva la pagina di accesso anche da collegati | +| 2026-11-16 | `IBrowserWindow.ShowAsync` tolto: «Apri il browser» passa da `IConnectionService.ShowBrowserAsync(openLogin)` | Aprire la pagina iniziale richiede il permesso di guida e il turno della pagina, che tiene il servizio di collegamento | +| 2026-11-16 | Con `--accesso-di-prova` il primo controllo della sessione all'avvio non segnala nulla (`RefreshAsync` con `mayReport: false`) | La sessione mancante è quella che l'accesso automatico sta per aprire, non una disconnessione | diff --git a/docs/guida/Installazione-Windows.md b/docs/guida/Installazione-Windows.md index ac416d8..94e372b 100644 --- a/docs/guida/Installazione-Windows.md +++ b/docs/guida/Installazione-Windows.md @@ -23,7 +23,8 @@ - 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 + rimpicciolita, sempre della stessa misura per Instagram; fuori vista, quando la usa il motore, la pagina torna al + 100%. 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 diff --git a/docs/guida/Primo-collegamento.md b/docs/guida/Primo-collegamento.md index 1239c05..b945a98 100644 --- a/docs/guida/Primo-collegamento.md +++ b/docs/guida/Primo-collegamento.md @@ -70,7 +70,8 @@ basso). Serve per controllare qualcosa a mano. Mentre lo usi il motore resta fer 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. +ci torna quando vuoi; se la barra dice «Il browser è a riposo su una pagina vuota», premilo. Se Febe sta finendo un +lavoro nel browser, «Pagina iniziale» aspetta che finisca: può volerci qualche secondo. Se lasci la pagina Browser, o la pagina Collegamento mentre accedi, senza premere «Ho finito» (un'altra pagina, la scheda chiusa o ricaricata): diff --git a/src/Febe.App/BrowserConnectionService.cs b/src/Febe.App/BrowserConnectionService.cs index 73000ef..2966fc7 100644 --- a/src/Febe.App/BrowserConnectionService.cs +++ b/src/Febe.App/BrowserConnectionService.cs @@ -206,6 +206,42 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } } + /// + /// «Pagina iniziale» of the window's bar and of the remote view (issue #52): Alberto's own navigation (rule 7) to + /// , as when he takes the browser from the rest page — after the engine's session ended and + /// with the page's turn, so that no step of a session or of the profile search has its page swapped under it. Only + /// while he is at the browser: otherwise the page is the engine's and nothing happens. + /// + public async Task OpenStartPageAsync(CancellationToken ct) + { + if (!_browser.IsAvailable) + { + return; + } + + await _commands.WaitAsync(ct).ConfigureAwait(false); + try + { + if (!_browser.UserIsDriving) + { + return; + } + + await WaitForSessionEndAsync(ct).ConfigureAwait(false); + using var turn = await TakePageAsync(ct).ConfigureAwait(false); + var target = StartPageUrl; + var what = target == _loginUrl ? "pagina di accesso" : "pagina iniziale del sito"; + var result = await _browser.Cdp.NavigateAsync(target, ct).ConfigureAwait(false); + _log.Info("collegamento", result.Succeeded + ? $"«Pagina iniziale»: {what} aperta." + : $"«Pagina iniziale»: {what} non aperta (errore di rete del browser)."); + } + finally + { + _commands.Release(); + } + } + public async Task ReleaseAsync(CancellationToken ct) { await _commands.WaitAsync(ct).ConfigureAwait(false); diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs index d82a16b..e0a6266 100644 --- a/src/Febe.App/FebeApp.cs +++ b/src/Febe.App/FebeApp.cs @@ -245,8 +245,8 @@ public sealed class FebeApp : IAsyncDisposable } // Browser, connection, engine. The engine loop starts only once the browser is up. - // The start page (issue #52) is the connection's, which exists only after the browser: read when asked. - var context = new FebePlatformContext(o, data, Database, Clock, Log, Tracker, () => Connection?.StartPageUrl ?? o.LoginUrl); + // «Pagina iniziale» (issue #52) is the connection's, which exists only after the browser: looked up when pressed. + var context = new FebePlatformContext(o, data, Database, Clock, Log, Tracker, ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask); var browser = await _platform.CreateBrowserAsync(context, ct).ConfigureAwait(false); Browser = browser; var connection = new BrowserConnectionService(browser, Database, Tracker, Clock, Log, o.LoginUrl, HomeUrl(o.Site.BaseUrl), o.Site.SessionCookie); diff --git a/src/Febe.App/IFebePlatform.cs b/src/Febe.App/IFebePlatform.cs index 6f5e947..ad52f06 100644 --- a/src/Febe.App/IFebePlatform.cs +++ b/src/Febe.App/IFebePlatform.cs @@ -55,15 +55,12 @@ public interface IFebePlatform /// The clock of the engine. /// The log. /// When Alberto last used the browser: the desktop window marks it when he uses and closes it. -/// -/// Where «Pagina iniziale» of the browser window goes (issue #52): the site's home when connected, the login page -/// otherwise. Null: the login page. +/// +/// What «Pagina iniziale» of the browser window does (issue #52): the connection opens the site's home when connected, +/// the login page otherwise, once the engine's session ended and with the page's turn +/// (BrowserConnectionService.OpenStartPageAsync). Null: the button does nothing. /// -public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func? StartPage = null) -{ - /// The start page now (, or the login page). - public string CurrentStartPage() => StartPage?.Invoke() ?? Options.LoginUrl; -} +public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func? OpenStartPage = null); /// Options of the shared composition, filled by each shell from its own configuration. public sealed record FebeAppOptions diff --git a/src/Febe.Browser/RemoteView/ScreencastSession.cs b/src/Febe.Browser/RemoteView/ScreencastSession.cs index 31604f4..bc389e1 100644 --- a/src/Febe.Browser/RemoteView/ScreencastSession.cs +++ b/src/Febe.Browser/RemoteView/ScreencastSession.cs @@ -22,7 +22,8 @@ public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, in /// lost acknowledgement stops the frames for good, and a change of renderer (another site, the rest page, a crash) may /// leave the screencast on the old one. After without frames — measured from the start, from the /// last frame or from the last change of document of the main frame — the screencast is stopped and started again (a -/// new screencast session), and one still picture of the page is sent when the start brings no frame. Each restart +/// new screencast session), and one still picture of the page is sent when no frame came within +/// of the start (Chromium sends the first frame only after answering the start). Each restart /// doubles the wait, up to : 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 ( after a /// restart) or a new document bring the wait back to . @@ -38,6 +39,9 @@ public sealed record ScreencastWatchdog(TimeSpan Silence, TimeSpan Tick, TimeSpa /// public const int FlowingFrames = 3; + /// How long a restart waits for its first frame before it sends a still picture instead. + public static readonly TimeSpan FirstFrameWait = TimeSpan.FromMilliseconds(500); + /// About two seconds, looked at four times a second, at most half a minute between restarts. public static ScreencastWatchdog Default { get; } = new(TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(250), TimeSpan.FromSeconds(30)); } @@ -118,6 +122,7 @@ public sealed class ScreencastSession : IAsyncDisposable private bool _restartWanted; private bool _silent; private DateTimeOffset _silentSince; + private TaskCompletionSource? _nextFrame; /// The page session. /// Where starts, restarts and silences are noted (never parameters or frames). @@ -338,9 +343,11 @@ public sealed class ScreencastSession : IAsyncDisposable private void OnReconnected(object? sender, EventArgs e) => _ = Task.Run(async () => { - var ct = _lifetime.Token; + // Read inside the try: a browser restart that races the dispose finds the source disposed. + var ct = CancellationToken.None; try { + ct = _lifetime.Token; await _starts.WaitAsync(ct).ConfigureAwait(false); try { @@ -412,10 +419,16 @@ public sealed class ScreencastSession : IAsyncDisposable } } - /// Stop and start again (a new screencast session), then one still picture when no frame came. + /// + /// Stop and start again (a new screencast session), then one still picture when no frame came within + /// . The silence counts from the start; the wait for the next restart + /// doubles here, before the start, so that frames flowing meanwhile bring it back to the short one. + /// private async Task RestartAsync(ScreencastWatchdog watchdog, TimeSpan silence, bool afterLoad, CancellationToken ct) { await _starts.WaitAsync(ct).ConfigureAwait(false); + var started = false; + TaskCompletionSource? nextFrame = null; try { bool first; @@ -427,6 +440,11 @@ public sealed class ScreencastSession : IAsyncDisposable _silent = true; _silentSince = _clock.Now - silence; } + + _restartWanted = false; + _framesSinceRestart = 0; + var longer = _silenceLimit + _silenceLimit; + _silenceLimit = longer < watchdog.LongestSilence ? longer : watchdog.LongestSilence; } var seconds = Math.Max(1, (int)Math.Round(silence.TotalSeconds)).ToString(CultureInfo.InvariantCulture); @@ -443,7 +461,6 @@ public sealed class ScreencastSession : IAsyncDisposable _log.Debug(line); } - var before = FramesReceived; try { await _cdp.SendAsync("Page.stopScreencast", null, ct).ConfigureAwait(false); @@ -453,9 +470,22 @@ public sealed class ScreencastSession : IAsyncDisposable // Nothing was running on the browser side: the start below is what matters. } + // Ready before the start: its first frame may come as soon as Chromium has answered. + nextFrame = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + lock (_watch) + { + _nextFrame = nextFrame; + } + await SendStartAsync(ct).ConfigureAwait(false); + lock (_watch) + { + _watchFrom = _clock.Now; + } + + started = true; Interlocked.Increment(ref _restarts); - if (FramesReceived == before) + if (!await FrameWithinAsync(nextFrame.Task, ScreencastWatchdog.FirstFrameWait, ct).ConfigureAwait(false)) { await SendStillAsync(ct).ConfigureAwait(false); } @@ -469,29 +499,65 @@ public sealed class ScreencastSession : IAsyncDisposable { lock (_watch) { - _watchFrom = _clock.Now; - _restartWanted = false; - _framesSinceRestart = 0; - var longer = _silenceLimit + _silenceLimit; - _silenceLimit = longer < watchdog.LongestSilence ? longer : watchdog.LongestSilence; + if (!started) + { + _watchFrom = _clock.Now; // a failed restart: the next one after a whole silence, not at the next look + } + + if (ReferenceEquals(_nextFrame, nextFrame)) + { + _nextFrame = null; + } } _starts.Release(); } } + /// True when completes within (on the clock). + private async Task FrameWithinAsync(Task frame, TimeSpan wait, CancellationToken ct) + { + if (frame.IsCompleted) + { + return true; + } + + using var stopWaiting = CancellationTokenSource.CreateLinkedTokenSource(ct); + var delay = _clock.Delay(wait, stopWaiting.Token); + await Task.WhenAny(frame, delay).ConfigureAwait(false); + + // Asked of the frame itself, not of which task woke the wait: both may be done by now, and a frame is a frame. + if (frame.IsCompleted) + { + // The pause ends here (a clock that moves only when asked keeps no sleeper behind). + await stopWaiting.CancelAsync().ConfigureAwait(false); + return true; + } + + await delay.ConfigureAwait(false); // cancelled with ct: the restart ends there + return false; + } + /// /// One picture of the page as it is (Page.captureScreenshot, already allowed for the preview): a page that /// does not repaint shows something, and the pointer can be placed on it. /// private async Task SendStillAsync(CancellationToken ct) { + var before = FramesReceived; var jpeg = await PagePreview.CaptureAsync(_cdp, Math.Clamp((_options ?? new ScreencastOptions()).Quality, 0, 100), ct).ConfigureAwait(false); if (jpeg.Length == 0 || Volatile.Read(ref _stopped) == 1) { return; } + if (FramesReceived != before) + { + // A real frame came during the capture: it is newer and carries the page's scroll and zoom. + _log.Debug("Vista remota: immagine ferma scartata, è arrivato un fotogramma."); + return; + } + var last = LastFrame; double width; double height; @@ -577,6 +643,8 @@ public sealed class ScreencastSession : IAsyncDisposable { _lastFrameAt = _clock.Now; _restartWanted = false; + _nextFrame?.TrySetResult(); + _nextFrame = null; if (++_framesSinceRestart >= ScreencastWatchdog.FlowingFrames && _options?.Watchdog is { } watchdog) { // The page moves: frames flow, and a silence from now on is worth a quick restart again. diff --git a/src/Febe.Desktop/Browser/BrowserWindow.cs b/src/Febe.Desktop/Browser/BrowserWindow.cs index 1387333..c3d1a5e 100644 --- a/src/Febe.Desktop/Browser/BrowserWindow.cs +++ b/src/Febe.Desktop/Browser/BrowserWindow.cs @@ -4,6 +4,7 @@ using System.Windows.Controls; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Threading; +using Febe.Desktop.Native; namespace Febe.Desktop.Browser; @@ -17,10 +18,16 @@ namespace Febe.Desktop.Browser; /// /// /// 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 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 (), always with the -/// same size in CSS pixels. While the page is the empty rest page the bar says so. +/// keeps Alberto at the wheel, but never for long (S2): after it is put out of view as if +/// he had closed it, restored there without coming on screen. When the page and its bar do not fit in the work area of +/// the screen (a small screen, a large text scale) the window shrinks to fit and the page is shown zoomed out +/// (), always with the same size in CSS pixels; out of view the page is at 100% again, so that the +/// engine's pages always see the same browser. While the page is the empty rest page the bar says so. +/// +/// +/// WPF changes the taskbar button of a shown window by hiding it and showing it again (seen in WM_WINDOWPOSCHANGED: +/// SWP_HIDEWINDOW, then SWP_SHOWWINDOW). The button is therefore changed only while the window is out of view: before it +/// comes on screen, after it left. /// /// internal sealed class BrowserWindow : Window @@ -183,6 +190,8 @@ internal sealed class BrowserWindow : Window { var area = SystemParameters.WorkArea; FitTo(area); + + // Still out of view: the hide and show with which WPF adds the button happen where nobody sees them. ShowInTaskbar = true; var width = ActualWidth > 0 ? ActualWidth : PageWidth * Fit; var height = ActualHeight > 0 ? ActualHeight : (PageHeight * Fit) + BarHeight; @@ -192,19 +201,42 @@ internal sealed class BrowserWindow : Window /// /// Parks the window just right of every screen: open, «visible» for Windows and for WebView2, out of Alberto's view - /// (S2), without its taskbar button. Never Hide(), never left minimised. + /// (S2), without its taskbar button and with the page at 100% ( 1). Never Hide(), never + /// left minimised: a minimised window is restored without taking the focus and cloaked meanwhile, because Windows + /// restores it where it was on screen (a restore position off every screen is moved back onto one). /// public void MoveOffScreen() { _minimized.Stop(); - if (WindowState == WindowState.Minimized) + var restoring = WindowState == WindowState.Minimized; + var cloaked = restoring && Cloak(true); + try { - WindowState = WindowState.Normal; + if (restoring) + { + Win32.ShowWindow(Handle, Win32.SwShowNoActivate); + if (WindowState == WindowState.Minimized) + { + WindowState = WindowState.Normal; + } + } + + Left = SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth + 64; + Top = SystemParameters.VirtualScreenTop; + + // Out of view first: the hide and show with which WPF removes the button happen where nobody sees them. + ShowInTaskbar = false; + } + finally + { + if (cloaked) + { + Cloak(false); + } } - ShowInTaskbar = false; - Left = SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth + 64; - Top = SystemParameters.VirtualScreenTop; + // The engine's pages see the browser as it is, at 100%, whatever the size of Alberto's screen (rule 4). + SetFit(1); } /// Lets the window really close (Febe is stopping). @@ -250,7 +282,7 @@ internal sealed class BrowserWindow : Window _minimized.Stop(); if (WindowState == WindowState.Minimized) { - WindowState = WindowState.Normal; + // Restored out of view by the owner (MoveOffScreen), never first on screen where it was. DoneRequested?.Invoke(this, EventArgs.Empty); } } @@ -260,7 +292,11 @@ internal sealed class BrowserWindow : Window // The frame of the window (title bar and borders) around the page and its bar. var frame = SystemParameters.WindowNonClientFrameThickness; var resize = SystemParameters.WindowResizeBorderThickness; - var fit = FitFor(area.Width, area.Height, PageWidth, PageHeight, frame.Left + frame.Right + resize.Left + resize.Right, frame.Top + frame.Bottom + resize.Top + resize.Bottom); + SetFit(FitFor(area.Width, area.Height, PageWidth, PageHeight, frame.Left + frame.Right + resize.Left + resize.Right, frame.Top + frame.Bottom + resize.Top + resize.Bottom)); + } + + private void SetFit(double fit) + { if (Math.Abs(fit - Fit) < 0.001) { return; @@ -273,6 +309,13 @@ internal sealed class BrowserWindow : Window PageAreaChanged?.Invoke(this, EventArgs.Empty); } + /// Cloaks or uncloaks the window (DWM); false when DWM refused. + private bool Cloak(bool on) + { + var value = on ? 1 : 0; + return Win32.DwmSetWindowAttribute(Handle, Win32.DwmCloak, ref value, sizeof(int)) == 0; + } + private static Button BarButton(string text, string tip) => new() { Content = text, diff --git a/src/Febe.Desktop/Browser/WebView2Browser.cs b/src/Febe.Desktop/Browser/WebView2Browser.cs index a80f3ab..b8fb7d9 100644 --- a/src/Febe.Desktop/Browser/WebView2Browser.cs +++ b/src/Febe.Desktop/Browser/WebView2Browser.cs @@ -52,7 +52,7 @@ internal sealed class WebView2Browser : IFebeBrowser _options = new BrowserOptions(ProfileDirectory, settings.Width, settings.Height); Host = new WebView2Host( ui, - new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.CurrentStartPage), + new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage), context.Log); Host.BrowserProcessFailed += (_, _) => RequestRestart(null); } diff --git a/src/Febe.Desktop/Browser/WebView2Host.cs b/src/Febe.Desktop/Browser/WebView2Host.cs index c3692cc..1980008 100644 --- a/src/Febe.Desktop/Browser/WebView2Host.cs +++ b/src/Febe.Desktop/Browser/WebView2Host.cs @@ -9,6 +9,7 @@ using Febe.Browser.Hosting; using Febe.Browser.WebView2; using Febe.Core.Abstractions; using Febe.Desktop.Core; +using Febe.Desktop.Native; using Microsoft.Web.WebView2.Core; namespace Febe.Desktop.Browser; @@ -18,8 +19,11 @@ namespace Febe.Desktop.Browser; /// The switches of S2 (). /// The icon of the window. /// Called when Alberto uses the browser and when he is done with it («Riprendi»). -/// Where «Pagina iniziale» goes: the site's home when connected, the login page otherwise (issue #52). -internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func? StartPage = null); +/// +/// What «Pagina iniziale» does (issue #52): the connection opens the site's home when connected, the login page otherwise, +/// once the engine's session ended and with the page's turn. Null: the button does nothing. +/// +internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func? OpenStartPage = null); /// What the host does when a process of WebView2 fails (issue #52). internal enum ProcessFailureResponse @@ -33,7 +37,7 @@ internal enum ProcessFailureResponse /// The page crashed (or hangs while nobody looks): back to the rest page (spec §6.1). Rest, - /// The GPU process restarted: the bounds are given again, or the window may stay blank or black. + /// The GPU process restarted: the page is resized by a pixel and back, or the window may stay blank or black. Redraw, } @@ -179,8 +183,10 @@ internal sealed class WebView2Host : IBrowserHost // The lease first: once the window is on screen the engine must be still, whatever happens to the focus. TakeLease(); - // On screen, perhaps shrunk to fit it: WebView2 gets its bounds again and learns where its window is now. + // On screen, perhaps shrunk to fit it: WebView2 gets its bounds again and learns where its window is now, and paints + // again (WPF hid and showed the window, out of view, to give it its taskbar button). UpdateBounds(); + Repaint(); try { _controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic); @@ -345,7 +351,7 @@ internal sealed class WebView2Host : IBrowserHost window.DoneRequested += (_, _) => Done(); window.BackRequested += (_, _) => UserNavigation(core => core.GoBack(), core => core.CanGoBack); window.ReloadRequested += (_, _) => UserNavigation(core => core.Reload(), _ => true); - window.HomeRequested += (_, _) => UserNavigation(core => core.Navigate(_settings.StartPage!()), _ => _settings.StartPage is not null); + window.HomeRequested += (_, _) => OpenStartPage(); window.DpiChanged += (_, _) => UpdateBounds(); window.PageAreaChanged += (_, _) => UpdateBounds(); @@ -508,9 +514,10 @@ internal sealed class WebView2Host : IBrowserHost break; case ProcessFailureResponse.Redraw: - // A windowed WebView can stay blank or black after the GPU process restarted until its bounds change: - // they are given again (never IsVisible = false, S2), once this handler has returned. - _ = _ui.InvokeAsync(UpdateBounds, DispatcherPriority.Background); + // A windowed WebView can stay blank or black after the GPU process restarted until its size changes: the + // same bounds again may be no change at all, so one pixel less and then the real ones (never + // IsVisible = false, S2), once this handler has returned. + _ = _ui.InvokeAsync(Redraw, DispatcherPriority.Background); break; default: if (kind == CoreWebView2ProcessFailedKind.RenderProcessUnresponsive) @@ -576,6 +583,73 @@ internal sealed class WebView2Host : IBrowserHost } } + /// + /// «Pagina iniziale»: Alberto's own navigation (rule 7), done by the connection, which first waits for the engine's + /// session to end and takes the page's turn (issue #52). + /// + private void OpenStartPage() + { + if (_settings.OpenStartPage is not { } open || _core is null) + { + return; + } + + TakeLease(); + _ = OpenStartPageQuietlyAsync(open); + } + + private async Task OpenStartPageQuietlyAsync(Func open) + { + try + { + await open(CancellationToken.None).ConfigureAwait(true); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + _log.Warn("browser", $"«Pagina iniziale» non aperta ({ex.GetType().Name})."); + } + } + + /// After a GPU restart: a real change of size (one pixel less), then the real bounds and a repaint. + private void Redraw() + { + if (_controller is not { } controller || _window is not { } window) + { + return; + } + + try + { + var bounds = window.PageBounds; + if (bounds.Height > 1) + { + controller.Bounds = bounds with { Height = bounds.Height - 1 }; + } + } + catch (Exception ex) when (ex is COMException or InvalidOperationException) + { + // The browser process is gone: the next start sizes the new WebView. + return; + } + + _ = _ui.InvokeAsync( + () => + { + UpdateBounds(); + Repaint(); + }, + DispatcherPriority.Background); + } + + /// Asks the window and WebView2's child windows to paint again; nothing the page can see changes. + private void Repaint() + { + if (_window is { } window) + { + Win32.RedrawWindow(window.Handle, IntPtr.Zero, IntPtr.Zero, Win32.RdwInvalidate | Win32.RdwAllChildren | Win32.RdwUpdateNow); + } + } + private void UpdateBounds() { if (_controller is not { } controller || _window is not { } window) diff --git a/src/Febe.Desktop/Native/Win32.cs b/src/Febe.Desktop/Native/Win32.cs index 528208d..e08b11c 100644 --- a/src/Febe.Desktop/Native/Win32.cs +++ b/src/Febe.Desktop/Native/Win32.cs @@ -66,6 +66,21 @@ internal static class Win32 [return: MarshalAs(UnmanagedType.Bool)] public static extern bool IsIconic(IntPtr window); + public const uint RdwInvalidate = 0x0001; + public const uint RdwAllChildren = 0x0080; + public const uint RdwUpdateNow = 0x0100; + + /// DWMWA_CLOAK: the window stays shown for Windows but DWM does not put it on screen. + public const int DwmCloak = 13; + + /// Asks a window and its children (WebView2's own) to paint again, without changing anything else. + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool RedrawWindow(IntPtr window, IntPtr updateRect, IntPtr updateRegion, uint flags); + + [DllImport("dwmapi.dll")] + public static extern int DwmSetWindowAttribute(IntPtr window, int attribute, ref int value, int size); + [DllImport("user32.dll")] public static extern IntPtr SetCursor(IntPtr cursor); diff --git a/src/Febe.Server/BrowserRemoteView.cs b/src/Febe.Server/BrowserRemoteView.cs index 9a9b3b2..5aa4203 100644 --- a/src/Febe.Server/BrowserRemoteView.cs +++ b/src/Febe.Server/BrowserRemoteView.cs @@ -25,7 +25,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost private readonly IClock _clock; private readonly IClock _browserClock; private readonly FebeLog _log; - private readonly Func? _startPage; + private readonly Func? _openStartPage; private readonly Lock _gate = new(); private readonly SemaphoreSlim _opening = new(1, 1); private BrowserRemoteViewConnection? _current; @@ -39,15 +39,18 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost /// Time for the waits on the browser itself and for the frames' watchdog; null: the wall clock, because the browser /// commits a navigation and paints in real time whatever clock the engine runs on (the tests compress it). /// - /// Where «Pagina iniziale» goes (issue #52); null: the button does nothing. - public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func? startPage = null) + /// + /// What «Pagina iniziale» does (issue #52): the connection opens the start page once the engine's session ended and + /// with the page's turn; null: the button does nothing. + /// + public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func? openStartPage = null) { _browser = browser ?? throw new ArgumentNullException(nameof(browser)); _tracker = tracker ?? throw new ArgumentNullException(nameof(tracker)); _clock = clock ?? throw new ArgumentNullException(nameof(clock)); _log = log ?? throw new ArgumentNullException(nameof(log)); _browserClock = browserClock ?? new SystemClock(clock.LocalZone); - _startPage = startPage; + _openStartPage = openStartPage; } /// @@ -93,7 +96,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false); } - var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock, _log.ForBrowser("vista"), _startPage, Watchdog); + var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock, _log.ForBrowser("vista"), _openStartPage, Watchdog); try { await connection.StartAsync(_browser.WindowWidth, _browser.WindowHeight, ct).ConfigureAwait(false); @@ -177,7 +180,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection private readonly BrowserUseTracker _tracker; private readonly IClock _clock; private readonly RemoteViewSession _session; - private readonly Func? _startPage; + private readonly Func? _openStartPage; private readonly ScreencastWatchdog? _watchdog; private readonly Lock _gate = new(); private readonly Queue _meta = new(); @@ -196,13 +199,13 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection private int _disposed; private bool _used; - public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock, IBrowserLog log, Func? startPage, ScreencastWatchdog? watchdog) + public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock, IBrowserLog log, Func? openStartPage, ScreencastWatchdog? watchdog) { _owner = owner; _browser = browser; _tracker = tracker; _clock = clock; - _startPage = startPage; + _openStartPage = openStartPage; _watchdog = watchdog; // A real log (issue #52): the starts, restarts and silences of the frames reach the registro. @@ -316,14 +319,22 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection public async Task NavigateAsync(RemoteViewNavigation action, CancellationToken ct) { MarkUsed(); + if (action == RemoteViewNavigation.Home) + { + // Alberto's own navigation (rule 7), done by the connection: like the start page opened from the rest page, + // it waits for the engine's session to end and takes the page's turn first. + if (_openStartPage is { } open) + { + await open(ct).ConfigureAwait(false); + } + + return; + } + string? target; lock (_gate) { - if (action == RemoteViewNavigation.Home) - { - target = _startPage?.Invoke(); - } - else if (action == RemoteViewNavigation.Back) + if (action == RemoteViewNavigation.Back) { // Back never lands on the empty rest page (issue #52): it skips it, and with nothing before it stays. var previous = _history.Count - 2; diff --git a/src/Febe.Server/DockerPlatform.cs b/src/Febe.Server/DockerPlatform.cs index cbe3919..5f4a81f 100644 --- a/src/Febe.Server/DockerPlatform.cs +++ b/src/Febe.Server/DockerPlatform.cs @@ -53,7 +53,7 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(app); - RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log, startPage: () => app.Connection?.StartPageUrl ?? app.Options.LoginUrl); + RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log, openStartPage: ct => app.Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask); services.AddSingleton(RemoteView); } diff --git a/src/Febe.Web/Api/ApiErrorMiddleware.cs b/src/Febe.Web/Api/ApiErrorMiddleware.cs index d31db34..f0e01fe 100644 --- a/src/Febe.Web/Api/ApiErrorMiddleware.cs +++ b/src/Febe.Web/Api/ApiErrorMiddleware.cs @@ -2,6 +2,7 @@ using System.Text.Json; using System.Text.Json.Serialization.Metadata; using Febe.Core.Storage; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Logging; namespace Febe.Web.Api; @@ -86,6 +87,40 @@ public static class ApiHttp } } + /// + /// Reads an optional JSON body: when there is none — no length and nothing to read, as an + /// empty POST may come chunked or over HTTP/2 — and the body otherwise (a 400 when it is not readable). + /// + public static async Task OptionalBodyAsync(HttpContext context, JsonTypeInfo type, T empty) + { + ArgumentNullException.ThrowIfNull(context); + var request = context.Request; + if (request.ContentLength == 0) + { + return empty; + } + + if (request.ContentLength is null) + { + if (context.Features.Get() is { CanHaveBody: false }) + { + return empty; + } + + // A body without a declared length may still be empty: one byte tells, then it is read from the start. + request.EnableBuffering(); + var probe = new byte[1]; + if (await request.Body.ReadAsync(probe, context.RequestAborted).ConfigureAwait(false) == 0) + { + return empty; + } + + request.Body.Position = 0; + } + + return await BodyAsync(context, type).ConfigureAwait(false); + } + /// A JSON answer with its source-generated metadata. public static IResult Json(T value, JsonTypeInfo type, int status = StatusCodes.Status200OK) => Results.Json(value, type, statusCode: status); diff --git a/src/Febe.Web/Api/ConnectionApi.cs b/src/Febe.Web/Api/ConnectionApi.cs index 06e534a..23f60e7 100644 --- a/src/Febe.Web/Api/ConnectionApi.cs +++ b/src/Febe.Web/Api/ConnectionApi.cs @@ -22,9 +22,7 @@ public static class ConnectionApi endpoints.MapPost("/api/connection/begin", async (HttpContext context, IConnectionService connection, CancellationToken ct) => { - var body = context.Request.ContentLength is null or > 0 - ? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest).ConfigureAwait(false) - : new BeginDrivingRequest(false); + var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest, new BeginDrivingRequest(false)).ConfigureAwait(false); await connection.BeginUserDrivingAsync(body.OpenLogin, ct).ConfigureAwait(false); return Results.NoContent(); }); @@ -41,9 +39,7 @@ public static class ConnectionApi // own: leaving a page of Febe leaves it as it is, on screen until Alberto closes it (issue #52). endpoints.MapPost("/api/connection/cancel", async (HttpContext context, IConnectionService connection, IBrowserWindow window, CancellationToken ct) => { - var body = context.Request.ContentLength is null or > 0 - ? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.CancelDrivingRequest).ConfigureAwait(false) - : new CancelDrivingRequest(false); + var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.CancelDrivingRequest, new CancelDrivingRequest(false)).ConfigureAwait(false); if (body.PageLeft && window.IsSeparateWindow) { await connection.ReleaseAsync(ct).ConfigureAwait(false); diff --git a/src/Febe.Web/Api/EngineApi.cs b/src/Febe.Web/Api/EngineApi.cs index fbb73cf..465ad23 100644 --- a/src/Febe.Web/Api/EngineApi.cs +++ b/src/Febe.Web/Api/EngineApi.cs @@ -65,9 +65,7 @@ public static class EngineApi throw new BadRequestException("Qui il browser di Febe si usa dalla pagina Browser."); } - var body = context.Request.ContentLength is null or > 0 - ? await ApiHttp.BodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest).ConfigureAwait(false) - : new BeginDrivingRequest(false); + var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest, new BeginDrivingRequest(false)).ConfigureAwait(false); await connection.ShowBrowserAsync(body.OpenLogin, ct).ConfigureAwait(false); tracker.MarkUsed(clock.Now); return ApiHttp.Message("Il browser di Febe è in primo piano."); diff --git a/src/Febe.Web/Connection/PROTOCOLLO.md b/src/Febe.Web/Connection/PROTOCOLLO.md index 95d9a45..911d85a 100644 --- a/src/Febe.Web/Connection/PROTOCOLLO.md +++ b/src/Febe.Web/Connection/PROTOCOLLO.md @@ -15,8 +15,10 @@ Lo usano due parti scritte in parallelo: non cambiarlo senza aggiornare entrambe | `POST /api/browser/show` | corpo facoltativo `{ openLogin: bool }` → `{ message }`. Solo Windows: porta in primo piano la finestra «Browser di Febe»; come `begin` apre la pagina di accesso (`openLogin`) o, se era a riposo, la pagina iniziale | **Pagina iniziale** (issue #52): la home del sito se Febe è collegato e non scollegato da Instagram, altrimenti la -pagina di accesso. Aprirla dal riposo è un'azione di Alberto, sotto il suo permesso di guida (`UserIsDriving`), non -del motore: Febe aspetta che la sessione del motore finisca, prende la pagina e solo dopo naviga. La striscia rossa +pagina di accesso. Aprirla, dal riposo o con il pulsante «Pagina iniziale» (barra della finestra di Windows, vista +remota), è un'azione di Alberto, sotto il suo permesso di guida (`UserIsDriving`), non del motore: Febe aspetta che la +sessione del motore finisca, prende il turno della pagina (un passo della ricerca dei profili finisce prima) e solo +dopo naviga. «Indietro», «Ricarica» e i clic nella pagina invece agiscono subito, come nel browser. La striscia rossa di una disconnessione apre il browser con `openLogin: true` (in Docker la pagina Browser con `?accesso=1`). In modalità dimostrativa la scena `scollegato` dà `notConnected`, la scena `fermo` dà `verificationRequired`. @@ -42,8 +44,9 @@ Dal server al browser di Alberto: I fotogrammi non devono fermarsi in silenzio (issue #52). Il server li riavvia (`Page.stopScreencast` e `Page.startScreencast`) quando una pagina nuova si è caricata (`Page.loadEventFired`) senza che ne sia arrivato uno, e quando non ne arrivano da circa 2 s; l'attesa raddoppia a ogni riavvio senza esito, fino a 30 s, e torna a -2 s quando i fotogrammi scorrono di nuovo o cambia la pagina. Se dopo un riavvio non arriva nulla, manda un'immagine -ferma della pagina (`Page.captureScreenshot`) come messaggio binario come gli altri. Avvii, riavvii e silenzi vanno +2 s quando i fotogrammi scorrono di nuovo o cambia la pagina. Se entro mezzo secondo dal riavvio non arriva nessun +fotogramma, manda un'immagine ferma della pagina (`Page.captureScreenshot`) come messaggio binario come gli altri; +se durante la cattura arriva un fotogramma vero, l'immagine ferma non si manda. Avvii, riavvii e silenzi vanno nel registro (livello Info, categoria `vista`), senza indirizzi né contenuti. L'interfaccia, se dopo 8 s dall'apertura non ha ancora un fotogramma, mostra «Nessuna immagine dal browser» con «Riprova», che riapre la vista. Sul riposo (`about:blank`) la barra dice «Il browser è a riposo su una pagina vuota» invece dell'indirizzo. diff --git a/src/Febe.Web/wwwroot/js/pages/browser.js b/src/Febe.Web/wwwroot/js/pages/browser.js index 41cf131..059f52f 100644 --- a/src/Febe.Web/wwwroot/js/pages/browser.js +++ b/src/Febe.Web/wwwroot/js/pages/browser.js @@ -3,12 +3,12 @@ // engine is still; «Ho finito» lets «Riprendi» become active after a verification. Leaving the page without «Ho finito» // (another page, a reload, closing the tab) gives the browser back, like «Annulla» (on Windows the window stays as it // is until Alberto closes it). A browser at rest opens its start page; «?accesso=1» (the red strip of a disconnection) -// opens the login page. +// opens the login page, once: the parameter leaves the address straight away. import { api } from '../core/api.js'; import { caps } from '../core/context.js'; import { h, icon, fill } from '../core/dom.js'; -import { navigate } from '../core/shell.js'; +import { navigate, setQuery } from '../core/shell.js'; import { t } from '../core/text.js'; import { toast } from '../core/ui.js'; import { drivingLease, finishDriving, passwordNote, windowPanel } from './connection.js'; @@ -28,6 +28,8 @@ export default { const lease = drivingLease(page); const login = new URLSearchParams(location.search).get('accesso') === '1'; lease.begin(login); + // Asked once: a reload of the page, or the tab restored later, must not open the login page again. + if (login) setQuery({ accesso: null }); const message = h('div', { 'aria-live': 'polite' }); const done = async () => { const result = await finishDriving(); diff --git a/tests/Febe.Tests.Windows/BrowserWindowTests.cs b/tests/Febe.Tests.Windows/BrowserWindowTests.cs index 4cfada2..6c63d20 100644 --- a/tests/Febe.Tests.Windows/BrowserWindowTests.cs +++ b/tests/Febe.Tests.Windows/BrowserWindowTests.cs @@ -1,6 +1,7 @@ using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; +using System.Windows.Interop; using Febe.Browser.Cdp; using Febe.Desktop.Browser; using Febe.SitoDiProva; @@ -44,8 +45,9 @@ public sealed class BrowserWindowDecisionTests /// /// 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. +/// the page is the empty rest page, «Pagina iniziale» opens the start page, the window is never hidden while on screen +/// (WPF hides it to change its taskbar button) and out of view the page is at 100%, and a minimised window keeps Alberto +/// at the wheel until it has been minimised too long. The window comes on screen for a moment. /// [TestClass] public sealed class BrowserWindowTests @@ -67,6 +69,30 @@ public sealed class BrowserWindowTests 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"); + // Every hide of the window (SWP_HIDEWINDOW), and those while it is on screen, where Alberto would see it go. + var hides = 0; + var hidesOnScreen = 0; + await bed.OnUiAsync(() => + { + var source = (HwndSource)PresentationSource.FromVisual(window); + source.AddHook((IntPtr _, int message, IntPtr _, IntPtr data, ref bool _) => + { + const int WindowPosChanged = 0x0047; + const int HideWindow = 0x0080; + if (message == WindowPosChanged && (System.Runtime.InteropServices.Marshal.ReadInt32(data, (IntPtr.Size * 2) + 16) & HideWindow) != 0) + { + hides++; + if (window.IsOnScreen) + { + hidesOnScreen++; + } + } + + return IntPtr.Zero; + }); + return true; + }); + 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"); @@ -90,6 +116,9 @@ public sealed class BrowserWindowTests await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct); Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar), "out of view again, no taskbar button"); + Assert.AreEqual(1.0, await bed.OnUiAsync(() => window.Fit), "out of view the page is at 100%, whatever the screen"); + Assert.AreEqual(0, await bed.OnUiAsync(() => hidesOnScreen), $"never hidden on screen ({await bed.OnUiAsync(() => hides)} hides out of view)"); + TestContext.WriteLine($"Nascosta fuori vista {await bed.OnUiAsync(() => hides)} volte per il pulsante nella barra delle applicazioni."); } [TestMethod] diff --git a/tests/Febe.Tests.Windows/Support/BrowserBed.cs b/tests/Febe.Tests.Windows/Support/BrowserBed.cs index bc96fe1..e3f6c2d 100644 --- a/tests/Febe.Tests.Windows/Support/BrowserBed.cs +++ b/tests/Febe.Tests.Windows/Support/BrowserBed.cs @@ -1,4 +1,5 @@ using Febe.App; +using Febe.Browser.Cdp; using Febe.Core.Abstractions; using Febe.Core.Library; using Febe.Data; @@ -44,7 +45,10 @@ internal sealed class BrowserBed : IAsyncDisposable /// Prefix of the temporary folder. /// How WebView2 draws (S2). - /// Where «Pagina iniziale» goes; null: the login page of the options. + /// + /// Where «Pagina iniziale» goes, opened as the connection would (here without an engine to wait for); null: the button + /// does nothing (never the default login page of the options, which is Instagram's). + /// public static async Task CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func? startPage = null) { var folder = new TestFolder(name); @@ -56,11 +60,14 @@ 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, startPage); + WebView2Browser? built = null; + Func? openStartPage = startPage is null ? null : async ct => await built!.Cdp.NavigateAsync(startPage(), ct); + var context = new FebePlatformContext(options, data, database, clock, log, tracker, openStartPage); var settings = new WebView2BrowserSettings(data.BrowserProfile, 1280, 900, hosting, BrowserArguments.ForWebView2()); // Built off the UI thread, as DesktopPlatform.CreateBrowserAsync does after its awaits. var browser = new WebView2Browser(ui.Dispatcher, settings, context, icon: null); + built = browser; return new BrowserBed(folder, ui, lines, log, database, tracker, browser); } diff --git a/tests/Febe.Tests/Browser/RemoteViewFramesTests.cs b/tests/Febe.Tests/Browser/RemoteViewFramesTests.cs index 0430b94..f4343b4 100644 --- a/tests/Febe.Tests/Browser/RemoteViewFramesTests.cs +++ b/tests/Febe.Tests/Browser/RemoteViewFramesTests.cs @@ -8,12 +8,17 @@ namespace Febe.Tests.Browser; /// /// 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. +/// page and back). Only in the Linux CI; never Instagram. The tests ask that a picture arrives, not how fast: the waits are +/// generous for a busy runner (issue #46), and the time it took goes to the test's output (about two seconds, the +/// watchdog's silence, at most five on a calm machine). /// [TestClass] [DoNotParallelize] public sealed class RemoteViewFramesTests { + /// How long a picture may take on a busy runner before the view counts as white. + private static readonly TimeSpan Patience = TimeSpan.FromSeconds(20); + public TestContext TestContext { get; set; } = null!; [TestInitialize] @@ -27,7 +32,7 @@ public sealed class RemoteViewFramesTests [TestMethod] [Timeout(120_000, CooperativeCancellation = true)] - public async Task AStillPageAndTheRestPageShowAPictureWithinFiveSeconds() + public async Task AStillPageAndTheRestPageShowAPicture() { var ct = TestContext.CancellationToken; await using var browser = await RealBrowser.StartAsync(); @@ -40,12 +45,16 @@ public sealed class RemoteViewFramesTests 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 watch = Stopwatch.StartNew(); + Assert.IsTrue(await PictureAfterAsync(view.Screencast, null, Patience, ct), "a picture of the login page"); + TestContext.WriteLine($"pagina di accesso: immagine dopo {watch.ElapsedMilliseconds} ms."); 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"); + watch.Restart(); + Assert.IsTrue(await PictureAfterAsync(view.Screencast, last, Patience, ct), "a picture of the rest page too"); + TestContext.WriteLine($"pagina di riposo: immagine dopo {watch.ElapsedMilliseconds} ms, riavvii {view.Screencast.Restarts}."); } finally { @@ -82,7 +91,7 @@ public sealed class RemoteViewFramesTests Assert.IsTrue(navigated.Succeeded, $"{address}: {navigated.ErrorText}"); var shown = moving ? await FramesAfterAsync(view.Screencast, ct) - : await PictureAfterAsync(view.Screencast, last, TimeSpan.FromSeconds(5), ct); + : await PictureAfterAsync(view.Screencast, last, Patience, ct); TestContext.WriteLine($"{address}: {(shown ? "immagini" : "niente")} dopo {watch.ElapsedMilliseconds} ms, riavvii {view.Screencast.Restarts}."); Assert.IsTrue(shown, $"{address}: the view is not white"); } @@ -110,12 +119,12 @@ public sealed class RemoteViewFramesTests return false; } - /// A few real frames of the screencast (not still pictures) after now, within ten seconds. + /// A few real frames of the screencast (not still pictures) after now, within . private static async Task FramesAfterAsync(ScreencastSession screencast, CancellationToken ct) { var before = screencast.FramesReceived; var deadline = Stopwatch.StartNew(); - while (deadline.Elapsed < TimeSpan.FromSeconds(10)) + while (deadline.Elapsed < Patience) { if (screencast.FramesReceived >= before + 3) { diff --git a/tests/Febe.Tests/Browser/ScreencastWatchdogTests.cs b/tests/Febe.Tests/Browser/ScreencastWatchdogTests.cs index dadfa73..c61409f 100644 --- a/tests/Febe.Tests/Browser/ScreencastWatchdogTests.cs +++ b/tests/Febe.Tests/Browser/ScreencastWatchdogTests.cs @@ -61,7 +61,8 @@ public sealed class ScreencastWatchdogTests await using var bed = new Bed(screenshot: Jpeg(800, 600)); await bed.StartAsync(ct); - await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct); + // The restart after two seconds, then its wait for a first frame. + await bed.StepAsync(TimeSpan.FromSeconds(2.25) + ScreencastWatchdog.FirstFrameWait, ct); var still = bed.Session.LastFrame; Assert.IsNotNull(still, "something to show"); @@ -80,6 +81,25 @@ public sealed class ScreencastWatchdogTests } } + [TestMethod] + [Timeout(30_000, CooperativeCancellation = true)] + public async Task AFrameSoonAfterARestartNeedsNoStillPicture() + { + var ct = TestContext.CancellationToken; + await using var bed = new Bed(screenshot: Jpeg(800, 600)); + await bed.StartAsync(ct); + + // Restarted after two seconds: Chromium answers the start first and sends its frame a moment later. + await bed.StepAsync(TimeSpan.FromSeconds(2.25), ct); + Assert.AreEqual(1, bed.Session.Restarts); + bed.Frame(); + await bed.StepAsync(TimeSpan.FromSeconds(1), ct); + + Assert.IsFalse(bed.Cdp.Sent.Any(c => c.Method == "Page.captureScreenshot"), "the frame came: no picture taken. " + string.Join(", ", bed.Cdp.Sent.Where(c => c.Method != "Page.screencastFrameAck").Select(c => $"{c.Method}@{c.At:ss.fff}")) + " | " + bed.AllLines); + Assert.IsNotNull(bed.Session.LastFrame); + Assert.IsFalse(bed.Session.LastFrame.Still); + } + [TestMethod] [Timeout(30_000, CooperativeCancellation = true)] public async Task ANewDocumentLoadedWithoutFramesStartsThemAgainAtTheNextLook() diff --git a/tests/Febe.Tests/Desktop/BrowserStartPageTests.cs b/tests/Febe.Tests/Desktop/BrowserStartPageTests.cs index c2d520b..74a7cc7 100644 --- a/tests/Febe.Tests/Desktop/BrowserStartPageTests.cs +++ b/tests/Febe.Tests/Desktop/BrowserStartPageTests.cs @@ -178,6 +178,35 @@ public sealed class BrowserStartPageTests } } + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task PaginaInizialeWaitsForThePageTurnAndActsOnlyWhileAlbertoIsAtTheBrowser() + { + var ct = TestContext.CancellationToken; + await using var bed = await DesktopTestBed.StartAsync(); + await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + + // Nobody at the browser: the page is the engine's, the button does nothing. + var navigations = Navigations(browser); + await connection.OpenStartPageAsync(ct); + Assert.AreEqual(navigations, Navigations(browser)); + + // At the browser, on a page of his: the start page — but only once a step of the profile search let go of the page. + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.Navigated("https://www.instagram.com/marta.prova/"); + var turns = bed.App.Engine!.Services.PageTurns; + var turn = await turns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct); + var home = connection.OpenStartPageAsync(ct); + await DesktopTestBed.WaitUntilAsync(() => turns.IsWaiting(Febe.Core.Engine.PageUser.Engine), TimeSpan.FromSeconds(10), "«Pagina iniziale» in attesa del turno della pagina"); + Assert.IsFalse(home.IsCompleted, "the search step still has the page"); + Assert.AreEqual("https://www.instagram.com/marta.prova/", browser.FakeCdp.Url); + turn.Dispose(); + await home.WaitAsync(TimeSpan.FromSeconds(10), ct); + Assert.AreEqual(Login, browser.FakeCdp.Url, "not connected: the login page"); + } + private static int Navigations(FakeBrowser browser) => browser.FakeCdp.Methods.Count(m => m == "Page.navigate"); private static async Task BeginAsync(DesktopTestBed bed, bool openLogin) diff --git a/tests/Febe.Tests/Server/RemoteViewStartTests.cs b/tests/Febe.Tests/Server/RemoteViewStartTests.cs index 3022a0e..cfe0454 100644 --- a/tests/Febe.Tests/Server/RemoteViewStartTests.cs +++ b/tests/Febe.Tests/Server/RemoteViewStartTests.cs @@ -229,7 +229,10 @@ public sealed class RemoteViewStartTests private int _starts; /// For the n-th start (from 1), the exception the browser answers with; null: started. - /// Where «Pagina iniziale» goes; null: nowhere. + /// + /// Where «Pagina iniziale» goes, as the connection would open it (BrowserConnectionService.OpenStartPageAsync, + /// tested in BrowserStartPageTests); null: nowhere. + /// public Bed(Func startFailure, Func? startPage = null) { Clock = new VirtualClock(); @@ -256,7 +259,7 @@ public sealed class RemoteViewStartTests }; Browser = new PageBrowser(Cdp); _log = new FebeLog(null, null, Clock); - Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, startPage: startPage) + Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, openStartPage: startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct)) { // The virtual clock moves only in the pauses: a watchdog on it would never wait. Watchdog = null, diff --git a/tests/Febe.Tests/Web/ConnectionApiTests.cs b/tests/Febe.Tests/Web/ConnectionApiTests.cs index 7ee9db3..b3ad536 100644 --- a/tests/Febe.Tests/Web/ConnectionApiTests.cs +++ b/tests/Febe.Tests/Web/ConnectionApiTests.cs @@ -94,6 +94,34 @@ public sealed class ConnectionApiTests CollectionAssert.AreEqual(new[] { "release", "cancel", "show:False", "show:True" }, windows.Calls); } + [TestMethod] + public async Task ABodyWithoutALengthIsReadAndAnEmptyOneIsNoBody() + { + // Chunked, as a body without Content-Length may come (HTTP/2 too): empty is the default, not a 400. + var windows = new RecordingConnection(); + await using var server = await Part2.StartAsync(services: s => s + .AddSingleton(windows) + .AddSingleton(new SeparateWindow())); + foreach (var (path, body) in new[] + { + ("/api/connection/begin", ""), + ("/api/connection/cancel", ""), + ("/api/browser/show", ""), + ("/api/connection/cancel", """{"pageLeft":true}"""), + ("/api/browser/show", """{"openLogin":true}"""), + }) + { + using var request = server.Request(HttpMethod.Post, path); + request.Content = new StreamContent(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(body))); + request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); + request.Headers.TransferEncodingChunked = true; + using var response = await server.Client.SendAsync(request); + Assert.IsTrue(response.IsSuccessStatusCode, $"{path} «{body}»: {(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}"); + } + + CollectionAssert.AreEqual(new[] { "begin:False", "cancel", "show:False", "release", "show:True" }, windows.Calls); + } + [TestMethod] public async Task CommandsFromAnotherPageAreRefused() {