using XFESystem.Browser;
using XFESystem.Console;
using XFESystem.ConsoleDemo;
using XFESystem.Core;
using XFESystem.Desktop;
using XFESystem.ManagedRuntime;
using XFESystem.Platform;
namespace XFESystem.NativeRuntime.Application;
/// <summary>Ordinary Microsoft NativeAOT Main, called after the independently installed PAL/bootstrapper.</summary>
internal static class Program
{
private const string ManagedDemoPath = "X:\\Programs\\ManagedHello\\ManagedHello.dll";
private static int Main()
{
NativePlatform.Write("XFE_INDEPENDENT_APPLICATION_ENTER\n");
try
{
global::System.Console.SetOut(new NativeDiagnosticWriter());
global::System.Console.SetError(new NativeDiagnosticWriter());
NativePlatform.RequireClock();
RuntimeSelfCheck.Run();
var surface = NativePlatform.ReadFramebuffer();
int scalePercent = surface.Width >= 3000 || surface.Height >= 1800 ? 200 : 100;
var canvas = new CpuFramebufferCanvas(new MemoryFramebufferPresenter(surface), scalePercent: scalePercent, timestamp: NativePlatform.Nanoseconds);
var workspace = CreateWorkspace();
var browser = new BrowserService { Trace = NativePlatform.Write };
var terminal = new TerminalBuffer(100, 30);
var writer = new TerminalTextWriter(terminal);
DesktopSession? desktop = null;
void RunConsoleDemo()
{
terminal.Reset(); ConsoleDemoScenario.Run(writer); ConsoleDemoScenario.RunXfeConsoleApi(writer);
terminal.Complete();
var snapshot = writer.Snapshot();
string text = string.Concat(snapshot.Cells.Select(cell => cell.Text));
if (!text.Contains(ConsoleDemoScenario.SuccessMarker, StringComparison.Ordinal) ||
!text.Contains("XFEConsole API: Real NuGet 2.6.0", StringComparison.Ordinal))
throw new InvalidOperationException("The real console demo did not produce its terminal markers.");
desktop!.SetTerminalSnapshot(snapshot);
NativePlatform.Write("XFE_INDEPENDENT_CONSOLE_DEMO_OK ANSI XFEConsole2.6.0 terminal_cells\n");
}
void RunManagedApplication(string path)
{
terminal.Reset();
try
{
var result = new ManagedApplicationRunner().Execute(workspace.ReadBytes(path), new TerminalManagedConsole(writer));
writer.WriteLine("Managed ConsoleIL exit: " + result.ExitCode);
var sampleText = string.Concat(writer.Snapshot().Cells.Select(cell => cell.Text));
if (result.ExitCode == 0 && sampleText.Contains("XFE_MANAGED_APP_OK", StringComparison.Ordinal) &&
sampleText.Contains("XFE_MANAGED_XFECONSOLE_OK", StringComparison.Ordinal))
NativePlatform.Write("XFE_INDEPENDENT_CONSOLE_IL_OK actual_embedded_net10_PE bounded_interpreter\n");
}
catch (Exception error) when (error is not OutOfMemoryException and not StackOverflowException)
{ writer.WriteLine("Managed program failed: " + error.Message); }
terminal.Complete(); desktop!.SetTerminalSnapshot(writer.Snapshot());
}
desktop = new DesktopSession(canvas, workspace, browser, RunConsoleDemo, RunManagedApplication,
NativePlatform.Milliseconds, threadIdentity: () => Environment.CurrentManagedThreadId) { Trace = NativePlatform.Write };
var input = new Ps2InputSource(new NativePs2ReportBackend(), canvas.NativeWidth, canvas.NativeHeight, canvas.ScalePercent,
() => new(desktop.HasBrowserContentFocus, desktop.ActiveWindow?.Application));
desktop.Open(DesktopApplication.Files);
// The initial terminal uses the shared real ANSI model. Actual package demo/IL launch remain explicit actions.
writer.WriteLine("XFESystem independent kernel / Microsoft .NET 10 NativeAOT");
writer.WriteLine("自研 CPU framebuffer · RAM 文件会话");
writer.WriteLine("PS/2 keyboard: " + ((input.Capabilities & 1) != 0 ? "initialized" : "unavailable") +
"; mouse: " + ((input.Capabilities & 2) != 0 ? "initialized" : "unavailable"));
writer.WriteLine("No persistent storage, native network, GPU or CUDA backend is enabled.");
desktop.SetTerminalSnapshot(writer.Snapshot());
desktop.Pointer(input.PointerX, input.PointerY, false, timestampMs: NativePlatform.Milliseconds());
desktop.Render();
if (!desktop.LastFrameCompleted || canvas.FramesPresented == 0)
throw new InvalidOperationException("The desktop did not finish an actual raw framebuffer presentation.");
NativePlatform.Write("XFE_INDEPENDENT_DESKTOP_FIRST_FRAME|Width|" + canvas.NativeWidth + "|Height|" + canvas.NativeHeight +
"|ScalePercent|" + canvas.ScalePercent + "|Presented|" + canvas.FramesPresented + "\n");
NativePlatform.Write("XFE_INDEPENDENT_INPUT|Connected|" + (input.IsAvailable ? 1 : 0) + "|Keyboard|" + (input.Capabilities & 1) +
"|Mouse|" + ((input.Capabilities >> 1) & 1) + "|Backend|PS2|UsbHid|0\n");
NativePlatform.Write("XFE_INDEPENDENT_CAPABILITIES|RAMOnly|1|NativeNetwork|0|Gpu|0|Cuda|0|BackgroundEditor|0\n");
ReportWindowState(desktop);
Pump(desktop, input);
return 0;
}
catch (Exception error)
{
NativePlatform.Write("XFE_INDEPENDENT_APPLICATION_FAILED|" + error.Message + "\n");
NativePlatform.Halt("Managed desktop failed: " + error.Message);
return 1;
}
}
private static MemoryWorkspace CreateWorkspace()
{
var workspace = new MemoryWorkspace();
workspace.WriteText(SystemPaths.Combine(SystemPaths.Documents, "Readme.md"), """
# XFESystem 独立内核
当前文件在 **RAM 会话** 中,关机后不会保留。
- 原有 Desktop、Browser、Documents 和 Terminal 接口继续使用。
- PS/2 输入按真实设备初始化状态启用;USB HID 尚未接入。
- 持久存储、网络和 GPU/CUDA 后端尚未接入。
""");
workspace.CreateDirectory("X:\\Programs\\ManagedHello");
using var sample = typeof(Program).Assembly.GetManifestResourceStream("ApplicationSamples/ManagedHello.dll")
?? throw new InvalidOperationException("The actual ConsoleIL sample assembly is missing.");
if (sample.Length > ManagedRuntimeCapabilities.MaxImageBytes) throw new InvalidDataException("Managed sample exceeds the ConsoleIL image budget.");
byte[] image = new byte[checked((int)sample.Length)]; sample.ReadExactly(image); workspace.WriteBytes(ManagedDemoPath, image);
workspace.WriteBytes(SystemPaths.Combine(SystemPaths.Documents, "ManagedHello.dll"), image);
return workspace;
}
// Input remains an explicit optional adapter. No fabricated reports or host window input enter this loop.
private static void Pump(DesktopSession desktop, INativeInputSource? input)
{
long previous = NativePlatform.Milliseconds(), nextTick = previous;
for (;;)
{
long now = NativePlatform.Milliseconds();
if (now < previous) throw new InvalidOperationException("The native monotonic clock moved backward.");
previous = now;
if (input is { IsAvailable: true })
for (int reports = 0; reports < 256 && input.TryRead(out var report); reports++) NativeInput.Dispatch(desktop, report, now);
if (now >= nextTick)
{
desktop.AdvanceFeedback(now);
if (desktop.NeedsRender)
{
desktop.Render();
if (desktop.LastFrameCompleted)
{
ReportWindowState(desktop);
if (desktop.ActiveWindow is { BrowserSession: not null } active) ReportBrowserState(active, now);
}
}
nextTick = now + 16;
}
Thread.Sleep(1);
}
}
private static string lastWindowState = "";
private static void ReportWindowState(DesktopSession desktop)
{
string report = "XFE_DESKTOP_FLAGS|" + (desktop.IsStartMenuOpen ? 1 : 0) + "|" + (desktop.IsWindowSwitching ? 1 : 0) +
"|Active|" + (desktop.ActiveWindow?.Id ?? 0) + "\n" +
"XFE_DESKTOP_APPEARANCE|" + desktop.Theme.Mode + "|" + desktop.Theme.Accent.ToString("X6") +
"|Persistent|" + (desktop.IsAppearancePersistent ? 1 : 0) + "\n";
foreach (var window in desktop.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;
NativePlatform.Write("XFE_DESKTOP_ACTIVE|" + (desktop.ActiveWindow?.Application.ToString() ?? "Desktop") + "\n" + report + "XFE_DESKTOP_STATE_END\n");
}
private static string lastBrowserState = "", lastBrowserInput = "", lastMonacoProof = "";
private static long lastBrowserReport;
private static void ReportBrowserState(DesktopWindow window, long now)
{
if (window.BrowserSession is not BrowserService browser) return;
if (browser.LastInputTrace != lastBrowserInput)
{
lastBrowserInput = browser.LastInputTrace;
NativePlatform.Write("XFE_BROWSER_INPUT|" + lastBrowserInput + "\n");
}
if (now - lastBrowserReport < 200) return;
lastBrowserReport = now;
string body = window.Content.Length <= 4096 ? window.Content : window.Content[..4096];
string state = window.Id + "|" + window.Location + "\n" + body;
if (state != lastBrowserState)
{
lastBrowserState = state;
NativePlatform.Write("XFE_BROWSER_STATE_BEGIN\n" + state + "\nXFE_BROWSER_STATE_END\n");
}
if (Uri.TryCreate(browser.CurrentPage.Address, UriKind.Absolute, out var uri) && BrowserService.IsMonacoAddress(uri))
{
string proof = browser.ReadMonacoProof();
if (proof != "{}" && proof != lastMonacoProof)
{
lastMonacoProof = proof;
NativePlatform.Write("XFE_MONACO_CSHARP_PROOF_BEGIN\n" + proof + "\nXFE_MONACO_CSHARP_PROOF_END\n");
}
NativePlatform.Write("XFE_MONACO_VALUE_BEGIN\n" + (browser.ReadEditorText() ?? "Editor unavailable") + "\nXFE_MONACO_VALUE_END\n");
}
}
}
using XFESystem.Browser;
using XFESystem.Console;
using XFESystem.ConsoleDemo;
using XFESystem.Core;
using XFESystem.Desktop;
using XFESystem.ManagedRuntime;
using XFESystem.Platform;
namespace XFESystem.NativeRuntime.Application;
/// <summary>Ordinary Microsoft NativeAOT Main, called after the independently installed PAL/bootstrapper.</summary>
internal static class Program
{
private const string ManagedDemoPath = "X:\\Programs\\ManagedHello\\ManagedHello.dll";
private static int Main()
{
NativePlatform.Write("XFE_INDEPENDENT_APPLICATION_ENTER\n");
try
{
global::System.Console.SetOut(new NativeDiagnosticWriter());
global::System.Console.SetError(new NativeDiagnosticWriter());
NativePlatform.RequireClock();
RuntimeSelfCheck.Run();
var surface = NativePlatform.ReadFramebuffer();
int scalePercent = surface.Width >= 3000 || surface.Height >= 1800 ? 200 : 100;
var canvas = new CpuFramebufferCanvas(new MemoryFramebufferPresenter(surface), scalePercent: scalePercent, timestamp: NativePlatform.Nanoseconds);
var workspace = CreateWorkspace();
var browser = new BrowserService { Trace = NativePlatform.Write };
var terminal = new TerminalBuffer(100, 30);
var writer = new TerminalTextWriter(terminal);
DesktopSession? desktop = null;
void RunConsoleDemo()
{
terminal.Reset(); ConsoleDemoScenario.Run(writer); ConsoleDemoScenario.RunXfeConsoleApi(writer);
terminal.Complete();
var snapshot = writer.Snapshot();
string text = string.Concat(snapshot.Cells.Select(cell => cell.Text));
if (!text.Contains(ConsoleDemoScenario.SuccessMarker, StringComparison.Ordinal) ||
!text.Contains("XFEConsole API: Real NuGet 2.6.0", StringComparison.Ordinal))
throw new InvalidOperationException("The real console demo did not produce its terminal markers.");
desktop!.SetTerminalSnapshot(snapshot);
NativePlatform.Write("XFE_INDEPENDENT_CONSOLE_DEMO_OK ANSI XFEConsole2.6.0 terminal_cells\n");
}
void RunManagedApplication(string path)
{
terminal.Reset();
try
{
var result = new ManagedApplicationRunner().Execute(workspace.ReadBytes(path), new TerminalManagedConsole(writer));
writer.WriteLine("Managed ConsoleIL exit: " + result.ExitCode);
var sampleText = string.Concat(writer.Snapshot().Cells.Select(cell => cell.Text));
if (result.ExitCode == 0 && sampleText.Contains("XFE_MANAGED_APP_OK", StringComparison.Ordinal) &&
sampleText.Contains("XFE_MANAGED_XFECONSOLE_OK", StringComparison.Ordinal))
NativePlatform.Write("XFE_INDEPENDENT_CONSOLE_IL_OK actual_embedded_net10_PE bounded_interpreter\n");
}
catch (Exception error) when (error is not OutOfMemoryException and not StackOverflowException)
{ writer.WriteLine("Managed program failed: " + error.Message); }
terminal.Complete(); desktop!.SetTerminalSnapshot(writer.Snapshot());
}
desktop = new DesktopSession(canvas, workspace, browser, RunConsoleDemo, RunManagedApplication,
NativePlatform.Milliseconds, threadIdentity: () => Environment.CurrentManagedThreadId) { Trace = NativePlatform.Write };
var input = new Ps2InputSource(new NativePs2ReportBackend(), canvas.NativeWidth, canvas.NativeHeight, canvas.ScalePercent,
() => new(desktop.HasBrowserContentFocus, desktop.ActiveWindow?.Application));
desktop.Open(DesktopApplication.Files);
// The initial terminal uses the shared real ANSI model. Actual package demo/IL launch remain explicit actions.
writer.WriteLine("XFESystem independent kernel / Microsoft .NET 10 NativeAOT");
writer.WriteLine("自研 CPU framebuffer · RAM 文件会话");
writer.WriteLine("PS/2 keyboard: " + ((input.Capabilities & 1) != 0 ? "initialized" : "unavailable") +
"; mouse: " + ((input.Capabilities & 2) != 0 ? "initialized" : "unavailable"));
writer.WriteLine("No persistent storage, native network, GPU or CUDA backend is enabled.");
desktop.SetTerminalSnapshot(writer.Snapshot());
desktop.Pointer(input.PointerX, input.PointerY, false, timestampMs: NativePlatform.Milliseconds());
desktop.Render();
if (!desktop.LastFrameCompleted || canvas.FramesPresented == 0)
throw new InvalidOperationException("The desktop did not finish an actual raw framebuffer presentation.");
NativePlatform.Write("XFE_INDEPENDENT_DESKTOP_FIRST_FRAME|Width|" + canvas.NativeWidth + "|Height|" + canvas.NativeHeight +
"|ScalePercent|" + canvas.ScalePercent + "|Presented|" + canvas.FramesPresented + "\n");
NativePlatform.Write("XFE_INDEPENDENT_INPUT|Connected|" + (input.IsAvailable ? 1 : 0) + "|Keyboard|" + (input.Capabilities & 1) +
"|Mouse|" + ((input.Capabilities >> 1) & 1) + "|Backend|PS2|UsbHid|0\n");
NativePlatform.Write("XFE_INDEPENDENT_CAPABILITIES|RAMOnly|1|NativeNetwork|0|Gpu|0|Cuda|0|BackgroundEditor|0\n");
ReportWindowState(desktop);
Pump(desktop, input);
return 0;
}
catch (Exception error)
{
NativePlatform.Write("XFE_INDEPENDENT_APPLICATION_FAILED|" + error.Message + "\n");
NativePlatform.Halt("Managed desktop failed: " + error.Message);
return 1;
}
}
private static MemoryWorkspace CreateWorkspace()
{
var workspace = new MemoryWorkspace();
workspace.WriteText(SystemPaths.Combine(SystemPaths.Documents, "Readme.md"), """
# XFESystem 独立内核
当前文件在 **RAM 会话** 中,关机后不会保留。
- 原有 Desktop、Browser、Documents 和 Terminal 接口继续使用。
- PS/2 输入按真实设备初始化状态启用;USB HID 尚未接入。
- 持久存储、网络和 GPU/CUDA 后端尚未接入。
""");
workspace.CreateDirectory("X:\\Programs\\ManagedHello");
using var sample = typeof(Program).Assembly.GetManifestResourceStream("ApplicationSamples/ManagedHello.dll")
?? throw new InvalidOperationException("The actual ConsoleIL sample assembly is missing.");
if (sample.Length > ManagedRuntimeCapabilities.MaxImageBytes) throw new InvalidDataException("Managed sample exceeds the ConsoleIL image budget.");
byte[] image = new byte[checked((int)sample.Length)]; sample.ReadExactly(image); workspace.WriteBytes(ManagedDemoPath, image);
workspace.WriteBytes(SystemPaths.Combine(SystemPaths.Documents, "ManagedHello.dll"), image);
return workspace;
}
// Input remains an explicit optional adapter. No fabricated reports or host window input enter this loop.
private static void Pump(DesktopSession desktop, INativeInputSource? input)
{
long previous = NativePlatform.Milliseconds(), nextTick = previous;
for (;;)
{
long now = NativePlatform.Milliseconds();
if (now < previous) throw new InvalidOperationException("The native monotonic clock moved backward.");
previous = now;
if (input is { IsAvailable: true })
for (int reports = 0; reports < 256 && input.TryRead(out var report); reports++) NativeInput.Dispatch(desktop, report, now);
if (now >= nextTick)
{
desktop.AdvanceFeedback(now);
if (desktop.NeedsRender)
{
desktop.Render();
if (desktop.LastFrameCompleted)
{
ReportWindowState(desktop);
if (desktop.ActiveWindow is { BrowserSession: not null } active) ReportBrowserState(active, now);
}
}
nextTick = now + 16;
}
Thread.Sleep(1);
}
}
private static string lastWindowState = "";
private static void ReportWindowState(DesktopSession desktop)
{
string report = "XFE_DESKTOP_FLAGS|" + (desktop.IsStartMenuOpen ? 1 : 0) + "|" + (desktop.IsWindowSwitching ? 1 : 0) +
"|Active|" + (desktop.ActiveWindow?.Id ?? 0) + "\n" +
"XFE_DESKTOP_APPEARANCE|" + desktop.Theme.Mode + "|" + desktop.Theme.Accent.ToString("X6") +
"|Persistent|" + (desktop.IsAppearancePersistent ? 1 : 0) + "\n";
foreach (var window in desktop.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;
NativePlatform.Write("XFE_DESKTOP_ACTIVE|" + (desktop.ActiveWindow?.Application.ToString() ?? "Desktop") + "\n" + report + "XFE_DESKTOP_STATE_END\n");
}
private static string lastBrowserState = "", lastBrowserInput = "", lastMonacoProof = "";
private static long lastBrowserReport;
private static void ReportBrowserState(DesktopWindow window, long now)
{
if (window.BrowserSession is not BrowserService browser) return;
if (browser.LastInputTrace != lastBrowserInput)
{
lastBrowserInput = browser.LastInputTrace;
NativePlatform.Write("XFE_BROWSER_INPUT|" + lastBrowserInput + "\n");
}
if (now - lastBrowserReport < 200) return;
lastBrowserReport = now;
string body = window.Content.Length <= 4096 ? window.Content : window.Content[..4096];
string state = window.Id + "|" + window.Location + "\n" + body;
if (state != lastBrowserState)
{
lastBrowserState = state;
NativePlatform.Write("XFE_BROWSER_STATE_BEGIN\n" + state + "\nXFE_BROWSER_STATE_END\n");
}
if (Uri.TryCreate(browser.CurrentPage.Address, UriKind.Absolute, out var uri) && BrowserService.IsMonacoAddress(uri))
{
string proof = browser.ReadMonacoProof();
if (proof != "{}" && proof != lastMonacoProof)
{
lastMonacoProof = proof;
NativePlatform.Write("XFE_MONACO_CSHARP_PROOF_BEGIN\n" + proof + "\nXFE_MONACO_CSHARP_PROOF_END\n");
}
NativePlatform.Write("XFE_MONACO_VALUE_BEGIN\n" + (browser.ReadEditorText() ?? "Editor unavailable") + "\nXFE_MONACO_VALUE_END\n");
}
}
}