Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions e2e/celu/servidor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ const HTML = leer('index.html')
const CSS = leer('app.css')
// Igual que PAGINA_JS en Rust: el sello y después la página.
const JS = `${leer('sello.js')}\n${leer('app.js')}`
const XTERM = join(__dirname, '..', '..', 'node_modules', '@xterm', 'xterm')
const XTERM_JS = readFileSync(join(XTERM, 'lib', 'xterm.js'), 'utf8')
const XTERM_CSS = readFileSync(join(XTERM, 'css', 'xterm.css'), 'utf8')
const MAX_CUERPO = 8192

function enviar(res: ServerResponse, status: number, tipo: string | null, cuerpo?: string): void {
Expand Down Expand Up @@ -88,6 +91,8 @@ export function crearServidorDePrueba(p: ProveedorDePrueba): { iniciar(): Promis
if (ruta === '/') return enviar(res, 200, 'text/html; charset=utf-8', HTML)
if (ruta === '/app.css') return enviar(res, 200, 'text/css; charset=utf-8', CSS)
if (ruta === '/app.js') return enviar(res, 200, 'text/javascript; charset=utf-8', JS)
if (ruta === '/xterm.js') return enviar(res, 200, 'text/javascript; charset=utf-8', XTERM_JS)
if (ruta === '/xterm.css') return enviar(res, 200, 'text/css; charset=utf-8', XTERM_CSS)
return enviar(res, 404, null)
}

Expand Down
89 changes: 88 additions & 1 deletion e2e/celular-pagina.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const MIN = 60_000
let estado: EstadoCelular
let claveActual = CLAVE
const decisiones: string[] = []
let terminalDePrueba: (cuerpo: unknown) => Promise<{ status: number; error: string } | Record<string, unknown>> = async () => ({ status: 403, error: 'apagada' })
const fuente = crearServidorDePrueba({
estado: async () => ({ ...estado, ahora: Date.now() }),
decidir: (id, d) => {
Expand All @@ -22,7 +23,7 @@ const fuente = crearServidorDePrueba({
},
puedeAprobar: () => estado.aprobar,
clave: () => claveActual,
terminal: async () => ({ status: 403, error: 'apagada' })
terminal: (cuerpo) => terminalDePrueba(cuerpo)
})

test.beforeAll(() => fuente.iniciar())
Expand Down Expand Up @@ -324,6 +325,92 @@ test('Celu: acostado con 18 sesiones no corta filas a la mitad, cuenta las que n
}
})

test('Celu: «Ajustar» pide el ancho que entra, lo devuelve al ocultarse o cerrar y cede si la PC toma el control', async () => {
estado = { ...BASE, terminal: true, sesiones: [sesion('api', 'working')] }
const PC = { cols: 150, rows: 40 }
let prestado: number | null = null
let pcMando = false
const tamanos: (number | 'pc')[] = []
terminalDePrueba = async (cuerpo) => {
const b = cuerpo as { desde: number; espera?: number; tam?: 'pc' | { cols: number } }
if (b.tam === 'pc') {
tamanos.push('pc')
prestado = null
pcMando = false
} else if (b.tam) {
tamanos.push(b.tam.cols)
if (!pcMando) prestado = b.tam.cols
}
if (b.espera) await new Promise((listo) => setTimeout(listo, 200))
const datos = b.desde < 0 && !b.tam ? 'hola desde la PC\r\n' : ''
return { reinicio: !!datos, datos, hasta: 1, mas: false, viva: true, cols: prestado ?? PC.cols, rows: PC.rows, ajustado: prestado !== null, pcMando }
}
const navegador = await chromium.launch()
try {
const { page } = await abrir(navegador, MOTORES[0].ficha)
const abrirTerm = page.getByRole('button', { name: 'Abrir la terminal de api' })
await abrirTerm.click()
await expect(page.locator('.xterm-rows')).toContainText('hola desde la PC')
const ajustar = page.getByRole('button', { name: /^Ajustar/ })
const vista = page.locator('#term-vista')
await expect(ajustar).toHaveAttribute('aria-pressed', 'false')
expect(tamanos, 'apagado de fábrica').toEqual([])

await ajustar.click()
await expect(ajustar).toHaveAttribute('aria-pressed', 'true')
await expect(vista).toBeHidden()
await expect.poll(() => tamanos.length).toBeGreaterThan(0)
const parado = tamanos[0] as number
expect(parado).toBeGreaterThanOrEqual(30)
expect(parado).toBeLessThanOrEqual(55)
const sobra = (): Promise<number> =>
page.locator('#term-pantalla').evaluate((p) => p.clientWidth - 16 - (p.querySelector('.xterm-screen') as HTMLElement).offsetWidth)
await expect.poll(sobra, { message: 'entra sin deslizar y casi no sobra' }).toBeLessThan(30)
expect(await sobra()).toBeGreaterThanOrEqual(13)
await page.screenshot({ path: test.info().outputPath('ajustada.png') })

const cdp = await page.context().newCDPSession(page)
await cdp.send('Emulation.setDeviceMetricsOverride', { width: 740, height: 360, deviceScaleFactor: 1, mobile: true })
await expect.poll(() => tamanos.at(-1), { message: 'girar recalcula' }).toBeGreaterThan(parado + 20)
await cdp.send('Emulation.setDeviceMetricsOverride', { width: 360, height: 740, deviceScaleFactor: 1, mobile: true })
await expect.poll(() => tamanos.at(-1)).toBe(parado)

const ocultar = (si: boolean): Promise<void> =>
page.evaluate((oculta) => {
Object.defineProperty(document, 'hidden', { value: oculta, configurable: true })
document.dispatchEvent(new Event('visibilitychange'))
}, si)
await ocultar(true)
await expect.poll(() => tamanos.at(-1), { message: 'al ocultarse se devuelve' }).toBe('pc')
await ocultar(false)
await expect.poll(() => tamanos.at(-1), { message: 'al volver se repide' }).toBe(parado)

prestado = null
pcMando = true
await expect(ajustar).toHaveAttribute('aria-pressed', 'false')
await expect(page.locator('#term-aviso')).toContainText('La PC cambió el tamaño')
await expect(vista).toBeVisible()
await expect.poll(() => tamanos.at(-1)).toBe('pc')
const hasta = tamanos.length
await page.waitForTimeout(1500)
expect(tamanos.slice(hasta), 'sin pelearle a la PC').toEqual([])

await ajustar.click()
await expect.poll(() => tamanos.at(-1)).toBe(parado)
await page.getByRole('button', { name: 'Volver a las sesiones' }).click()
await expect.poll(() => tamanos.at(-1), { message: 'al cerrar se devuelve' }).toBe('pc')
await abrirTerm.click()
await expect(ajustar, 'se recuerda').toHaveAttribute('aria-pressed', 'true')
await expect.poll(() => tamanos.at(-1)).toBe(parado)
await ajustar.click()
await expect.poll(() => tamanos.at(-1), { message: 'al apagarlo se devuelve' }).toBe('pc')
await expect(vista).toBeVisible()
} finally {
terminalDePrueba = async () => ({ status: 403, error: 'apagada' })
await navegador.close()
}
})

test('Celu: en tablet van dos columnas (lo que espera a la izquierda, la lista a la derecha) y no se estira de lado a lado', async () => {
estado = { ...BASE, sesiones: [sesion('api', 'waiting', { detalle: MENSAJE }), ...Array.from({ length: 8 }, (_, i) => sesion(`espacio-${i}`, 'working'))] }
const navegador = await chromium.launch()
Expand Down
100 changes: 100 additions & 0 deletions native/core/src/features/celular/ajuste.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
//! El ancho que un celu le pide prestado a una terminal para leerla sin deslizar. Solo cambian las columnas (nunca más
//! que las de la PC), siempre se devuelve, y si la PC redimensiona en el medio manda la PC.
//! Los métodos que devuelven un tamaño dicen a cuál hay que llevar la PTY (`None`: no se toca).
use super::terminal_core::tamano_actual;
use std::collections::HashMap;

/// Quién pidió el ancho: solo los pedidos de esa página lo mantienen.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dueno {
pub sesion: Option<String>,
pub celu: Option<String>,
}

/// El tamaño que ve una página.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Tamano {
pub cols: u32,
pub rows: u32,
pub ajustado: bool,
/// La PC redimensionó mientras esta página tenía el ancho prestado.
pub pc_mando: bool,
}

struct Ajuste {
dueno: Dueno,
/// El tamaño de la PC cuando se pidió: si cambia, la PC tomó el control.
pc: (u32, u32),
/// `None`: la PC tomó el control. Queda anotado hasta que la página lo suelte, para avisarle y no pelearle.
cols: Option<u32>,
usado_en: i64,
}

#[derive(Default)]
pub struct Ajustes(HashMap<String, Ajuste>);

impl Ajustes {
pub fn vacio(&self) -> bool {
self.0.is_empty()
}

pub fn ids(&self) -> Vec<String> {
self.0.keys().cloned().collect()
}

pub fn de_celu(&self, celu: &str) -> Vec<String> {
self.0.iter().filter(|(_, a)| a.dueno.celu.as_deref() == Some(celu)).map(|(id, _)| id.clone()).collect()
}

pub fn vencidos(&self, ahora: i64, vence_ms: i64) -> Vec<String> {
self.0.iter().filter(|(_, a)| ahora - a.usado_en > vence_ms).map(|(id, _)| id.clone()).collect()
}

pub fn pedir(&mut self, id: &str, dueno: Dueno, cols: u32, pc: (u32, u32), ahora: i64) -> Option<(u32, u32)> {
self.revisar(id, pc);
let actual = match self.0.get(id) {
Some(a) if a.cols.is_none() && a.dueno.sesion == dueno.sesion => return None,
a => a.and_then(|a| a.cols).unwrap_or(pc.0),
};
let cols = cols.min(pc.0);
self.0.insert(id.into(), Ajuste { dueno, pc, cols: Some(cols), usado_en: ahora });
(cols != actual).then_some((cols, pc.1))
}

pub fn soltar(&mut self, id: &str, pc: Option<(u32, u32)>) -> Option<(u32, u32)> {
let a = self.0.remove(id)?;
(pc == Some(a.pc) && a.cols? != a.pc.0).then_some(a.pc)
}

/// true si había un ancho prestado.
pub fn pc_mando(&mut self, id: &str) -> bool {
self.0.get_mut(id).is_some_and(|a| a.cols.take().is_some())
}

pub fn olvidar(&mut self, id: &str) {
self.0.remove(id);
}

pub fn usar(&mut self, id: &str, sesion: Option<&str>, ahora: i64) {
if let Some(a) = self.0.get_mut(id).filter(|a| a.dueno.sesion.as_deref() == sesion) {
a.usado_en = ahora;
}
}

pub fn tamano(&mut self, id: &str, sesion: Option<&str>, pc: Option<(u32, u32)>) -> Tamano {
if let Some(pc) = pc {
self.revisar(id, pc);
}
let (cols, rows) = tamano_actual(pc);
let a = self.0.get(id);
let prestado = a.and_then(|a| a.cols);
let pc_mando = a.is_some_and(|a| a.cols.is_none() && a.dueno.sesion.as_deref() == sesion);
Tamano { cols: prestado.unwrap_or(cols), rows, ajustado: prestado.is_some(), pc_mando }
}

fn revisar(&mut self, id: &str, pc: (u32, u32)) {
if self.0.get(id).is_some_and(|a| a.pc != pc) {
self.pc_mando(id);
}
}
}
2 changes: 2 additions & 0 deletions native/core/src/features/celular/contexto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ pub trait ContextoCelular: Send + Sync {
/// Escribe en la terminal de un espacio. Lo que llega del celu ya pasó por `sin_automaticas` y por la validación del pedido.
fn escribir_pty(&self, id: &str, texto: &str);
fn tam_pty(&self, id: &str) -> Option<(u32, u32)>;
/// Cambia el tamaño de la PTY sin tocar el que recuerda la PC (`tam_pty`).
fn redimensionar_pty(&self, id: &str, cols: u32, rows: u32);

fn interfaces_de_red(&self) -> Vec<(String, Vec<InterfazRed>)>;
/// Los PNG de la página: sin archivo, el de 192 px.
Expand Down
1 change: 1 addition & 0 deletions native/core/src/features/celular/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//! `contexto::ContextoCelular`, que implementa la cáscara.
pub mod acceso;
pub mod actividad;
pub mod ajuste;
pub mod conexiones;
pub mod config;
pub mod contexto;
Expand Down
2 changes: 1 addition & 1 deletion native/core/src/features/celular/pagina/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ html.quieto *, html.quieto *::before, html.quieto *::after, html.quieto ::backdr
.term-volver { flex: none; width: 44px; height: 44px; display: inline-flex; align-items: center; justify-content: center; border: 0; border-radius: 12px; background: transparent; color: var(--texto); }
.term-nombre { min-width: 0; font-size: 15px; font-weight: 600; color: var(--fuerte); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.term-vista { flex: none; min-height: 44px; padding: 0 12px; border: 1px solid var(--borde); border-radius: 12px; background: var(--panel); color: var(--texto); font-size: 13px; font-weight: 600; }
.term-vista[data-vista="celu"] { background: var(--pista); color: var(--fuerte); }
.term-vista[data-vista="celu"], .term-vista[aria-pressed="true"] { background: var(--pista); color: var(--fuerte); }
.term-aviso { flex: none; padding: 8px 14px; font-size: 13px; color: var(--espera); background: rgba(255,159,67,0.10); border-bottom: 1px solid rgba(255,176,103,0.3); }
.term-pantalla { touch-action: pan-x pan-y; flex: 1; min-height: 0; overflow: auto; padding: 6px 4px; background: var(--fondo); -webkit-overflow-scrolling: touch; overscroll-behavior: contain; }
.term-pantalla .xterm { padding: 0; }
Expand Down
Loading
Loading