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>
This commit is contained in:
1 parent
525d7dfdaa
commit
be662f2d28
46 files changed
+2091
-283
No files matched your search
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- Le schermate dell'interfaccia di Febe per il confronto con i mockup (specifica §10.7): un Chromium guidato con
|
||||
il protocollo DevTools, solo verso indirizzi di questo computer. Scritto in C#, senza Node né pacchetti. -->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<AssemblyName>febe-schermate</AssemblyName>
|
||||
<RootNamespace>Febe.Schermate</RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Febe.Browser\Febe.Browser.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<!-- I passi: script valutati nella pagina prima della schermata. -->
|
||||
<None Include="passi\*.js" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="Febe.Tests" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,170 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Febe.Schermate;
|
||||
|
||||
/// <summary>
|
||||
/// Retakes the screenshots of docs/schermate from a running demo (spec §10.7):
|
||||
/// <code>
|
||||
/// dotnet run --project src/Febe.Server -- --demo --porta 8490 (in another terminal)
|
||||
/// dotnet run --project tools/Febe.Schermate -- [porta] [cartella] (all of them)
|
||||
/// dotnet run --project tools/Febe.Schermate -- una <indirizzo> <file.png> [larghezza] [altezza] [attesa-ms] [passo.js]
|
||||
/// </code>
|
||||
/// One screenshot at a time, each in its own Chromium: the browser and the demo share the computer.
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
internal const string Usage =
|
||||
"Uso: febe-schermate [porta] [cartella]\n" +
|
||||
" febe-schermate una <indirizzo> <file.png> [larghezza] [altezza] [attesa-ms] [passo.js]";
|
||||
|
||||
private static readonly TimeSpan PerShot = TimeSpan.FromSeconds(90);
|
||||
|
||||
public static async Task<int> Main(string[] args)
|
||||
{
|
||||
Request request;
|
||||
try
|
||||
{
|
||||
request = Request.Parse(args, Directory.GetCurrentDirectory());
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
await Console.Error.WriteLineAsync(ex.Message);
|
||||
await Console.Error.WriteLineAsync(Usage);
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (Screenshotter.FindChromium() is not { } chromium)
|
||||
{
|
||||
await Console.Error.WriteLineAsync("Chromium non trovato: indica il percorso in FEBE_CHROMIUM.");
|
||||
return 2;
|
||||
}
|
||||
|
||||
Directory.CreateDirectory(request.Folder);
|
||||
var failed = 0;
|
||||
foreach (var shot in request.Shots)
|
||||
{
|
||||
Console.WriteLine($"== {shot.File}");
|
||||
try
|
||||
{
|
||||
await TakeAsync(chromium, request, shot);
|
||||
}
|
||||
catch (Exception ex) when (ex is OperationCanceledException or InvalidOperationException or TimeoutException
|
||||
or IOException or System.Net.WebSockets.WebSocketException or ArgumentException)
|
||||
{
|
||||
failed++;
|
||||
Console.WriteLine($"non riuscita: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
return failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static async Task TakeAsync(string chromium, Request request, Shot shot)
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(PerShot);
|
||||
var step = shot.Step is null ? null : await File.ReadAllTextAsync(request.StepPath(shot.Step), timeout.Token);
|
||||
await using var browser = await Screenshotter.StartAsync(chromium, shot.Width, shot.Height, Console.Out, timeout.Token);
|
||||
var png = await browser.TakeAsync(request.AddressOf(shot), shot.Width, shot.Height, TimeSpan.FromMilliseconds(shot.WaitMs), step, timeout.Token);
|
||||
var file = Path.Combine(request.Folder, shot.File);
|
||||
await File.WriteAllBytesAsync(file, png, timeout.Token);
|
||||
Console.WriteLine($"salvata {file}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What the command line asks: the shots, where they go, and against which address.</summary>
|
||||
/// <param name="Base">The demo («http://127.0.0.1:8480»); for a single shot, its whole address.</param>
|
||||
/// <param name="Folder">Where the PNG files go.</param>
|
||||
/// <param name="Shots">The shots, in order.</param>
|
||||
/// <param name="Steps">The folder of the steps named by the list; a single shot names its step by path.</param>
|
||||
internal sealed record Request(Uri Base, string Folder, IReadOnlyList<Shot> Shots, string Steps)
|
||||
{
|
||||
public const int DefaultPort = 8480;
|
||||
|
||||
public Uri AddressOf(Shot shot) => shot.Page.Length == 0 ? Base : new Uri(Base, shot.Page);
|
||||
|
||||
public string StepPath(string step) => Path.IsPathFullyQualified(step) ? step : Path.Combine(Steps, step);
|
||||
|
||||
public static Request Parse(IReadOnlyList<string> args, string currentDirectory)
|
||||
{
|
||||
if (args.Count > 0 && args[0] == "una")
|
||||
{
|
||||
return One(args, currentDirectory);
|
||||
}
|
||||
|
||||
if (args.Count > 2)
|
||||
{
|
||||
throw new ArgumentException("Troppi argomenti.");
|
||||
}
|
||||
|
||||
var port = args.Count > 0 ? Port(args[0]) : DefaultPort;
|
||||
var folder = args.Count > 1
|
||||
? Path.GetFullPath(args[1], currentDirectory)
|
||||
: Path.Combine(RepositoryRoot(currentDirectory)
|
||||
?? throw new ArgumentException("Fuori dal repository di Febe: indica la cartella delle schermate."), "docs", "schermate");
|
||||
return new Request(new Uri($"http://127.0.0.1:{port.ToString(CultureInfo.InvariantCulture)}"), folder, Schermate.Shots.All, StepsFolder());
|
||||
}
|
||||
|
||||
private static Request One(IReadOnlyList<string> args, string currentDirectory)
|
||||
{
|
||||
if (args.Count is < 3 or > 7)
|
||||
{
|
||||
throw new ArgumentException("«una» vuole l'indirizzo e il file, poi a scelta larghezza, altezza, attesa e passo.");
|
||||
}
|
||||
|
||||
if (!Uri.TryCreate(args[1], UriKind.Absolute, out var address) || !Schermate.Shots.IsOnThisComputer(address))
|
||||
{
|
||||
throw new ArgumentException("Solo l'interfaccia di Febe su questo computer (127.0.0.1, localhost o [::1]).");
|
||||
}
|
||||
|
||||
var file = Path.GetFullPath(args[2], currentDirectory);
|
||||
if (!file.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new ArgumentException("Il file della schermata è un .png.");
|
||||
}
|
||||
|
||||
var shot = new Shot(
|
||||
string.Empty,
|
||||
Path.GetFileName(file),
|
||||
args.Count > 3 ? Size(args[3], "larghezza") : 1440,
|
||||
args.Count > 4 ? Size(args[4], "altezza") : 900,
|
||||
args.Count > 5 ? Wait(args[5]) : 3000,
|
||||
args.Count > 6 ? Path.GetFullPath(args[6], currentDirectory) : null);
|
||||
return new Request(address, Path.GetDirectoryName(file)!, [shot], StepsFolder());
|
||||
}
|
||||
|
||||
private static int Port(string text) =>
|
||||
int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var port) && port is >= 1 and <= 65535
|
||||
? port
|
||||
: throw new ArgumentException($"Porta non valida: {text}.");
|
||||
|
||||
private static int Size(string text, string what) =>
|
||||
int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var size) && size is >= 200 and <= 8000
|
||||
? size
|
||||
: throw new ArgumentException($"{what} non valida: {text} (da 200 a 8000 punti).");
|
||||
|
||||
private static int Wait(string text) =>
|
||||
int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var wait) && wait <= 60_000
|
||||
? wait
|
||||
: throw new ArgumentException($"Attesa non valida: {text} (millisecondi, al massimo 60000).");
|
||||
|
||||
/// <summary>The steps next to the program (copied at build), else in the sources.</summary>
|
||||
private static string StepsFolder()
|
||||
{
|
||||
var beside = Path.Combine(AppContext.BaseDirectory, "passi");
|
||||
return Directory.Exists(beside) ? beside : Path.Combine(RepositoryRoot(AppContext.BaseDirectory) ?? AppContext.BaseDirectory, "tools", "Febe.Schermate", "passi");
|
||||
}
|
||||
|
||||
/// <summary>The nearest folder, from <paramref name="start"/> up, that holds Febe.slnx.</summary>
|
||||
internal static string? RepositoryRoot(string start)
|
||||
{
|
||||
for (var folder = new DirectoryInfo(start); folder is not null; folder = folder.Parent)
|
||||
{
|
||||
if (File.Exists(Path.Combine(folder.FullName, "Febe.slnx")))
|
||||
{
|
||||
return folder.FullName;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
namespace Febe.Schermate;
|
||||
|
||||
/// <summary>One screenshot: the page (path and query on the demo), the file, the viewport, the wait and an optional step.</summary>
|
||||
internal sealed record Shot(string Page, string File, int Width = 1440, int Height = 900, int WaitMs = 3000, string? Step = null);
|
||||
|
||||
/// <summary>The screenshots of docs/schermate (spec §10.7), in the order they are taken.</summary>
|
||||
internal static class Shots
|
||||
{
|
||||
/// <summary>
|
||||
/// One at a time: Chromium and the demo share the computer. The stopped scenes come first where it matters:
|
||||
/// «Riprendi» stays off until the browser has been used (spec §7.6).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<Shot> All { get; } =
|
||||
[
|
||||
new("/libreria?tema=chiaro", "01-libreria.png", Step: "puntatore.js"),
|
||||
new("/libreria?tema=chiaro", "02-visualizzatore.png", Step: "visualizzatore.js"),
|
||||
new("/account?tema=chiaro", "03-account.png"),
|
||||
new("/account?tema=chiaro", "03-account-telefono.png", 390, 844),
|
||||
new("/account?dialogo=aggiungi&tema=chiaro", "04-aggiungi-account.png", Step: "aggiungi.js"),
|
||||
new("/account/3/impostazioni?tema=chiaro", "05-account-impostazioni.png"),
|
||||
new("/libreria?scena=fermo&tema=scuro", "11-libreria-fermo-tema-scuro.png"),
|
||||
new("/account/2?tema=scuro&tipo=storie", "12-account-storie-tema-scuro.png"),
|
||||
new("/libreria?tema=chiaro", "14-finestra-stretta.png", 860, 900),
|
||||
new("/libreria?tema=chiaro", "14-telefono.png", 390, 844),
|
||||
new("/account/2/cronologia?tema=chiaro", "account-cronologia.png"),
|
||||
|
||||
// Part 2: Attività, Impostazioni, Collegamento, Importa, doppioni, primo avvio, errore di configurazione.
|
||||
new("/attivita?scena=fermo&tema=scuro", "11-attivita-fermo-tema-scuro.png"),
|
||||
new("/attivita?scena=sessione&tema=chiaro", "06-attivita.png"),
|
||||
new("/attivita?scena=sessione&tema=chiaro", "06-attivita-tutti-i-tetti.png", Step: "tutti-tetti.js"),
|
||||
new("/attivita?scena=sessione&tema=chiaro", "14-attivita-finestra-stretta.png", 860, 900),
|
||||
new("/attivita?scena=sessione&tema=chiaro", "14-attivita-telefono.png", 390, 844),
|
||||
new("/attivita?scena=normale&tema=chiaro", "14-attivita-finestra-stretta-normale.png", 860, 900),
|
||||
new("/attivita?scena=normale&tema=chiaro", "14-attivita-telefono-normale.png", 390, 844),
|
||||
new("/impostazioni/limiti?tema=chiaro", "07-limiti-e-comportamento.png", 1440, 1470),
|
||||
new("/impostazioni/limiti?tema=chiaro", "07-limiti-su-misura.png", Step: "su-misura.js"),
|
||||
new("/impostazioni/generali?tema=chiaro", "08-impostazioni-generali.png"),
|
||||
new("/impostazioni/notifiche?tema=chiaro", "impostazioni-notifiche.png"),
|
||||
new("/impostazioni/dati?tema=chiaro", "impostazioni-dati.png"),
|
||||
new("/impostazioni/informazioni?tema=chiaro", "impostazioni-informazioni.png"),
|
||||
new("/importa?passo=1&tema=chiaro&veste=docker", "09-importa-sorgente.png"),
|
||||
new("/importa?passo=3&tema=chiaro", "09-importa-revisione.png", Step: "doppione-scelto.js"),
|
||||
new("/importa?passo=3&tema=chiaro", "09-importa-telefono.png", 390, 844),
|
||||
new("/impostazioni/collegamento?scena=scollegato&tema=chiaro&veste=docker", "10-collegamento-instagram.png"),
|
||||
new("/impostazioni/collegamento?scena=scollegato&tema=chiaro&veste=windows", "10-collegamento-windows.png"),
|
||||
new("/impostazioni/collegamento?scena=normale&tema=chiaro&veste=docker", "10-collegamento-collegato.png"),
|
||||
new("/browser?scena=fermo&tema=chiaro&veste=docker", "10-browser.png"),
|
||||
new("/doppioni?tema=chiaro", "doppioni-download.png"),
|
||||
new("/libreria?scena=scollegato&tema=chiaro", "primo-avvio.png", Step: "benvenuto.js"),
|
||||
new("/libreria?scena=errore&tema=chiaro", "errore-configurazione.png"),
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Only Febe's own interface on this computer: http or https to 127.0.0.1, localhost or [::1]. Instagram is never
|
||||
/// opened this way (spec §2, rule 4).
|
||||
/// </summary>
|
||||
public static bool IsOnThisComputer(Uri address) =>
|
||||
address.IsAbsoluteUri
|
||||
&& (address.Scheme == Uri.UriSchemeHttp || address.Scheme == Uri.UriSchemeHttps)
|
||||
&& string.IsNullOrEmpty(address.UserInfo)
|
||||
&& address.Host is "127.0.0.1" or "localhost" or "[::1]";
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,119 +0,0 @@
|
||||
// node tools/schermate/schermata.mjs <indirizzo> <file.png> [larghezza] [altezza] [attesa-ms] [passo.js]
|
||||
//
|
||||
// Screenshot of Febe's own interface (spec §10.7) 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 JS file evaluated in
|
||||
// the page and awaited; when it returns { hover: [x, y] } the pointer is moved there, so :hover styles show).
|
||||
//
|
||||
// Only for Febe's own interface: the address must be on this computer (127.0.0.1 or localhost). Instagram is never
|
||||
// opened this way (spec §2, rule 4). Needs Node 22 or later (global WebSocket) and a Chromium: set FEBE_CHROMIUM, or
|
||||
// the Playwright build under /opt/pw-browsers is used.
|
||||
import { spawn } from 'node:child_process';
|
||||
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const [address, out, width = '1440', height = '900', wait = '3000', step] = process.argv.slice(2);
|
||||
if (!address || !out) {
|
||||
console.error('Uso: node tools/schermate/schermata.mjs <indirizzo> <file.png> [larghezza] [altezza] [attesa-ms] [passo.js]');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const target = new URL(address);
|
||||
if (!['127.0.0.1', 'localhost', '[::1]'].includes(target.hostname)) {
|
||||
console.error('Solo l\'interfaccia di Febe su questo computer (127.0.0.1 o localhost).');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
function findChromium() {
|
||||
if (process.env.FEBE_CHROMIUM) return process.env.FEBE_CHROMIUM;
|
||||
const root = '/opt/pw-browsers';
|
||||
if (existsSync(root)) {
|
||||
for (const name of readdirSync(root).filter((n) => /^chromium-\d+$/.test(n)).sort().reverse()) {
|
||||
const candidate = join(root, name, 'chrome-linux', 'chrome');
|
||||
if (existsSync(candidate)) return candidate;
|
||||
}
|
||||
}
|
||||
console.error('Chromium non trovato: indica il percorso in FEBE_CHROMIUM.');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const profile = mkdtempSync(join(tmpdir(), 'febe-schermata-'));
|
||||
const port = 9300 + Math.floor(Math.random() * 500);
|
||||
const chrome = spawn(findChromium(), [
|
||||
'--headless', '--no-sandbox', '--disable-gpu', '--hide-scrollbars', '--disable-background-networking',
|
||||
'--disable-component-update', '--no-first-run', '--no-default-browser-check', '--disable-extensions',
|
||||
`--user-data-dir=${profile}`, `--remote-debugging-port=${port}`, '--remote-debugging-address=127.0.0.1', 'about:blank',
|
||||
], { stdio: 'ignore' });
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
function finish(code) {
|
||||
chrome.kill('SIGKILL');
|
||||
setTimeout(() => {
|
||||
try {
|
||||
rmSync(profile, { recursive: true, force: true });
|
||||
} catch {
|
||||
// the profile stays in the temporary folder
|
||||
}
|
||||
process.exit(code);
|
||||
}, 300);
|
||||
}
|
||||
|
||||
let ws;
|
||||
for (let i = 0; i < 50 && !ws; i++) {
|
||||
try {
|
||||
const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
|
||||
const page = list.find((t) => t.type === 'page');
|
||||
if (page) ws = new WebSocket(page.webSocketDebuggerUrl);
|
||||
} catch {
|
||||
// Chromium is still starting
|
||||
}
|
||||
if (!ws) await sleep(200);
|
||||
}
|
||||
if (!ws) {
|
||||
console.error('Chromium non risponde.');
|
||||
finish(1);
|
||||
} else {
|
||||
await new Promise((r) => ws.addEventListener('open', r));
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
ws.addEventListener('message', (e) => {
|
||||
const msg = JSON.parse(e.data);
|
||||
if (msg.id && pending.has(msg.id)) {
|
||||
pending.get(msg.id)(msg);
|
||||
pending.delete(msg.id);
|
||||
} else if (msg.method === 'Runtime.consoleAPICalled' && ['error', 'warning'].includes(msg.params.type)) {
|
||||
console.log(`console.${msg.params.type}:`, msg.params.args.map((a) => a.value ?? a.description).join(' '));
|
||||
} else if (msg.method === 'Runtime.exceptionThrown') {
|
||||
console.log('eccezione:', msg.params.exceptionDetails.exception?.description || msg.params.exceptionDetails.text);
|
||||
} else if (msg.method === 'Log.entryAdded' && msg.params.entry.level === 'error') {
|
||||
console.log('errore:', msg.params.entry.text, msg.params.entry.url || '');
|
||||
}
|
||||
});
|
||||
const send = (method, params = {}) => new Promise((resolve) => {
|
||||
const n = ++id;
|
||||
pending.set(n, resolve);
|
||||
ws.send(JSON.stringify({ id: n, method, params }));
|
||||
});
|
||||
await send('Runtime.enable');
|
||||
await send('Log.enable');
|
||||
await send('Page.enable');
|
||||
await send('Emulation.setDeviceMetricsOverride', { width: Number(width), height: Number(height), deviceScaleFactor: 1.25, mobile: false });
|
||||
await send('Page.navigate', { url: target.href });
|
||||
await sleep(Number(wait));
|
||||
if (step) {
|
||||
const code = readFileSync(step, 'utf8');
|
||||
const r = await send('Runtime.evaluate', { expression: `(async () => { ${code} })()`, awaitPromise: true, returnByValue: true });
|
||||
const value = r.result?.result?.value;
|
||||
if (r.result?.exceptionDetails) console.log('errore nel passo:', r.result.exceptionDetails.exception?.description);
|
||||
else if (value !== undefined) console.log('passo:', JSON.stringify(value));
|
||||
if (value && typeof value === 'object' && Array.isArray(value.hover)) {
|
||||
await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: value.hover[0], y: value.hover[1] });
|
||||
}
|
||||
await sleep(800);
|
||||
}
|
||||
const shot = await send('Page.captureScreenshot', { format: 'png' });
|
||||
writeFileSync(out, Buffer.from(shot.result.data, 'base64'));
|
||||
console.log('salvata', out);
|
||||
ws.close();
|
||||
finish(0);
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Retakes the screenshots of docs/schermate from a running demo (spec §10.7):
|
||||
# dotnet run --project src/Febe.Server -- --demo --porta 8490 (in another terminal)
|
||||
# bash tools/schermate/tutte.sh [porta] [cartella]
|
||||
# One screenshot at a time: Chromium and the demo share the computer.
|
||||
set -u
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
port="${1:-8480}"
|
||||
out="${2:-$here/../../docs/schermate}"
|
||||
b="http://127.0.0.1:$port"
|
||||
mkdir -p "$out"
|
||||
shot() { echo "== $2"; timeout 90 node "$here/schermata.mjs" "$1" "$out/$2" "${3:-1440}" "${4:-900}" "${5:-3000}" ${6:-}; }
|
||||
shot "$b/libreria?tema=chiaro" 01-libreria.png 1440 900 3000 "$here/passi/puntatore.js"
|
||||
shot "$b/libreria?tema=chiaro" 02-visualizzatore.png 1440 900 3000 "$here/passi/visualizzatore.js"
|
||||
shot "$b/account?tema=chiaro" 03-account.png
|
||||
shot "$b/account?tema=chiaro" 03-account-telefono.png 390 844
|
||||
shot "$b/account?dialogo=aggiungi&tema=chiaro" 04-aggiungi-account.png 1440 900 3000 "$here/passi/aggiungi.js"
|
||||
shot "$b/account/3/impostazioni?tema=chiaro" 05-account-impostazioni.png
|
||||
shot "$b/libreria?scena=fermo&tema=scuro" 11-libreria-fermo-tema-scuro.png
|
||||
shot "$b/account/2?tema=scuro&tipo=storie" 12-account-storie-tema-scuro.png
|
||||
shot "$b/libreria?tema=chiaro" 14-finestra-stretta.png 860 900
|
||||
shot "$b/libreria?tema=chiaro" 14-telefono.png 390 844
|
||||
shot "$b/account/2/cronologia?tema=chiaro" account-cronologia.png
|
||||
# Part 2: Attività, Impostazioni, Collegamento, Importa, doppioni, primo avvio, errore di configurazione.
|
||||
# The stopped scene first: «Riprendi» stays off until the browser has been used (spec §7.6).
|
||||
shot "$b/attivita?scena=fermo&tema=scuro" 11-attivita-fermo-tema-scuro.png
|
||||
shot "$b/attivita?scena=sessione&tema=chiaro" 06-attivita.png
|
||||
shot "$b/attivita?scena=sessione&tema=chiaro" 06-attivita-tutti-i-tetti.png 1440 900 3000 "$here/passi/tutti-tetti.js"
|
||||
shot "$b/attivita?scena=sessione&tema=chiaro" 14-attivita-finestra-stretta.png 860 900
|
||||
shot "$b/attivita?scena=sessione&tema=chiaro" 14-attivita-telefono.png 390 844
|
||||
shot "$b/attivita?scena=normale&tema=chiaro" 14-attivita-finestra-stretta-normale.png 860 900
|
||||
shot "$b/attivita?scena=normale&tema=chiaro" 14-attivita-telefono-normale.png 390 844
|
||||
shot "$b/impostazioni/limiti?tema=chiaro" 07-limiti-e-comportamento.png 1440 1470
|
||||
shot "$b/impostazioni/limiti?tema=chiaro" 07-limiti-su-misura.png 1440 900 3000 "$here/passi/su-misura.js"
|
||||
shot "$b/impostazioni/generali?tema=chiaro" 08-impostazioni-generali.png
|
||||
shot "$b/impostazioni/notifiche?tema=chiaro" impostazioni-notifiche.png
|
||||
shot "$b/impostazioni/dati?tema=chiaro" impostazioni-dati.png
|
||||
shot "$b/impostazioni/informazioni?tema=chiaro" impostazioni-informazioni.png
|
||||
shot "$b/importa?passo=1&tema=chiaro&veste=docker" 09-importa-sorgente.png
|
||||
shot "$b/importa?passo=3&tema=chiaro" 09-importa-revisione.png 1440 900 3000 "$here/passi/doppione-scelto.js"
|
||||
shot "$b/importa?passo=3&tema=chiaro" 09-importa-telefono.png 390 844
|
||||
shot "$b/impostazioni/collegamento?scena=scollegato&tema=chiaro&veste=docker" 10-collegamento-instagram.png
|
||||
shot "$b/impostazioni/collegamento?scena=scollegato&tema=chiaro&veste=windows" 10-collegamento-windows.png
|
||||
shot "$b/impostazioni/collegamento?scena=normale&tema=chiaro&veste=docker" 10-collegamento-collegato.png
|
||||
shot "$b/browser?scena=fermo&tema=chiaro&veste=docker" 10-browser.png
|
||||
shot "$b/doppioni?tema=chiaro" doppioni-download.png
|
||||
shot "$b/libreria?scena=scollegato&tema=chiaro" primo-avvio.png 1440 900 3000 "$here/passi/benvenuto.js"
|
||||
shot "$b/libreria?scena=errore&tema=chiaro" errore-configurazione.png
|
||||
Reference in new issue
Block a user