using System.Globalization;
using Febe.App;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Core.Abstractions;
using Febe.Core.Library;
using Febe.Web;
using Febe.Web.Api;
using Febe.Web.Connection;
using Febe.Web.Library;
using Febe.Web.Native;
using Microsoft.Extensions.DependencyInjection;
namespace Febe.Desktop.Core;
/// How the window «Browser di Febe» hosts WebView2 (spec §6.1, §12, S2).
/// The WebView2 user data folder: Dati\browser, with the Instagram session.
/// Width of the page in CSS pixels, always the same.
/// Height of the page in CSS pixels, always the same.
/// or .
/// The switches of S2 ().
public sealed record WebView2BrowserSettings(string ProfileDirectory, int Width, int Height, BrowserHosting Hosting, string AdditionalBrowserArguments);
///
/// What the Windows-only part of the desktop (Febe.Desktop, WPF) gives the platform: the native shell (with the
/// notifications), the WebView2 browser, Edge's window, the WebView2 runtime probe. Tests on Linux pass fakes.
///
public interface IDesktopShell
{
///
/// Folder picker, «Mostra nella cartella», default browser, notifications, start with the computer. Its
/// notifications are the Windows channel of the alerts (spec §13.3): the shared composition sends them through it.
///
INativeShell Native { get; }
/// The installed WebView2 runtime; null when missing.
string? WebView2Version();
/// The window «Browser di Febe» on WebView2.
IFebeBrowser CreateWebView2Browser(WebView2BrowserSettings settings, FebePlatformContext context);
/// Microsoft Edge (fallback «edge» of S2); null when it is not installed.
string? FindEdge();
/// Brings the main window of a process (Edge) to the front, on screen.
Task ShowProcessWindowAsync(int processId, CancellationToken ct);
/// Moves the main window of a process (Edge) out of view, still open: never minimised (S2).
Task HideProcessWindowAsync(int processId, CancellationToken ct);
///
/// Ties a process Febe started (Edge) to the life of Febe.exe: Windows ends it, with the processes it opens, when
/// Febe ends — also after a crash or «Termina attività», so that it never stays behind holding the profile and the
/// debugging port. False when Windows refused (the process then lives on its own, as before).
///
bool EndWithFebe(System.Diagnostics.Process process);
}
///
/// The Windows edition's parts of the composition (spec §12, §13.1): the interface on 127.0.0.1 with a port chosen at
/// start-up and a token of this start, the Data folder and the WebView2 runtime checked at start-up, the browser of
/// Instagram in its own window (or, for S2, as a composition visual or as Edge), and the native functions.
///
public sealed class DesktopPlatform : IFebePlatform
{
private readonly DesktopOptions _options;
private readonly IDesktopShell _shell;
private readonly IDataFolderLocationStore _locations;
private readonly bool _dataFolderFixed;
/// The command line.
/// The Windows-only part.
/// Where a move of the Data folder is recorded.
/// True when the Data folder came from --dati: «Cambia…» is not offered.
public DesktopPlatform(DesktopOptions options, IDesktopShell shell, IDataFolderLocationStore locations, bool dataFolderFixed)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
_shell = shell ?? throw new ArgumentNullException(nameof(shell));
_locations = locations ?? throw new ArgumentNullException(nameof(locations));
_dataFolderFixed = dataFolderFixed;
WebOptions = new FebeWebOptions
{
Edition = FebeEdition.Desktop,
Access = AccessMode.Token,
AccessToken = AccessToken,
AllowedHosts = FebeWebOptions.LoopbackHosts(0),
};
}
/// The token of this start: the interface window opens /?gettone=… once. Never logged.
public string AccessToken { get; } = Febe.Web.Security.AccessToken.Create();
public FebeWebOptions WebOptions { get; }
/// 127.0.0.1 only, on a port chosen at start-up.
public FebeListen Listen => FebeListen.Loopback(0);
/// The hosting actually used (after a missing Edge fell back to the window).
public BrowserHosting? Hosting { get; private set; }
/// The address the interface window opens once: the token becomes a cookie and leaves the address.
public Uri FirstAddress(Uri address)
{
ArgumentNullException.ThrowIfNull(address);
return new Uri(address, "/?" + Febe.Web.Security.AccessToken.QueryName + "=" + Uri.EscapeDataString(AccessToken));
}
public IReadOnlyList CheckConfiguration(FebeAppOptions options, DataFolderCheck dataFolderCheck)
{
ArgumentNullException.ThrowIfNull(options);
return DesktopStartupChecks.Run(options.DataFolder, _shell.WebView2Version, dataFolderCheck);
}
public async Task CreateBrowserAsync(FebePlatformContext context, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(context);
var settings = context.Storage.Settings;
BrowserHosting hosting;
if (_options.Hosting is { } chosen)
{
hosting = chosen;
await settings.SetAsync(BrowserHostingNames.SettingKey, BrowserHostingNames.Name(chosen), ct).ConfigureAwait(false);
}
else
{
BrowserHostingNames.TryParse(await settings.GetAsync(BrowserHostingNames.SettingKey, ct).ConfigureAwait(false), out hosting);
}
var profile = context.Data.BrowserProfile;
if (hosting == BrowserHosting.Edge)
{
if (_shell.FindEdge() is { } edge)
{
Hosting = hosting;
context.Log.Info("browser", $"Browser di Febe: Microsoft Edge avviato come processo (ripiego di S2), porta di debug {_options.EdgeDebugPort.ToString(CultureInfo.InvariantCulture)} solo su 127.0.0.1.");
return new EdgeBrowser(CreateEdge(context, edge), _shell, context);
}
context.Log.Warn("browser", "Microsoft Edge non si trova su questo computer: il browser di Febe usa la sua finestra WebView2.");
hosting = BrowserHosting.Window;
}
Hosting = hosting;
context.Log.Info("browser", $"Browser di Febe: WebView2 nella sua finestra ({BrowserHostingNames.Name(hosting)}), fuori vista quando non serve.");
return _shell.CreateWebView2Browser(
new WebView2BrowserSettings(profile, _options.BrowserWidth, _options.BrowserHeight, hosting, BrowserArguments.ForWebView2()),
context);
}
public void RegisterServices(IServiceCollection services, FebeApp app)
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(app);
services.AddSingleton(_shell.Native);
services.AddSingleton(new DesktopBrowserWindow());
services.AddSingleton(new DesktopDataFolderChange(_locations, app.Options.DataFolder, _dataFolderFixed));
}
public void RegisterProblemServices(IServiceCollection services, FebeApp app)
{
ArgumentNullException.ThrowIfNull(services);
services.AddSingleton(_shell.Native);
}
public Task StoppingAsync() => Task.CompletedTask;
///
/// Edge for the last fallback of S2: the same as Docker, with its fixed DevTools
/// port on 127.0.0.1, a profile of its own inside Dati\browser (so «Scollega» deletes both), preferences
/// with password saving and autofill off, and the switches of S2. Every Edge started is tied to the life of
/// Febe.exe (): an Edge left behind by a crash would keep the port, and every
/// later start would find it «occupata».
///
private ChromiumBrowser CreateEdge(FebePlatformContext context, string executable) => new(
new ChromiumBrowserSettings
{
ProfileDirectory = Path.Combine(context.Data.BrowserProfile, "edge"),
ProfileFolderToDelete = context.Data.BrowserProfile,
WindowWidth = _options.BrowserWidth,
WindowHeight = _options.BrowserHeight,
DebugPort = _options.EdgeDebugPort,
ExecutablePath = executable,
Display = null,
Launch = new ChromiumLaunchOptions
{
ExtraArguments = BrowserArguments.ForEdge(),
SessionCookie = _options.Site.SessionCookie,
SeedProfilePreferences = true,
ProcessStarted = process =>
{
if (!_shell.EndWithFebe(process))
{
context.Log.Warn("browser", "Windows non ha legato Edge a Febe: se Febe si chiudesse all'improvviso, Edge resterebbe aperto (chiudilo dal Gestione attività).");
}
},
},
},
context.Clock,
context.Log);
}
///
/// 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 : IBrowserWindow
{
public bool IsSeparateWindow => true;
}
///
/// Edge started as a process (the last fallback of S2): a whose window is moved out of
/// view after every start and brought to the front when Alberto uses it. While it is in front Alberto is driving.
///
public sealed class EdgeBrowser : IFebeBrowser
{
private readonly ChromiumBrowser _inner;
private readonly IDesktopShell _shell;
private readonly FebePlatformContext _context;
private readonly Lock _gate = new();
private IDisposable? _lease;
public EdgeBrowser(ChromiumBrowser inner, IDesktopShell shell, FebePlatformContext context)
{
_inner = inner ?? throw new ArgumentNullException(nameof(inner));
_shell = shell ?? throw new ArgumentNullException(nameof(shell));
_context = context ?? throw new ArgumentNullException(nameof(context));
_inner.Host.Connection.Reconnected += OnRestarted;
}
public ChromiumBrowser Inner => _inner;
public ICdpSession Cdp => _inner.Cdp;
public UserDrivingGate UserDriving => _inner.UserDriving;
public bool UserIsDriving => _inner.UserIsDriving;
public bool IsAvailable => _inner.IsAvailable;
public string? LastError => _inner.LastError;
public string ProfileDirectory => _inner.ProfileDirectory;
public int WindowWidth => _inner.WindowWidth;
public int WindowHeight => _inner.WindowHeight;
public async Task RunAsync(CancellationToken ct)
{
await _inner.RunAsync(ct).ConfigureAwait(false);
if (_inner.IsAvailable)
{
await MoveOutOfViewAsync(ct).ConfigureAwait(false);
}
}
public Task RestAsync(CancellationToken ct) => _inner.RestAsync(ct);
public async Task ShowToUserAsync(CancellationToken ct)
{
lock (_gate)
{
_lease ??= _inner.UserDriving.Begin();
}
_context.Tracker.MarkUsed(_context.Clock.Now);
if (_inner.Host.ProcessId is { } pid)
{
await _shell.ShowProcessWindowAsync(pid, ct).ConfigureAwait(false);
}
}
public async Task HideFromUserAsync(CancellationToken ct)
{
ReleaseLease();
await MoveOutOfViewAsync(ct).ConfigureAwait(false);
}
public Task RestartWithEmptyProfileAsync(CancellationToken ct) => _inner.RestartWithEmptyProfileAsync(ct);
public async ValueTask DisposeAsync()
{
_inner.Host.Connection.Reconnected -= OnRestarted;
ReleaseLease();
await _inner.DisposeAsync().ConfigureAwait(false);
}
private async Task MoveOutOfViewAsync(CancellationToken ct)
{
if (_inner.Host.ProcessId is { } pid)
{
await _shell.HideProcessWindowAsync(pid, ct).ConfigureAwait(false);
}
}
/// Edge restarted (it crashed, or Alberto closed its window): a new window opens on screen, it goes out of view.
private void OnRestarted(object? sender, EventArgs e)
{
ReleaseLease();
_ = Task.Run(async () =>
{
try
{
await MoveOutOfViewAsync(CancellationToken.None).ConfigureAwait(false);
}
catch (Exception ex) when (ex is InvalidOperationException or IOException)
{
_context.Log.Warn("browser", "La finestra di Edge non è andata fuori vista.", ex);
}
});
}
private void ReleaseLease()
{
IDisposable? lease;
lock (_gate)
{
lease = _lease;
_lease = null;
}
if (lease is not null)
{
lease.Dispose();
_context.Tracker.MarkUsed(_context.Clock.Now);
}
}
}