translate to english!

This commit is contained in:
2026-03-24 13:40:18 +00:00
parent 4e633163ce
commit 9ba2aab1a5
49 changed files with 2488 additions and 2488 deletions
+8 -8
View File
@@ -1,17 +1,17 @@
# PROMETEU Desktop Runtime
Esta é a implementação de host para plataformas desktop, permitindo que o PROMETEU rode em Windows, Linux e macOS.
This is the host implementation for desktop platforms, allowing PROMETEU to run on Windows, Linux, and macOS.
## Funcionalidades
## Features
- **Renderização**: Utiliza a GPU via biblioteca `pixels` para apresentar o framebuffer de baixa resolução.
- **Input**: Traduz eventos de teclado e controle (via `winit`) para os sinais de hardware do PROMETEU.
- **Áudio**: Interface com o sistema de som do host (via `cpal`).
- **Debugging**: Hospeda um servidor TCP que implementa o **DevTools Protocol**, permitindo conexões de IDEs ou debuggers externos.
- **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.
## Como rodar
## How to run
Geralmente executado via CLI principal (`prometeu`), mas pode ser chamado diretamente para testes:
Generally executed via the main CLI (`prometeu`), but can be called directly for testing:
```bash
cargo run -- --run path/to/cart
+7 -7
View File
@@ -39,7 +39,7 @@ impl HostAudio {
let mut mixer = AudioMixer::new();
// Para passar dados de performance da thread de áudio para a principal
// 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();
@@ -47,13 +47,13 @@ impl HostAudio {
.build_output_stream(
&config,
move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
// Consome comandos da ringbuffer
// Consumes commands from ringbuffer
while let Some(cmd) = cons.try_pop() {
mixer.process_command(cmd);
}
// Mixa áudio
// Mixes audio
mixer.fill_buffer(data);
// Envia tempo de processamento em microssegundos
// Sends processing time in microseconds
let _ = perf_prod.try_push(mixer.last_processing_time.as_micros() as u64);
},
|err| eprintln!("audio stream error: {}", err),
@@ -144,7 +144,7 @@ impl AudioMixer {
pub fn fill_buffer(&mut self, buffer: &mut [f32]) {
let start = std::time::Instant::now();
// Zera o buffer (estéreo)
// Zeroes the buffer (stereo)
for sample in buffer.iter_mut() {
*sample = 0.0;
}
@@ -172,7 +172,7 @@ impl AudioMixer {
break;
}
// Interpolação Linear
// 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
@@ -204,7 +204,7 @@ impl AudioMixer {
}
}
// Clamp final para evitar clipping (opcional se usarmos f32, mas bom para fidelidade)
// 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);
}
@@ -28,7 +28,7 @@ impl HostDebugger {
if let BootTarget::Cartridge { path, debug: true, debug_port } = boot_target {
self.waiting_for_start = true;
// Pré-carrega informações do cartucho para o handshake
// Pre-loads cartridge information for the handshake
if let Ok(cartridge) = CartridgeLoader::load(path) {
firmware.os.initialize_vm(&mut firmware.vm, &cartridge);
}
@@ -75,7 +75,7 @@ impl HostDebugger {
self.stream = Some(stream);
// Enviar Handshake
// Send Handshake
let handshake = DebugResponse::Handshake {
protocol_version: DEVTOOLS_PROTOCOL_VERSION,
runtime_version: "0.1".to_string(),
@@ -104,10 +104,10 @@ impl HostDebugger {
}
Ok(n) => {
let data = &buf[..n];
// Processar múltiplos comandos se houver \n
// Process multiple commands if there's \n
let msg = String::from_utf8_lossy(data);
self.stream = Some(stream); // Coloca de volta antes de processar comandos
self.stream = Some(stream); // Put it back before processing commands
for line in msg.lines() {
let trimmed = line.trim();
@@ -154,7 +154,7 @@ impl HostDebugger {
}
DebugCommand::Step => {
firmware.os.paused = true;
// Executa uma instrução imediatamente
// Executes an instruction immediately
let _ = firmware.os.debug_step_instruction(&mut firmware.vm, hardware);
}
DebugCommand::StepFrame => {
@@ -192,7 +192,7 @@ impl HostDebugger {
for event in new_events {
self.last_log_seq = event.seq;
// Verifica se é um breakpoint hit via tag
// Check if it's a breakpoint hit via tag
if event.tag == 0xDEB1 {
self.send_event(DebugEvent::BreakpointHit {
pc: firmware.vm.pc,
@@ -200,7 +200,7 @@ impl HostDebugger {
});
}
// Certificação via Tags 0xCA01-0xCA03
// Certification via Tags 0xCA01-0xCA03
if event.tag >= 0xCA01 && event.tag <= 0xCA03 {
let rule = match event.tag {
0xCA01 => "cycles_budget",
@@ -211,7 +211,7 @@ impl HostDebugger {
self.send_event(DebugEvent::Cert {
rule,
used: 0, // Simplificado, informações detalhadas estão na msg do log
used: 0, // Simplified, detailed information is in the log message
limit: 0,
frame_index: firmware.os.logical_frame_index,
});
+1 -1
View File
@@ -21,7 +21,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut debug_mode = false;
let mut debug_port = 7777;
let mut i = 1; // Pula o nome do executável
let mut i = 1; // Skip the executable name
while i < args.len() {
match args[i].as_str() {
"--run" => {
+60 -60
View File
@@ -95,7 +95,7 @@ impl HostRunner {
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; // Azul escuro para destacar
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);
@@ -129,7 +129,7 @@ impl ApplicationHandler for HostRunner {
let window = event_loop.create_window(attrs).expect("failed to create window");
// 🔥 Leak: Window vira &'static Window (bootstrap)
// 🔥 Leak: Window becomes &'static Window (bootstrap)
let window: &'static Window = Box::leak(Box::new(window));
self.window = Some(window);
@@ -165,18 +165,18 @@ impl ApplicationHandler for HostRunner {
}
WindowEvent::RedrawRequested => {
// Pegue o Pixels diretamente do campo (não via helper que pega &mut self inteiro)
// 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");
{
// Borrow mutável do frame (dura só dentro deste bloco)
// Mutable borrow of the frame (lasts only within this block)
let frame = pixels.frame_mut();
// Borrow imutável do prometeu-core (campo diferente, ok)
// Immutable borrow of prometeu-core (different field, ok)
let src = self.hardware.gfx.front_buffer();
draw_rgb565_to_rgba8(src, frame);
} // <- frame borrow termina aqui
} // <- frame borrow ends here
if pixels.render().is_err() {
event_loop.exit();
@@ -206,7 +206,7 @@ impl ApplicationHandler for HostRunner {
fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
self.debugger.check_commands(&mut self.firmware, &mut self.hardware);
// Atualiza estado do Filesystem no OS (específico do prometeu-runtime-desktop)
// Updates Filesystem state in OS (specific to prometeu-runtime-desktop)
if let Some(root) = &self.fs_root {
use prometeu_core::fs::FsState;
if matches!(self.firmware.os.fs_state, FsState::Unmounted | FsState::Error(_)) {
@@ -220,7 +220,7 @@ impl ApplicationHandler for HostRunner {
let now = Instant::now();
let mut frame_delta = now.duration_since(self.last_frame_time);
// Limitador para evitar a "espiral da morte" se o SO travar (máximo de 100ms por volta)
// Limiter to avoid the "death spiral" if the OS freezes (max 100ms per loop)
if frame_delta > Duration::from_millis(100) {
frame_delta = Duration::from_millis(100);
}
@@ -228,7 +228,7 @@ impl ApplicationHandler for HostRunner {
self.last_frame_time = now;
self.accumulator += frame_delta;
// 🔥 O coração do determinismo: consome o tempo em fatias exatas de 60Hz
// 🔥 The heart of determinism: consumes time in exact 60Hz slices
while self.accumulator >= self.frame_target_dt {
if !self.debugger.waiting_for_start {
self.firmware.step_frame(&self.input.signals, &mut self.hardware);
@@ -242,10 +242,10 @@ impl ApplicationHandler for HostRunner {
self.audio.update_stats(&mut self.stats);
// Atualiza estatísticas a cada 1 segundo real
// Updates statistics every 1 real second
self.stats.update(now, self.window, &self.hardware, &self.firmware);
// Processa logs do sistema
// Process system logs
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)
@@ -254,11 +254,11 @@ impl ApplicationHandler for HostRunner {
};
self.log_sink.process_events(new_events);
// Overlay de Telemetria
// Telemetry Overlay
if self.overlay_enabled {
self.hardware.gfx.present(); // Traz o front para o back para desenhar por cima
self.hardware.gfx.present(); // Bring front to back to draw over
self.display_dbg_overlay();
self.hardware.gfx.present(); // Devolve para o front com o overlay aplicado
self.hardware.gfx.present(); // Return to front with overlay applied
}
self.request_redraw();
@@ -286,37 +286,37 @@ mod tests {
assert!(runner.debugger.waiting_for_start);
assert!(runner.debugger.listener.is_some());
// Verifica se conseguimos conectar
// Check if we can connect
{
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Deve conectar");
// Pequeno sleep para garantir que o SO processe
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));
// Simula o loop para aceitar a conexão
// Simulates the loop to accept the connection
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(runner.debugger.stream.is_some(), "Stream deve ter sido mantido aberto");
assert!(runner.debugger.stream.is_some(), "Stream should have been kept open");
// Verifica Handshake
// Handshake Check
let mut buf = [0u8; 2048];
let n = stream.read(&mut buf).expect("Deve ler handshake");
let resp: serde_json::Value = serde_json::from_slice(&buf[..n]).expect("Handshake deve ser JSON válido");
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);
// Envia start via JSON
stream.write_all(b"{\"type\":\"start\"}\n").expect("Conexão deve estar aberta para escrita");
// 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));
// Processa o comando recebido
// Process the received command
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware);
assert!(!runner.debugger.waiting_for_start, "Execução deve ter iniciado após comando start");
assert!(runner.debugger.listener.is_some(), "Listener deve permanecer aberto para reconexões");
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");
}
// Agora que o stream saiu do escopo do teste, o runner deve detectar o fechamento no próximo check
// 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 deve ter sido fechado após o cliente desconectar");
assert!(runner.debugger.stream.is_none(), "Stream should have been closed after client disconnected");
}
#[test]
@@ -329,32 +329,32 @@ mod tests {
debug_port: port,
});
// 1. Conecta e inicia
// 1. Connect and start
{
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Deve conectar 1");
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("Deve escrever start");
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);
// Atualmente o listener é fechado aqui.
// Currently the listener is closed here.
}
// 2. Desconecta (limpa o stream no runner)
// 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. Tenta reconectar - DEVE FALHAR atualmente, mas queremos que FUNCIONE
// 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(), "Deve aceitar nova conexão mesmo após o start");
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 deve ter sido aceito na reconexão");
assert!(runner.debugger.stream.is_some(), "Stream should have been accepted on reconnection");
}
#[test]
@@ -367,24 +367,24 @@ mod tests {
debug_port: port,
});
// 1. Primeira conexão
let mut _stream1 = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Deve conectar 1");
// 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. Segunda conexão
let mut stream2 = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Deve conectar 2 (SO aceita)");
// 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); // Deve aceitar e fechar stream2
runner.debugger.check_commands(&mut runner.firmware, &mut runner.hardware); // Should accept and close stream2
// Verifica se stream2 foi fechado pelo servidor
// 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(), "Segunda conexão deve ser fechada pelo servidor");
assert!(matches!(res, Ok(0)) || res.is_err(), "Second connection should be closed by server");
assert!(runner.debugger.stream.is_some(), "Primeira conexão deve continuar ativa");
assert!(runner.debugger.stream.is_some(), "First connection should continue active");
}
#[test]
@@ -397,7 +397,7 @@ mod tests {
debug_port: port,
});
let stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Deve conectar");
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);
@@ -405,19 +405,19 @@ mod tests {
let mut reader = std::io::BufReader::new(stream);
let mut line = String::new();
reader.read_line(&mut line).expect("Deve ler handshake");
reader.read_line(&mut line).expect("Should read handshake");
assert!(line.contains("handshake"));
// Envia getState
reader.get_mut().write_all(b"{\"type\":\"getState\"}\n").expect("Deve escrever getState");
// 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);
// Verifica se recebeu resposta (pode haver eventos/logs antes)
// Check if response received (may have events/logs before)
loop {
line.clear();
reader.read_line(&mut line).expect("Deve ler linha");
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) {
@@ -426,7 +426,7 @@ mod tests {
}
}
}
panic!("Não recebeu resposta getState");
panic!("Did not receive getState response");
}
#[test]
@@ -439,24 +439,24 @@ mod tests {
debug_port: port,
});
// 1. Conecta e pausa
// 1. Connect and pause
{
let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port)).expect("Deve conectar");
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("Deve escrever pause");
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 deve estar pausada");
assert!(runner.firmware.os.paused, "VM should be paused");
}
// 2. Desconecta (stream sai de escopo)
// 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. Verifica se despausou
assert!(!runner.firmware.os.paused, "VM deve ter despausado após desconexão");
assert!(!runner.debugger.waiting_for_start, "VM deve ter saído do estado waiting_for_start");
// 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 -1
View File
@@ -39,7 +39,7 @@ impl HostStats {
if let Some(window) = window {
let kb = hardware.gfx.memory_usage_bytes() as f64 / 1024.0;
// comparação fixa sempre contra 60Hz, manter mesmo quando fazer teste de stress na CPU
// 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;
@@ -1,5 +1,5 @@
/// Copia RGB565 (u16) -> RGBA8888 (u8[4]) para o frame do pixels.
/// Formato do pixels: RGBA8.
/// 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);
@@ -11,7 +11,7 @@ pub fn draw_rgb565_to_rgba8(src: &[u16], dst_rgba: &mut [u8]) {
}
}
/// Expande RGB565 para RGB888 (replicação de bits altos).
/// 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;