refresh: stack al día (vello 0.7 / wgpu 27 / parley 0.6) + motor 3D voxel

Re-sincroniza las fuentes desde el monorepo (estaba en vello 0.5/wgpu 24 y con la
estructura vieja de eventloop) y suma el 3D:

- bump del workspace a vello 0.7 / wgpu 27 / parley 0.6, + accesskit 0.24 /
  accesskit_winit 0.33 / vello_hybrid 0.0.9.
- nuevos crates: llimphi-3d (voxels ray-march + mallas en un depth compartido,
  montable dentro de un View 2D vía set_viewport+scissor) y llimphi-voxel
  (world-gen, personajes, director de escenas) + shared/foreign-vox (puente .vox).
- README: sección "Not just 2D — a 3D voxel engine" + GIF (docs/llimphi_voxel.gif).
- excluido modules/allichay (arrastra deps fuera del alcance del front-door).
- cargo check --workspace: verde.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Sergio
2026-06-18 14:40:00 +00:00
parent e74800d9da
commit ccab39f140
202 changed files with 44034 additions and 1811 deletions
+30
View File
@@ -0,0 +1,30 @@
[package]
name = "llimphi-module-allichay"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
publish.workspace = true
description = "llimphi-module-allichay — el renderizador único de la config declarativa. Pinta un `allichay::Schema` con el rail de dientes (secciones) y controles escalares (toggle/slider/dropdown/color/texto), y emite los cambios como (FieldPath, FieldValue). State + Msg + apply_key/view, el patrón de módulo Llimphi. Reutilizable por el panel central y por cada app."
[dependencies]
allichay = { workspace = true }
llimphi-ui = { workspace = true }
llimphi-theme = { workspace = true }
llimphi-widget-dock-rail = { workspace = true }
llimphi-widget-switch = { workspace = true }
llimphi-widget-slider = { workspace = true }
llimphi-widget-segmented = { workspace = true }
llimphi-widget-scroll = { workspace = true }
llimphi-widget-text-input = { workspace = true }
llimphi-widget-table = { workspace = true }
llimphi-widget-color-picker = { workspace = true }
llimphi-widget-modal = { workspace = true }
[dev-dependencies]
# Volcado headless del view a PNG (llvmpipe) para verlo sin levantar ventana,
# usando el schema real de mirada como muestra.
mirada-brain = { path = "../../../mirada/mirada-brain" }
pata-core = { path = "../../../pata/pata-core" }
png = { workspace = true }
pollster = { workspace = true }
+408
View File
@@ -0,0 +1,408 @@
//! Volcado headless del renderizador `allichay` a PNG: monta `allichay_view`
//! sobre el schema REAL de mirada, computa el layout, lo pinta a una
//! `vello::Scene` y lee la textura (GPU llvmpipe). Sirve para VER el panel sin
//! levantar ventana.
//!
//! `cargo run -p llimphi-module-allichay --example dump_panel -- [out.png] [seccion]`
//! (seccion = índice de diente; 1 = Decoración, rica en sliders + colores)
use std::fs::File;
use std::io::BufWriter;
use allichay::{Configurable, Field, Schema, Section};
use llimphi_module_allichay::{schema_panel, settings_overlay, AllichayMsg, AllichayState};
use llimphi_widget_dock_rail::{dock_rail_view, DockRailItem, DockRailPalette};
use llimphi_ui::llimphi_text::Alignment;
use llimphi_ui::llimphi_compositor::{measure_text_node, mount, paint};
use llimphi_ui::llimphi_hal::{wgpu, Hal};
use llimphi_ui::llimphi_layout::taffy;
use llimphi_ui::llimphi_layout::taffy::prelude::{
auto, length, percent, FlexDirection, Position, Size, Style,
};
use llimphi_ui::llimphi_layout::taffy::{AlignItems, Rect};
use llimphi_ui::llimphi_layout::LayoutTree;
use llimphi_ui::llimphi_raster::peniko::Color;
use llimphi_ui::llimphi_raster::{vello, Renderer};
use llimphi_ui::llimphi_text::Typesetter;
use llimphi_ui::View;
const W: u32 = 960;
const H: u32 = 620;
const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
fn prefix(mut s: Schema, target: &str) -> Schema {
for sec in &mut s.sections {
sec.id = format!("{target}::{}", sec.id);
}
s
}
fn main() {
let out = std::env::args().nth(1).unwrap_or_else(|| "allichay.png".to_string());
let sel: usize = std::env::args().nth(2).and_then(|s| s.parse().ok()).unwrap_or(1);
let theme = llimphi_theme::Theme::default();
// Rail de pestañas representativo del panel: la categoría Sistema (varios
// items) + dos apps. Aprovecha la triple jerarquía (sin paneles de 1 item).
let eo = allichay::EnumOption::new;
let sistema = Schema::new()
.section(
Section::new("wawa::apariencia", "Apariencia")
.icon("🎨")
.field(Field::toggle("oscuro", "Modo oscuro", true))
.field(Field::dropdown("acento", "Acento", "tawasuyu", vec![eo("tawasuyu", "tawasuyu"), eo("yachay", "yachay")])),
)
.section(
Section::new("wawa::idioma", "Idioma")
.icon("🌐")
.field(Field::dropdown("lang", "Idioma", "es-PE", vec![eo("es-PE", "Español"), eo("en-US", "English")])),
)
.section(
Section::new("wawa::interfaz", "Interfaz")
.icon("🎛")
.field(Field::display("toolkit", "Toolkit", "llimphi")),
)
.section(
Section::new("wawa::arranque", "Arranque")
.icon("")
.field(Field::display("init", "Init", "systemd (actual)")),
)
.section(
Section::new("wawa::modulos", "Módulos")
.icon("")
.field(Field::toggle("mirada", "mirada", true))
.field(Field::toggle("shuma", "shuma", true)),
);
// Mirada con un par de entradas de menú, para que la tabla del menú raíz se
// vea poblada (el default trae el menú vacío).
let mut mirada_cfg = mirada_brain::Config::default();
mirada_cfg.menu = vec![
mirada_brain::MenuEntry {
label: "Editor".into(),
command: "nada".into(),
submenu: Vec::new(),
},
mirada_brain::MenuEntry {
label: "Terminal".into(),
command: "alacritty".into(),
submenu: Vec::new(),
},
];
mirada_cfg.outputs = vec![mirada_brain::OutputOverride {
name: "HDMI-A-1".into(),
wallpaper_path: "/fondos/mar.png".into(),
wallpaper_fit: "fill".into(),
order: 0,
scale_120: 0,
transform: String::new(),
}];
// El keymap de mirada como tabla (combinación · acción) — una tabla alta
// que ejercita el scroll del panel.
let keymap_rows = mirada_brain::Keymap::default().to_rows();
let atajos = Schema::new().section(
Section::new("mirada::atajos", "Atajos").icon("").field(Field::table(
"bindings",
"Atajos de teclado",
vec![
allichay::Column::new("combo", "Combinación"),
allichay::Column::new("action", "Acción"),
],
keymap_rows,
)),
);
let dientes: Vec<(&str, &str, Schema)> = vec![
("", "Sistema", sistema),
("", "mirada", prefix(mirada_cfg.schema(), "mirada")),
("🎛", "pata", prefix(pata_core::Config::preset().schema(), "pata")),
("", "Atajos", atajos),
];
let mut state = AllichayState::new();
state.select(sel);
let rail_items: Vec<DockRailItem> = dientes
.iter()
.enumerate()
.map(|(i, _)| DockRailItem {
id: i as u64,
active: i == sel,
})
.collect();
let icons: Vec<String> = dientes.iter().map(|(icon, _, _)| (*icon).to_string()).collect();
let rail = dock_rail_view::<(), _, _, _>(
&rail_items,
52.0,
&DockRailPalette::from_theme(&theme),
move |id, size, color| {
let g = icons.get(id as usize).cloned().unwrap_or_default();
View::<()>::new(Style {
size: Size {
width: percent(1.0),
height: percent(1.0),
},
..Default::default()
})
.text_aligned(g, size * 0.9, color, Alignment::Center)
},
|_id| (),
|_| None,
);
// 3 niveles: sidebar (items = secciones de la pestaña activa) | pestañas que
// sobresalen | canvas (contenido del item activo). El item se elige con el
// 3er arg (default 0) — útil para fotografiar una sección puntual (p. ej. la
// tabla del menú raíz de mirada).
let active = &dientes[sel.min(dientes.len() - 1)].2;
let item: usize = std::env::args()
.nth(3)
.and_then(|s| s.parse().ok())
.unwrap_or(0)
.min(active.sections.len().saturating_sub(1));
// Sidebar: lista de items (secciones) con su iconito.
let mut sidebar_kids: Vec<View<()>> = Vec::new();
for (i, sec) in active.sections.iter().enumerate() {
let act = i == item;
let icon = if sec.icon.is_empty() { "·" } else { sec.icon.as_str() };
let fg = if act { theme.fg_text } else { theme.fg_muted };
let row = View::<()>::new(Style {
flex_direction: FlexDirection::Row,
size: Size {
width: percent(1.0),
height: length(32.0),
},
align_items: Some(AlignItems::Center),
padding: Rect {
left: length(8.0),
right: length(8.0),
top: length(0.0),
bottom: length(0.0),
},
gap: Size {
width: length(6.0),
height: length(0.0),
},
..Default::default()
})
.fill(if act { theme.bg_selected } else { theme.bg_panel })
.radius(4.0)
.children(vec![
View::<()>::new(Style {
size: Size {
width: length(22.0),
height: auto(),
},
..Default::default()
})
.text_aligned(icon.to_string(), 14.0, fg, Alignment::Center),
View::<()>::new(Style {
size: Size {
width: percent(1.0),
height: auto(),
},
..Default::default()
})
.text_aligned(sec.title.clone(), 12.5, fg, Alignment::Start),
]);
sidebar_kids.push(row);
}
let sidebar = View::<()>::new(Style {
flex_direction: FlexDirection::Column,
size: Size {
width: length(232.0),
height: percent(1.0),
},
..Default::default()
})
.fill(theme.bg_panel)
.children(sidebar_kids);
// Canvas: el contenido del item activo (una sección).
let one = Schema {
sections: vec![active.sections[item.min(active.sections.len() - 1)].clone()],
};
let canvas_content =
schema_panel::<(), _>(&one, &state, &theme, H as f32 - 40.0, |_m: AllichayMsg| ());
let canvas = View::<()>::new(Style {
flex_grow: 1.0,
size: Size {
width: percent(1.0),
height: percent(1.0),
},
padding: Rect {
top: length(0.0),
bottom: length(0.0),
left: length(46.0),
right: length(0.0),
},
..Default::default()
})
.children(vec![canvas_content]);
let rail_overlay = View::<()>::new(Style {
position: Position::Absolute,
inset: Rect {
top: length(6.0),
left: length(0.0),
right: auto(),
bottom: auto(),
},
size: Size {
width: length(46.0),
height: auto(),
},
..Default::default()
})
.children(vec![rail]);
let center = View::<()>::new(Style {
position: Position::Relative,
flex_grow: 1.0,
size: Size {
width: percent(0.0),
height: percent(1.0),
},
..Default::default()
})
.fill(theme.bg_app)
.children(vec![canvas, rail_overlay]);
let v = View::<()>::new(Style {
flex_direction: FlexDirection::Row,
size: Size {
width: percent(1.0),
height: percent(1.0),
},
..Default::default()
})
.fill(theme.bg_app)
.children(vec![sidebar, center]);
// Modo "overlay": pasá `overlay` como arg para ver `settings_overlay`
// (el modal embebible) sobre el panel como fondo de app.
let v = if std::env::args().any(|a| a == "overlay") {
let modal = settings_overlay::<(), _>(
"Configuración",
"Cerrar",
active,
&state,
&theme,
(W as f32, H as f32),
|_m: AllichayMsg| (),
(),
);
View::<()>::new(Style {
position: Position::Relative,
size: Size {
width: percent(1.0),
height: percent(1.0),
},
..Default::default()
})
.children(vec![v, modal])
} else {
v
};
// view → layout → scene (misma secuencia que el eventloop).
let mut layout = LayoutTree::new();
let mounted = mount(&mut layout, v);
let mut ts = Typesetter::new();
let computed = {
let tmap = &mounted.text_measures;
layout
.compute_with_measure(mounted.root, (W as f32, H as f32), |nid, known, avail| {
match tmap.get(&nid) {
Some(tm) => measure_text_node(&mut ts, tm, known, avail),
None => taffy::Size::ZERO,
}
})
.expect("layout")
};
let mut scene = vello::Scene::new();
paint(&mut scene, &mounted, &computed, &mut ts, None, None);
let hal = pollster::block_on(Hal::new(None)).expect("hal");
let mut renderer = Renderer::new(&hal).expect("renderer");
let target = hal.device.create_texture(&wgpu::TextureDescriptor {
label: Some("dump-allichay"),
size: wgpu::Extent3d {
width: W,
height: H,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: FMT,
usage: wgpu::TextureUsages::STORAGE_BINDING
| wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = target.create_view(&wgpu::TextureViewDescriptor::default());
let [r, g, b, _] = theme.bg_app.components;
let bg = Color::from_rgba8((r * 255.0) as u8, (g * 255.0) as u8, (b * 255.0) as u8, 255);
renderer
.render_to_view(&hal, &scene, &view, W, H, bg)
.expect("render_to_view");
write_png(&hal, &target, &out);
eprintln!("dump_panel: escrito {out} ({W}x{H}) · diente {sel}");
}
fn write_png(hal: &Hal, target: &wgpu::Texture, path: &str) {
let unpadded = (W * 4) as usize;
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize;
let padded = unpadded.div_ceil(align) * align;
let buf = hal.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("readback"),
size: (padded * H as usize) as u64,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let mut enc = hal
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
enc.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
texture: target,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyBufferInfo {
buffer: &buf,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(padded as u32),
rows_per_image: Some(H),
},
},
wgpu::Extent3d {
width: W,
height: H,
depth_or_array_layers: 1,
},
);
hal.queue.submit(std::iter::once(enc.finish()));
let slice = buf.slice(..);
let (tx, rx) = std::sync::mpsc::channel();
slice.map_async(wgpu::MapMode::Read, move |r| {
let _ = tx.send(r);
});
hal.device.poll(wgpu::PollType::wait_indefinitely());
rx.recv().unwrap().unwrap();
let data = slice.get_mapped_range();
let mut pixels = Vec::with_capacity((W * H * 4) as usize);
for row in 0..H as usize {
let s = row * padded;
pixels.extend_from_slice(&data[s..s + unpadded]);
}
drop(data);
buf.unmap();
let file = File::create(path).expect("png");
let mut enc = png::Encoder::new(BufWriter::new(file), W, H);
enc.set_color(png::ColorType::Rgba);
enc.set_depth(png::BitDepth::Eight);
let mut w = enc.write_header().unwrap();
w.write_image_data(&pixels).unwrap();
}
+268
View File
@@ -0,0 +1,268 @@
//! Demo del renderizador `allichay`: una config de juguete editable.
//!
//! Ejercita el módulo sin levantar ninguna app de dominio: un `DemoConfig`
//! implementa [`allichay::Configurable`], el renderizador lo pinta con dientes
//! y controles, y cada cambio se aplica + se loguea por consola.
//!
//! ```bash
//! cargo run -p llimphi-module-allichay --example settings_demo --release
//! ```
use allichay::{Column, Configurable, EnumOption, Field, FieldPath, FieldValue, Schema, Section};
use llimphi_module_allichay::{allichay_view, AllichayMsg, AllichayState};
use llimphi_theme::Theme;
use llimphi_ui::llimphi_layout::taffy::prelude::{percent, Size, Style};
use llimphi_ui::{App, Handle, KeyEvent, View};
/// Config de juguete con un campo de cada tipo.
#[derive(Clone)]
struct DemoConfig {
oscuro: bool,
gap: f64,
columnas: i64,
idioma: String,
acento: [u8; 4],
nombre: String,
auto: bool,
/// Lista de textos (ejercita [`Control::List`]).
rutas: Vec<String>,
/// Tabla (etiqueta, comando) — ejercita [`Control::Table`].
accesos: Vec<(String, String)>,
}
impl Default for DemoConfig {
fn default() -> Self {
Self {
oscuro: true,
gap: 8.0,
columnas: 2,
idioma: "es-PE".into(),
acento: [92, 143, 235, 255],
nombre: "mi escritorio".into(),
auto: false,
rutas: vec!["~/proyectos".into(), "/usr/share".into()],
accesos: vec![
("Editor".into(), "nada".into()),
("Terminal".into(), "alacritty".into()),
],
}
}
}
impl Configurable for DemoConfig {
fn schema(&self) -> Schema {
Schema::new()
.section(
Section::new("apariencia", "Apariencia")
.icon("")
.help("Cómo se ve el escritorio")
.field(Field::toggle("oscuro", "Modo oscuro", self.oscuro))
.field(
Field::slider("gap", "Margen entre ventanas", self.gap, 0.0, 32.0, 1.0)
.help("En píxeles"),
)
.field(Field::color("acento", "Color de acento", self.acento))
.subsection(
Section::new("teselado", "Teselado").field(Field::slider_int(
"columnas",
"Columnas",
self.columnas,
1,
6,
)),
),
)
.section(
Section::new("general", "General")
.icon("")
.field(Field::dropdown(
"idioma",
"Idioma",
self.idioma.clone(),
vec![
EnumOption::new("es-PE", "Español"),
EnumOption::new("en-US", "English"),
EnumOption::new("qu-PE", "Runasimi"),
],
))
.field(Field::text("nombre", "Nombre del equipo", self.nombre.clone()))
.field(Field::toggle("auto", "Arrancar al inicio", self.auto)),
)
.section(
Section::new("agregados", "Listas y tablas")
.icon("")
.help("Los controles v2")
.field(Field::list(
"rutas",
"Rutas de búsqueda",
self.rutas.clone(),
"ruta",
))
.field(Field::table(
"accesos",
"Accesos directos",
vec![Column::new("label", "Nombre"), Column::new("cmd", "Comando")],
self.accesos
.iter()
.map(|(l, c)| vec![l.clone(), c.clone()])
.collect(),
)),
)
}
fn apply(
&mut self,
path: &FieldPath,
value: FieldValue,
) -> Result<(), allichay::AllichayError> {
match path.leaf() {
Some("oscuro") => self.oscuro = value.as_bool().unwrap_or(self.oscuro),
Some("gap") => self.gap = value.as_float().unwrap_or(self.gap),
Some("columnas") => self.columnas = value.as_int().unwrap_or(self.columnas),
Some("idioma") => {
if let Some(s) = value.as_str() {
self.idioma = s.to_string();
}
}
Some("acento") => self.acento = value.as_color().unwrap_or(self.acento),
Some("nombre") => {
if let Some(s) = value.as_str() {
self.nombre = s.to_string();
}
}
Some("auto") => self.auto = value.as_bool().unwrap_or(self.auto),
Some("rutas") => {
if let Some(items) = value.as_list() {
self.rutas = items.to_vec();
}
}
Some("accesos") => {
if let Some(rows) = value.as_table() {
self.accesos = rows
.iter()
.map(|r| {
(
r.first().cloned().unwrap_or_default(),
r.get(1).cloned().unwrap_or_default(),
)
})
.collect();
}
}
other => {
return Err(allichay::AllichayError::UnknownPath(
other.unwrap_or("").into(),
))
}
}
Ok(())
}
}
struct Model {
cfg: DemoConfig,
state: AllichayState,
}
#[derive(Clone)]
enum Msg {
Allichay(AllichayMsg),
Key(KeyEvent),
}
struct Demo;
impl App for Demo {
type Model = Model;
type Msg = Msg;
fn title() -> &'static str {
"allichay · demo"
}
fn initial_size() -> (u32, u32) {
(760, 560)
}
fn init(_handle: &Handle<Msg>) -> Model {
Model {
cfg: DemoConfig::default(),
state: AllichayState::new(),
}
}
fn update(model: Model, msg: Msg, _handle: &Handle<Msg>) -> Model {
let mut m = model;
match msg {
Msg::Allichay(AllichayMsg::SelectSection(i)) => m.state.select(i),
Msg::Allichay(AllichayMsg::Focus(path)) => {
// Sembrar el buffer con el valor actual del campo.
let seed = m
.cfg
.schema()
.find_field(&path)
.and_then(|f| f.value.as_str().map(str::to_string))
.unwrap_or_default();
m.state.focus(&path, &seed);
}
Msg::Allichay(AllichayMsg::FocusCell(path, row, col)) => {
// El estado siembra el buffer leyendo la celda del valor actual.
if let Some(f) = m.cfg.schema().find_field(&path) {
m.state.focus_cell(&path, f.value.clone(), row, col);
}
}
Msg::Allichay(AllichayMsg::FocusHex(path)) => {
let seed = m
.cfg
.schema()
.find_field(&path)
.and_then(|f| f.value.as_color())
.map(llimphi_module_allichay::color_hex)
.unwrap_or_default();
m.state.focus_hex(&path, &seed);
}
Msg::Allichay(AllichayMsg::Change(path, value)) => {
println!("cambio: {path} = {value:?}");
if let Err(e) = m.cfg.apply(&path, value) {
eprintln!(" error: {e}");
}
}
Msg::Allichay(AllichayMsg::ScrollTo(offset)) => m.state.set_scroll(offset),
Msg::Key(event) => {
if let Some((path, value)) = m.state.apply_key(&event) {
println!("texto: {path} = {value:?}");
let _ = m.cfg.apply(&path, value);
}
}
}
m
}
fn on_key(model: &Model, event: &KeyEvent) -> Option<Msg> {
// Sólo capturamos teclas cuando hay un campo de texto en edición.
if model.state.is_editing() {
Some(Msg::Key(event.clone()))
} else {
None
}
}
fn view(model: &Model) -> View<Msg> {
let theme = Theme::dark();
let schema = model.cfg.schema();
let body = allichay_view(&schema, &model.state, &theme, Msg::Allichay);
View::new(Style {
size: Size {
width: percent(1.0_f32),
height: percent(1.0_f32),
},
..Default::default()
})
.fill(theme.bg_app)
.children(vec![body])
}
}
fn main() {
llimphi_ui::run::<Demo>();
}
File diff suppressed because it is too large Load Diff
+1 -3
View File
@@ -5,8 +5,6 @@ edition.workspace = true
license.workspace = true
authors.workspace = true
publish.workspace = true
description = "llimphi-module-selector — trait Selector con dos backends: HostSelector (paths del FS via std::fs) y WawaSelector (khipus por hash, sello digital). Una sola API 'abrir/guardar' que funciona en cualquier entorno gioser."
description = "llimphi-module-selector — trait Selector con dos backends: HostSelector (paths del FS via std::fs) y WawaSelector (khipus por hash, sello digital). Una sola API 'abrir/guardar' que funciona en cualquier entorno tawasuyu."
[dependencies]
llimphi-ui = { workspace = true }
llimphi-theme = { workspace = true }
+2 -2
View File
@@ -3,7 +3,7 @@
//!
//! ## Por qué
//!
//! Una app gioser que sólo conoce paths (`PathBuf`) se rompe en wawa,
//! Una app tawasuyu que sólo conoce paths (`PathBuf`) se rompe en wawa,
//! donde el almacenamiento es direccionado por contenido (BLAKE3 + DAG)
//! y no existe el concepto de "carpeta /home/usuario". Pero la mayoría
//! de las apps no necesitan saber la diferencia: sólo quieren preguntar
@@ -68,7 +68,7 @@ pub enum ItemHandle {
WawaHash([u8; 32]),
}
/// Trait que abstrae el medio de almacenamiento. Una app gioser que
/// Trait que abstrae el medio de almacenamiento. Una app tawasuyu que
/// quiera funcionar tanto en host como en wawa toma un `&dyn Selector`
/// en su modelo en lugar de un `PathBuf` concreto.
pub trait Selector {
+33
View File
@@ -95,6 +95,39 @@ impl ShumaTermState {
pub fn cwd(&self) -> &str {
&self.cwd
}
/// Envía bytes crudos al stdin del PTY. Para hosts que ya producen sus
/// propios códigos de tecla y no quieren pasar por [`apply`] —p. ej. el
/// backend layer-shell de pata, que recibe `Keysym` de SCTK y no
/// `KeyEvent` de llimphi. Los hosts con `KeyEvent` deberían usar
/// `apply(ShumaTermMsg::KeyInput(ev))` (que internamente llama a esto).
pub fn send_input(&self, bytes: Vec<u8>) -> bool {
if bytes.is_empty() {
return false;
}
self.handle.write_input(bytes)
}
/// Reescala el PTY y el buffer vt100 a `cols`×`rows`. No-op si el tamaño
/// no cambió. El host la llama cuando el panel que lo hospeda cambia de
/// tamaño (en pata: al abrir/redimensionar el drawer Quake).
pub fn resize(&mut self, cols: u16, rows: u16) {
let cols = cols.max(2);
let rows = rows.max(1);
if cols == self.cols && rows == self.rows {
return;
}
self.cols = cols;
self.rows = rows;
self.handle.resize(rows, cols);
self.parser.screen_mut().set_size(rows, cols);
}
/// Drena los eventos pendientes del PTY (bytes + exit). Atajo de
/// `apply(ShumaTermMsg::Tick)` para hosts que tickean a mano.
pub fn tick(&mut self) -> ShumaTermAction {
drain(self)
}
}
impl Drop for ShumaTermState {