using System.Collections.Concurrent;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.App;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Desktop.Core;
using Febe.Web.Native;
namespace Febe.Tests.Desktop.Support;
/// The Windows-only part of the desktop, faked: what the platform asks of it is recorded.
internal sealed class FakeDesktopShell : IDesktopShell
{
public FakeNativeShell NativeShell { get; } = new();
public INativeShell Native => NativeShell;
/// The WebView2 runtime this «Windows» has (null: missing).
public string? RuntimeVersion { get; set; } = "141.0.3537.71";
/// Where «Edge» is (null: not installed).
public string? EdgePath { get; set; }
/// The browsers created, with the settings the platform gave them.
public ConcurrentQueue<(WebView2BrowserSettings Settings, FakeBrowser Browser)> Created { get; } = new();
public ConcurrentQueue ProcessWindows { get; } = new();
/// Called with each browser as it is created, before Febe uses it (to set up the fake page).
public Action? OnCreated { get; set; }
public string? WebView2Version() => RuntimeVersion;
public IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context)
{
var browser = new FakeBrowser(settings.ProfileDirectory, settings.Width, settings.Height, context);
OnCreated?.Invoke(browser);
Created.Enqueue((settings, browser));
return browser;
}
public string? FindEdge() => EdgePath;
public Task ShowProcessWindowAsync(int processId, CancellationToken ct)
{
ProcessWindows.Enqueue("mostra " + processId);
return Task.CompletedTask;
}
public Task HideProcessWindowAsync(int processId, CancellationToken ct)
{
ProcessWindows.Enqueue("nascondi " + processId);
return Task.CompletedTask;
}
/// The processes the platform asked to tie to Febe's life (Edge), by id.
public ConcurrentQueue TiedToFebe { get; } = new();
/// What «Windows» answers when a process is tied to Febe.
public bool TieSucceeds { get; set; } = true;
public bool EndWithFebe(System.Diagnostics.Process process)
{
TiedToFebe.Enqueue(process.Id);
return TieSucceeds;
}
}
/// Folder picker, explorer, default browser, notifications (the Windows alerts) and autostart, faked.
internal sealed class FakeNativeShell : INativeShell
{
public bool CanPickFolder => true;
public bool CanShowInFolder => true;
public bool CanOpenUrl => true;
public bool CanNotify => true;
public bool SupportsAutostart => true;
public bool Autostart { get; private set; }
public string? FolderToPick { get; set; }
public ConcurrentQueue Shown { get; } = new();
public ConcurrentQueue Opened { get; } = new();
public ConcurrentQueue<(string Title, string Message)> Notified { get; } = new();
public Task PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => Task.FromResult(FolderToPick);
public Task ShowInFolderAsync(string fullPath, CancellationToken ct)
{
Shown.Enqueue(fullPath);
return Task.FromResult(true);
}
public Task OpenUrlAsync(Uri address, CancellationToken ct)
{
Opened.Enqueue(address);
return Task.FromResult(true);
}
public Task NotifyAsync(string title, string message, CancellationToken ct)
{
Notified.Enqueue((title, message));
return Task.CompletedTask;
}
public Task GetAutostartAsync(CancellationToken ct) => Task.FromResult(Autostart);
public Task SetAutostartAsync(bool enabled, CancellationToken ct)
{
Autostart = enabled;
return Task.CompletedTask;
}
}
///
/// The window «Browser di Febe», faked: a CDP session that answers like a browser on a blank page, a session cookie
/// that exists once «Alberto» has logged in, and a record of every time the window came to the front or went away.
///
internal sealed class FakeBrowser : IFebeBrowser
{
private readonly FebePlatformContext _context;
private IDisposable? _lease;
public FakeBrowser(string profileDirectory, int width, int height, FebePlatformContext context)
{
ProfileDirectory = profileDirectory;
WindowWidth = width;
WindowHeight = height;
_context = context;
}
public FakeCdp FakeCdp { get; } = new();
public ICdpSession Cdp => FakeCdp;
public UserDrivingGate UserDriving { get; } = new();
public bool UserIsDriving => UserDriving.IsDriving;
public bool IsAvailable { get; private set; }
public string? LastError => null;
public string ProfileDirectory { get; }
public int WindowWidth { get; }
public int WindowHeight { get; }
public int Shown { get; private set; }
public int Hidden { get; private set; }
public int EmptiedProfiles { get; private set; }
public bool Disposed { get; private set; }
public Task RunAsync(CancellationToken ct)
{
Directory.CreateDirectory(ProfileDirectory);
IsAvailable = true;
return Task.CompletedTask;
}
public Task RestAsync(CancellationToken ct) => FakeCdp.NavigateAsync(CdpPageExtensions.RestUrl, ct);
/// Like the real window: in front, Alberto is driving.
public Task ShowToUserAsync(CancellationToken ct)
{
Shown++;
_lease ??= UserDriving.Begin();
_context.Tracker.MarkUsed(_context.Clock.Now);
return Task.CompletedTask;
}
public Task HideFromUserAsync(CancellationToken ct)
{
Hidden++;
_lease?.Dispose();
_lease = null;
return Task.CompletedTask;
}
/// The next «Scollega» finds a file held by another process (Windows) and cannot delete the profile.
public bool ProfileLocked { get; set; }
public Task RestartWithEmptyProfileAsync(CancellationToken ct)
{
if (ProfileLocked)
{
throw new IOException("Il file Cookies è in uso da un altro processo.");
}
if (Directory.Exists(ProfileDirectory))
{
Directory.Delete(ProfileDirectory, recursive: true);
}
Directory.CreateDirectory(ProfileDirectory);
FakeCdp.LoggedIn = false;
EmptiedProfiles++;
return Task.CompletedTask;
}
public ValueTask DisposeAsync()
{
Disposed = true;
IsAvailable = false;
return ValueTask.CompletedTask;
}
}
///
/// A CDP session answering like a page: frame tree, navigation (with its Page.frameNavigated event, as the
/// collection pipeline hears it), the session cookie (name only).
///
internal sealed class FakeCdp : ICdpSession
{
private readonly Lock _gate = new();
private readonly Dictionary>> _handlers = new(StringComparer.Ordinal);
public bool LoggedIn { get; set; }
///
/// Like the test site, which sets its session cookie on any visit: a navigation to an address starting with this
/// logs in, and the page reports itself loaded. Null: only the test logs in.
///
public string? LogsInOnVisit { get; set; }
public string Url { get; private set; } = "about:blank";
public ConcurrentQueue Methods { get; } = new();
/// The main frame moved to by itself (a redirect of the site), not by a command.
public void Navigated(string url)
{
Url = url;
Raise("Page.frameNavigated", new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = url } });
}
public Task SendAsync(string method, object? parameters = null, CancellationToken ct = default)
{
CdpCommandPolicy.EnsureAllowed(method);
Methods.Enqueue(method);
JsonNode result = method switch
{
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = Url } } },
"Page.navigate" => Navigate(parameters),
// The session cookie of Instagram, and the test site's one.
"Network.getCookies" => new JsonObject { ["cookies"] = LoggedIn ? new JsonArray(new JsonObject { ["name"] = "sessionid" }, new JsonObject { ["name"] = "sessione_prova" }) : new JsonArray() },
"Runtime.evaluate" when LogsInOnVisit is not null => new JsonObject { ["result"] = new JsonObject { ["type"] = "string", ["value"] = "complete" } },
_ => new JsonObject(),
};
return Task.FromResult(JsonDocument.Parse(result.ToJsonString()).RootElement.Clone());
}
public IDisposable On(string eventName, Action handler)
{
lock (_gate)
{
if (!_handlers.TryGetValue(eventName, out var list))
{
_handlers[eventName] = list = [];
}
list.Add(handler);
}
return new Removal(() =>
{
lock (_gate)
{
_handlers[eventName].Remove(handler);
}
});
}
private JsonObject Navigate(object? parameters)
{
var url = (parameters as JsonObject)?["url"]?.GetValue();
if (url is not null)
{
if (LogsInOnVisit is { } site && url.StartsWith(site, StringComparison.Ordinal))
{
LoggedIn = true;
}
Navigated(url);
}
return new JsonObject { ["frameId"] = "F1" };
}
private void Raise(string eventName, JsonObject parameters)
{
Action[] handlers;
lock (_gate)
{
handlers = _handlers.TryGetValue(eventName, out var list) ? [.. list] : [];
}
var element = JsonDocument.Parse(parameters.ToJsonString()).RootElement.Clone();
foreach (var handler in handlers)
{
handler(element);
}
}
private sealed class Removal(Action remove) : IDisposable
{
private Action? _remove = remove;
public void Dispose() => Interlocked.Exchange(ref _remove, null)?.Invoke();
}
}