using Cosmos.Kernel.System;
using Cosmos.Kernel.System.Diagnostics;
using Cosmos.Kernel.System.Input;
using ConsoleKeyEx = Cosmos.Kernel.System.Input.Key;
using XFESystem.Core;
using XFESystem.Desktop;
using XFESystem.ConsoleDemo;
using XFESystem.Console;
using XFESystem.ManagedRuntime;
using XFESystem.Browser;
using System.Text;
using Cosmos.Kernel.System.Network;
using Cosmos.Kernel.System.Timers;
using System.Diagnostics;
namespace XFESystem.Kernel;
/// <summary>NativeAOT bare-metal kernel with explicit, bounded managed application compatibility.</summary>
public sealed class Kernel : Cosmos.Kernel.System.Kernel
{
private DesktopSession? desktop;
private TerminalSnapshot? demonstration;
private int lastWindow;
private MemoryWorkspace? workspace;
private CanvasAdapter? display;
private FramePacer? framePacer;
private readonly NativeDesktopInput desktopInput = new();
private string lastWindowState = "";
private long lastRenderReport;
private long lastChromeFrameReport;
private string lastChromeFrame = "";
private bool previousLeftButton;
private string lastBrowserState = "";
private long lastBrowserStateReport;
private string lastBrowserInput = "";
private long lastBrowserProofRevision = -1, lastBrowserProofReport;
private int lastBrowserProofWindow;
private string lastMonacoProof = "";
private bool lastPointerReportLeft;
private NativeManagedWorkScheduler? editorWorker;
private System.Threading.Thread? uiThread;
private const string ManagedDemoPath = "X:\\Programs\\ManagedHello\\ManagedHello.dll";
// Only the bounded serial byte write masks interrupts; formatting and all
// kernel/network work happen before entering the runtime's atomic log API.
private static void WriteDiagnostic(string message) => Log.WriteBytes(Encoding.UTF8.GetBytes("\n" + message));
protected override void BeforeRun()
{
desktopInput.Trace = WriteDiagnostic;
desktopInput.NavigationDispatched = () =>
{
// Navigation diagnostics inspect only the UI-owned Browser. The
// background editor proxy never exposes its worker-owned engine.
if (desktop?.ActiveWindow is { Application: DesktopApplication.Browser, BrowserSession: BrowserService navigation } &&
Uri.TryCreate(navigation.CurrentPage.Address, UriKind.Absolute, out var address) && BrowserService.IsMonacoAddress(address))
WriteDiagnostic("XFE_NATIVE_NAV_SELECTION_BEGIN\n" + navigation.ReadEditorNavigationProof() + "\nXFE_NATIVE_NAV_SELECTION_END\n");
};
NativeKeyboardCapture.Prepare();
NativePointerCapture.Prepare();
NativeNvidiaDiscovery.Report(WriteDiagnostic);
WriteDiagnostic("XFE_CSHARP_NATIVEAOT_BOOT_OK\n");
int documentTextResources = XFESystem.Documents.WebsiteAssets.PrewarmTextResources();
int browserTextResources = PackagedBrowserResources.PrewarmTextResources();
WriteDiagnostic("XFE_PACKAGED_TEXT_PREWARM|Documents|" + documentTextResources + "|Browser|" + browserTextResources + "|Immutable|1\n");
if (!RuntimeVarianceRegression.Run())
throw new InvalidOperationException("The managed generic variance runtime regression failed.");
WriteDiagnostic("XFE_RUNTIME_VARIANCE_OK\n");
WriteDiagnostic("XFE_GC_DEEP_BEGIN\n");
bool deepGc = NativeGcRegression.Run();
WriteDiagnostic("XFE_GC_DEEP_RESULT|" + deepGc + "|Frames|"+NativeGcRegression.FramesVerified+"|Collections|"+NativeGcRegression.CollectionsRequested+"|FailureDepth|"+NativeGcRegression.FailureDepth+"\n");
if (!deepGc) throw new InvalidOperationException("The native deep-stack GC root regression failed.");
WriteDiagnostic("XFE_EH_DEEP_RETHROW_BEGIN\n");
if (!NativeEhRegression.Run())
throw new InvalidOperationException("The native deep catch/rethrow recovery regression failed.");
WriteDiagnostic("XFE_EH_DEEP_RETHROW_OK|Frames|" + NativeEhRegression.FramesCaught + "|Post|" + NativeEhRegression.PostCatchFrames + "\n");
WriteDiagnostic("XFE_THREAD_EH_GC_BEGIN\n");
bool threadRuntimeReady = NativeThreadRegression.Run();
WriteDiagnostic("XFE_THREAD_EH_GC_RESULT|" + threadRuntimeReady + "|Steps|" + NativeThreadRegression.Steps + "|Collections|" + NativeThreadRegression.Collections + "|SingleCpu|1|GcStopTheWorld|1\n");
WriteDiagnostic("XFE_THREAD_PREEMPTION|Checks|" + NativeThreadRegression.PreemptionChecks + "|FirstId|" + NativeThreadRegression.FirstThreadId + "|SecondId|" + NativeThreadRegression.SecondThreadId + "|FirstFailure|" + NativeThreadRegression.FirstFailure + "|SecondFailure|" + NativeThreadRegression.SecondFailure + "\n");
WriteDiagnostic("XFE_THREAD_TLS|Checks|" + NativeThreadRegression.ThreadStaticChecks + "|FirstManagedId|" + NativeThreadRegression.FirstManagedThreadId + "|SecondManagedId|" + NativeThreadRegression.SecondManagedThreadId + "|OrdinaryThreadsOnly|1\n");
if (!threadRuntimeReady)
{
WriteDiagnostic("[FAILFAST] Native thread EH/GC/preemption contract failed; background work and desktop startup remain disabled.\n");
while (true) Power.Halt();
}
RunConsoleDemo();
workspace = new MemoryWorkspace();
workspace.WriteText(SystemPaths.Combine(SystemPaths.Documents, "Readme.md"),
"# XFESystem Markdown\n\n**Website renderer** is active.\n\n- C# desktop\n- JavaScript preview\n");
workspace.WriteText(SystemPaths.Combine(SystemPaths.Documents, "WebsiteParity.md"), XFESystem.Documents.WebsiteAssets.ReadText("Fixtures/WebsiteParity.md"));
workspace.WriteText(SystemPaths.Combine(SystemPaths.Documents, "ZCSharp.cs"), "using System;\nnamespace XFEstudio;\npublic sealed class Preview\n{\n public string Message { get; set; } = \"Hello XFESystem\";\n public static int Run(int value)\n {\n if (value > 0) return Math.Max(value, 42);\n Console.WriteLine(\"Ready\");\n return 0;\n }\n}");
workspace.CreateDirectory("X:\\Programs\\ManagedHello");
using (var application = typeof(Kernel).Assembly.GetManifestResourceStream("XFESystem.Programs.ManagedHello.dll")
?? throw new InvalidOperationException("The independent C# example assembly is missing."))
{
var bytes = new byte[application.Length];
application.ReadExactly(bytes);
workspace.WriteBytes(ManagedDemoPath, bytes);
}
RunManagedApplicationCore(ManagedDemoPath, verifyDemonstration: true);
InitializeNetwork();
WriteDiagnostic("XFE_BROWSER_CONSTRUCT_BEGIN\n");
var browser = new BrowserService(new NativeWebTransport()) { Trace = WriteDiagnostic };
WriteDiagnostic("XFE_BROWSER_CONSTRUCT_OK\nXFE_BROWSER_NAVIGATE_BEGIN\n");
var constrainedJavaScript = new JavaScriptRuntime(new BrowserLimits { MaximumStatements = 50 });
if (constrainedJavaScript.Evaluate("while (true) {}").Success)
throw new InvalidOperationException("The guest JavaScript statement budget was not enforced.");
var recoveredJavaScript = constrainedJavaScript.Evaluate("6 * 7");
if (!recoveredJavaScript.Success || recoveredJavaScript.Text != "42")
throw new InvalidOperationException("The guest JavaScript runtime could not recover after its statement limit.");
WriteDiagnostic("XFE_JAVASCRIPT_LIMIT_RECOVERY_OK\n");
var page = browser.Navigate("about:Start");
BrowserNativeEventRegression.Run(browser,WriteDiagnostic);
WriteDiagnostic("XFE_BROWSER_NAVIGATE_OK\n");
if (!page.Text.Contains("JavaScript ready: 12", StringComparison.Ordinal))
throw new InvalidOperationException("The guest browser JavaScript/DOM test failed: " + page.Text);
WriteDiagnostic("XFE_BROWSER_MARKDOWN_BEGIN\n");
var markdown = browser.PreviewMarkdown("# XFESystem\n\n**Markdown** from the website renderer.");
if (!markdown.Contains("Markdown", StringComparison.Ordinal))
throw new InvalidOperationException("The guest Markdown preview test failed.");
WriteDiagnostic("XFE_CSHARP_JAVASCRIPT_DOM_OK\nXFE_CSHARP_MARKDOWN_OK\n");
var canvas = new CanvasAdapter();
display = canvas;
editorWorker = new NativeManagedWorkScheduler(WriteDiagnostic, canvas.ScalePercent / 100);
IEditorPreparationService editorPreparation = new BrowserEditorPreparationService(browser, editorWorker, editorWorker, WriteDiagnostic, NativeThreadRegression.CurrentThreadId, monotonicMilliseconds: MonotonicMilliseconds);
WriteDiagnostic("XFE_WEB_FONT_METRICS|" + canvas.WebFontMetricsEvidence + "\n");
MouseManager.SetScreenSize(canvas.NativeWidth, canvas.NativeHeight);
MouseManager.SetPosition(canvas.NativeWidth / 2, canvas.NativeHeight / 2);
var monitor = NativeDisplayInfo.Read(canvas.NativeWidth, canvas.NativeHeight);
int refreshTarget = canvas.DriverRefreshHz > 0 ? canvas.DriverRefreshHz * 1000 :
monitor.Timing.HasAdvertisedTiming ? monitor.Timing.AdvertisedRefreshMilliHz : 60_000;
framePacer = new FramePacer(Stopwatch.Frequency, refreshTarget);
// Wake the input/render loop often enough to service high-refresh input.
// This is a timer cadence, not a claim of display scanout or VSync.
if (TimerManager.IsInitialized && TimerManager.Frequency < 1000) TimerManager.Frequency = 1000;
desktop = new DesktopSession(canvas, workspace, browser, consoleDemo: () => RunManagedApplication(ManagedDemoPath), managedApplication: RunManagedApplication,
monotonicMilliseconds: MonotonicMilliseconds, editorPreparation: editorPreparation, threadIdentity: NativeThreadRegression.CurrentThreadId) { Trace = WriteDiagnostic };
desktop.Pointer(canvas.ToLayout(MouseManager.X), canvas.ToLayout(MouseManager.Y), false);
while (NativePointerCapture.TryRead(out _)) { }
desktop.PointerReportsLost(canvas.ToLayout(MouseManager.X),canvas.ToLayout(MouseManager.Y),MouseManager.LeftButton,MonotonicMilliseconds());
desktop.Render();
WriteDiagnostic("XFE_RENDER_BACKEND|Rasterization|CPU|GpuAcceleration|0|CudaAcceleration|0|Reason|No initialized native GPU or CUDA command backend\n");
WriteDiagnostic("XFE_MONITOR_TIMING|" + monitor.Timing.AdvertisedRefreshMilliHz + "|TargetMilliHz|" + refreshTarget +
"|DriverConfirmedHz|" + canvas.DriverRefreshHz + "|VSync|0|Origin|" + monitor.Origin + "|" + monitor.Timing.Source + "\n");
WriteDiagnostic("XFE_INPUT_RAW_HOOK_EXPECTED\n");
WriteDiagnostic("XFE_DISPLAY_NATIVE|" + canvas.NativeWidth + "|" + canvas.NativeHeight +
"|ScalePercent|" + canvas.ScalePercent + "\n");
WriteDiagnostic("XFE_CSHARP_DESKTOP_READY\n");
}
private static void InitializeNetwork()
{
// Driver-kit workers publish adapters asynchronously. The manager itself
// is initialized by Cosmos before the driver stage, not by this kernel.
for (var elapsed = 0; elapsed < 5_000 &&
(NetworkManager.DeviceCount == 0 || !NetworkManager.Ready || !NetworkManager.LinkUp); elapsed += 10)
TimerManager.Wait(10);
if (NetworkManager.DeviceCount == 0 || !NetworkManager.Ready || !NetworkManager.LinkUp)
{
WriteDiagnostic("XFE_NETWORK_UNAVAILABLE\n");
return;
}
try
{
var dhcp = new DhcpClient();
try { dhcp.SendDiscoverPacket(); }
catch { dhcp.Close(); throw; }
dhcp.Close();
if (NetworkManager.Primary.IPConfig is { } config && !config.Address.IsZero)
{
WriteDiagnostic("XFE_NETWORK_DHCP_OK|" + config.Address + "|DnsServers|" + DnsConfig.Nameservers.Count + "\n");
}
else WriteDiagnostic("XFE_NETWORK_DHCP_FAILED\n");
}
catch (Exception error) when (error is not OutOfMemoryException and not StackOverflowException)
{
WriteDiagnostic("XFE_NETWORK_DHCP_FAILED|" + error.Message + "\n");
}
}
protected override void Run()
{
if (!NativeThreadRegression.Passed) { WriteDiagnostic("[FAILFAST] The native desktop requires its verified thread runtime.\n"); while (true) Power.Halt(); }
// The boot thread is the scheduler's idle fallback. A CPU-bound worker
// would starve it, so the UI must itself be an ordinary runnable thread.
uiThread = new System.Threading.Thread(RunDesktopLoop, NativeManagedWorkScheduler.StackBytes);
uiThread.Start();
while (true) Power.Halt();
}
private void RunDesktopLoop()
{
WriteDiagnostic("XFE_DESKTOP_UI_THREAD|" + NativeThreadRegression.CurrentThreadId() + "|StackBytes|" + NativeManagedWorkScheduler.StackBytes + "\n");
while (true)
{
if (desktop is { } session)
{
long inputMilliseconds = MonotonicMilliseconds();
if (MouseManager.ScrollDelta != 0) MouseManager.ResetScrollDelta();
bool leftButton = MouseManager.LeftButton, processedKey = false;
NativePointerReport? pendingMotion = null;
bool packetLeft = lastPointerReportLeft;
// Bound one drain so continuous input cannot starve rendering,
// animation, keyboard handling or diagnostics.
int pointerBudget = 64;
while (pointerBudget-- > 0 && NativePointerCapture.TryRead(out var pointerReport))
{
if (pointerReport.LostReports)
{
pendingMotion = null; packetLeft = leftButton;
session.PointerReportsLost(display!.ToLayout(MouseManager.X),display.ToLayout(MouseManager.Y),leftButton,inputMilliseconds);
WriteDiagnostic("XFE_POINTER_REPORTS_LOST\n"); continue;
}
if (pointerReport.LeftButton == packetLeft && pointerReport.Wheel == 0) { pendingMotion = pointerReport; continue; }
if (pendingMotion is { } motion) { DispatchPointer(session,motion); pendingMotion = null; }
DispatchPointer(session,pointerReport); packetLeft = pointerReport.LeftButton;
}
if (pendingMotion is { } finalMotion) DispatchPointer(session,finalMotion);
// Preserve the upstream queue for its other consumers but drain
// our copy: desktop input must include modifier break reports.
while (KeyboardManager.TryReadKey(out _)) { }
while (NativeKeyboardCapture.TryRead(out var scanCode, out var released, out var lostReports))
if (desktopInput.Translate(scanCode, released, lostReports, session, out var character) is { } mapped)
{
processedKey = true;
session.Key(mapped, character);
if (mapped == DesktopKey.Enter && session.ActiveWindow is { Application: DesktopApplication.Browser } navigated)
{
// WriteBytes is the runtime's atomic serial protocol API.
// The plain string logger truncates UTF-16 to bytes and
// permits IRQ logs to split acceptance frame markers.
var body = navigated.Content.Length <= 4_096 ? navigated.Content : navigated.Content[..4_096];
var report = "XFE_BROWSER_NAVIGATED|" + navigated.Location +
"\nXFE_BROWSER_TEXT_BEGIN\n" + body + "\nXFE_BROWSER_TEXT_END\n";
if (navigated.Content.Contains("中文 HTTP 正文", StringComparison.Ordinal))
report += "XFE_BROWSER_UTF8_BODY_OK\n";
WriteDiagnostic(report);
}
if (mapped == DesktopKey.Save && session.ActiveWindow is { IsDirty: false } saved &&
saved.BrowserSession is not IBackgroundEditorSession)
{
WriteDiagnostic("XFE_DESKTOP_SAVED|" + saved.Location + "|" + saved.Content.Length + "\n");
}
}
// Already queued input takes priority over a cooperative page
// loading phase. In particular Win+D/close can hide or remove
// the page before an indivisible script evaluation starts.
session.AdvanceFeedback(inputMilliseconds);
var active = session.ActiveWindow;
bool activeChanged = (active?.Id ?? 0) != lastWindow;
// A queued readback can open a preview without another input
// report. Publish its actual geometry before any DOM evidence.
if (activeChanged) ReportWindowState(session);
if (active is { BrowserSession: not null }) ReportBrowserState(active);
if (activeChanged)
{
lastWindow = active?.Id ?? 0;
WriteDiagnostic("XFE_DESKTOP_ACTIVE|" + (active?.Application.ToString() ?? "Desktop") + "\n");
if (active is { Application: DesktopApplication.Browser })
{
if (active.Content.Contains("JavaScript ready: 12", StringComparison.Ordinal))
WriteDiagnostic("XFE_BROWSER_START_DOM_RENDER_OK\n");
if (active.Content.Contains("Hello from XFESystem!", StringComparison.Ordinal))
WriteDiagnostic("XFE_EDITOR_JAVASCRIPT_PREVIEW_OK\n");
if (active.Content.Contains("Website renderer", StringComparison.Ordinal))
WriteDiagnostic("XFE_EDITOR_MARKDOWN_PREVIEW_OK\n");
}
}
if (!leftButton && (processedKey || previousLeftButton || lastWindowState.Length == 0)) ReportWindowState(session);
previousLeftButton = leftButton;
long now = Stopwatch.GetTimestamp();
if (framePacer!.ShouldRender(now, session.NeedsRender))
{
session.Render();
if (session.LastFrameCompleted)
{
framePacer.Rendered(now, Stopwatch.GetTimestamp());
ReportChromeFrame(session, now);
}
}
if (now - lastRenderReport >= Stopwatch.Frequency)
{
lastRenderReport = now;
WriteDiagnostic("XFE_RENDER_STATS|" + now + "|Frames|" + framePacer.FramesRendered + "|Partial|" + display!.PartialFrames +
"|Pixels|" + display.PixelsPresented + "|Glyphs|" + display.CachedGlyphCount + "|Fallback|" + display.FullCopyFallbackFrames +
"|LastRenderTicks|" + framePacer.LastRenderDurationTicks + "|Frequency|" + Stopwatch.Frequency +
"|MotionReuses|" + display.MotionReuseCount + "|MotionPixels|" + display.MotionPixelsReused +
"|ScanoutPixelsSaved|" + display.ScanoutPixelsSaved + "|RenderYields|" + session.RenderYieldCount +
"|RawFreePages|" + NativeRuntimeMemoryDiagnostics.FreePages() + "|RawTotalPages|" + NativeRuntimeMemoryDiagnostics.TotalPages() +
"|RawLargestFreeRunPages|" + NativeRuntimeMemoryDiagnostics.LargestFreeRunPages() + "\n");
if (active?.BrowserSession is BrowserService measuredPage)
WriteDiagnostic("XFE_WEB_WORK|Window|" + active.Id + "|Layout|" + measuredPage.LayoutPassCount +
"|ScrollReuse|" + measuredPage.ScrollLayoutReuseCount + "|Raster|" + measuredPage.RasterPaintCount +
"|CachedPaint|" + measuredPage.CachedPaintCount + "|AstHits|" + measuredPage.PackagedScriptCacheHits +
"|AstPrepared|" + measuredPage.PackagedScriptPreparations + "\n");
else if (active?.BrowserSession is IBackgroundEditorSession backgroundPage)
{
var published = backgroundPage.Diagnostics;
WriteDiagnostic("XFE_WEB_WORK|Window|" + active.Id + "|Layout|" + published.LayoutPassCount +
"|ScrollReuse|" + published.ScrollLayoutReuseCount + "|Raster|" + backgroundPage.RasterPaintCount +
"|CachedPaint|" + backgroundPage.CachedPaintCount + "|AstHits|" +
published.PackagedScriptCacheHits + "|AstPrepared|" + published.PackagedScriptPreparations +
"|EngineThread|" + published.WorkerThreadId + "|PaintSource|Snapshot\n");
}
}
}
Power.Halt();
}
}
private static long MonotonicMilliseconds() => (long)(Stopwatch.GetTimestamp() / (double)Stopwatch.Frequency * 1000);
private void DispatchPointer(DesktopSession session,NativePointerReport report)
{
int x = display!.ToLayout(report.X), y = display.ToLayout(report.Y);
bool released = lastPointerReportLeft && !report.LeftButton;
// Button transitions are enough for click evidence. Per-wheel serial
// formatting at high input rates would distort the measured rendering.
if (report.LeftButton != lastPointerReportLeft)
{
lastPointerReportLeft = report.LeftButton;
WriteDiagnostic("XFE_NATIVE_POINTER|X|" + x + "|Y|" + y + "|Left|" + (report.LeftButton ? 1 : 0) +
"|Wheel|" + report.Wheel + "|Ticks|" + report.TimestampTicks + "\n");
}
session.Pointer(x,y,report.LeftButton,report.Wheel,(long)(report.TimestampTicks/(double)Stopwatch.Frequency*1000));
// A complete down/move/up can be drained in one UI iteration. The
// MouseManager snapshot taken before that drain may already be up,
// so publish final bounds from the actual release transition.
if (released) ReportWindowState(session);
}
private void ReportBrowserState(DesktopWindow window)
{
long now = MonotonicMilliseconds();
// Background editors publish immutable diagnostics. Never unwrap their
// engine or ask a worker-owned BrowserService to acquire its page gate.
var background = window.BrowserSession as IBackgroundEditorSession;
var published = background?.Diagnostics;
string? inputTrace = window.BrowserSession is BrowserService traced ? traced.LastInputTrace : published?.LastInputTrace;
if (inputTrace is not null && inputTrace != lastBrowserInput)
{ lastBrowserInput = inputTrace; WriteDiagnostic("XFE_BROWSER_INPUT|" + lastBrowserInput + "\n"); }
if (window.BrowserSession is BrowserService documentBrowser && now - lastBrowserProofReport >= 500 &&
(lastBrowserProofWindow != window.Id || lastBrowserProofRevision != documentBrowser.Revision))
{
lastBrowserProofWindow = window.Id; lastBrowserProofRevision = documentBrowser.Revision; lastBrowserProofReport = now;
var documentProof = documentBrowser.ReadWebsiteDocumentProof();
if (documentProof != "{}") WriteDiagnostic("XFE_WEBSITE_DOCUMENT_PROOF_BEGIN\n" + documentProof + "\nXFE_WEBSITE_DOCUMENT_PROOF_END\n");
if (Uri.TryCreate(documentBrowser.CurrentPage.Address, UriKind.Absolute, out var proofUri) && BrowserService.IsMonacoAddress(proofUri))
{
// Background tokenization can change span classes without changing
// textContent. Read real view state after each changed revision.
var colorProof = documentBrowser.ReadMonacoProof();
if (colorProof != "{}" && colorProof != lastMonacoProof)
{ lastMonacoProof = colorProof; WriteDiagnostic("XFE_MONACO_CSHARP_PROOF_BEGIN\n" + colorProof + "\nXFE_MONACO_CSHARP_PROOF_END\n"); }
}
}
else if (background is not null && published is not null && now - lastBrowserProofReport >= 500 &&
(lastBrowserProofWindow != window.Id || lastBrowserProofRevision != background.Revision))
{
lastBrowserProofWindow = window.Id; lastBrowserProofRevision = background.Revision; lastBrowserProofReport = now;
string colorProof = published.MonacoProof;
if (colorProof != "{}" && colorProof != lastMonacoProof)
{ lastMonacoProof = colorProof; WriteDiagnostic("XFE_MONACO_CSHARP_PROOF_BEGIN\n" + colorProof + "\nXFE_MONACO_CSHARP_PROOF_END\n"); }
}
if (now - lastBrowserStateReport < 200) return;
lastBrowserStateReport = now;
var body = window.Content.Length <= 4096 ? window.Content : window.Content[..4096];
string state = window.Id + "|" + window.Location + "\n" + body;
if (state == lastBrowserState) return;
lastBrowserState = state;
WriteDiagnostic("XFE_BROWSER_STATE_BEGIN\n" + state + "\nXFE_BROWSER_STATE_END\n");
if (background is not null || window.BrowserSession is BrowserService browser && Uri.TryCreate(browser.CurrentPage.Address, UriKind.Absolute, out var browserUri) && BrowserService.IsMonacoAddress(browserUri) &&
(window.Application == DesktopApplication.Editor || body.Contains("Official Monaco 0.52.2 - ready", StringComparison.Ordinal) || body.Contains("Monaco - edited", StringComparison.Ordinal) || body.Contains("Monaco C# - website grammar and palette", StringComparison.Ordinal)))
{
var value = window.BrowserSession!.ReadEditorText() ?? "Editor unavailable";
WriteDiagnostic("XFE_MONACO_VALUE_BEGIN\n" + value + "\nXFE_MONACO_VALUE_END\n");
}
}
private void ReportChromeFrame(DesktopSession session, long now)
{
if (now - lastChromeFrameReport < Stopwatch.Frequency / 25) return;
var active = session.ActiveWindow;
if (active is null) return;
var chrome = active.ChromeAnimation;
string state = "XFE_CHROME_FRAME|" + active.Id + "|Min|" + (int)Math.Round(chrome.MinimizeProgress * 1000) +
"|Close|" + (int)Math.Round(chrome.CloseProgress * 1000) + "|Title|" + (int)Math.Round(chrome.TitleHintProgress * 1000) +
"|Resize|" + (int)Math.Round(chrome.ResizeProgress * 1000);
if (state == lastChromeFrame) return;
lastChromeFrame = state; lastChromeFrameReport = now;
WriteDiagnostic(state + "\n");
}
private void ReportWindowState(DesktopSession session)
{
string report = "XFE_DESKTOP_FLAGS|" + (session.IsStartMenuOpen ? 1 : 0) + "|" + (session.IsWindowSwitching ? 1 : 0) +
"|Active|" + (session.ActiveWindow?.Id ?? 0) + "\n" +
"XFE_DESKTOP_APPEARANCE|" + session.Theme.Mode + "|" + session.Theme.Accent.ToString("X6") +
"|Persistent|" + (session.IsAppearancePersistent ? 1 : 0) + "\n";
foreach (var window in session.Windows)
{
var b = window.Bounds;
report += "XFE_WINDOW_STATE|" + window.Id + "|" + window.Application + "|" + b.X + "|" + b.Y + "|" + b.Width + "|" + b.Height +
"|" + (window.IsMinimized ? 1 : 0) + "|" + (window.IsMaximized ? 1 : 0) + "|" + (window.IsSnapped ? 1 : 0) + "\n";
}
if (report == lastWindowState) return;
lastWindowState = report; WriteDiagnostic(report);
}
private void RunConsoleDemo()
{
var buffer = new TerminalBuffer(90, 18);
var writer = new TerminalTextWriter(buffer);
ConsoleDemoScenario.Run(writer);
ConsoleDemoScenario.RunXfeConsoleApi(writer);
writer.Complete();
demonstration = writer.Snapshot();
if (!buffer.GetText().Contains(ConsoleDemoScenario.SuccessMarker, StringComparison.Ordinal))
throw new InvalidOperationException("The guest console application did not complete.");
if (!buffer.GetText().Contains("XFEConsole API: Real NuGet 2.6.0", StringComparison.Ordinal))
throw new InvalidOperationException("The real XFEConsole API did not write to the guest terminal.");
var rgb = buffer.GetCell(0, 1).Style.Foreground;
if (rgb != TerminalColor.ThemeForeground)
throw new InvalidOperationException("The guest ANSI true color output was not preserved.");
ConsoleDemoScenario.RunSystemConsoleColors();
var previousForeground = global::System.Console.ForegroundColor;
global::System.Console.ForegroundColor = ConsoleColor.Cyan;
if (global::System.Console.ForegroundColor != ConsoleColor.Cyan)
throw new InvalidOperationException("The guest Console color PAL did not preserve its state.");
global::System.Console.ForegroundColor = previousForeground;
desktop?.SetTerminalSnapshot(demonstration);
WriteDiagnostic("XFE_CSHARP_CONSOLE_DEMO_OK\nXFE_CSHARP_ANSI_RGB_OK\nXFE_CSHARP_CONSOLE_PAL_COLOR_OK\nXFE_CSHARP_XFECONSOLE_API_OK\n");
}
private void RunManagedApplication(string path)
{
try { RunManagedApplicationCore(path); }
catch (Exception error) when (error is not OutOfMemoryException and not StackOverflowException)
{
var buffer = new TerminalBuffer(90, 18);
buffer.Write("The program cannot run in this compatibility profile.\r\n" + error.Message);
desktop?.SetTerminalSnapshot(buffer.Snapshot());
WriteDiagnostic("XFE_MANAGED_APP_REJECTED\n");
}
}
private void RunManagedApplicationCore(string path, bool verifyDemonstration = false)
{
var bytes = (workspace ?? throw new InvalidOperationException("The workspace is not initialized.")).ReadBytes(path);
var buffer = new TerminalBuffer(90, 18);
var writer = new TerminalTextWriter(buffer);
var result = new ManagedApplicationRunner().Execute(bytes, new TerminalManagedConsole(writer));
writer.Complete();
bool demonstrationSucceeded = result.ExitCode == 0 &&
buffer.GetText().Contains("XFE_MANAGED_APP_OK", StringComparison.Ordinal) &&
buffer.GetText().Contains("XFE_MANAGED_XFECONSOLE_OK", StringComparison.Ordinal) &&
buffer.GetCell(0, 1).Style.Foreground == TerminalColor.ThemeForeground;
if (verifyDemonstration && !demonstrationSucceeded)
throw new InvalidOperationException("The independent C# example assembly did not complete its console/ANSI scenario.");
desktop?.SetTerminalSnapshot(buffer.Snapshot());
if (demonstrationSucceeded)
WriteDiagnostic("XFE_MANAGED_APP_OK\nXFE_MANAGED_XFECONSOLE_OK\nXFE_MANAGED_ANSI_RGB_OK\n");
WriteDiagnostic("XFE_MANAGED_APPLICATION_EXIT|" + result.AssemblyName + "|" + result.ExitCode + "\n");
WriteDiagnostic("XFE_MANAGED_IL_INSTRUCTIONS|" + result.Instructions + "|InteropCalls|" + result.InteropCalls + "\n");
}
private static DesktopKey? MapKey(KeyEvent key)
{
if ((key.Modifiers & ConsoleModifiers.Control) != 0 && key.Key == ConsoleKeyEx.S)
return DesktopKey.Save;
if ((key.Modifiers & ConsoleModifiers.Control) != 0 && key.Key == ConsoleKeyEx.L)
return DesktopKey.FocusAddress;
return key.Key switch
{
ConsoleKeyEx.Enter => DesktopKey.Enter,
ConsoleKeyEx.Backspace => DesktopKey.Backspace,
ConsoleKeyEx.Delete => DesktopKey.Delete,
ConsoleKeyEx.LeftArrow => DesktopKey.Left,
ConsoleKeyEx.RightArrow => DesktopKey.Right,
ConsoleKeyEx.UpArrow => DesktopKey.Up,
ConsoleKeyEx.DownArrow => DesktopKey.Down,
ConsoleKeyEx.Home => DesktopKey.Home,
ConsoleKeyEx.End => DesktopKey.End,
ConsoleKeyEx.Tab => DesktopKey.Tab,
ConsoleKeyEx.Escape => DesktopKey.Escape,
ConsoleKeyEx.F5 => DesktopKey.Run,
_ => key.KeyChar >= ' ' ? DesktopKey.Character : null
};
}
}
using Cosmos.Kernel.System;
using Cosmos.Kernel.System.Diagnostics;
using Cosmos.Kernel.System.Input;
using ConsoleKeyEx = Cosmos.Kernel.System.Input.Key;
using XFESystem.Core;
using XFESystem.Desktop;
using XFESystem.ConsoleDemo;
using XFESystem.Console;
using XFESystem.ManagedRuntime;
using XFESystem.Browser;
using System.Text;
using Cosmos.Kernel.System.Network;
using Cosmos.Kernel.System.Timers;
using System.Diagnostics;
namespace XFESystem.Kernel;
/// <summary>NativeAOT bare-metal kernel with explicit, bounded managed application compatibility.</summary>
public sealed class Kernel : Cosmos.Kernel.System.Kernel
{
private DesktopSession? desktop;
private TerminalSnapshot? demonstration;
private int lastWindow;
private MemoryWorkspace? workspace;
private CanvasAdapter? display;
private FramePacer? framePacer;
private readonly NativeDesktopInput desktopInput = new();
private string lastWindowState = "";
private long lastRenderReport;
private long lastChromeFrameReport;
private string lastChromeFrame = "";
private bool previousLeftButton;
private string lastBrowserState = "";
private long lastBrowserStateReport;
private string lastBrowserInput = "";
private long lastBrowserProofRevision = -1, lastBrowserProofReport;
private int lastBrowserProofWindow;
private string lastMonacoProof = "";
private bool lastPointerReportLeft;
private NativeManagedWorkScheduler? editorWorker;
private System.Threading.Thread? uiThread;
private const string ManagedDemoPath = "X:\\Programs\\ManagedHello\\ManagedHello.dll";
// Only the bounded serial byte write masks interrupts; formatting and all
// kernel/network work happen before entering the runtime's atomic log API.
private static void WriteDiagnostic(string message) => Log.WriteBytes(Encoding.UTF8.GetBytes("\n" + message));
protected override void BeforeRun()
{
desktopInput.Trace = WriteDiagnostic;
desktopInput.NavigationDispatched = () =>
{
// Navigation diagnostics inspect only the UI-owned Browser. The
// background editor proxy never exposes its worker-owned engine.
if (desktop?.ActiveWindow is { Application: DesktopApplication.Browser, BrowserSession: BrowserService navigation } &&
Uri.TryCreate(navigation.CurrentPage.Address, UriKind.Absolute, out var address) && BrowserService.IsMonacoAddress(address))
WriteDiagnostic("XFE_NATIVE_NAV_SELECTION_BEGIN\n" + navigation.ReadEditorNavigationProof() + "\nXFE_NATIVE_NAV_SELECTION_END\n");
};
NativeKeyboardCapture.Prepare();
NativePointerCapture.Prepare();
NativeNvidiaDiscovery.Report(WriteDiagnostic);
WriteDiagnostic("XFE_CSHARP_NATIVEAOT_BOOT_OK\n");
int documentTextResources = XFESystem.Documents.WebsiteAssets.PrewarmTextResources();
int browserTextResources = PackagedBrowserResources.PrewarmTextResources();
WriteDiagnostic("XFE_PACKAGED_TEXT_PREWARM|Documents|" + documentTextResources + "|Browser|" + browserTextResources + "|Immutable|1\n");
if (!RuntimeVarianceRegression.Run())
throw new InvalidOperationException("The managed generic variance runtime regression failed.");
WriteDiagnostic("XFE_RUNTIME_VARIANCE_OK\n");
WriteDiagnostic("XFE_GC_DEEP_BEGIN\n");
bool deepGc = NativeGcRegression.Run();
WriteDiagnostic("XFE_GC_DEEP_RESULT|" + deepGc + "|Frames|"+NativeGcRegression.FramesVerified+"|Collections|"+NativeGcRegression.CollectionsRequested+"|FailureDepth|"+NativeGcRegression.FailureDepth+"\n");
if (!deepGc) throw new InvalidOperationException("The native deep-stack GC root regression failed.");
WriteDiagnostic("XFE_EH_DEEP_RETHROW_BEGIN\n");
if (!NativeEhRegression.Run())
throw new InvalidOperationException("The native deep catch/rethrow recovery regression failed.");
WriteDiagnostic("XFE_EH_DEEP_RETHROW_OK|Frames|" + NativeEhRegression.FramesCaught + "|Post|" + NativeEhRegression.PostCatchFrames + "\n");
WriteDiagnostic("XFE_THREAD_EH_GC_BEGIN\n");
bool threadRuntimeReady = NativeThreadRegression.Run();
WriteDiagnostic("XFE_THREAD_EH_GC_RESULT|" + threadRuntimeReady + "|Steps|" + NativeThreadRegression.Steps + "|Collections|" + NativeThreadRegression.Collections + "|SingleCpu|1|GcStopTheWorld|1\n");
WriteDiagnostic("XFE_THREAD_PREEMPTION|Checks|" + NativeThreadRegression.PreemptionChecks + "|FirstId|" + NativeThreadRegression.FirstThreadId + "|SecondId|" + NativeThreadRegression.SecondThreadId + "|FirstFailure|" + NativeThreadRegression.FirstFailure + "|SecondFailure|" + NativeThreadRegression.SecondFailure + "\n");
WriteDiagnostic("XFE_THREAD_TLS|Checks|" + NativeThreadRegression.ThreadStaticChecks + "|FirstManagedId|" + NativeThreadRegression.FirstManagedThreadId + "|SecondManagedId|" + NativeThreadRegression.SecondManagedThreadId + "|OrdinaryThreadsOnly|1\n");
if (!threadRuntimeReady)
{
WriteDiagnostic("[FAILFAST] Native thread EH/GC/preemption contract failed; background work and desktop startup remain disabled.\n");
while (true) Power.Halt();
}
RunConsoleDemo();
workspace = new MemoryWorkspace();
workspace.WriteText(SystemPaths.Combine(SystemPaths.Documents, "Readme.md"),
"# XFESystem Markdown\n\n**Website renderer** is active.\n\n- C# desktop\n- JavaScript preview\n");
workspace.WriteText(SystemPaths.Combine(SystemPaths.Documents, "WebsiteParity.md"), XFESystem.Documents.WebsiteAssets.ReadText("Fixtures/WebsiteParity.md"));
workspace.WriteText(SystemPaths.Combine(SystemPaths.Documents, "ZCSharp.cs"), "using System;\nnamespace XFEstudio;\npublic sealed class Preview\n{\n public string Message { get; set; } = \"Hello XFESystem\";\n public static int Run(int value)\n {\n if (value > 0) return Math.Max(value, 42);\n Console.WriteLine(\"Ready\");\n return 0;\n }\n}");
workspace.CreateDirectory("X:\\Programs\\ManagedHello");
using (var application = typeof(Kernel).Assembly.GetManifestResourceStream("XFESystem.Programs.ManagedHello.dll")
?? throw new InvalidOperationException("The independent C# example assembly is missing."))
{
var bytes = new byte[application.Length];
application.ReadExactly(bytes);
workspace.WriteBytes(ManagedDemoPath, bytes);
}
RunManagedApplicationCore(ManagedDemoPath, verifyDemonstration: true);
InitializeNetwork();
WriteDiagnostic("XFE_BROWSER_CONSTRUCT_BEGIN\n");
var browser = new BrowserService(new NativeWebTransport()) { Trace = WriteDiagnostic };
WriteDiagnostic("XFE_BROWSER_CONSTRUCT_OK\nXFE_BROWSER_NAVIGATE_BEGIN\n");
var constrainedJavaScript = new JavaScriptRuntime(new BrowserLimits { MaximumStatements = 50 });
if (constrainedJavaScript.Evaluate("while (true) {}").Success)
throw new InvalidOperationException("The guest JavaScript statement budget was not enforced.");
var recoveredJavaScript = constrainedJavaScript.Evaluate("6 * 7");
if (!recoveredJavaScript.Success || recoveredJavaScript.Text != "42")
throw new InvalidOperationException("The guest JavaScript runtime could not recover after its statement limit.");
WriteDiagnostic("XFE_JAVASCRIPT_LIMIT_RECOVERY_OK\n");
var page = browser.Navigate("about:Start");
BrowserNativeEventRegression.Run(browser,WriteDiagnostic);
WriteDiagnostic("XFE_BROWSER_NAVIGATE_OK\n");
if (!page.Text.Contains("JavaScript ready: 12", StringComparison.Ordinal))
throw new InvalidOperationException("The guest browser JavaScript/DOM test failed: " + page.Text);
WriteDiagnostic("XFE_BROWSER_MARKDOWN_BEGIN\n");
var markdown = browser.PreviewMarkdown("# XFESystem\n\n**Markdown** from the website renderer.");
if (!markdown.Contains("Markdown", StringComparison.Ordinal))
throw new InvalidOperationException("The guest Markdown preview test failed.");
WriteDiagnostic("XFE_CSHARP_JAVASCRIPT_DOM_OK\nXFE_CSHARP_MARKDOWN_OK\n");
var canvas = new CanvasAdapter();
display = canvas;
editorWorker = new NativeManagedWorkScheduler(WriteDiagnostic, canvas.ScalePercent / 100);
IEditorPreparationService editorPreparation = new BrowserEditorPreparationService(browser, editorWorker, editorWorker, WriteDiagnostic, NativeThreadRegression.CurrentThreadId, monotonicMilliseconds: MonotonicMilliseconds);
WriteDiagnostic("XFE_WEB_FONT_METRICS|" + canvas.WebFontMetricsEvidence + "\n");
MouseManager.SetScreenSize(canvas.NativeWidth, canvas.NativeHeight);
MouseManager.SetPosition(canvas.NativeWidth / 2, canvas.NativeHeight / 2);
var monitor = NativeDisplayInfo.Read(canvas.NativeWidth, canvas.NativeHeight);
int refreshTarget = canvas.DriverRefreshHz > 0 ? canvas.DriverRefreshHz * 1000 :
monitor.Timing.HasAdvertisedTiming ? monitor.Timing.AdvertisedRefreshMilliHz : 60_000;
framePacer = new FramePacer(Stopwatch.Frequency, refreshTarget);
// Wake the input/render loop often enough to service high-refresh input.
// This is a timer cadence, not a claim of display scanout or VSync.
if (TimerManager.IsInitialized && TimerManager.Frequency < 1000) TimerManager.Frequency = 1000;
desktop = new DesktopSession(canvas, workspace, browser, consoleDemo: () => RunManagedApplication(ManagedDemoPath), managedApplication: RunManagedApplication,
monotonicMilliseconds: MonotonicMilliseconds, editorPreparation: editorPreparation, threadIdentity: NativeThreadRegression.CurrentThreadId) { Trace = WriteDiagnostic };
desktop.Pointer(canvas.ToLayout(MouseManager.X), canvas.ToLayout(MouseManager.Y), false);
while (NativePointerCapture.TryRead(out _)) { }
desktop.PointerReportsLost(canvas.ToLayout(MouseManager.X),canvas.ToLayout(MouseManager.Y),MouseManager.LeftButton,MonotonicMilliseconds());
desktop.Render();
WriteDiagnostic("XFE_RENDER_BACKEND|Rasterization|CPU|GpuAcceleration|0|CudaAcceleration|0|Reason|No initialized native GPU or CUDA command backend\n");
WriteDiagnostic("XFE_MONITOR_TIMING|" + monitor.Timing.AdvertisedRefreshMilliHz + "|TargetMilliHz|" + refreshTarget +
"|DriverConfirmedHz|" + canvas.DriverRefreshHz + "|VSync|0|Origin|" + monitor.Origin + "|" + monitor.Timing.Source + "\n");
WriteDiagnostic("XFE_INPUT_RAW_HOOK_EXPECTED\n");
WriteDiagnostic("XFE_DISPLAY_NATIVE|" + canvas.NativeWidth + "|" + canvas.NativeHeight +
"|ScalePercent|" + canvas.ScalePercent + "\n");
WriteDiagnostic("XFE_CSHARP_DESKTOP_READY\n");
}
private static void InitializeNetwork()
{
// Driver-kit workers publish adapters asynchronously. The manager itself
// is initialized by Cosmos before the driver stage, not by this kernel.
for (var elapsed = 0; elapsed < 5_000 &&
(NetworkManager.DeviceCount == 0 || !NetworkManager.Ready || !NetworkManager.LinkUp); elapsed += 10)
TimerManager.Wait(10);
if (NetworkManager.DeviceCount == 0 || !NetworkManager.Ready || !NetworkManager.LinkUp)
{
WriteDiagnostic("XFE_NETWORK_UNAVAILABLE\n");
return;
}
try
{
var dhcp = new DhcpClient();
try { dhcp.SendDiscoverPacket(); }
catch { dhcp.Close(); throw; }
dhcp.Close();
if (NetworkManager.Primary.IPConfig is { } config && !config.Address.IsZero)
{
WriteDiagnostic("XFE_NETWORK_DHCP_OK|" + config.Address + "|DnsServers|" + DnsConfig.Nameservers.Count + "\n");
}
else WriteDiagnostic("XFE_NETWORK_DHCP_FAILED\n");
}
catch (Exception error) when (error is not OutOfMemoryException and not StackOverflowException)
{
WriteDiagnostic("XFE_NETWORK_DHCP_FAILED|" + error.Message + "\n");
}
}
protected override void Run()
{
if (!NativeThreadRegression.Passed) { WriteDiagnostic("[FAILFAST] The native desktop requires its verified thread runtime.\n"); while (true) Power.Halt(); }
// The boot thread is the scheduler's idle fallback. A CPU-bound worker
// would starve it, so the UI must itself be an ordinary runnable thread.
uiThread = new System.Threading.Thread(RunDesktopLoop, NativeManagedWorkScheduler.StackBytes);
uiThread.Start();
while (true) Power.Halt();
}
private void RunDesktopLoop()
{
WriteDiagnostic("XFE_DESKTOP_UI_THREAD|" + NativeThreadRegression.CurrentThreadId() + "|StackBytes|" + NativeManagedWorkScheduler.StackBytes + "\n");
while (true)
{
if (desktop is { } session)
{
long inputMilliseconds = MonotonicMilliseconds();
if (MouseManager.ScrollDelta != 0) MouseManager.ResetScrollDelta();
bool leftButton = MouseManager.LeftButton, processedKey = false;
NativePointerReport? pendingMotion = null;
bool packetLeft = lastPointerReportLeft;
// Bound one drain so continuous input cannot starve rendering,
// animation, keyboard handling or diagnostics.
int pointerBudget = 64;
while (pointerBudget-- > 0 && NativePointerCapture.TryRead(out var pointerReport))
{
if (pointerReport.LostReports)
{
pendingMotion = null; packetLeft = leftButton;
session.PointerReportsLost(display!.ToLayout(MouseManager.X),display.ToLayout(MouseManager.Y),leftButton,inputMilliseconds);
WriteDiagnostic("XFE_POINTER_REPORTS_LOST\n"); continue;
}
if (pointerReport.LeftButton == packetLeft && pointerReport.Wheel == 0) { pendingMotion = pointerReport; continue; }
if (pendingMotion is { } motion) { DispatchPointer(session,motion); pendingMotion = null; }
DispatchPointer(session,pointerReport); packetLeft = pointerReport.LeftButton;
}
if (pendingMotion is { } finalMotion) DispatchPointer(session,finalMotion);
// Preserve the upstream queue for its other consumers but drain
// our copy: desktop input must include modifier break reports.
while (KeyboardManager.TryReadKey(out _)) { }
while (NativeKeyboardCapture.TryRead(out var scanCode, out var released, out var lostReports))
if (desktopInput.Translate(scanCode, released, lostReports, session, out var character) is { } mapped)
{
processedKey = true;
session.Key(mapped, character);
if (mapped == DesktopKey.Enter && session.ActiveWindow is { Application: DesktopApplication.Browser } navigated)
{
// WriteBytes is the runtime's atomic serial protocol API.
// The plain string logger truncates UTF-16 to bytes and
// permits IRQ logs to split acceptance frame markers.
var body = navigated.Content.Length <= 4_096 ? navigated.Content : navigated.Content[..4_096];
var report = "XFE_BROWSER_NAVIGATED|" + navigated.Location +
"\nXFE_BROWSER_TEXT_BEGIN\n" + body + "\nXFE_BROWSER_TEXT_END\n";
if (navigated.Content.Contains("中文 HTTP 正文", StringComparison.Ordinal))
report += "XFE_BROWSER_UTF8_BODY_OK\n";
WriteDiagnostic(report);
}
if (mapped == DesktopKey.Save && session.ActiveWindow is { IsDirty: false } saved &&
saved.BrowserSession is not IBackgroundEditorSession)
{
WriteDiagnostic("XFE_DESKTOP_SAVED|" + saved.Location + "|" + saved.Content.Length + "\n");
}
}
// Already queued input takes priority over a cooperative page
// loading phase. In particular Win+D/close can hide or remove
// the page before an indivisible script evaluation starts.
session.AdvanceFeedback(inputMilliseconds);
var active = session.ActiveWindow;
bool activeChanged = (active?.Id ?? 0) != lastWindow;
// A queued readback can open a preview without another input
// report. Publish its actual geometry before any DOM evidence.
if (activeChanged) ReportWindowState(session);
if (active is { BrowserSession: not null }) ReportBrowserState(active);
if (activeChanged)
{
lastWindow = active?.Id ?? 0;
WriteDiagnostic("XFE_DESKTOP_ACTIVE|" + (active?.Application.ToString() ?? "Desktop") + "\n");
if (active is { Application: DesktopApplication.Browser })
{
if (active.Content.Contains("JavaScript ready: 12", StringComparison.Ordinal))
WriteDiagnostic("XFE_BROWSER_START_DOM_RENDER_OK\n");
if (active.Content.Contains("Hello from XFESystem!", StringComparison.Ordinal))
WriteDiagnostic("XFE_EDITOR_JAVASCRIPT_PREVIEW_OK\n");
if (active.Content.Contains("Website renderer", StringComparison.Ordinal))
WriteDiagnostic("XFE_EDITOR_MARKDOWN_PREVIEW_OK\n");
}
}
if (!leftButton && (processedKey || previousLeftButton || lastWindowState.Length == 0)) ReportWindowState(session);
previousLeftButton = leftButton;
long now = Stopwatch.GetTimestamp();
if (framePacer!.ShouldRender(now, session.NeedsRender))
{
session.Render();
if (session.LastFrameCompleted)
{
framePacer.Rendered(now, Stopwatch.GetTimestamp());
ReportChromeFrame(session, now);
}
}
if (now - lastRenderReport >= Stopwatch.Frequency)
{
lastRenderReport = now;
WriteDiagnostic("XFE_RENDER_STATS|" + now + "|Frames|" + framePacer.FramesRendered + "|Partial|" + display!.PartialFrames +
"|Pixels|" + display.PixelsPresented + "|Glyphs|" + display.CachedGlyphCount + "|Fallback|" + display.FullCopyFallbackFrames +
"|LastRenderTicks|" + framePacer.LastRenderDurationTicks + "|Frequency|" + Stopwatch.Frequency +
"|MotionReuses|" + display.MotionReuseCount + "|MotionPixels|" + display.MotionPixelsReused +
"|ScanoutPixelsSaved|" + display.ScanoutPixelsSaved + "|RenderYields|" + session.RenderYieldCount +
"|RawFreePages|" + NativeRuntimeMemoryDiagnostics.FreePages() + "|RawTotalPages|" + NativeRuntimeMemoryDiagnostics.TotalPages() +
"|RawLargestFreeRunPages|" + NativeRuntimeMemoryDiagnostics.LargestFreeRunPages() + "\n");
if (active?.BrowserSession is BrowserService measuredPage)
WriteDiagnostic("XFE_WEB_WORK|Window|" + active.Id + "|Layout|" + measuredPage.LayoutPassCount +
"|ScrollReuse|" + measuredPage.ScrollLayoutReuseCount + "|Raster|" + measuredPage.RasterPaintCount +
"|CachedPaint|" + measuredPage.CachedPaintCount + "|AstHits|" + measuredPage.PackagedScriptCacheHits +
"|AstPrepared|" + measuredPage.PackagedScriptPreparations + "\n");
else if (active?.BrowserSession is IBackgroundEditorSession backgroundPage)
{
var published = backgroundPage.Diagnostics;
WriteDiagnostic("XFE_WEB_WORK|Window|" + active.Id + "|Layout|" + published.LayoutPassCount +
"|ScrollReuse|" + published.ScrollLayoutReuseCount + "|Raster|" + backgroundPage.RasterPaintCount +
"|CachedPaint|" + backgroundPage.CachedPaintCount + "|AstHits|" +
published.PackagedScriptCacheHits + "|AstPrepared|" + published.PackagedScriptPreparations +
"|EngineThread|" + published.WorkerThreadId + "|PaintSource|Snapshot\n");
}
}
}
Power.Halt();
}
}
private static long MonotonicMilliseconds() => (long)(Stopwatch.GetTimestamp() / (double)Stopwatch.Frequency * 1000);
private void DispatchPointer(DesktopSession session,NativePointerReport report)
{
int x = display!.ToLayout(report.X), y = display.ToLayout(report.Y);
bool released = lastPointerReportLeft && !report.LeftButton;
// Button transitions are enough for click evidence. Per-wheel serial
// formatting at high input rates would distort the measured rendering.
if (report.LeftButton != lastPointerReportLeft)
{
lastPointerReportLeft = report.LeftButton;
WriteDiagnostic("XFE_NATIVE_POINTER|X|" + x + "|Y|" + y + "|Left|" + (report.LeftButton ? 1 : 0) +
"|Wheel|" + report.Wheel + "|Ticks|" + report.TimestampTicks + "\n");
}
session.Pointer(x,y,report.LeftButton,report.Wheel,(long)(report.TimestampTicks/(double)Stopwatch.Frequency*1000));
// A complete down/move/up can be drained in one UI iteration. The
// MouseManager snapshot taken before that drain may already be up,
// so publish final bounds from the actual release transition.
if (released) ReportWindowState(session);
}
private void ReportBrowserState(DesktopWindow window)
{
long now = MonotonicMilliseconds();
// Background editors publish immutable diagnostics. Never unwrap their
// engine or ask a worker-owned BrowserService to acquire its page gate.
var background = window.BrowserSession as IBackgroundEditorSession;
var published = background?.Diagnostics;
string? inputTrace = window.BrowserSession is BrowserService traced ? traced.LastInputTrace : published?.LastInputTrace;
if (inputTrace is not null && inputTrace != lastBrowserInput)
{ lastBrowserInput = inputTrace; WriteDiagnostic("XFE_BROWSER_INPUT|" + lastBrowserInput + "\n"); }
if (window.BrowserSession is BrowserService documentBrowser && now - lastBrowserProofReport >= 500 &&
(lastBrowserProofWindow != window.Id || lastBrowserProofRevision != documentBrowser.Revision))
{
lastBrowserProofWindow = window.Id; lastBrowserProofRevision = documentBrowser.Revision; lastBrowserProofReport = now;
var documentProof = documentBrowser.ReadWebsiteDocumentProof();
if (documentProof != "{}") WriteDiagnostic("XFE_WEBSITE_DOCUMENT_PROOF_BEGIN\n" + documentProof + "\nXFE_WEBSITE_DOCUMENT_PROOF_END\n");
if (Uri.TryCreate(documentBrowser.CurrentPage.Address, UriKind.Absolute, out var proofUri) && BrowserService.IsMonacoAddress(proofUri))
{
// Background tokenization can change span classes without changing
// textContent. Read real view state after each changed revision.
var colorProof = documentBrowser.ReadMonacoProof();
if (colorProof != "{}" && colorProof != lastMonacoProof)
{ lastMonacoProof = colorProof; WriteDiagnostic("XFE_MONACO_CSHARP_PROOF_BEGIN\n" + colorProof + "\nXFE_MONACO_CSHARP_PROOF_END\n"); }
}
}
else if (background is not null && published is not null && now - lastBrowserProofReport >= 500 &&
(lastBrowserProofWindow != window.Id || lastBrowserProofRevision != background.Revision))
{
lastBrowserProofWindow = window.Id; lastBrowserProofRevision = background.Revision; lastBrowserProofReport = now;
string colorProof = published.MonacoProof;
if (colorProof != "{}" && colorProof != lastMonacoProof)
{ lastMonacoProof = colorProof; WriteDiagnostic("XFE_MONACO_CSHARP_PROOF_BEGIN\n" + colorProof + "\nXFE_MONACO_CSHARP_PROOF_END\n"); }
}
if (now - lastBrowserStateReport < 200) return;
lastBrowserStateReport = now;
var body = window.Content.Length <= 4096 ? window.Content : window.Content[..4096];
string state = window.Id + "|" + window.Location + "\n" + body;
if (state == lastBrowserState) return;
lastBrowserState = state;
WriteDiagnostic("XFE_BROWSER_STATE_BEGIN\n" + state + "\nXFE_BROWSER_STATE_END\n");
if (background is not null || window.BrowserSession is BrowserService browser && Uri.TryCreate(browser.CurrentPage.Address, UriKind.Absolute, out var browserUri) && BrowserService.IsMonacoAddress(browserUri) &&
(window.Application == DesktopApplication.Editor || body.Contains("Official Monaco 0.52.2 - ready", StringComparison.Ordinal) || body.Contains("Monaco - edited", StringComparison.Ordinal) || body.Contains("Monaco C# - website grammar and palette", StringComparison.Ordinal)))
{
var value = window.BrowserSession!.ReadEditorText() ?? "Editor unavailable";
WriteDiagnostic("XFE_MONACO_VALUE_BEGIN\n" + value + "\nXFE_MONACO_VALUE_END\n");
}
}
private void ReportChromeFrame(DesktopSession session, long now)
{
if (now - lastChromeFrameReport < Stopwatch.Frequency / 25) return;
var active = session.ActiveWindow;
if (active is null) return;
var chrome = active.ChromeAnimation;
string state = "XFE_CHROME_FRAME|" + active.Id + "|Min|" + (int)Math.Round(chrome.MinimizeProgress * 1000) +
"|Close|" + (int)Math.Round(chrome.CloseProgress * 1000) + "|Title|" + (int)Math.Round(chrome.TitleHintProgress * 1000) +
"|Resize|" + (int)Math.Round(chrome.ResizeProgress * 1000);
if (state == lastChromeFrame) return;
lastChromeFrame = state; lastChromeFrameReport = now;
WriteDiagnostic(state + "\n");
}
private void ReportWindowState(DesktopSession session)
{
string report = "XFE_DESKTOP_FLAGS|" + (session.IsStartMenuOpen ? 1 : 0) + "|" + (session.IsWindowSwitching ? 1 : 0) +
"|Active|" + (session.ActiveWindow?.Id ?? 0) + "\n" +
"XFE_DESKTOP_APPEARANCE|" + session.Theme.Mode + "|" + session.Theme.Accent.ToString("X6") +
"|Persistent|" + (session.IsAppearancePersistent ? 1 : 0) + "\n";
foreach (var window in session.Windows)
{
var b = window.Bounds;
report += "XFE_WINDOW_STATE|" + window.Id + "|" + window.Application + "|" + b.X + "|" + b.Y + "|" + b.Width + "|" + b.Height +
"|" + (window.IsMinimized ? 1 : 0) + "|" + (window.IsMaximized ? 1 : 0) + "|" + (window.IsSnapped ? 1 : 0) + "\n";
}
if (report == lastWindowState) return;
lastWindowState = report; WriteDiagnostic(report);
}
private void RunConsoleDemo()
{
var buffer = new TerminalBuffer(90, 18);
var writer = new TerminalTextWriter(buffer);
ConsoleDemoScenario.Run(writer);
ConsoleDemoScenario.RunXfeConsoleApi(writer);
writer.Complete();
demonstration = writer.Snapshot();
if (!buffer.GetText().Contains(ConsoleDemoScenario.SuccessMarker, StringComparison.Ordinal))
throw new InvalidOperationException("The guest console application did not complete.");
if (!buffer.GetText().Contains("XFEConsole API: Real NuGet 2.6.0", StringComparison.Ordinal))
throw new InvalidOperationException("The real XFEConsole API did not write to the guest terminal.");
var rgb = buffer.GetCell(0, 1).Style.Foreground;
if (rgb != TerminalColor.ThemeForeground)
throw new InvalidOperationException("The guest ANSI true color output was not preserved.");
ConsoleDemoScenario.RunSystemConsoleColors();
var previousForeground = global::System.Console.ForegroundColor;
global::System.Console.ForegroundColor = ConsoleColor.Cyan;
if (global::System.Console.ForegroundColor != ConsoleColor.Cyan)
throw new InvalidOperationException("The guest Console color PAL did not preserve its state.");
global::System.Console.ForegroundColor = previousForeground;
desktop?.SetTerminalSnapshot(demonstration);
WriteDiagnostic("XFE_CSHARP_CONSOLE_DEMO_OK\nXFE_CSHARP_ANSI_RGB_OK\nXFE_CSHARP_CONSOLE_PAL_COLOR_OK\nXFE_CSHARP_XFECONSOLE_API_OK\n");
}
private void RunManagedApplication(string path)
{
try { RunManagedApplicationCore(path); }
catch (Exception error) when (error is not OutOfMemoryException and not StackOverflowException)
{
var buffer = new TerminalBuffer(90, 18);
buffer.Write("The program cannot run in this compatibility profile.\r\n" + error.Message);
desktop?.SetTerminalSnapshot(buffer.Snapshot());
WriteDiagnostic("XFE_MANAGED_APP_REJECTED\n");
}
}
private void RunManagedApplicationCore(string path, bool verifyDemonstration = false)
{
var bytes = (workspace ?? throw new InvalidOperationException("The workspace is not initialized.")).ReadBytes(path);
var buffer = new TerminalBuffer(90, 18);
var writer = new TerminalTextWriter(buffer);
var result = new ManagedApplicationRunner().Execute(bytes, new TerminalManagedConsole(writer));
writer.Complete();
bool demonstrationSucceeded = result.ExitCode == 0 &&
buffer.GetText().Contains("XFE_MANAGED_APP_OK", StringComparison.Ordinal) &&
buffer.GetText().Contains("XFE_MANAGED_XFECONSOLE_OK", StringComparison.Ordinal) &&
buffer.GetCell(0, 1).Style.Foreground == TerminalColor.ThemeForeground;
if (verifyDemonstration && !demonstrationSucceeded)
throw new InvalidOperationException("The independent C# example assembly did not complete its console/ANSI scenario.");
desktop?.SetTerminalSnapshot(buffer.Snapshot());
if (demonstrationSucceeded)
WriteDiagnostic("XFE_MANAGED_APP_OK\nXFE_MANAGED_XFECONSOLE_OK\nXFE_MANAGED_ANSI_RGB_OK\n");
WriteDiagnostic("XFE_MANAGED_APPLICATION_EXIT|" + result.AssemblyName + "|" + result.ExitCode + "\n");
WriteDiagnostic("XFE_MANAGED_IL_INSTRUCTIONS|" + result.Instructions + "|InteropCalls|" + result.InteropCalls + "\n");
}
private static DesktopKey? MapKey(KeyEvent key)
{
if ((key.Modifiers & ConsoleModifiers.Control) != 0 && key.Key == ConsoleKeyEx.S)
return DesktopKey.Save;
if ((key.Modifiers & ConsoleModifiers.Control) != 0 && key.Key == ConsoleKeyEx.L)
return DesktopKey.FocusAddress;
return key.Key switch
{
ConsoleKeyEx.Enter => DesktopKey.Enter,
ConsoleKeyEx.Backspace => DesktopKey.Backspace,
ConsoleKeyEx.Delete => DesktopKey.Delete,
ConsoleKeyEx.LeftArrow => DesktopKey.Left,
ConsoleKeyEx.RightArrow => DesktopKey.Right,
ConsoleKeyEx.UpArrow => DesktopKey.Up,
ConsoleKeyEx.DownArrow => DesktopKey.Down,
ConsoleKeyEx.Home => DesktopKey.Home,
ConsoleKeyEx.End => DesktopKey.End,
ConsoleKeyEx.Tab => DesktopKey.Tab,
ConsoleKeyEx.Escape => DesktopKey.Escape,
ConsoleKeyEx.F5 => DesktopKey.Run,
_ => key.KeyChar >= ' ' ? DesktopKey.Character : null
};
}
}