This commit is contained in:
2026-03-24 13:40:18 +00:00
parent 075fe8526c
commit c7e9acbdc2
21 changed files with 389 additions and 37 deletions
@@ -1,13 +0,0 @@
[package]
name = "prometeu-runtime-desktop"
version = "0.1.0"
edition = "2024"
license.workspace = true
[dependencies]
prometeu-core = { path = "../prometeu-core" }
winit = "0.30.12"
pixels = "0.15.0"
cpal = "0.15.3"
ringbuf = "0.4.7"
serde_json = "1.0"
-18
View File
@@ -1,18 +0,0 @@
# PROMETEU Desktop Runtime
This is the host implementation for desktop platforms, allowing PROMETEU to run on Windows, Linux, and macOS.
## Features
- **Rendering**: Uses the GPU via the `pixels` library to present the low-resolution framebuffer.
- **Input**: Translates keyboard and controller events (via `winit`) into PROMETEU hardware signals.
- **Audio**: Interfaces with the host's sound system (via `cpal`).
- **Debugging**: Hosts a TCP server that implements the **DevTools Protocol**, allowing connections from external IDEs or debuggers.
## How to run
Generally executed via the main CLI (`prometeu`), but can be called directly for testing:
```bash
cargo run -- --run path/to/cart
```
@@ -1,213 +0,0 @@
use prometeu_core::hardware::{AudioCommand, Channel, LoopMode, MAX_CHANNELS, OUTPUT_SAMPLE_RATE};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use ringbuf::traits::{Consumer, Producer, Split};
use ringbuf::HeapRb;
use std::sync::Arc;
use std::time::Duration;
pub struct HostAudio {
pub producer: Option<ringbuf::wrap::CachingProd<Arc<HeapRb<AudioCommand>>>>,
pub perf_consumer: Option<ringbuf::wrap::CachingCons<Arc<HeapRb<u64>>>>,
_stream: Option<cpal::Stream>,
}
impl HostAudio {
pub fn new() -> Self {
Self {
producer: None,
perf_consumer: None,
_stream: None,
}
}
pub fn init(&mut self) {
let host = cpal::default_host();
let device = host
.default_output_device()
.expect("no output device available");
let config = cpal::StreamConfig {
channels: 2,
sample_rate: cpal::SampleRate(OUTPUT_SAMPLE_RATE),
buffer_size: cpal::BufferSize::Default,
};
let rb = HeapRb::<AudioCommand>::new(1024);
let (prod, mut cons) = rb.split();
self.producer = Some(prod);
let mut mixer = AudioMixer::new();
// To pass performance data from the audio thread to the main thread
let audio_perf_rb = HeapRb::<u64>::new(64);
let (mut perf_prod, perf_cons) = audio_perf_rb.split();
let stream = device
.build_output_stream(
&config,
move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
// Consumes commands from ringbuffer
while let Some(cmd) = cons.try_pop() {
mixer.process_command(cmd);
}
// Mixes audio
mixer.fill_buffer(data);
// Sends processing time in microseconds
let _ = perf_prod.try_push(mixer.last_processing_time.as_micros() as u64);
},
|err| eprintln!("audio stream error: {}", err),
None,
)
.expect("failed to build audio stream");
stream.play().expect("failed to play audio stream");
self._stream = Some(stream);
self.perf_consumer = Some(perf_cons);
}
pub fn send_commands(&mut self, commands: &mut Vec<AudioCommand>) {
if let Some(producer) = &mut self.producer {
for cmd in commands.drain(..) {
let _ = producer.try_push(cmd);
}
}
}
pub fn update_stats(&mut self, stats: &mut crate::stats::HostStats) {
if let Some(cons) = &mut self.perf_consumer {
while let Some(us) = cons.try_pop() {
stats.record_audio_perf(us);
}
}
}
}
pub struct AudioMixer {
voices: [Channel; MAX_CHANNELS],
pub last_processing_time: Duration,
}
impl AudioMixer {
pub fn new() -> Self {
Self {
voices: Default::default(),
last_processing_time: Duration::ZERO,
}
}
pub fn process_command(&mut self, cmd: AudioCommand) {
match cmd {
AudioCommand::Play {
sample,
voice_id,
volume,
pan,
pitch,
priority,
loop_mode,
} => {
if voice_id < MAX_CHANNELS {
self.voices[voice_id] = Channel {
sample: Some(sample),
pos: 0.0,
pitch,
volume,
pan,
loop_mode,
priority,
};
}
}
AudioCommand::Stop { voice_id } => {
if voice_id < MAX_CHANNELS {
self.voices[voice_id].sample = None;
}
}
AudioCommand::SetVolume { voice_id, volume } => {
if voice_id < MAX_CHANNELS {
self.voices[voice_id].volume = volume;
}
}
AudioCommand::SetPan { voice_id, pan } => {
if voice_id < MAX_CHANNELS {
self.voices[voice_id].pan = pan;
}
}
AudioCommand::SetPitch { voice_id, pitch } => {
if voice_id < MAX_CHANNELS {
self.voices[voice_id].pitch = pitch;
}
}
}
}
pub fn fill_buffer(&mut self, buffer: &mut [f32]) {
let start = std::time::Instant::now();
// Zeroes the buffer (stereo)
for sample in buffer.iter_mut() {
*sample = 0.0;
}
for voice in self.voices.iter_mut() {
let sample_data = match &voice.sample {
Some(s) => s,
None => continue,
};
let pitch_ratio = sample_data.sample_rate as f64 / OUTPUT_SAMPLE_RATE as f64;
let step = voice.pitch * pitch_ratio;
let vol_f = voice.volume as f32 / 255.0;
let pan_f = voice.pan as f32 / 255.0;
let vol_l = vol_f * (1.0 - pan_f).sqrt();
let vol_r = vol_f * pan_f.sqrt();
for frame in buffer.chunks_exact_mut(2) {
let pos_int = voice.pos as usize;
let pos_fract = voice.pos - pos_int as f64;
if pos_int >= sample_data.data.len() {
voice.sample = None;
break;
}
// Linear Interpolation
let s1 = sample_data.data[pos_int] as f32 / 32768.0;
let s2 = if pos_int + 1 < sample_data.data.len() {
sample_data.data[pos_int + 1] as f32 / 32768.0
} else if voice.loop_mode == LoopMode::On {
let loop_start = sample_data.loop_start.unwrap_or(0) as usize;
sample_data.data[loop_start] as f32 / 32768.0
} else {
0.0
};
let sample_val = s1 + (s2 - s1) * pos_fract as f32;
frame[0] += sample_val * vol_l;
frame[1] += sample_val * vol_r;
voice.pos += step;
let end_pos = sample_data.loop_end.map(|e| e as f64).unwrap_or(sample_data.data.len() as f64);
if voice.pos >= end_pos {
if voice.loop_mode == LoopMode::On {
let loop_start = sample_data.loop_start.unwrap_or(0) as f64;
voice.pos = loop_start + (voice.pos - end_pos);
} else {
voice.sample = None;
break;
}
}
}
}
// Final clamp to avoid clipping (optional if using f32, but good for fidelity)
for sample in buffer.iter_mut() {
*sample = sample.clamp(-1.0, 1.0);
}
self.last_processing_time = start.elapsed();
}
}
@@ -1,53 +0,0 @@
use prometeu_core::telemetry::CertificationConfig;
pub fn load_cap_config(path: &str) -> Option<CertificationConfig> {
let content = std::fs::read_to_string(path).ok()?;
let mut config = CertificationConfig {
enabled: true,
..Default::default()
};
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') { continue; }
let parts: Vec<&str> = line.split('=').collect();
if parts.len() != 2 { continue; }
let key = parts[0].trim();
let val = parts[1].trim();
match key {
"cycles_budget" => config.cycles_budget_per_frame = val.parse().ok(),
"max_syscalls" => config.max_syscalls_per_frame = val.parse().ok(),
"max_host_cpu_us" => config.max_host_cpu_us_per_frame = val.parse().ok(),
_ => {}
}
}
Some(config)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_load_cap_config() {
let content = "cycles_budget=500\nmax_syscalls=10\n# comentário\nmax_host_cpu_us=2000";
let path = "test_cap.cfg";
std::fs::write(path, content).unwrap();
let config = load_cap_config(path).unwrap();
assert!(config.enabled);
assert_eq!(config.cycles_budget_per_frame, Some(500));
assert_eq!(config.max_syscalls_per_frame, Some(10));
assert_eq!(config.max_host_cpu_us_per_frame, Some(2000));
std::fs::remove_file(path).unwrap();
}
#[test]
fn test_load_cap_config_not_found() {
let config = load_cap_config("non_existent.cfg");
assert!(config.is_none());
}
}
@@ -1,268 +0,0 @@
use prometeu_core::firmware::{BootTarget, Firmware};
use prometeu_core::Hardware;
use prometeu_core::model::CartridgeLoader;
use prometeu_core::debugger_protocol::*;
use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
/// Host-side implementation of the PROMETEU DevTools Protocol.
///
/// This component acts as a TCP server that allows external tools (like the
/// Prometeu Debugger) to observe and control the execution of the virtual machine.
///
/// Communication is based on JSONL (JSON lines) over TCP.
pub struct HostDebugger {
/// If true, the VM will not start execution until a 'start' command is received.
pub waiting_for_start: bool,
/// The TCP listener for incoming debugger connections.
pub(crate) listener: Option<TcpListener>,
/// The currently active connection to a debugger client.
pub(crate) stream: Option<TcpStream>,
/// Sequence tracker to ensure logs are sent only once.
last_log_seq: u64,
/// Frame tracker to send telemetry snapshots periodically.
last_telemetry_frame: u64,
}
impl HostDebugger {
/// Creates a new debugger interface in an idle state.
pub fn new() -> Self {
Self {
waiting_for_start: false,
listener: None,
stream: None,
last_log_seq: 0,
last_telemetry_frame: 0,
}
}
/// Configures the debugger based on the boot target.
/// If debug mode is enabled, it binds to the specified TCP port.
pub fn setup_boot_target(&mut self, boot_target: &BootTarget, firmware: &mut Firmware) {
if let BootTarget::Cartridge { path, debug: true, debug_port } = boot_target {
self.waiting_for_start = true;
// Pre-load cartridge metadata so the Handshake message can contain
// valid information about the App being debugged.
if let Ok(cartridge) = CartridgeLoader::load(path) {
firmware.os.initialize_vm(&mut firmware.vm, &cartridge);
}
match TcpListener::bind(format!("127.0.0.1:{}", debug_port)) {
Ok(listener) => {
// Set listener to non-blocking so it doesn't halt the main loop.
listener.set_nonblocking(true).expect("Cannot set non-blocking");
self.listener = Some(listener);
println!("[Debugger] Listening for start command on port {}...", debug_port);
}
Err(e) => {
eprintln!("[Debugger] Failed to bind to port {}: {}", debug_port, e);
}
}
println!("[Debugger] (Or press D to start execution)");
}
}
/// Sends a structured response to the connected debugger client.
fn send_response(&mut self, resp: DebugResponse) {
if let Some(stream) = &mut self.stream {
if let Ok(json) = serde_json::to_string(&resp) {
let _ = stream.write_all(json.as_bytes());
let _ = stream.write_all(b"\n");
}
}
}
/// Sends an asynchronous event to the connected debugger client.
fn send_event(&mut self, event: DebugEvent) {
if let Some(stream) = &mut self.stream {
if let Ok(json) = serde_json::to_string(&event) {
let _ = stream.write_all(json.as_bytes());
let _ = stream.write_all(b"\n");
}
}
}
/// Main maintenance method called by the HostRunner every iteration.
/// It handles new connections and processes incoming commands.
pub fn check_commands(&mut self, firmware: &mut Firmware, hardware: &mut Hardware) {
// 1. Accept new client connections.
if let Some(listener) = &self.listener {
if let Ok((stream, _addr)) = listener.accept() {
// Currently, only one debugger client is supported at a time.
if self.stream.is_none() {
println!("[Debugger] Connection received!");
stream.set_nonblocking(true).expect("Cannot set non-blocking on stream");
self.stream = Some(stream);
// Immediately send the Handshake message to identify the Runtime and App.
let handshake = DebugResponse::Handshake {
protocol_version: DEVTOOLS_PROTOCOL_VERSION,
runtime_version: "0.1".to_string(),
cartridge: HandshakeCartridge {
app_id: firmware.os.current_app_id,
title: firmware.os.current_cartridge_title.clone(),
app_version: firmware.os.current_cartridge_app_version.clone(),
app_mode: firmware.os.current_cartridge_app_mode,
},
};
self.send_response(handshake);
} else {
println!("[Debugger] Connection refused: already connected.");
}
}
}
// 2. Read and process pending commands from the network stream.
if let Some(mut stream) = self.stream.take() {
let mut buf = [0u8; 4096];
match stream.read(&mut buf) {
Ok(0) => {
// TCP socket closed by the client.
println!("[Debugger] Connection closed by remote.");
self.stream = None;
// Resume VM execution if it was paused waiting for the debugger.
firmware.os.paused = false;
self.waiting_for_start = false;
}
Ok(n) => {
let data = &buf[..n];
let msg = String::from_utf8_lossy(data);
self.stream = Some(stream);
// Support multiple JSON messages in a single TCP packet.
for line in msg.lines() {
let trimmed = line.trim();
if trimmed.is_empty() { continue; }
if let Ok(cmd) = serde_json::from_str::<DebugCommand>(trimmed) {
self.handle_command(cmd, firmware, hardware);
}
}
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
// No data available right now, continue.
self.stream = Some(stream);
}
Err(e) => {
eprintln!("[Debugger] Connection error: {}", e);
self.stream = None;
firmware.os.paused = false;
self.waiting_for_start = false;
}
}
}
// 3. Push events (logs, telemetry) to the client.
if self.stream.is_some() {
self.stream_events(firmware);
}
}
/// Dispatches a specific DebugCommand to the system components.
fn handle_command(&mut self, cmd: DebugCommand, firmware: &mut Firmware, hardware: &mut Hardware) {
match cmd {
DebugCommand::Ok | DebugCommand::Start => {
if self.waiting_for_start {
println!("[Debugger] Starting execution...");
self.waiting_for_start = false;
}
firmware.os.paused = false;
}
DebugCommand::Pause => {
firmware.os.paused = true;
}
DebugCommand::Resume => {
firmware.os.paused = false;
}
DebugCommand::Step => {
// Execute exactly one instruction and keep paused.
firmware.os.paused = true;
let _ = firmware.os.debug_step_instruction(&mut firmware.vm, hardware);
}
DebugCommand::StepFrame => {
// Execute until the end of the current logical frame.
firmware.os.paused = false;
firmware.os.debug_step_request = true;
}
DebugCommand::GetState => {
// Return detailed VM register and stack state.
let stack_top = firmware.vm.operand_stack.iter()
.rev().take(10).cloned().collect();
let resp = DebugResponse::GetState {
pc: firmware.vm.pc,
stack_top,
frame_index: firmware.os.logical_frame_index,
app_id: firmware.os.current_app_id,
};
self.send_response(resp);
}
DebugCommand::SetBreakpoint { pc } => {
firmware.vm.breakpoints.insert(pc);
}
DebugCommand::ListBreakpoints => {
let pcs = firmware.vm.breakpoints.iter().cloned().collect();
self.send_response(DebugResponse::Breakpoints { pcs });
}
DebugCommand::ClearBreakpoint { pc } => {
firmware.vm.breakpoints.remove(&pc);
}
}
}
/// Scans the system for new information to push to the debugger client.
fn stream_events(&mut self, firmware: &mut Firmware) {
// 1. Process and send new log entries.
let new_events = firmware.os.log_service.get_after(self.last_log_seq);
for event in new_events {
self.last_log_seq = event.seq;
// Map specific internal log tags to protocol events.
if event.tag == 0xDEB1 {
self.send_event(DebugEvent::BreakpointHit {
pc: firmware.vm.pc,
frame_index: firmware.os.logical_frame_index,
});
}
// Map Certification tags (0xCA01-0xCA03) to 'Cert' protocol events.
if event.tag >= 0xCA01 && event.tag <= 0xCA03 {
let rule = match event.tag {
0xCA01 => "cycles_budget",
0xCA02 => "max_syscalls",
0xCA03 => "max_host_cpu_us",
_ => "unknown"
}.to_string();
self.send_event(DebugEvent::Cert {
rule,
used: 0,
limit: 0,
frame_index: firmware.os.logical_frame_index,
});
}
self.send_event(DebugEvent::Log {
level: format!("{:?}", event.level),
source: format!("{:?}", event.source),
msg: event.msg.clone(),
});
}
// 2. Send telemetry snapshots at the completion of every frame.
let current_frame = firmware.os.logical_frame_index;
if current_frame > self.last_telemetry_frame {
let tel = &firmware.os.telemetry_last;
self.send_event(DebugEvent::Telemetry {
frame_index: tel.frame_index,
vm_steps: tel.vm_steps,
syscalls: tel.syscalls,
cycles: tel.cycles_used,
});
self.last_telemetry_frame = current_frame;
}
}
}
@@ -1,112 +0,0 @@
use std::path::PathBuf;
use std::fs;
use prometeu_core::fs::{FsBackend, FsEntry, FsError};
pub struct HostDirBackend {
root: PathBuf,
}
impl HostDirBackend {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
fn resolve(&self, path: &str) -> PathBuf {
let path = path.trim_start_matches('/');
self.root.join(path)
}
}
impl FsBackend for HostDirBackend {
fn mount(&mut self) -> Result<(), FsError> {
if !self.root.exists() {
return Err(FsError::NotFound);
}
for dir in &["system", "apps", "media", "user"] {
let path = self.root.join(dir);
if !path.exists() {
fs::create_dir_all(&path).map_err(|e| FsError::IOError(e.to_string()))?;
}
}
Ok(())
}
fn unmount(&mut self) {}
fn list_dir(&self, path: &str) -> Result<Vec<FsEntry>, FsError> {
let full_path = self.resolve(path);
let entries = fs::read_dir(full_path).map_err(|e| FsError::IOError(e.to_string()))?;
let mut result = Vec::new();
for entry in entries {
let entry = entry.map_err(|e| FsError::IOError(e.to_string()))?;
let metadata = entry.metadata().map_err(|e| FsError::IOError(e.to_string()))?;
result.push(FsEntry {
name: entry.file_name().to_string_lossy().into_owned(),
is_dir: metadata.is_dir(),
size: metadata.len(),
});
}
Ok(result)
}
fn read_file(&self, path: &str) -> Result<Vec<u8>, FsError> {
let full_path = self.resolve(path);
fs::read(full_path).map_err(|e| match e.kind() {
std::io::ErrorKind::NotFound => FsError::NotFound,
_ => FsError::IOError(e.to_string()),
})
}
fn write_file(&mut self, path: &str, data: &[u8]) -> Result<(), FsError> {
let full_path = self.resolve(path);
if let Some(parent) = full_path.parent() {
fs::create_dir_all(parent).map_err(|e| FsError::IOError(e.to_string()))?;
}
fs::write(full_path, data).map_err(|e| FsError::IOError(e.to_string()))
}
fn delete(&mut self, path: &str) -> Result<(), FsError> {
let full_path = self.resolve(path);
if full_path.is_dir() {
fs::remove_dir_all(full_path).map_err(|e| FsError::IOError(e.to_string()))
} else {
fs::remove_file(full_path).map_err(|e| FsError::IOError(e.to_string()))
}
}
fn exists(&self, path: &str) -> bool {
self.resolve(path).exists()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::env;
fn get_temp_dir(name: &str) -> PathBuf {
let mut path = env::temp_dir();
path.push(format!("prometeu_host_test_{}_{}", name, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
fs::create_dir_all(&path).unwrap();
path
}
#[test]
fn test_host_dir_backend_mount_and_dirs() {
let root = get_temp_dir("mount");
let mut backend = HostDirBackend::new(root.clone());
backend.mount().unwrap();
assert!(root.join("system").is_dir());
assert!(root.join("apps").is_dir());
assert!(root.join("media").is_dir());
assert!(root.join("user").is_dir());
let _ = fs::remove_dir_all(root);
}
}
@@ -1,78 +0,0 @@
use winit::event::{ElementState, MouseButton, WindowEvent};
use winit::keyboard::{KeyCode, PhysicalKey};
use winit::window::Window;
use prometeu_core::hardware::InputSignals;
use prometeu_core::Hardware;
pub struct HostInputHandler {
pub signals: InputSignals,
}
impl HostInputHandler {
pub fn new() -> Self {
Self {
signals: InputSignals::default(),
}
}
pub fn handle_event(&mut self, event: &WindowEvent, window: &Window) {
match event {
WindowEvent::KeyboardInput { event, .. } => {
if let PhysicalKey::Code(code) = event.physical_key {
let is_down = event.state == ElementState::Pressed;
match code {
KeyCode::ArrowUp => self.signals.up_signal = is_down,
KeyCode::ArrowDown => self.signals.down_signal = is_down,
KeyCode::ArrowLeft => self.signals.left_signal = is_down,
KeyCode::ArrowRight => self.signals.right_signal = is_down,
KeyCode::KeyA => self.signals.a_signal = is_down,
KeyCode::KeyD => self.signals.b_signal = is_down,
KeyCode::KeyW => self.signals.x_signal = is_down,
KeyCode::KeyS => self.signals.y_signal = is_down,
KeyCode::KeyQ => self.signals.l_signal = is_down,
KeyCode::KeyE => self.signals.r_signal = is_down,
KeyCode::KeyZ => self.signals.start_signal = is_down,
KeyCode::ShiftLeft | KeyCode::ShiftRight => self.signals.select_signal = is_down,
_ => {}
}
}
}
WindowEvent::CursorMoved { position, .. } => {
let v = window_to_fb(position.x as f32, position.y as f32, window);
self.signals.x_pos = v.0;
self.signals.y_pos = v.1;
}
WindowEvent::MouseInput { state, button, .. } => {
if *button == MouseButton::Left {
match state {
ElementState::Pressed => {
self.signals.f_signal = true;
}
ElementState::Released => {
self.signals.f_signal = false;
}
}
}
}
_ => {}
}
}
}
pub fn window_to_fb(wx: f32, wy: f32, window: &Window) -> (i32, i32) {
let size = window.inner_size();
let fb_w = Hardware::W as f32;
let fb_h = Hardware::H as f32;
let x = (wx * fb_w / size.width as f32).floor() as i32;
let y = (wy * fb_h / size.height as f32).floor() as i32;
(x.clamp(0, Hardware::W as i32 - 1), y.clamp(0, Hardware::H as i32 - 1))
}
@@ -1,46 +0,0 @@
use prometeu_core::log::{LogEvent, LogLevel, LogSource};
pub struct HostConsoleSink {
last_seq: Option<u64>,
}
impl HostConsoleSink {
pub fn new() -> Self {
Self { last_seq: None }
}
pub fn process_events(&mut self, events: Vec<LogEvent>) {
for event in events {
let level_str = match event.level {
LogLevel::Trace => "TRACE",
LogLevel::Debug => "DEBUG",
LogLevel::Info => "INFO",
LogLevel::Warn => "WARN",
LogLevel::Error => "ERROR",
};
let source_buf;
let source_str = match event.source {
LogSource::Pos => "POS",
LogSource::Hub => "HUB",
LogSource::Vm => "VM",
LogSource::Fs => "FS",
LogSource::App { app_id } => {
source_buf = format!("APP:{}", app_id);
&source_buf
}
};
println!(
"[{:06}ms][{}][{}][{}] {}",
event.ts_ms, event.frame, level_str, source_str, event.msg
);
self.last_seq = Some(event.seq);
}
}
pub fn last_seq(&self) -> Option<u64> {
self.last_seq
}
}
@@ -1,84 +0,0 @@
mod audio;
mod runner;
mod fs_backend;
mod log_sink;
mod debugger;
mod stats;
mod input;
mod cap;
mod utilities;
use crate::runner::HostRunner;
use crate::cap::load_cap_config;
use winit::event_loop::EventLoop;
use prometeu_core::firmware::BootTarget;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().collect();
let mut fs_root = None;
let mut cap_config = None;
let mut cartridge_path = None;
let mut debug_mode = false;
let mut debug_port = 7777;
let mut i = 1; // Skip the executable name
while i < args.len() {
match args[i].as_str() {
"--run" => {
if i + 1 < args.len() {
cartridge_path = Some(args[i + 1].clone());
debug_mode = false;
i += 1;
}
}
"--debug" => {
if i + 1 < args.len() {
cartridge_path = Some(args[i + 1].clone());
debug_mode = true;
i += 1;
}
}
"--port" => {
if i + 1 < args.len() {
if let Ok(port) = args[i + 1].parse::<u16>() {
debug_port = port;
}
i += 1;
}
}
"--fs-root" => {
if i + 1 < args.len() {
fs_root = Some(args[i + 1].clone());
i += 1;
}
}
"--cap" => {
if i + 1 < args.len() {
cap_config = load_cap_config(&args[i + 1]);
i += 1;
}
}
_ => {}
}
i += 1;
}
let boot_target = if let Some(path) = cartridge_path {
BootTarget::Cartridge {
path,
debug: debug_mode,
debug_port: if debug_mode { debug_port } else { 7777 },
}
} else {
BootTarget::Hub
};
let event_loop = EventLoop::new()?;
let mut runner = HostRunner::new(fs_root, cap_config);
runner.set_boot_target(boot_target);
event_loop.run_app(&mut runner)?;
Ok(())
}
@@ -1,501 +0,0 @@
use crate::audio::HostAudio;
use crate::fs_backend::HostDirBackend;
use crate::log_sink::HostConsoleSink;
use crate::debugger::HostDebugger;
use crate::stats::HostStats;
use crate::input::HostInputHandler;
use crate::utilities::draw_rgb565_to_rgba8;
use pixels::{Pixels, SurfaceTexture};
use prometeu_core::firmware::{BootTarget, Firmware};
use prometeu_core::Hardware;
use std::time::{Duration, Instant};
use winit::application::ApplicationHandler;
use winit::dpi::LogicalSize;
use winit::event::{ElementState, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow};
use winit::keyboard::{KeyCode, PhysicalKey};
use winit::window::{Window, WindowAttributes, WindowId};
use prometeu_core::telemetry::CertificationConfig;
/// The Desktop implementation of the PROMETEU Runtime.
///
/// This struct acts as the physical "chassis" of the virtual console. It is
/// responsible for:
/// - Creating and managing the OS window (via `winit`).
/// - Initializing the GPU-accelerated framebuffer (via `pixels`).
/// - Handling real keyboard/gamepad events and converting them to virtual signals.
/// - Providing a high-fidelity audio backend (via `cpal`).
/// - Implementing the DevTools Protocol for remote debugging.
/// - Maintaining a deterministic 60Hz timing loop.
pub struct HostRunner {
/// The OS window handle.
window: Option<&'static Window>,
/// The pixel buffer interface for rendering to the GPU.
pixels: Option<Pixels<'static>>,
/// The instance of the virtual hardware peripherals.
hardware: Hardware,
/// The instance of the system firmware and OS logic.
firmware: Firmware,
/// Helper to collect and normalize input signals.
input: HostInputHandler,
/// Root path for the virtual sandbox filesystem.
fs_root: Option<String>,
/// Sink for system and application logs (prints to console).
log_sink: HostConsoleSink,
/// Target duration for a single frame (nominally 16.66ms for 60Hz).
frame_target_dt: Duration,
/// Last recorded wall-clock time to calculate deltas.
last_frame_time: Instant,
/// Time accumulator used to guarantee exact 60Hz logic updates.
accumulator: Duration,
/// Performance metrics collector.
stats: HostStats,
/// Remote debugger interface.
debugger: HostDebugger,
/// Flag to enable/disable the technical telemetry display.
overlay_enabled: bool,
/// The physical audio driver.
audio: HostAudio,
}
impl HostRunner {
/// Configures the boot target (Hub or specific Cartridge).
pub(crate) fn set_boot_target(&mut self, boot_target: BootTarget) {
self.firmware.boot_target = boot_target.clone();
self.debugger.setup_boot_target(&boot_target, &mut self.firmware);
}
/// Creates a new desktop runner instance.
pub(crate) fn new(fs_root: Option<String>, cap_config: Option<CertificationConfig>) -> Self {
let target_fps = 60;
let mut firmware = Firmware::new(cap_config);
if let Some(root) = &fs_root {
let backend = HostDirBackend::new(root);
firmware.os.mount_fs(Box::new(backend));
}
Self {
window: None,
pixels: None,
hardware: Hardware::new(),
firmware,
input: HostInputHandler::new(),
fs_root,
log_sink: HostConsoleSink::new(),
frame_target_dt: Duration::from_nanos(1_000_000_000 / target_fps),
last_frame_time: Instant::now(),
accumulator: Duration::ZERO,
stats: HostStats::new(),
debugger: HostDebugger::new(),
overlay_enabled: false,
audio: HostAudio::new(),
}
}
fn window(&self) -> &'static Window {
self.window.expect("window not created yet")
}
fn resize_surface(&mut self, width: u32, height: u32) {
if let Some(p) = self.pixels.as_mut() {
let _ = p.resize_surface(width, height);
}
}
fn request_redraw(&self) {
if let Some(w) = self.window.as_ref() {
w.request_redraw();
}
}
fn display_dbg_overlay(&mut self) {
let tel = &self.firmware.os.telemetry_last;
let color_text = prometeu_core::model::Color::WHITE;
let color_bg = prometeu_core::model::Color::INDIGO; // Dark blue to stand out
let color_warn = prometeu_core::model::Color::RED;
self.hardware.gfx.fill_rect(5, 5, 140, 65, color_bg);
self.hardware.gfx.draw_text(10, 10, &format!("FPS: {:.1}", self.stats.current_fps), color_text);
self.hardware.gfx.draw_text(10, 18, &format!("HOST: {:.2}MS", tel.host_cpu_time_us as f64 / 1000.0), color_text);
self.hardware.gfx.draw_text(10, 26, &format!("STEPS: {}", tel.vm_steps), color_text);
self.hardware.gfx.draw_text(10, 34, &format!("SYSC: {}", tel.syscalls), color_text);
self.hardware.gfx.draw_text(10, 42, &format!("CYC: {}", tel.cycles_used), color_text);
let cert_color = if tel.violations > 0 { color_warn } else { color_text };
self.hardware.gfx.draw_text(10, 50, &format!("CERT LAST: {}", tel.violations), cert_color);
if tel.violations > 0 {
if let Some(event) = self.firmware.os.log_service.get_recent(10).into_iter().rev().find(|e| e.tag >= 0xCA01 && e.tag <= 0xCA03) {
let mut msg = event.msg.clone();
if msg.len() > 30 { msg.truncate(30); }
self.hardware.gfx.draw_text(10, 58, &msg, color_warn);
}
}
}
}
impl ApplicationHandler for HostRunner {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let attrs = WindowAttributes::default()
.with_title(format!(
"PROMETEU | GFX: {:.1} KB | FPS: {:.1} | Load: {:.1}% (C) + {:.1}% (A) | Frame: tick {} logical {}",
0.0, 0.0, 0.0, 0, 0, 0))
.with_inner_size(LogicalSize::new(960.0, 540.0))
.with_min_inner_size(LogicalSize::new(320.0, 180.0));
let window = event_loop.create_window(attrs).expect("failed to create window");
// 🔥 Leak: Window becomes &'static Window (bootstrap)
let window: &'static Window = Box::leak(Box::new(window));
self.window = Some(window);
let size = window.inner_size();
let surface_texture = SurfaceTexture::new(size.width, size.height, window);
let mut pixels = Pixels::new(Hardware::W as u32, Hardware::H as u32, surface_texture)
.expect("failed to create Pixels");
pixels.frame_mut().fill(0);
self.pixels = Some(pixels);
self.audio.init();
event_loop.set_control_flow(ControlFlow::Poll);
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
self.input.handle_event(&event, self.window());
match event {
WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::Resized(size) => {
self.resize_surface(size.width, size.height);
}
WindowEvent::ScaleFactorChanged { .. } => {
let size = self.window().inner_size();
self.resize_surface(size.width, size.height);
}
WindowEvent::RedrawRequested => {
// Get Pixels directly from the field (not via helper that gets the entire &mut self)
let pixels = self.pixels.as_mut().expect("pixels not initialized");
{
// Mutable borrow of the frame (lasts only within this block)
let frame = pixels.frame_mut();
// Immutable borrow of prometeu-core (different field, ok)
let src = self.hardware.gfx.front_buffer();
draw_rgb565_to_rgba8(src, frame);
} // <- frame borrow ends here
if pixels.render().is_err() {
event_loop.exit();
}
}
WindowEvent::KeyboardInput { event, .. } => {
if let PhysicalKey::Code(code) = event.physical_key {
let is_down = event.state == ElementState::Pressed;
if is_down && code == KeyCode::KeyD && self.debugger.waiting_for_start {
self.debugger.waiting_for_start = false;
println!("[Debugger] Execution started!");
}
if is_down && code == KeyCode::F1 {
self.overlay_enabled = !self.overlay_enabled;
}
}
}
_ => {}
}
}
/// Called by `winit` when the application is idle and ready to perform updates.
/// This is where the core execution loop lives.
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
// 1. Process pending debug commands from the network.
self.debugger.check_commands(&mut self.firmware, &mut self.hardware);
// 2. Maintain filesystem connection if it was lost (e.g., directory removed).
if let Some(root) = &self.fs_root {
use prometeu_core::fs::FsState;
if matches!(self.firmware.os.fs_state, FsState::Unmounted | FsState::Error(_)) {
if std::path::Path::new(root).exists() {
let backend = HostDirBackend::new(root);
self.firmware.os.mount_fs(Box::new(backend));
}
}
}
// 3. Timing Management (The heart of determinism).
// We measure the elapsed time since the last iteration and add it to an
// accumulator. We then execute exactly as many 60Hz slices as the
// accumulator allows.
let now = Instant::now();
let mut frame_delta = now.duration_since(self.last_frame_time);
// Safety cap: if the OS freezes or we fall behind too much, we don't try
// to catch up indefinitely (avoiding the "death spiral").
if frame_delta > Duration::from_millis(100) {
frame_delta = Duration::from_millis(100);
}
self.last_frame_time = now;
self.accumulator += frame_delta;
// 🔥 Logic Update Loop: consumes time in exact 60Hz (16.66ms) slices.
while self.accumulator >= self.frame_target_dt {
// Unless the debugger is waiting for a 'start' command, advance the system.
if !self.debugger.waiting_for_start {
self.firmware.step_frame(&self.input.signals, &mut self.hardware);
}
// Sync virtual audio commands to the physical mixer.
self.audio.send_commands(&mut self.hardware.audio.commands);
self.accumulator -= self.frame_target_dt;
self.stats.record_frame();
}
// 4. Feedback and Synchronization.
self.audio.update_stats(&mut self.stats);
// Update technical statistics displayed in the window title.
self.stats.update(now, self.window, &self.hardware, &self.firmware);
// Synchronize system logs to the host console.
let last_seq = self.log_sink.last_seq().unwrap_or(u64::MAX);
let new_events = if last_seq == u64::MAX {
self.firmware.os.log_service.get_recent(4096)
} else {
self.firmware.os.log_service.get_after(last_seq)
};
self.log_sink.process_events(new_events);
// 5. Rendering the Telemetry Overlay (if enabled).
if self.overlay_enabled {
// We temporarily swap buffers to draw over the current image.
self.hardware.gfx.present();
self.display_dbg_overlay();
self.hardware.gfx.present();
}
// Finally, request a window redraw to present the new pixels.
self.request_redraw();
}
}
#[cfg(test)]
mod tests {
use super::*;
use prometeu_core::firmware::BootTarget;
use prometeu_core::debugger_protocol::DEVTOOLS_PROTOCOL_VERSION;
use std::net::TcpStream;
use std::io::{Read, Write};
#[test]
fn test_debug_port_opens() {
let mut runner = HostRunner::new(None, None);
let port = 9999;
runner.set_boot_target(BootTarget::Cartridge {
path: "dummy.bin".to_string(),
debug: true,
debug_port: port,
});
assert!(runner.debugger.waiting_for_start);
assert!(runner.debugger.listener.is_some());
// Check if we can connect
{
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect");
// Short sleep to ensure the OS processes
std::thread::sleep(std::time::Duration::from_millis(100));
// Simulates the loop to accept the connection
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(runner.debugger.stream.is_some(), "Stream should have been kept open");
// Handshake Check
let mut buf = [0u8; 2048];
let n = stream.read(&mut buf).expect("Should read handshake");
let resp: serde_json::Value = serde_json::from_slice(&buf[..n]).expect("Handshake should be valid JSON");
assert_eq!(resp["type"], "handshake");
assert_eq!(resp["protocol_version"], DEVTOOLS_PROTOCOL_VERSION);
// Send start via JSON
stream.write_all(b"{\"type\":\"start\"}\n").expect("Connection should be open for writing");
std::thread::sleep(std::time::Duration::from_millis(50));
// Process the received command
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(!runner.debugger.waiting_for_start, "Execution should have started after start command");
assert!(runner.debugger.listener.is_some(), "Listener should remain open for reconnections");
}
// Now that the stream is out of the test scope, the runner should detect closure on next check
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(runner.debugger.stream.is_none(), "Stream should have been closed after client disconnected");
}
#[test]
fn test_debug_reconnection() {
let mut runner = HostRunner::new(None, None);
let port = 9998;
runner.set_boot_target(BootTarget::Cartridge {
path: "dummy.bin".to_string(),
debug: true,
debug_port: port,
});
// 1. Connect and start
{
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect 1");
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(runner.debugger.stream.is_some());
stream.write_all(b"{\"type\":\"start\"}\n").expect("Should write start");
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(!runner.debugger.waiting_for_start);
// Currently the listener is closed here.
}
// 2. Disconnect (clears stream in runner)
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(runner.debugger.stream.is_none());
// 3. Try to reconnect - SHOULD FAIL currently, but we want it to WORK
let stream2 = TcpStream::connect(format!("127.0.0.1:{}", port));
assert!(stream2.is_ok(), "Should accept new connection even after start");
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(runner.debugger.stream.is_some(), "Stream should have been accepted on reconnection");
}
#[test]
fn test_debug_refuse_second_connection() {
let mut runner = HostRunner::new(None, None);
let port = 9997;
runner.set_boot_target(BootTarget::Cartridge {
path: "dummy.bin".to_string(),
debug: true,
debug_port: port,
});
// 1. First connection
let mut _stream1 = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect 1");
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(runner.debugger.stream.is_some());
// 2. Second connection
let mut stream2 = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect 2 (OS accepts)");
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware); // Should accept and close stream2
// Check if stream2 was closed by the server
let mut buf = [0u8; 10];
stream2.set_read_timeout(Some(std::time::Duration::from_millis(100))).unwrap();
let res = stream2.read(&mut buf);
assert!(matches!(res, Ok(0)) || res.is_err(), "Second connection should be closed by server");
assert!(runner.debugger.stream.is_some(), "First connection should continue active");
}
#[test]
fn test_get_state_returns_response() {
let mut runner = HostRunner::new(None, None);
let port = 9996;
runner.set_boot_target(BootTarget::Cartridge {
path: "dummy.bin".to_string(),
debug: true,
debug_port: port,
});
let stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect");
std::thread::sleep(std::time::Duration::from_millis(100));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
use std::io::BufRead;
let mut reader = std::io::BufReader::new(stream);
let mut line = String::new();
reader.read_line(&mut line).expect("Should read handshake");
assert!(line.contains("handshake"));
// Send getState
reader.get_mut().write_all(b"{\"type\":\"getState\"}\n").expect("Should write getState");
std::thread::sleep(std::time::Duration::from_millis(100));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
// Check if response received (may have events/logs before)
loop {
line.clear();
reader.read_line(&mut line).expect("Should read line");
if line.is_empty() { break; }
if let Ok(resp) = serde_json::from_str::<serde_json::Value>(&line) {
if resp["type"] == "getState" {
return;
}
}
}
panic!("Did not receive getState response");
}
#[test]
fn test_debug_resume_on_disconnect() {
let mut runner = HostRunner::new(None, None);
let port = 9995;
runner.set_boot_target(BootTarget::Cartridge {
path: "dummy.bin".to_string(),
debug: true,
debug_port: port,
});
// 1. Connect and pause
{
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Should connect");
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
stream.write_all(b"{\"type\":\"pause\"}\n").expect("Should write pause");
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(runner.firmware.os.paused, "VM should be paused");
}
// 2. Disconnect (stream goes out of scope)
std::thread::sleep(std::time::Duration::from_millis(50));
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
// 3. Check if unpaused
assert!(!runner.firmware.os.paused, "VM should have unpaused after disconnect");
assert!(!runner.debugger.waiting_for_start, "VM should have left waiting_for_start state");
}
}
@@ -1,65 +0,0 @@
use std::time::{Duration, Instant};
use winit::window::Window;
use prometeu_core::Hardware;
use prometeu_core::firmware::Firmware;
pub struct HostStats {
pub last_stats_update: Instant,
pub frames_since_last_update: u64,
pub current_fps: f64,
pub audio_load_accum_us: u64,
pub audio_load_samples: u64,
}
impl HostStats {
pub fn new() -> Self {
Self {
last_stats_update: Instant::now(),
frames_since_last_update: 0,
current_fps: 0.0,
audio_load_accum_us: 0,
audio_load_samples: 0,
}
}
pub fn record_frame(&mut self) {
self.frames_since_last_update += 1;
}
pub fn record_audio_perf(&mut self, us: u64) {
self.audio_load_accum_us += us;
self.audio_load_samples += 1;
}
pub fn update(&mut self, now: Instant, window: Option<&Window>, hardware: &Hardware, firmware: &Firmware) {
let stats_elapsed = now.duration_since(self.last_stats_update);
if stats_elapsed >= Duration::from_secs(1) {
self.current_fps = self.frames_since_last_update as f64 / stats_elapsed.as_secs_f64();
if let Some(window) = window {
let kb = hardware.gfx.memory_usage_bytes() as f64 / 1024.0;
// Fixed comparison always against 60Hz, keep even when doing CPU stress tests
let frame_budget_us = 16666.0;
let cpu_load_core = (firmware.os.last_frame_cpu_time_us as f64 / frame_budget_us) * 100.0;
let cpu_load_audio = if self.audio_load_samples > 0 {
(self.audio_load_accum_us as f64 / stats_elapsed.as_micros() as f64) * 100.0
} else {
0.0
};
let title = format!(
"PROMETEU | GFX: {:.1} KB | FPS: {:.1} | Load: {:.1}% (C) + {:.1}% (A) | Frame: tick {} logical {}",
kb, self.current_fps, cpu_load_core, cpu_load_audio, firmware.os.tick_index, firmware.os.logical_frame_index
);
window.set_title(&title);
}
self.last_stats_update = now;
self.frames_since_last_update = 0;
self.audio_load_accum_us = 0;
self.audio_load_samples = 0;
}
}
}
@@ -1,26 +0,0 @@
/// Copies RGB565 (u16) -> RGBA8888 (u8[4]) to the pixels frame.
/// Pixels format: RGBA8.
pub fn draw_rgb565_to_rgba8(src: &[u16], dst_rgba: &mut [u8]) {
for (i, &px) in src.iter().enumerate() {
let (r8, g8, b8) = rgb565_to_rgb888(px);
let o = i * 4;
dst_rgba[o] = r8;
dst_rgba[o + 1] = g8;
dst_rgba[o + 2] = b8;
dst_rgba[o + 3] = 0xFF;
}
}
/// Expands RGB565 to RGB888 (high bit replication).
#[inline(always)]
pub fn rgb565_to_rgb888(px: u16) -> (u8, u8, u8) {
let r5 = ((px >> 11) & 0x1F) as u8;
let g6 = ((px >> 5) & 0x3F) as u8;
let b5 = (px & 0x1F) as u8;
let r8 = (r5 << 3) | (r5 >> 2);
let g8 = (g6 << 2) | (g6 >> 4);
let b8 = (b5 << 3) | (b5 >> 2);
(r8, g8, b8)
}