using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Interop;
using Febe.Browser.Cdp;
using Febe.Desktop.Browser;
using Febe.SitoDiProva;
using Febe.Tests.Windows.Support;
using Microsoft.Web.WebView2.Core;
namespace Febe.Tests.Windows;
///
/// The decisions of the window «Browser di Febe» that need no browser (Gitea issue #52): what a failed process of
/// WebView2 asks of the host, and how much a page is shrunk to fit a small screen.
///
[TestClass]
public sealed class BrowserWindowDecisionTests
{
[TestMethod]
public void AFailedProcessIsAnsweredByWhatItBroke()
{
Assert.AreEqual(ProcessFailureResponse.Restart, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.BrowserProcessExited, userIsDriving: false));
Assert.AreEqual(ProcessFailureResponse.Restart, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.BrowserProcessExited, userIsDriving: true));
Assert.AreEqual(ProcessFailureResponse.Rest, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.RenderProcessExited, userIsDriving: true), "a crashed page is gone anyway");
Assert.AreEqual(ProcessFailureResponse.Rest, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.RenderProcessUnresponsive, userIsDriving: false));
Assert.AreEqual(ProcessFailureResponse.None, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.RenderProcessUnresponsive, userIsDriving: true), "never white under Alberto's eyes");
Assert.AreEqual(ProcessFailureResponse.Redraw, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.GpuProcessExited, userIsDriving: false));
Assert.AreEqual(ProcessFailureResponse.Redraw, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.GpuProcessExited, userIsDriving: true));
Assert.AreEqual(ProcessFailureResponse.None, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.UtilityProcessExited, userIsDriving: false));
Assert.AreEqual(ProcessFailureResponse.None, WebView2Host.ResponseTo(CoreWebView2ProcessFailedKind.FrameRenderProcessExited, userIsDriving: true));
}
[TestMethod]
public void APageThatDoesNotFitIsShrunkButNeverBelowTheSmallestFit()
{
// 1280×900 and its bar, in a frame of 16×39.
Assert.AreEqual(1, BrowserWindow.FitFor(1920, 1040, 1280, 900, 16, 39), "a full HD screen: as it is");
Assert.AreEqual(0.72, BrowserWindow.FitFor(1366, 728, 1280, 900, 16, 39), 1e-9, "a small laptop: by the height");
Assert.AreEqual(0.78, BrowserWindow.FitFor(1024, 1200, 1280, 900, 16, 39), 1e-9, "a narrow screen: by the width");
Assert.AreEqual(BrowserWindow.SmallestFit, BrowserWindow.FitFor(400, 300, 1280, 900, 16, 39));
Assert.AreEqual(1, BrowserWindow.FitFor(1366, 728, 0, 0, 16, 39), "no page size: nothing to fit");
}
}
///
/// The window «Browser di Febe» on a real Windows (Gitea issue #52): on screen it has its taskbar button and says when
/// the page is the empty rest page, «Pagina iniziale» opens the start page, the window is never hidden while on screen
/// (WPF hides it to change its taskbar button) and out of view the page is at 100%, and a minimised window keeps Alberto
/// at the wheel until it has been minimised too long. The window comes on screen for a moment.
///
[TestClass]
public sealed class BrowserWindowTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireWebView2() => WebView2Runtime.Require();
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task OnScreenTheWindowHasItsTaskbarButtonAndSaysWhenItRests()
{
var ct = TestContext.CancellationToken;
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
var start = site.Url("/benvenuto");
await using var bed = await BrowserBed.CreateAsync("finestra-pagina-iniziale", startPage: () => start);
await bed.StartAsync(ct);
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar), "out of view, no taskbar button");
// Every hide of the window (SWP_HIDEWINDOW), and those while it is on screen, where Alberto would see it go.
var hides = 0;
var hidesOnScreen = 0;
await bed.OnUiAsync(() =>
{
var source = (HwndSource)PresentationSource.FromVisual(window);
source.AddHook((IntPtr _, int message, IntPtr _, IntPtr data, ref bool _) =>
{
const int WindowPosChanged = 0x0047;
const int HideWindow = 0x0080;
if (message == WindowPosChanged && (System.Runtime.InteropServices.Marshal.ReadInt32(data, (IntPtr.Size * 2) + 16) & HideWindow) != 0)
{
hides++;
if (window.IsOnScreen)
{
hidesOnScreen++;
}
}
return IntPtr.Zero;
});
return true;
});
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
Assert.IsTrue(await bed.OnUiAsync(() => window.IsOnScreen));
Assert.IsTrue(await bed.OnUiAsync(() => window.ShowInTaskbar), "on screen, a taskbar button");
Assert.AreEqual(BrowserWindow.RestNotice, await bed.OnUiAsync(() => window.AddressText), "the empty page says what it is");
Assert.IsGreaterThan(0, await bed.OnUiAsync(() => window.Fit));
// «Pagina iniziale»: Alberto's own navigation, to the start page the composition gives.
await bed.OnUiAsync(() =>
{
Button(window, "Pagina iniziale").RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
return true;
});
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while (await bed.OnUiAsync(() => window.AddressText) != start)
{
Assert.IsLessThan(deadline, DateTime.UtcNow, "la pagina iniziale nella barra: " + bed.Lines.Text);
await Task.Delay(100, ct);
}
Assert.AreEqual(start, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct);
Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar), "out of view again, no taskbar button");
Assert.AreEqual(1.0, await bed.OnUiAsync(() => window.Fit), "out of view the page is at 100%, whatever the screen");
Assert.AreEqual(0, await bed.OnUiAsync(() => hidesOnScreen), $"never hidden on screen ({await bed.OnUiAsync(() => hides)} hides out of view)");
TestContext.WriteLine($"Nascosta fuori vista {await bed.OnUiAsync(() => hides)} volte per il pulsante nella barra delle applicazioni.");
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task PaginaInizialeLastsAsLongAsTheWindowsLease()
{
var ct = TestContext.CancellationToken;
var pressedWith = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
// As the connection while a session ends or a search step holds the page: it waits, here until the press is over.
await using var bed = await BrowserBed.CreateAsync("finestra-pagina-iniziale-chiusa", openStartPage: async token =>
{
pressedWith.TrySetResult(token);
await Task.Delay(Timeout.Infinite, token);
});
await bed.StartAsync(ct);
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
await bed.OnUiAsync(() =>
{
Button(window, "Pagina iniziale").RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
return true;
});
var token = await pressedWith.Task.WaitAsync(TimeSpan.FromSeconds(30), ct);
Assert.IsFalse(token.IsCancellationRequested, "the window is still on screen");
// Alberto closes the window before the start page opened: the press is over with the window's lease.
await bed.OnUiAsync(() =>
{
window.Close();
return true;
});
Assert.IsFalse(bed.Browser.UserIsDriving);
await bed.WaitUntilAsync(() => token.IsCancellationRequested, TimeSpan.FromSeconds(10), "la fine della «Pagina iniziale» con la finestra", ct);
Assert.IsFalse(bed.Lines.Any("non aperta"), "a press given up is no failure: " + bed.Lines.Text);
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task AMinimisedWindowKeepsAlbertoAtTheWheelUntilItIsMinimisedTooLong()
{
var ct = TestContext.CancellationToken;
await using var bed = await BrowserBed.CreateAsync("finestra-ridotta");
await bed.StartAsync(ct);
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
await bed.OnUiAsync(() => window.MinimizedLimit = TimeSpan.FromSeconds(1));
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
await bed.OnUiAsync(() => window.WindowState = WindowState.Minimized);
Assert.IsTrue(bed.Browser.UserIsDriving, "minimised is not «ho finito»: its taskbar button brings it back");
Assert.IsTrue(await bed.OnUiAsync(() => window.ShowInTaskbar));
// Left there: restored and put out of view, as if closed (S2: never minimised for long).
await bed.WaitUntilAsync(() => !bed.Browser.UserIsDriving, TimeSpan.FromSeconds(15), "la fine della guida dopo la finestra ridotta a icona", ct);
Assert.AreEqual(WindowState.Normal, await bed.OnUiAsync(() => window.WindowState));
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar));
// Brought back before the limit, it stays Alberto's.
await bed.OnUiAsync(() => window.MinimizedLimit = TimeSpan.FromMinutes(2));
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
await bed.OnUiAsync(() => window.WindowState = WindowState.Minimized);
await bed.OnUiAsync(() => window.WindowState = WindowState.Normal);
await Task.Delay(1500, ct);
Assert.IsTrue(bed.Browser.UserIsDriving);
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct);
}
[TestMethod]
[Timeout(240_000, CooperativeCancellation = true)]
public async Task LeavingThePageOfFebeLeavesTheWindowOnScreenWithItsPage()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopBed.StartAsync("finestra-resta", autoLogin: false, ct);
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
var connection = bed.App.Connection!;
var browser = bed.Browser;
var window = await bed.Ui.InvokeAsync(() => browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
// «Usa il browser» on the rest page, not connected: the login page of the test site, never a white window.
await connection.BeginUserDrivingAsync(openLogin: false, ct);
var opened = (await connection.GetStatusAsync(ct)).CurrentUrl;
StringAssert.StartsWith(opened, bed.Site.Url("/benvenuto"));
Assert.IsTrue(await bed.Ui.InvokeAsync(() => window.IsOnScreen));
// The page of Febe goes (another page, the tab closed): the window stays, with its page and the engine still.
await connection.ReleaseAsync(ct);
await Task.Delay(1500, ct);
Assert.IsTrue(await bed.Ui.InvokeAsync(() => window.IsOnScreen), "still on screen");
Assert.IsTrue(browser.UserIsDriving, "the window on screen holds the engine");
Assert.AreEqual(opened, (await connection.GetStatusAsync(ct)).CurrentUrl, "its page as it was");
Assert.IsTrue(bed.Lines.Any("Pagina di Febe lasciata: la finestra del browser resta com'è finché non la chiudi."), bed.Lines.Text);
// Closed with its X: out of view, the engine may work again.
await bed.Ui.InvokeAsync(() =>
{
window.Close();
return true;
});
await bed.WaitUntilAsync(() => Task.FromResult(!browser.UserIsDriving), TimeSpan.FromSeconds(10), "la fine della guida dopo la chiusura", ct);
Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen));
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
}
private static Button Button(DependencyObject root, string text) =>
FindOrNull(root, text) ?? throw new AssertFailedException($"Nessun pulsante «{text}» nella finestra.");
private static Button? FindOrNull(DependencyObject root, string text)
{
foreach (var child in LogicalTreeHelper.GetChildren(root).OfType())
{
if (child is Button { Content: string content } button && content == text)
{
return button;
}
if (FindOrNull(child, text) is { } found)
{
return found;
}
}
return null;
}
}