diff --git a/docs/decisioni.md b/docs/decisioni.md index 2d1afe5..b3fa08e 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -361,3 +361,20 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-16 | I rifiuti del catalogo delle richieste (`RequestCatalog`) stanno nel codice, non nel JSON: ogni nome che contiene `Mutation`, le famiglie GraphQL di chat, messaggi, presenza, promozioni, pubblicità e telemetria, i percorsi di telemetria e navigazione (`/logging_client_events`, `/ajax/…`, `/ws/`, `/api/v1/web/`, `/api/v1/discover/web/`…), ogni percorso con un host, una query o un valore come primo segmento; GraphQL solo verso `/api/graphql` e `/graphql/query` con POST, gli indirizzi semplici solo con GET; niente intestazione `cookie` nel modello | Una copia di `richieste..json` modificata nella cartella dei dati non deve poter togliere un divieto (regole 3, 6) | | 2026-11-16 | `richieste..json` ha chiavi in inglese come gli altri file di configurazione; per ogni intestazione e campo dice la fonte del valore (`constant:`, `cookie:csrftoken`, `session:` user_agent, lsd, fb_dtsg, app_id, claim, account_id, doc_id, `operation`, `variables`, `computed`, `pending` se ancora da stabilire nella tappa S4). Un'operazione con un nome o un valore tolto dalla sonda nelle variabili resta «non configurata» e il client la rifiuta; nessun `doc_id` nel repository. Le categorie del Governatore sono quelle che ci sono già, fino ai tetti per richiesta della tappa S3 | Regola 9: le forme non mostrano tutto, e ciò che manca non si indovina | | 2026-11-16 | Il contratto del client del sito (S1 di #36) si chiude nel codice: un'operazione con un'intestazione o un campo `pending` (o col nome tolto dalla sonda) non può essere configurata, quindi oggi nessuna operazione di Instagram lo è; un permesso vale per una sola richiesta, contato per riferimento (`SpentPermits`) e speso anche se la richiesta è poi rifiutata; i valori del caso hanno una forma (cifre per gli identificativi, i caratteri di un nome utente, di un codice o di una raccolta) e quelli che finiscono nel percorso non portano `/ ? # %` né punti soli; i percorsi del catalogo non hanno segmenti vuoti, `.` o `..` né caratteri fuori da lettere, cifre e `/_.-{}`; un indirizzo semplice non può puntare a GraphQL; la categoria «ricerca» è solo di un'operazione che porta `{search_text}` e nessun account o contenuto, e viceversa; `SiteAnswer` prende l'operazione del catalogo, non un percorso | Revisione della tappa S1: altrimenti una copia modificata nella cartella dei dati (`/./ajax/bz`, che `System.Uri` riduce a `/ajax/bz`), un valore come `..` o un permesso riusato aggirerebbero i divieti delle regole 4, 8, 9 e 10; il tetto della ricerca è fuori dalle sessioni (§7.4) | +| 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 | +| 2026-11-16 | «Pagina iniziale» vale finché dura il permesso di chi l'ha premuta: la finestra di Windows e la vista remota passano un gettone che si annulla con il loro permesso, e la connessione guarda di nuovo, con il turno della pagina in mano, che Alberto guidi ancora; senza turno rinuncia invece di prendere la pagina. Nella vista remota la pressione corre a parte, una per volta, e intanto clic e tasti si scartano | L'attesa (fine della sessione, turno della pagina) può durare mezzo minuto: Alberto poteva aver chiuso la finestra e Febe navigava senza permesso e fuori dal Governatore (regole 7 e 8); nella vista l'attesa nel ciclo di ricezione bloccava i comandi e poi li riversava sulla pagina nuova | +| 2026-11-16 | `Repaint` della finestra «Browser di Febe» chiede solo di ridisegnare (`RDW_INVALIDATE \| RDW_ALLCHILDREN`), senza `RDW_UPDATENOW` | Le finestre figlie sono del processo del browser di WebView2: un processo bloccato avrebbe fermato il thread dell'interfaccia in un ridisegno sincrono | +| 2026-11-16 | Le porte libere delle prove (`LocalTestSite.FreePort`) vengono da 20000–29999, ciascuna una volta sola per processo e provata prima di darla, non più dalla porta 0 del sistema | Nella CI 350 (#52) Chromium non è partito perché la porta di debug, presa dall'intervallo effimero di Linux e chiusa prima di usarla, era stata nel frattempo occupata (come per #46: la causa, non un tempo più lungo) | diff --git a/docs/guida/Attivita-e-arresti.md b/docs/guida/Attivita-e-arresti.md index 8bfbab1..2261165 100644 --- a/docs/guida/Attivita-e-arresti.md +++ b/docs/guida/Attivita-e-arresti.md @@ -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. diff --git a/docs/guida/Installazione-Windows.md b/docs/guida/Installazione-Windows.md index 4e31286..94e372b 100644 --- a/docs/guida/Installazione-Windows.md +++ b/docs/guida/Installazione-Windows.md @@ -19,6 +19,14 @@ 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; 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 tuo browser predefinito (mai nel browser di Febe), notifiche di Windows, avvio con il computer. diff --git a/docs/guida/Primo-collegamento.md b/docs/guida/Primo-collegamento.md index 36bd4f0..93abc81 100644 --- a/docs/guida/Primo-collegamento.md +++ b/docs/guida/Primo-collegamento.md @@ -64,10 +64,23 @@ 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 Febe sta finendo un +lavoro nel browser, «Pagina iniziale» aspetta che finisca: può volerci qualche secondo (nella vista remota, intanto, +clic e tasti non arrivano al browser). Se nel frattempo chiudi il browser, o se il lavoro dura troppo, non succede +nulla: premilo di nuovo. + +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 diff --git a/docs/guida/Problemi-comuni.md b/docs/guida/Problemi-comuni.md index c4f5f4c..d09d198 100644 --- a/docs/guida/Problemi-comuni.md +++ b/docs/guida/Problemi-comuni.md @@ -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)) | diff --git a/docs/stato.md b/docs/stato.md index 4ddf897..62dd24d 100644 --- a/docs/stato.md +++ b/docs/stato.md @@ -23,7 +23,22 @@ fra le sessioni; ciò che è da fare si legge nelle issue aperte. viste. Le tappe S0–S7 stanno in #36. - **Il browser che a volte restava vuoto** (#52): nove cause trovate e ordinate (la pagina di riposo `about:blank` mostrata all'apertura, «Apri il browser» dopo una disconnessione, la finestra nascosta su Windows quando si lascia - la pagina, lo schermo remoto senza controllo dei fotogrammi in Docker, e altre); correzione su un ramo a parte. + la pagina, lo schermo remoto senza controllo dei fotogrammi in Docker, e altre). Corretto: + - aperto dal riposo, il browser va alla home se collegato, altrimenti all'accesso, come azione di Alberto; pulsante + «Pagina iniziale» nella finestra e nella vista remota, che aspetta la fine della sessione del motore e il turno + della pagina e vale solo finché dura il permesso di guida di chi l'ha premuto; avviso «a riposo su una pagina + vuota»; «Indietro» salta la pagina di riposo; + - «Apri il browser» della striscia rossa apre l'accesso; con `--accesso-di-prova` niente falso allarme all'avvio; + - Windows: lasciare una pagina di Febe non nasconde più la finestra; pulsante nella barra delle applicazioni solo + mentre è sullo schermo (cambiarlo con la finestra visibile la nasconde per un attimo); ridotta a icona non vale + più «Ho finito» e dopo 2 minuti torna fuori vista senza lampeggiare (DWM cloak); su uno schermo piccolo la finestra + si restringe con lo zoom della pagina, che torna a 1 fuori vista; ridisegno dopo il riavvio del processo GPU; + - Docker: controllo dei fotogrammi della vista remota (riavvio dopo 2 s di silenzio o un caricamento senza + fotogrammi, attesa che raddoppia fino a 30 s, immagine ferma con `Page.captureScreenshot` se il riavvio non porta + nulla in 500 ms), «Nessuna immagine dal browser» con «Riprova» dopo 8 s, registro della vista; nessun comando CDP + nuovo. 16 righe in `docs/decisioni.md`, due giri di revisione indipendente (14 punti, tutti chiusi). + - **Non verificato**: il disegno vero dopo un crash della GPU, uno schermo piccolo vero, la vista remota con Chromium + vero (solo nella CI Linux), le schermate nuove contro il mockup. - **Tappa S1, il giunto senza cambiare comportamento**: `ResponseDelivery` (in Core) consegna ai lettori le risposte catturate e, da S2, quelle chieste, nello stesso modo; `ResponseTap` la usa con gli stessi conteggi e messaggi. Contratti `SiteRequest`, `SiteAnswer` (che non stampa mai corpi, cookie o percorsi concreti) e `ISiteRequester`, diff --git a/src/Febe.App/BrowserConnectionService.cs b/src/Febe.App/BrowserConnectionService.cs index 08da929..5b51947 100644 --- a/src/Febe.App/BrowserConnectionService.cs +++ b/src/Febe.App/BrowserConnectionService.cs @@ -17,9 +17,10 @@ namespace Febe.App; /// means that the session cookie exists in the browser profile: only its existence is checked /// (Network.getCookies, 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). /// /// /// @@ -29,6 +30,11 @@ namespace Febe.App; /// must not stay still for ever. /// /// +/// 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 — the site's home when connected, the login +/// page when not connected or after a disconnection. +/// +/// /// 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) + /// The browser of Febe. + /// The database (first connection, «Scollega»). + /// When Alberto last used the browser. + /// The composition's clock. + /// Febe's log. + /// The page «Accedi a Instagram» opens. + /// The site's home, the start page once connected. + /// The session cookie looked for (its name only). + 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 } } + /// + /// 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. + /// + public string StartPageUrl => + IsConnected == true && _engine?.Services.Breaker.State.Status != BreakerStatus.Disconnected ? _homeUrl : _loginUrl; + /// /// Hook for the readers (hypothesis H10): when the data of the page tell which account is connected, the composition /// marks it as «Tu» (); the status shows that account. Raised after every change of the @@ -104,6 +128,12 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa /// public TimeSpan DrivingGrace { get; set; } = TimeSpan.FromMinutes(2); + /// + /// How long Alberto's page waits for its turn while a step of the profile search holds it (real time). Read at every + /// wait; tests shorten it. + /// + public TimeSpan PageTurnWait { get; set; } = TimeSpan.FromSeconds(15); + /// The engine, once it exists (it is built after the browser). public void AttachEngine(EngineHost engine) => _engine = engine ?? throw new ArgumentNullException(nameof(engine)); @@ -150,21 +180,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 +191,116 @@ 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(); + } + } + + /// + /// «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. + /// + /// + /// Cancelled when the lease of whoever pressed the button ends (the window closed, the remote view closed): the press + /// is then forgotten, whatever it was waiting for. + /// + /// + /// The waits can last up to and more: Alberto may have let go of the browser meanwhile, and + /// then the page is the engine's again (rules 7 and 8: no navigation without his lease, outside the Governor). So + /// right before navigating, with the page's turn in hand, it looks again: he still drives and the caller's lease still + /// holds. Without the page's turn (a step of the search kept it) nothing happens either: the page is not taken from + /// under the step. + /// + public async Task OpenStartPageAsync(CancellationToken ct) + { + if (!_browser.IsAvailable) + { + return; + } + + try + { + await _commands.WaitAsync(ct).ConfigureAwait(false); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + return; + } + + try + { + if (!_browser.UserIsDriving) + { + return; + } + + await WaitForSessionEndAsync(ct).ConfigureAwait(false); + using var turn = await TakePageAsync(ct).ConfigureAwait(false); + if (_engine is not null && turn is null) + { + _log.Info("collegamento", "«Pagina iniziale» non aperta: la pagina è ancora occupata dalla ricerca dei profili. Riprova fra poco."); + return; + } + + // The last look, with the page's turn in hand (no recipe and no search step can open a page until it is given + // back): Alberto still drives and the caller's lease still holds. + if (ct.IsCancellationRequested || !_browser.UserIsDriving) + { + _log.Info("collegamento", "«Pagina iniziale» non aperta: nel frattempo hai lasciato il browser."); + return; + } + + 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)."); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + _log.Info("collegamento", "«Pagina iniziale» non aperta: nel frattempo hai lasciato il browser."); + } + finally + { + _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 FinishAsync(CancellationToken ct) { await _commands.WaitAsync(ct).ConfigureAwait(false); @@ -305,16 +431,18 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa /// /// 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 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). /// - public async Task RefreshAsync(CancellationToken ct) + public async Task 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 +656,64 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa return true; } + /// + /// 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. + /// + 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)."); + } + + /// The empty rest page (or no document at all): never what Alberto should be shown. + private static bool IsRest(string? url) => url is "" or CdpPageExtensions.RestUrl; + + /// The address of the main frame, in full (never logged); null when the browser does not answer. + private async Task 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) @@ -543,8 +729,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } /// - /// The page turn for Alberto's login page, so that no step of the profile search runs under it; after 15 seconds - /// the page is taken anyway (Alberto asked for it), and null comes back. + /// The page turn for Alberto's own navigation, so that no step of the profile search runs under it; null after + /// (and always without an engine). The login and the start page from the rest page then + /// take the page anyway (Alberto asked for it, under his lease); «Pagina iniziale» gives up. /// private async Task TakePageAsync(CancellationToken ct) { @@ -554,7 +741,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct); - limit.CancelAfter(TimeSpan.FromSeconds(15)); + limit.CancelAfter(PageTurnWait); try { return await engine.Services.PageTurns.TakeAsync(PageUser.Engine, limit.Token).ConfigureAwait(false); diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs index 932ed93..e0a6266 100644 --- a/src/Febe.App/FebeApp.cs +++ b/src/Febe.App/FebeApp.cs @@ -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); + // «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, 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 } } + /// The site's home page as the browser writes it (with its final slash), for «Pagina iniziale». + private static string HomeUrl(string baseUrl) => + Uri.TryCreate(baseUrl, UriKind.Absolute, out var home) ? home.AbsoluteUri : baseUrl; + /// /// Development with the test site only (--accesso-di-prova): what Alberto does by hand on Instagram — open /// the site once, so that its session cookie exists — then back to the rest page. diff --git a/src/Febe.App/FebeLog.cs b/src/Febe.App/FebeLog.cs index 90dbac2..fb3a81f 100644 --- a/src/Febe.App/FebeLog.cs +++ b/src/Febe.App/FebeLog.cs @@ -101,7 +101,8 @@ public sealed partial class FebeLog : IDisposable } /// The adapter for the browser layer (it logs only CDP command names, states and counts). - public IBrowserLog ForBrowser() => new DelegateBrowserLog((level, message, exception) => Write( + /// The category of the lines (the remote view writes as «vista»). + 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)); diff --git a/src/Febe.App/IFebePlatform.cs b/src/Febe.App/IFebePlatform.cs index acf5238..ad52f06 100644 --- a/src/Febe.App/IFebePlatform.cs +++ b/src/Febe.App/IFebePlatform.cs @@ -55,7 +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. -public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker); +/// +/// 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? OpenStartPage = null); /// Options of the shared composition, filled by each shell from its own configuration. public sealed record FebeAppOptions diff --git a/src/Febe.App/StartupProblems.cs b/src/Febe.App/StartupProblems.cs index 77338b6..b750e2d 100644 --- a/src/Febe.App/StartupProblems.cs +++ b/src/Febe.App/StartupProblems.cs @@ -47,6 +47,10 @@ public sealed class ProblemConnectionService(IReadOnlyList 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() => diff --git a/src/Febe.Browser/RemoteView/RemoteViewSession.cs b/src/Febe.Browser/RemoteView/RemoteViewSession.cs index 9ab7dd1..c59fdf9 100644 --- a/src/Febe.Browser/RemoteView/RemoteViewSession.cs +++ b/src/Febe.Browser/RemoteView/RemoteViewSession.cs @@ -66,7 +66,7 @@ public sealed class RemoteViewSession : IAsyncDisposable /// The page session. /// Where the «Alberto is driving» lease is taken. - /// Where opening and closing are noted (never keys). + /// Where the frames' starts, restarts and silences are noted (never keys). /// Wall-clock time for the screencast's start attempts; null: the system clock. 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() diff --git a/src/Febe.Browser/RemoteView/ScreencastSession.cs b/src/Febe.Browser/RemoteView/ScreencastSession.cs index 5b3e299..bc389e1 100644 --- a/src/Febe.Browser/RemoteView/ScreencastSession.cs +++ b/src/Febe.Browser/RemoteView/ScreencastSession.cs @@ -1,3 +1,4 @@ +using System.Globalization; using System.Runtime.CompilerServices; using System.Text.Json; using System.Text.Json.Nodes; @@ -13,7 +14,37 @@ namespace Febe.Browser.RemoteView; /// Largest frame width in pixels. /// Largest frame height in pixels. /// Send one frame out of this many. -public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, int MaxHeight = 900, int EveryNthFrame = 1); +/// How missing frames are noticed and the frames started again; null: never (issue #52). +public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, int MaxHeight = 900, int EveryNthFrame = 1, ScreencastWatchdog? Watchdog = null); + +/// +/// 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 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 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 . +/// +/// Time without frames before the first restart. +/// How often the watchdog looks. +/// The longest wait between two restarts without frames. +public sealed record ScreencastWatchdog(TimeSpan Silence, TimeSpan Tick, TimeSpan LongestSilence) +{ + /// + /// 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. + /// + 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)); +} /// One frame of the remote view. /// The image. @@ -24,6 +55,7 @@ public sealed record ScreencastOptions(int Quality = 70, int MaxWidth = 1280, in /// Horizontal scroll position. /// Vertical scroll position. /// Browser timestamp (seconds), when given. +/// True for a still picture (Page.captureScreenshot) sent because no frame came. public sealed record ScreencastFrame( byte[] Jpeg, double DeviceWidth, @@ -32,7 +64,8 @@ public sealed record ScreencastFrame( double OffsetTop, double ScrollOffsetX, double ScrollOffsetY, - double? Timestamp); + double? Timestamp, + bool Still = false); /// /// The remote view's video (spec §4.1, §11): Page.startScreencast in JPEG, every frame acknowledged with @@ -40,9 +73,16 @@ public sealed record ScreencastFrame( /// (only the latest ones are kept when the reader is slow) and . /// /// +/// /// 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 . Any other failure is reported at once. +/// +/// +/// With a the frames are started again when they stop coming (issue #52): after a +/// silence, and when the main frame finished loading a new document (Page.loadEventFired) 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. +/// /// public sealed class ScreencastSession : IAsyncDisposable { @@ -60,15 +100,33 @@ public sealed class ScreencastSession : IAsyncDisposable private readonly Channel _acks = Channel.CreateUnbounded(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 _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; + private TaskCompletionSource? _nextFrame; /// The page session. - /// Where the start and stop are noted (never parameters or frames). - /// Wall-clock time for the pauses between start attempts; null: the system clock. + /// Where starts, restarts and silences are noted (never parameters or frames). + /// Wall-clock time for the pauses between start attempts and the watchdog; null: the system clock. public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null, IClock? clock = null) { _cdp = cdp ?? throw new ArgumentNullException(nameof(cdp)); @@ -79,11 +137,15 @@ public sealed class ScreencastSession : IAsyncDisposable /// Raised on the browser event thread for every frame: handlers must be quick. public event EventHandler? FrameReceived; - /// The last frame received, for mapping input coordinates. + /// The last frame received (or still picture sent), for mapping input coordinates. public ScreencastFrame? LastFrame { get; private set; } + /// Frames of the screencast received so far (still pictures not counted). public long FramesReceived => Interlocked.Read(ref _framesReceived); + /// How many times the watchdog started the frames again. + public long Restarts => Interlocked.Read(ref _restarts); + public async Task StartAsync(ScreencastOptions? options = null, CancellationToken ct = default) { if (_subscription is not null) @@ -100,7 +162,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."); } /// Frames as they arrive; the oldest are dropped if the reader falls behind. Ends when the session stops. @@ -124,31 +199,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 +246,55 @@ public sealed class ScreencastSession : IAsyncDisposable { await StopAsync().ConfigureAwait(false); _lifetime.Dispose(); + _starts.Dispose(); + } + + /// The width and height written in a JPEG's frame header (SOFn), or null when the data has none. + internal static (int Width, int Height)? JpegSize(ReadOnlySpan 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 +319,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 +343,274 @@ public sealed class ScreencastSession : IAsyncDisposable private void OnReconnected(object? sender, EventArgs e) => _ = Task.Run(async () => { + // Read inside the try: a browser restart that races the dispose finds the source disposed. + var ct = CancellationToken.None; try { - await SendStartAsync(_lifetime.Token).ConfigureAwait(false); + ct = _lifetime.Token; + 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); } }); + /// + /// The watchdog: every it looks how long no frame came; past the allowed + /// silence (or when a new document loaded without frames) it starts the frames again. + /// + 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})."); + } + } + } + + /// + /// 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; + lock (_watch) + { + first = !_silent; + if (first) + { + _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); + 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); + } + + 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. + } + + // 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 (!await FrameWithinAsync(nextFrame.Task, ScreencastWatchdog.FirstFrameWait, ct).ConfigureAwait(false)) + { + 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) + { + 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; + 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 +637,37 @@ 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; + _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. + _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 +682,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; } diff --git a/src/Febe.Desktop.Core/DesktopPlatform.cs b/src/Febe.Desktop.Core/DesktopPlatform.cs index d65691c..7147b55 100644 --- a/src/Febe.Desktop.Core/DesktopPlatform.cs +++ b/src/Febe.Desktop.Core/DesktopPlatform.cs @@ -152,7 +152,7 @@ public sealed class DesktopPlatform : IFebePlatform ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(app); services.AddSingleton(_shell.Native); - services.AddSingleton(new DesktopBrowserWindow(() => app.Browser)); + services.AddSingleton(new DesktopBrowserWindow()); services.AddSingleton(new DesktopDataFolderChange(_locations, app.Options.DataFolder, _dataFolderFixed)); } @@ -200,29 +200,14 @@ public sealed class DesktopPlatform : IFebePlatform } /// -/// «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 (IConnectionService.ShowBrowserAsync, 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). /// -public sealed class DesktopBrowserWindow(Func 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); - } } /// diff --git a/src/Febe.Desktop/Browser/BrowserWindow.cs b/src/Febe.Desktop/Browser/BrowserWindow.cs index d5017b8..c3d1a5e 100644 --- a/src/Febe.Desktop/Browser/BrowserWindow.cs +++ b/src/Febe.Desktop/Browser/BrowserWindow.cs @@ -3,21 +3,47 @@ using System.Windows; using System.Windows.Controls; using System.Windows.Interop; using System.Windows.Media; +using System.Windows.Threading; +using Febe.Desktop.Native; namespace Febe.Desktop.Browser; /// /// 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. /// +/// +/// +/// 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 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 { /// Height of the bar under the page, in device-independent pixels. public const double BarHeight = 40; + /// The smallest zoom the page is shown at when the screen is small. + public const double SmallestFit = 0.4; + + /// What the bar says while the page is the empty rest page. + 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 +57,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 +67,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 +86,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(); } /// Width of the page in device-independent pixels (CSS pixels of the page at zoom 100%). @@ -82,15 +117,30 @@ internal sealed class BrowserWindow : Window public int PageHeight { get; } + /// + /// 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). + /// + public double Fit { get; private set; } = 1; + + /// How long the window may stay minimised before it is put out of view as «ho finito» (S2). + public TimeSpan MinimizedLimit { get; set; } = TimeSpan.FromMinutes(2); + /// Raised by «Indietro». public event EventHandler? BackRequested; /// Raised by «Ricarica». public event EventHandler? ReloadRequested; - /// Raised when Alberto closes or minimises the window: the owner puts it out of view. + /// Raised by «Pagina iniziale». + public event EventHandler? HomeRequested; + + /// Raised when Alberto closes the window, or leaves it minimised too long: the owner puts it out of view. public event EventHandler? DoneRequested; + /// Raised when the page area changed size (a new fit): the owner sizes WebView2 again. + public event EventHandler? PageAreaChanged; + /// The window handle (created on first use). public IntPtr Handle => new WindowInteropHelper(this).EnsureHandle(); @@ -98,40 +148,102 @@ internal sealed class BrowserWindow : Window public double Scale => VisualTreeHelper.GetDpi(this).DpiScaleX; /// Where WebView2 draws, in physical pixels of the client area. - 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)); /// True while the window is on a screen, false while it is parked out of view. public bool IsOnScreen => Left < SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth && Left + ActualWidth > SystemParameters.VirtualScreenLeft; - /// Shows the address of the page, without query string or fragment (they may carry tokens). - public void ShowAddress(string? address) => _address.Text = address ?? string.Empty; + /// The text the bar shows now (the address, or ). + public string AddressText => _address.Text; - /// Centres the window on the work area of the primary screen. + /// + /// The zoom at which a page of × plus its bar and the + /// window's frame fits in an area of × (all in + /// device-independent pixels): 1 when it fits, never below . + /// + 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); + } + + /// + /// Shows the address of the page, without query string or fragment (they may carry tokens); on the empty rest page, + /// . + /// + public void ShowAddress(string? address) => + _address.Text = address is null or "" or "about:blank" ? RestNotice : address; + + /// + /// Centres the window on the work area of the primary screen, shrunk to fit it when needed, with its taskbar button. + /// public void MoveOnScreen() { var area = SystemParameters.WorkArea; - var width = ActualWidth > 0 ? ActualWidth : PageWidth; - var height = ActualHeight > 0 ? ActualHeight : PageHeight + BarHeight; + 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; Left = area.Left + Math.Max(0, (area.Width - width) / 2); Top = area.Top + Math.Max(0, (area.Height - height) / 2); } /// /// Parks the window just right of every screen: open, «visible» for Windows and for WebView2, out of Alberto's view - /// (S2). Never Hide() and never 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() { - Left = SystemParameters.VirtualScreenLeft + SystemParameters.VirtualScreenWidth + 64; - Top = SystemParameters.VirtualScreenTop; + _minimized.Stop(); + var restoring = WindowState == WindowState.Minimized; + var cloaked = restoring && Cloak(true); + try + { + 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); + } + } + + // 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). public void CloseForGood() { _allowClose = true; + _minimized.Stop(); Close(); } @@ -151,14 +263,59 @@ 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) + { + // Restored out of view by the owner (MoveOffScreen), never first on screen where it was. + 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; + 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; + } + + Fit = fit; + _page.Width = PageWidth * fit; + _page.Height = PageHeight * fit; + UpdateLayout(); + 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 36c8405..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)), + 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 51db2fc..830ac43 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,7 +19,27 @@ 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»). -internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed); +/// +/// 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 +{ + /// Nothing: WebView2 recovers by itself (an unresponsive page while Alberto looks at it, a helper process). + None, + + /// The whole browser is gone: the owner starts it again. + Restart, + + /// The page crashed (or hangs while nobody looks): back to the rest page (spec §6.1). + Rest, + + /// The GPU process restarted: the page is resized by a pixel and back, or the window may stay blank or black. + Redraw, +} /// /// The browser host of the Windows edition (spec §5, §6.1, §12): WebView2 in the window «Browser di Febe», with its own @@ -36,6 +57,9 @@ internal sealed record WebView2HostOptions(BrowserHosting Hosting, string Additi /// «Ho finito»; using and closing it marks the browser as used for «Riprendi». /// Stopping closes the WebView and waits for its browser process to exit, so the session is on disk (S3); /// («Scollega») does the same before deleting the profile. +/// 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. /// Threads: every WebView2 object (environment, controller, CoreWebView2, 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 @@ -71,6 +95,7 @@ internal sealed class WebView2Host : IBrowserHost private CoreWebView2DevTools? _devTools; private TaskCompletionSource? _exited; private IDisposable? _lease; + private CancellationTokenSource? _leaseEnded; private int _generation; private bool _starting; private bool _crashedWhileStarting; @@ -147,12 +172,22 @@ 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, 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); @@ -169,9 +204,24 @@ internal sealed class WebView2Host : IBrowserHost { _window?.MoveOffScreen(); ReleaseLease(); + NotifyPositionChanged(); return Task.CompletedTask; }); + /// + /// 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. + /// + 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, + }; + /// /// Closes the WebView, waits for its browser process to exit (the profile is free and written), runs /// — «Scollega» deletes the profile there — and starts it again. @@ -302,7 +352,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 += (_, _) => OpenStartPage(); window.DpiChanged += (_, _) => UpdateBounds(); + window.PageAreaChanged += (_, _) => UpdateBounds(); + + // The raw controller does not follow its parent by itself: popups (lists of a