Files
Febe/tools/Febe.Schermate/Screenshotter.cs
T
Alby96andClaude Opus 5.5 be662f2d28 Correzioni della revisione di C6: installatore, CI senza jq, caratteri e schermate senza Node
Le 14 osservazioni della revisione di funzione/senza-terzi, ciascuna con la prova che l'avrebbe trovata.

Installatore: un aggiornamento senza /D= va nella cartella già installata (InstallLocation)
invece che in quella predefinita, che lasciava la vecchia copia. Una cartella senza permessi
non sembra più «Febe aperto». La dimensione in «App installate» conta solo i due file
dell'installatore. I file in sola lettura si sostituiscono e si tolgono. «Febe» in Esegui
all'avvio si toglie solo se avvia quella copia, non un Febe portatile. Febe parte alla fine
solo con «Fine» e la casella spuntata. /PROVA= rifiuta la radice di un disco.

CI: jq non c'era ed era un componente esterno. JSON letto e scritto con .gitea/scripts/json.sh
(json-campi.awk e json-stringa.awk sul lettore json.awk) per gitleaks, Trivy e la release.
Le credenziali del registro stanno solo in un DOCKER_CONFIG temporaneo della pubblicazione,
con plugin, contesti e contesto corrente del runner, tolto alla fine. Le prove del rilascio
girano in debian:trixie con Chromium, come la verifica, senza prove saltate. Ogni flusso usa
shell: bash.

Caratteri: tolti fonts-liberation e fonts-noto-color-emoji dall'immagine e dalle prove della
CI, perché Chromium non li chiede. Resta fonts-dejavu-core.

Icone: la prova della griglia legge davvero i percorsi SVG (tutti i comandi, archi e curve) e
i punti. La lettura dei nomi delle icone vede ogni forma con cui l'interfaccia li chiede.

Schermate: tools/schermate (Node) diventa tools/Febe.Schermate, in C# con ClientWebSocket e
System.Text.Json, nessun pacchetto, solo verso indirizzi di questo computer. Provato contro
una dimostrazione con Edge su Windows.

Documenti: CLAUDE.md, processo, guida, LEGGIMI e docker.md aggiornati. Righe nuove in
decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 16:04:39 +01:00

385 lines
15 KiB
C#

using System.Collections.Concurrent;
using System.Diagnostics;
using System.Globalization;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Browser.Hosting;
namespace Febe.Schermate;
/// <summary>
/// One screenshot of Febe's own interface through the DevTools protocol of a Chromium without window: exact viewport at
/// scale 1.25 (like the mockups), console errors printed, an optional step (a script evaluated in the page and awaited;
/// when it returns <c>{ hover: [x, y] }</c> the pointer is moved there, so :hover styles show). A fresh profile every
/// time, deleted at the end. Only addresses on this computer (<see cref="Shots.IsOnThisComputer"/>).
/// </summary>
internal sealed class Screenshotter : IAsyncDisposable
{
/// <summary>The scale of the mockups.</summary>
public const double Scale = 1.25;
private static readonly TimeSpan StartPatience = TimeSpan.FromSeconds(20);
private readonly Process _process;
private readonly string _profile;
private readonly ClientWebSocket _socket;
private readonly ConcurrentDictionary<int, TaskCompletionSource<JsonElement>> _pending = new();
private readonly CancellationTokenSource _stop = new();
private readonly Task _receiving;
private readonly TextWriter _log;
private int _id;
private Screenshotter(Process process, string profile, ClientWebSocket socket, TextWriter log)
{
_process = process;
_profile = profile;
_socket = socket;
_log = log;
_receiving = Task.Run(ReceiveAsync);
}
/// <summary>Chromium: FEBE_CHROMIUM, then PATH and the usual places (Debian's «chromium», Edge on Windows).</summary>
public static string? FindChromium() => ChromiumCommandLine.FindExecutable();
/// <summary>The command line of the screenshot browser: no window, a private profile, the debug port only on 127.0.0.1.</summary>
internal static List<string> Arguments(string profile, int width, int height, bool noSandbox)
{
// Port 0: Chromium picks a free port and writes it in DevToolsActivePort, so no other process can take it.
List<string> arguments =
[
"--headless", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check",
"--disable-extensions", "--disable-background-networking", "--disable-component-update", "--no-proxy-server",
"--mute-audio", string.Create(CultureInfo.InvariantCulture, $"--window-size={width},{height}"),
$"--user-data-dir={profile}", "--remote-debugging-port=0", "--remote-debugging-address=127.0.0.1",
];
if (noSandbox)
{
arguments.Add("--no-sandbox");
}
arguments.Add("about:blank");
return arguments;
}
public static async Task<Screenshotter> StartAsync(string chromium, int width, int height, TextWriter log, CancellationToken ct)
{
var profile = Path.Combine(Path.GetTempPath(), "febe-schermata-" + Guid.NewGuid().ToString("N"));
var info = new ProcessStartInfo(chromium) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true };
foreach (var argument in Arguments(profile, width, height, OperatingSystem.IsLinux() && Environment.UserName == "root"))
{
info.ArgumentList.Add(argument);
}
var process = Process.Start(info) ?? throw new InvalidOperationException("Chromium non parte.");
process.OutputDataReceived += (_, _) => { };
process.ErrorDataReceived += (_, _) => { };
process.BeginOutputReadLine();
process.BeginErrorReadLine();
try
{
using var http = new HttpClient(new HttpClientHandler { UseProxy = false }) { Timeout = TimeSpan.FromSeconds(5) };
var watch = Stopwatch.StartNew();
string? debugger = null;
while (debugger is null)
{
if (process.HasExited)
{
throw new InvalidOperationException($"Chromium si è chiuso all'avvio (codice {process.ExitCode}).");
}
if (watch.Elapsed > StartPatience)
{
throw new TimeoutException("Chromium non risponde sulla porta di debug.");
}
if (ActivePort(profile) is > 0 and var port)
{
try
{
debugger = PageDebugger(await http.GetStringAsync(new Uri($"http://127.0.0.1:{port}/json/list"), ct));
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException)
{
// Chromium is still starting.
}
}
if (debugger is null)
{
await Task.Delay(100, ct);
}
}
var socket = new ClientWebSocket();
socket.Options.Proxy = null;
await socket.ConnectAsync(new Uri(debugger), ct);
return new Screenshotter(process, profile, socket, log);
}
catch
{
Kill(process);
TryDelete(profile);
throw;
}
}
/// <summary>Navigates, waits, runs the step, and returns the PNG.</summary>
public async Task<byte[]> TakeAsync(Uri address, int width, int height, TimeSpan wait, string? stepCode, CancellationToken ct)
{
if (!Shots.IsOnThisComputer(address))
{
throw new ArgumentException("Solo l'interfaccia di Febe su questo computer (127.0.0.1, localhost o [::1]).", nameof(address));
}
await SendAsync("Runtime.enable", null, ct);
await SendAsync("Log.enable", null, ct);
await SendAsync("Page.enable", null, ct);
await SendAsync("Emulation.setDeviceMetricsOverride", new JsonObject
{
["width"] = width, ["height"] = height, ["deviceScaleFactor"] = Scale, ["mobile"] = false,
}, ct);
await SendAsync("Page.navigate", new JsonObject { ["url"] = address.AbsoluteUri }, ct);
await Task.Delay(wait, ct);
if (stepCode is not null)
{
var evaluated = await SendAsync("Runtime.evaluate", new JsonObject
{
["expression"] = $"(async () => {{ {stepCode}\n}})()", ["awaitPromise"] = true, ["returnByValue"] = true,
}, ct);
if (evaluated.TryGetProperty("exceptionDetails", out var failure))
{
_log.WriteLine($"errore nel passo: {Description(failure)}");
}
else if (evaluated.TryGetProperty("result", out var result) && result.TryGetProperty("value", out var value))
{
_log.WriteLine($"passo: {value.GetRawText()}");
if (HoverPoint(value) is { } point)
{
await SendAsync("Input.dispatchMouseEvent", new JsonObject
{
["type"] = "mouseMoved", ["x"] = point.X, ["y"] = point.Y,
}, ct);
}
}
await Task.Delay(800, ct);
}
var shot = await SendAsync("Page.captureScreenshot", new JsonObject { ["format"] = "png" }, ct);
return Convert.FromBase64String(shot.GetProperty("data").GetString() ?? string.Empty);
}
/// <summary>The point of <c>{ hover: [x, y] }</c>, or null.</summary>
internal static (double X, double Y)? HoverPoint(JsonElement value) =>
value.ValueKind == JsonValueKind.Object
&& value.TryGetProperty("hover", out var hover)
&& hover.ValueKind == JsonValueKind.Array
&& hover.GetArrayLength() == 2
&& hover[0].ValueKind == JsonValueKind.Number
&& hover[1].ValueKind == JsonValueKind.Number
? (hover[0].GetDouble(), hover[1].GetDouble())
: null;
/// <summary>The debugger address of the first page target of <c>/json/list</c>, or null.</summary>
internal static string? PageDebugger(string list)
{
using var document = JsonDocument.Parse(list);
foreach (var target in document.RootElement.EnumerateArray())
{
if (target.TryGetProperty("type", out var type) && type.GetString() == "page"
&& target.TryGetProperty("webSocketDebuggerUrl", out var url) && url.GetString() is { } address
&& Uri.TryCreate(address, UriKind.Absolute, out var parsed) && parsed.Host == "127.0.0.1")
{
return address;
}
}
return null;
}
public async ValueTask DisposeAsync()
{
await _stop.CancelAsync();
try
{
await _receiving;
}
catch (OperationCanceledException)
{
// Stopped on purpose.
}
_socket.Dispose();
Kill(_process);
_process.Dispose();
_stop.Dispose();
TryDelete(_profile);
}
private async Task<JsonElement> SendAsync(string method, JsonObject? parameters, CancellationToken ct)
{
var id = Interlocked.Increment(ref _id);
var answer = new TaskCompletionSource<JsonElement>(TaskCreationOptions.RunContinuationsAsynchronously);
_pending[id] = answer;
var message = new JsonObject { ["id"] = id, ["method"] = method, ["params"] = parameters ?? new JsonObject() };
await _socket.SendAsync(Encoding.UTF8.GetBytes(message.ToJsonString()), WebSocketMessageType.Text, endOfMessage: true, ct);
using var registration = ct.Register(() => answer.TrySetCanceled(ct));
return await answer.Task;
}
private async Task ReceiveAsync()
{
var buffer = new byte[64 * 1024];
using var message = new MemoryStream();
while (!_stop.IsCancellationRequested && _socket.State == WebSocketState.Open)
{
ValueWebSocketReceiveResult result;
try
{
result = await _socket.ReceiveAsync(buffer.AsMemory(), _stop.Token);
}
catch (WebSocketException)
{
break;
}
if (result.MessageType == WebSocketMessageType.Close)
{
break;
}
message.Write(buffer, 0, result.Count);
if (!result.EndOfMessage)
{
continue;
}
Dispatch(message.GetBuffer().AsSpan(0, (int)message.Length));
message.SetLength(0);
}
foreach (var pending in _pending.Values)
{
pending.TrySetException(new InvalidOperationException("Chromium ha chiuso il collegamento."));
}
}
private void Dispatch(ReadOnlySpan<byte> text)
{
var reader = new Utf8JsonReader(text);
using var document = JsonDocument.ParseValue(ref reader);
var root = document.RootElement;
if (root.TryGetProperty("id", out var id) && _pending.TryRemove(id.GetInt32(), out var answer))
{
if (root.TryGetProperty("error", out var error))
{
answer.TrySetException(new InvalidOperationException($"DevTools: {error.GetRawText()}"));
}
else
{
answer.TrySetResult(root.GetProperty("result").Clone());
}
return;
}
if (!root.TryGetProperty("method", out var method) || !root.TryGetProperty("params", out var parameters))
{
return;
}
// Only Febe's own pages: what they print in their console is Febe's own interface talking.
switch (method.GetString())
{
case "Runtime.consoleAPICalled" when parameters.GetProperty("type").GetString() is "error" or "warning":
var words = new List<string>();
foreach (var argument in parameters.GetProperty("args").EnumerateArray())
{
words.Add(argument.TryGetProperty("value", out var value) ? value.ToString() : Description(argument));
}
_log.WriteLine($"console.{parameters.GetProperty("type").GetString()}: {string.Join(' ', words)}");
break;
case "Runtime.exceptionThrown":
_log.WriteLine($"eccezione: {Description(parameters.GetProperty("exceptionDetails"))}");
break;
case "Log.entryAdded" when parameters.GetProperty("entry").GetProperty("level").GetString() == "error":
var entry = parameters.GetProperty("entry");
_log.WriteLine($"errore: {entry.GetProperty("text").GetString()} {(entry.TryGetProperty("url", out var url) ? url.GetString() : string.Empty)}");
break;
}
}
private static string Description(JsonElement element)
{
if (element.TryGetProperty("exception", out var exception) && exception.TryGetProperty("description", out var described))
{
return described.GetString() ?? string.Empty;
}
if (element.TryGetProperty("description", out var description))
{
return description.GetString() ?? string.Empty;
}
return element.TryGetProperty("text", out var text) ? text.GetString() ?? string.Empty : string.Empty;
}
/// <summary>The port Chromium wrote in DevToolsActivePort (first line), or 0 while it has not.</summary>
private static int ActivePort(string profile)
{
try
{
using var reader = new StreamReader(Path.Combine(profile, "DevToolsActivePort"));
return int.TryParse(reader.ReadLine(), NumberStyles.None, CultureInfo.InvariantCulture, out var port) ? port : 0;
}
catch (IOException)
{
return 0;
}
catch (UnauthorizedAccessException)
{
return 0;
}
}
private static void Kill(Process process)
{
try
{
if (!process.HasExited)
{
process.Kill(entireProcessTree: true);
process.WaitForExit(5000);
}
}
catch (InvalidOperationException)
{
// Already gone.
}
}
private static void TryDelete(string profile)
{
// Chromium may hold its files for a moment after it exits.
for (var attempt = 0; attempt < 10; attempt++)
{
try
{
if (Directory.Exists(profile))
{
Directory.Delete(profile, recursive: true);
}
return;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Thread.Sleep(200);
}
}
}
}