diff --git a/Cargo.lock b/Cargo.lock index a7a6b13..1de74de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -910,16 +910,6 @@ dependencies = [ name = "xframe-indicators" version = "0.1.0" -[[package]] -name = "xframe-layout" -version = "0.1.0" -dependencies = [ - "x11rb", - "xframe-common", - "xframe-core", - "xframe-widgets", -] - [[package]] name = "xframe-palette" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 8a401a9..d797576 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,6 @@ members = [ "crates/xframe-common", "crates/xframe-demo", "crates/xframe-palette", - "crates/xframe-layout", "crates/xframe-test-runner", "crates/xframe-core", "crates/xframe-indicators", diff --git a/crates/xframe-common/Cargo.toml b/crates/xframe-common/Cargo.toml index 291b116..cb1cd1e 100644 --- a/crates/xframe-common/Cargo.toml +++ b/crates/xframe-common/Cargo.toml @@ -2,7 +2,7 @@ name = "xframe-common" version = "0.1.0" edition = "2021" -description = "Shared X11/registry/stub-widget support for the LightGUI Rust port (xframe-demo, xframe-palette, xframe-layout, xframe-test-runner). Port of widgets/common/{registry,ico,ipc}.h and the widgets/core style manager (lightgui eb0b5fc)." +description = "Shared X11/registry/stub-widget support for the LightGUI Rust port (xframe-demo, xframe-palette, xframe-test-runner). Port of widgets/common/{registry,ico,ipc}.h and the widgets/core style manager (lightgui eb0b5fc)." license = "MIT" [dependencies] diff --git a/crates/xframe-common/src/x11.rs b/crates/xframe-common/src/x11.rs index 537ea33..b20d472 100644 --- a/crates/xframe-common/src/x11.rs +++ b/crates/xframe-common/src/x11.rs @@ -283,10 +283,9 @@ impl X11 { /// Bring a window to the front and give it keyboard focus, the /// EWMH way: restack above its siblings, ask the WM to activate /// it (`_NET_ACTIVE_WINDOW`, source = application), and set the - /// input focus. Used by xframe-layout when a new palette - /// selection arrives: without this the layout window stays buried - /// behind the designer and the user's placement click lands on - /// the designer's canvas instead. + /// input focus. Kept as a utility for windows that must come to + /// the front on demand (the standalone layout that used it is + /// deleted; the canvas lives inside the designer now). pub fn activate_window(&self, win: Window) -> Result<(), Box> { self.conn .configure_window(win, &ConfigureWindowAux::new().stack_mode(StackMode::ABOVE))?; diff --git a/crates/xframe-layout/Cargo.toml b/crates/xframe-layout/Cargo.toml deleted file mode 100644 index a1fb801..0000000 --- a/crates/xframe-layout/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "xframe-layout" -version = "0.1.0" -edition = "2021" -description = "LightGUI layout/design window on x11rb: place/move/resize/delete widgets, resize handles, script mode. Port of widgets/layout/main_layout.cpp (lightgui eb0b5fc)." -license = "MIT" - -[[bin]] -name = "xframe-layout" -path = "src/main.rs" - -[dependencies] -xframe-common = { path = "../xframe-common" } -xframe-core = { path = "../xframe-core" } -xframe-widgets = { path = "../xframe-widgets" } -x11rb = "0.13" diff --git a/crates/xframe-layout/src/main.rs b/crates/xframe-layout/src/main.rs deleted file mode 100644 index bf96e7c..0000000 --- a/crates/xframe-layout/src/main.rs +++ /dev/null @@ -1,1152 +0,0 @@ -//! xframe-layout — the LightGUI layout/design window on x11rb. -//! -//! A faithful port of `widgets/layout/main_layout.cpp`: a 1024x720 -//! window that instantiates widgets (via `xframe_widgets::create` — the -//! real widgets, one of the 14 archetypes). The -//! widget type selected in the palette (shared selection file) is -//! placed with a click, then can be selected, dragged to move, and -//! deleted. Double-click shows resize handles (corners + edges); -//! dragging a handle resizes live; Escape dismisses. -//! -//! Interactive keys: Delete/BackSpace delete, Escape dismiss handles / -//! clear selection, s save layout, q quit. -//! -//! Script mode (for automated testing): -//! xframe-layout --script cmds.txt --log out.log -//! Commands (one per line, # comments): PLACE [x y w h], -//! PLACE_ALL, MOVE , RESIZE , DELETE , -//! SELECT , DBLCLICK , HANDLE , -//! CHECKDRAW , SAVE / LOAD , LIST / COUNT / QUIT, -//! HOLD . Every mutation rewrites the layout state file so a -//! test driver can verify bounds without guessing from pixels. -//! -//! Deviation: the selection outline uses a second GC with -//! LineOnOffDash (same visual as the C++ dashed outline). - -use std::io::Write; -use std::process::ExitCode; -use std::time::{Duration, Instant}; -use x11rb::connection::Connection; -use x11rb::protocol::xproto::*; -use x11rb::protocol::Event; -use xframe_common::ipc; -use xframe_common::registry::{self, WidgetMeta, WIDGET_COUNT}; -use xframe_common::style::FONT_DEFAULT; -use xframe_common::target::CtxTarget; -use xframe_common::x11::{DrawCtx, X11}; -use xframe_core::{Srgb, StyleManager}; -use xframe_widgets::{create, Widget}; - -const WIN_W: u16 = 1024; -const WIN_H: u16 = 720; -const K_STATUS_H: i32 = 22; -const K_HANDLE_SIZE: i32 = 16; -/// Half-width of the grab target around a handle centre: handles are -/// grabbed in a 32x32 square even though only 16x16 is drawn, so a -/// shaky hand still catches them (the C++ side uses the same idea). -const K_HANDLE_HIT: i32 = 16; - -const KEY_DELETE: u32 = 0xffff; -const KEY_BACKSPACE: u32 = 0xff08; -const KEY_ESCAPE: u32 = 0xff1b; - -/// `default` / `dark` styles, exactly as registered by every C++ demo -/// main (`add_style_ex`, C++ arg order fill/outline/text/line). -fn register_styles(styles: &mut StyleManager) { - styles.add_style_ex( - "default", - Srgb::new(225, 225, 225), - Srgb::new(120, 120, 120), - Srgb::new(20, 20, 20), - Srgb::new(60, 60, 60), - 6, - 1, - FONT_DEFAULT, - ); - styles.add_style_ex( - "dark", - Srgb::new(45, 45, 48), - Srgb::new(20, 20, 22), - Srgb::new(240, 240, 240), - Srgb::new(200, 200, 200), - 6, - 1, - FONT_DEFAULT, - ); -} - -/// Build a real widget for `meta` at the given bounds, labelled with its -/// registry `kind` (the C++ constructor's default text, approximately — -/// see `xframe-demo`'s module docs). `None` for an unknown name. -fn make_widget( - meta: &'static WidgetMeta, - x: i32, - y: i32, - w: i32, - h: i32, -) -> Option> { - let mut wdg = create(meta.name)?; - wdg.set_bounds(x, y, w, h); - let kind = wdg.kind().to_string(); - wdg.set_text(&kind); - Some(wdg) -} - -#[derive(Clone, Copy, PartialEq)] -enum Handle { - Nw = 0, - N = 1, - Ne = 2, - E = 3, - Se = 4, - S = 5, - Sw = 6, - W = 7, -} - -struct Placed { - id: i32, - type_idx: usize, - x: i32, - y: i32, - w: i32, - h: i32, - wdg: Box, -} - -struct State { - placed: Vec, - next_id: i32, - last_placed_id: i32, - selected_id: i32, - handles_on: bool, - sel_type: i32, - sel_mtime: i128, - win_w: i32, - win_h: i32, -} - -impl State { - fn new() -> Self { - State { - placed: Vec::new(), - next_id: 1, - last_placed_id: -1, - selected_id: -1, - handles_on: false, - sel_type: -1, - sel_mtime: -1, - win_w: WIN_W as i32, - win_h: WIN_H as i32, - } - } - - fn find_placed(&mut self, id: i32) -> Option<&mut Placed> { - self.placed.iter_mut().find(|p| p.id == id) - } - - fn find_placed_ref(&self, id: i32) -> Option<&Placed> { - self.placed.iter().find(|p| p.id == id) - } - - fn write_state(&self) { - let mut text = String::new(); - for p in &self.placed { - text.push_str(&format!( - "{} {} {} {} {} {} selected={} handles={}\n", - p.id, - registry::WIDGETS[p.type_idx].name, - p.x, - p.y, - p.w, - p.h, - if p.id == self.selected_id { 1 } else { 0 }, - if self.handles_on && p.id == self.selected_id { - 1 - } else { - 0 - }, - )); - } - let _ = std::fs::write(ipc::layout_state_path(), text); - } - - fn place_widget(&mut self, type_idx: usize, x: i32, y: i32, w: i32, h: i32) -> i32 { - if type_idx >= WIDGET_COUNT { - return -1; - } - let meta: &'static WidgetMeta = ®istry::WIDGETS[type_idx]; - let w = if w <= 0 { meta.default_w as i32 } else { w }; - let h = if h <= 0 { meta.default_h as i32 } else { h }; - let x = if x < 0 { (self.win_w - w) / 2 } else { x }; - let y = if y < 0 { - (self.win_h - K_STATUS_H - h) / 2 - } else { - y - }; - let Some(wdg) = make_widget(meta, x, y, w, h) else { - return -1; - }; - let id = self.next_id; - self.next_id += 1; - self.last_placed_id = id; - self.placed.push(Placed { - id, - type_idx, - x, - y, - w, - h, - wdg, - }); - self.selected_id = id; - self.handles_on = false; - self.write_state(); - id - } - - fn delete_widget(&mut self, id: i32) -> bool { - if let Some(pos) = self.placed.iter().position(|p| p.id == id) { - self.placed.remove(pos); - if self.selected_id == id { - self.selected_id = -1; - self.handles_on = false; - } - if self.last_placed_id == id { - self.last_placed_id = self.placed.last().map(|p| p.id).unwrap_or(-1); - } - self.write_state(); - true - } else { - false - } - } - - fn save_layout(&self, path: &str) -> bool { - let mut text = String::new(); - for p in &self.placed { - text.push_str(&format!( - "{} {} {} {} {}\n", - registry::WIDGETS[p.type_idx].name, - p.x, - p.y, - p.w, - p.h - )); - } - std::fs::write(path, text).is_ok() - } - - fn load_layout(&mut self, path: &str) -> i32 { - let text = match std::fs::read_to_string(path) { - Ok(t) => t, - Err(_) => return -1, - }; - self.placed.clear(); - self.selected_id = -1; - self.handles_on = false; - let mut n = 0; - for line in text.lines() { - let mut it = line.split_whitespace(); - let (Some(name), Some(x), Some(y), Some(w), Some(h)) = - (it.next(), it.next(), it.next(), it.next(), it.next()) - else { - continue; - }; - let Ok((x, y, w, h)) = (|| { - Ok::<_, std::num::ParseIntError>(( - x.parse::()?, - y.parse::()?, - w.parse::()?, - h.parse::()?, - )) - })() else { - continue; - }; - let Some(t) = registry::index_of(name) else { - continue; - }; - if self.place_widget(t, x, y, w, h) >= 0 { - n += 1; - } - } - self.write_state(); - n - } -} - -/// Centre of a handle: corners sit on the widget corners, edge -/// handles on the edge midpoints. -fn handle_center(p: &Placed, h: Handle) -> (i32, i32) { - let hi = h as usize; - let cx = p.x + p.w / 2; - let cy = p.y + p.h / 2; - let xs = [p.x, cx, p.x + p.w, p.x + p.w, p.x + p.w, cx, p.x, p.x]; - let ys = [p.y, p.y, p.y, cy, p.y + p.h, p.y + p.h, p.y + p.h, cy]; - (xs[hi], ys[hi]) -} - -fn handle_rect(p: &Placed, h: Handle) -> (i32, i32) { - let (cx, cy) = handle_center(p, h); - (cx - K_HANDLE_SIZE / 2, cy - K_HANDLE_SIZE / 2) -} - -fn handle_at(state: &State, mx: i32, my: i32) -> Option { - if !state.handles_on || state.selected_id < 0 { - return None; - } - let p = state.find_placed_ref(state.selected_id)?; - for hi in 0..8 { - let h = match hi { - 0 => Handle::Nw, - 1 => Handle::N, - 2 => Handle::Ne, - 3 => Handle::E, - 4 => Handle::Se, - 5 => Handle::S, - 6 => Handle::Sw, - _ => Handle::W, - }; - let (cx, cy) = handle_center(p, h); - if mx >= cx - K_HANDLE_HIT - && mx <= cx + K_HANDLE_HIT - && my >= cy - K_HANDLE_HIT - && my <= cy + K_HANDLE_HIT - { - return Some(h); - } - } - None -} - -fn apply_handle_drag(p: &mut Placed, h: Handle, dx: i32, dy: i32) { - let (mut x, mut y, mut w, mut hh) = (p.x, p.y, p.w, p.h); - match h { - Handle::Nw => { - x += dx; - y += dy; - w -= dx; - hh -= dy; - } - Handle::N => { - y += dy; - hh -= dy; - } - Handle::Ne => { - y += dy; - w += dx; - hh -= dy; - } - Handle::E => { - w += dx; - } - Handle::Se => { - w += dx; - hh += dy; - } - Handle::S => { - hh += dy; - } - Handle::Sw => { - x += dx; - w -= dx; - hh += dy; - } - Handle::W => { - x += dx; - w -= dx; - } - } - if w < 24 { - w = 24; - } - if hh < 16 { - hh = 16; - } - if x < 0 { - x = 0; - } - if y < 0 { - y = 0; - } - p.x = x; - p.y = y; - p.w = w; - p.h = hh; - p.wdg.set_bounds(x, y, w, hh); -} - -fn redraw( - x: &X11, - ctx: &mut DrawCtx, - sel_gc: Gcontext, - styles: &mut StyleManager, - state: &mut State, -) { - let (win_w, win_h) = (state.win_w, state.win_h); - ctx.clear(255, 255, 255, win_w as u16, win_h as u16); - // Dotted canvas grid. - let mut pts = Vec::new(); - let mut gx = 24; - while gx < win_w { - let mut gy = 24; - while gy < win_h - K_STATUS_H { - pts.push((gx as i16, gy as i16)); - gy += 24; - } - gx += 24; - } - ctx.draw_points(&pts, 225, 225, 228); - { - let mut target = CtxTarget::new(&*ctx); - for p in state.placed.iter_mut() { - p.wdg.draw(&mut target, styles); - } - } - // Selection outline + handles. - if state.selected_id >= 0 { - if let Some(p) = state.find_placed_ref(state.selected_id) { - let _ = x.conn.change_gc( - sel_gc, - &ChangeGCAux::new().foreground(ctx.color(37, 99, 235)), - ); - let _ = x.conn.poly_rectangle( - ctx.drawable, - sel_gc, - &[Rectangle { - x: (p.x - 2) as i16, - y: (p.y - 2) as i16, - width: (p.w + 4) as u16, - height: (p.h + 4) as u16, - }], - ); - if state.handles_on { - for hi in 0..8 { - let h = match hi { - 0 => Handle::Nw, - 1 => Handle::N, - 2 => Handle::Ne, - 3 => Handle::E, - 4 => Handle::Se, - 5 => Handle::S, - 6 => Handle::Sw, - _ => Handle::W, - }; - let (hx, hy) = handle_rect(p, h); - ctx.fill_rect( - hx as i16, - hy as i16, - K_HANDLE_SIZE as u16, - K_HANDLE_SIZE as u16, - 255, - 127, - 0, - ); - ctx.draw_rect( - hx as i16, - hy as i16, - (K_HANDLE_SIZE - 1) as u16, - (K_HANDLE_SIZE - 1) as u16, - 0, - 0, - 0, - ); - } - } - } - } - // Status bar. - ctx.fill_rect( - 0, - (win_h - K_STATUS_H) as i16, - win_w as u16, - K_STATUS_H as u16, - 238, - 238, - 240, - ); - let sel = if state.sel_type >= 0 { - registry::WIDGETS[state.sel_type as usize].name - } else { - "(none - pick in palette)" - }; - let buf = format!( - "layout: {} widget(s) | selected to place: {} | click=place drag=move double-click=resize handles Del=delete s=save Esc=dismiss", - state.placed.len(), - sel - ); - ctx.draw_text(8, (win_h - 7) as i16, &buf, 0, 0, 0); - ctx.flush(); -} - -fn count_nonwhite(x: &X11, win: Window, px: i32, py: i32, w: i32, h: i32) -> i32 { - let (mut x0, mut y0, mut w, mut h) = (px, py, w, h); - if x0 < 0 { - w += x0; - x0 = 0; - } - if y0 < 0 { - h += y0; - y0 = 0; - } - if w <= 0 || h <= 0 { - return -1; - } - match x.get_image_rgb(win, x0 as i16, y0 as i16, w as u16, h as u16) { - Ok(img) => img.count_nonwhite() as i32, - Err(_) => -1, - } -} - -fn handle_name_to_id(s: &str) -> Option { - match s { - "nw" => Some(Handle::Nw), - "n" => Some(Handle::N), - "ne" => Some(Handle::Ne), - "e" => Some(Handle::E), - "se" => Some(Handle::Se), - "s" => Some(Handle::S), - "sw" => Some(Handle::Sw), - "w" => Some(Handle::W), - _ => None, - } -} - -fn resolve_id(state: &State, tok: &str) -> Option { - if tok == "LAST" { - if state.last_placed_id < 0 { - None - } else { - Some(state.last_placed_id) - } - } else { - tok.parse::().ok() - } -} - -fn log_fail(log: &mut dyn Write, line: &str, why: &str) { - let _ = writeln!(log, "FAIL {} : {}", line, why); -} - -#[allow(clippy::too_many_arguments)] -fn run_script( - x: &X11, - ctx: &mut DrawCtx, - sel_gc: Gcontext, - win: Window, - styles: &mut StyleManager, - state: &mut State, - path: &str, - log: &mut dyn Write, -) -> i32 { - let text = match std::fs::read_to_string(path) { - Ok(t) => t, - Err(_) => { - let _ = writeln!(log, "FAIL script file not found: {}", path); - return 1; - } - }; - let mut fails = 0; - let mut cmds = 0; - for line in text.lines() { - if line.starts_with('#') { - continue; - } - let mut it = line.split_whitespace(); - let Some(cmd) = it.next() else { continue }; - cmds += 1; - match cmd { - "PLACE" => { - let name = it.next().unwrap_or(""); - let (x0, y0, w, h) = ( - it.next().and_then(|v| v.parse().ok()).unwrap_or(-1), - it.next().and_then(|v| v.parse().ok()).unwrap_or(-1), - it.next().and_then(|v| v.parse().ok()).unwrap_or(0), - it.next().and_then(|v| v.parse().ok()).unwrap_or(0), - ); - let Some(t) = registry::index_of(name) else { - log_fail(log, line, "unknown widget"); - fails += 1; - continue; - }; - let id = state.place_widget(t, x0, y0, w, h); - if id < 0 { - log_fail(log, line, "create returned null"); - fails += 1; - continue; - } - redraw(x, ctx, sel_gc, styles, state); - let p = state.find_placed_ref(id).unwrap(); - let _ = writeln!( - log, - "OK PLACE {} id={} {} {} {} {}", - name, id, p.x, p.y, p.w, p.h - ); - } - "PLACE_ALL" => { - let mut n = 0; - for t in 0..WIDGET_COUNT { - let px = (t % 4) as i32 * 260 + 10; - let py = (t / 4) as i32 * 130 + 10; - if state.place_widget(t, px, py, 240, 110) >= 0 { - n += 1; - } - } - redraw(x, ctx, sel_gc, styles, state); - let _ = writeln!(log, "OK PLACE_ALL {}/{}", n, WIDGET_COUNT); - if n != WIDGET_COUNT { - log_fail(log, line, "not all placed"); - fails += 1; - } - } - "MOVE" => { - let (Some(tok), Some(dx), Some(dy)) = (it.next(), it.next(), it.next()) else { - log_fail(log, line, "bad args"); - fails += 1; - continue; - }; - let (Ok(dx), Ok(dy)) = (dx.parse::(), dy.parse::()) else { - log_fail(log, line, "bad args"); - fails += 1; - continue; - }; - let Some(id) = resolve_id(state, tok) else { - log_fail(log, line, "bad id"); - fails += 1; - continue; - }; - let Some(p) = state.find_placed(id) else { - log_fail(log, line, "no such id"); - fails += 1; - continue; - }; - p.x += dx; - p.y += dy; - let (nx, ny, nw, nh) = (p.x, p.y, p.w, p.h); - p.wdg.set_bounds(nx, ny, nw, nh); - state.write_state(); - redraw(x, ctx, sel_gc, styles, state); - let _ = writeln!(log, "OK MOVE {} -> {} {}", id, nx, ny); - } - "RESIZE" => { - let (Some(tok), Some(w), Some(h)) = (it.next(), it.next(), it.next()) else { - log_fail(log, line, "bad args"); - fails += 1; - continue; - }; - let (Ok(w), Ok(h)) = (w.parse::(), h.parse::()) else { - log_fail(log, line, "bad args"); - fails += 1; - continue; - }; - let Some(id) = resolve_id(state, tok) else { - log_fail(log, line, "bad id"); - fails += 1; - continue; - }; - let Some(p) = state.find_placed(id) else { - log_fail(log, line, "no such id"); - fails += 1; - continue; - }; - p.w = w; - p.h = h; - p.wdg.set_bounds(p.x, p.y, w, h); - state.write_state(); - redraw(x, ctx, sel_gc, styles, state); - let _ = writeln!(log, "OK RESIZE {} -> {} {}", id, w, h); - } - "DELETE" => { - let Some(tok) = it.next() else { - log_fail(log, line, "bad args"); - fails += 1; - continue; - }; - let Some(id) = resolve_id(state, tok) else { - log_fail(log, line, "bad id"); - fails += 1; - continue; - }; - if !state.delete_widget(id) { - log_fail(log, line, "no such id"); - fails += 1; - continue; - } - redraw(x, ctx, sel_gc, styles, state); - let _ = writeln!(log, "OK DELETE {} count={}", id, state.placed.len()); - } - "SELECT" => { - let Some(tok) = it.next() else { - log_fail(log, line, "bad args"); - fails += 1; - continue; - }; - let Some(id) = resolve_id(state, tok) else { - log_fail(log, line, "bad id"); - fails += 1; - continue; - }; - if state.find_placed_ref(id).is_none() { - log_fail(log, line, "no such id"); - fails += 1; - continue; - } - state.selected_id = id; - state.handles_on = false; - state.write_state(); - redraw(x, ctx, sel_gc, styles, state); - let _ = writeln!(log, "OK SELECT {}", id); - } - "DBLCLICK" => { - let Some(tok) = it.next() else { - log_fail(log, line, "bad args"); - fails += 1; - continue; - }; - let Some(id) = resolve_id(state, tok) else { - log_fail(log, line, "bad id"); - fails += 1; - continue; - }; - if state.find_placed_ref(id).is_none() { - log_fail(log, line, "no such id"); - fails += 1; - continue; - } - state.selected_id = id; - state.handles_on = true; - state.write_state(); - redraw(x, ctx, sel_gc, styles, state); - let _ = writeln!(log, "OK DBLCLICK {} handles=on", id); - } - "HANDLE" => { - let (Some(hn), Some(dx), Some(dy)) = (it.next(), it.next(), it.next()) else { - log_fail(log, line, "bad args"); - fails += 1; - continue; - }; - let (Ok(dx), Ok(dy)) = (dx.parse::(), dy.parse::()) else { - log_fail(log, line, "bad args"); - fails += 1; - continue; - }; - let Some(h) = handle_name_to_id(hn) else { - log_fail(log, line, "bad handle name"); - fails += 1; - continue; - }; - if !state.handles_on || state.selected_id < 0 { - log_fail(log, line, "handles not shown"); - fails += 1; - continue; - } - let Some(p) = state.find_placed(state.selected_id) else { - log_fail(log, line, "no selected widget"); - fails += 1; - continue; - }; - let (ox, oy, ow, oh) = (p.x, p.y, p.w, p.h); - apply_handle_drag(p, h, dx, dy); - state.write_state(); - redraw(x, ctx, sel_gc, styles, state); - let p = state.find_placed_ref(state.selected_id).unwrap(); - let _ = writeln!( - log, - "OK HANDLE {} {} {} : {} {} {} {} -> {} {} {} {}", - hn, dx, dy, ox, oy, ow, oh, p.x, p.y, p.w, p.h - ); - } - "CHECKDRAW" => { - let Some(tok) = it.next() else { - log_fail(log, line, "bad args"); - fails += 1; - continue; - }; - let Some(id) = resolve_id(state, tok) else { - log_fail(log, line, "bad id"); - fails += 1; - continue; - }; - let Some(p) = state.find_placed_ref(id) else { - log_fail(log, line, "no such id"); - fails += 1; - continue; - }; - let (px, py, pw, ph, tname) = - (p.x, p.y, p.w, p.h, registry::WIDGETS[p.type_idx].name); - redraw(x, ctx, sel_gc, styles, state); - let n = count_nonwhite(x, win, px, py, pw, ph); - if n < 0 { - log_fail(log, line, "XGetImage failed"); - fails += 1; - continue; - } - if n == 0 { - if tname == "GtkInvisible" { - let _ = writeln!( - log, - "OK CHECKDRAW {} {} nonwhite={} BLANK-EXPECTED", - id, tname, n - ); - } else { - log_fail(log, line, "widget drew nothing (0 non-white pixels)"); - fails += 1; - continue; - } - } else { - let _ = writeln!(log, "OK CHECKDRAW {} {} nonwhite={} DRAWN", id, tname, n); - } - } - "SAVE" => { - let Some(f) = it.next() else { - log_fail(log, line, "bad args"); - fails += 1; - continue; - }; - if !state.save_layout(f) { - log_fail(log, line, "save failed"); - fails += 1; - continue; - } - let _ = writeln!(log, "OK SAVE {} count={}", f, state.placed.len()); - } - "LOAD" => { - let Some(f) = it.next() else { - log_fail(log, line, "bad args"); - fails += 1; - continue; - }; - let n = state.load_layout(f); - if n < 0 { - log_fail(log, line, "load failed"); - fails += 1; - continue; - } - redraw(x, ctx, sel_gc, styles, state); - let _ = writeln!(log, "OK LOAD {} count={}", f, n); - } - "COUNT" => { - let _ = writeln!(log, "OK COUNT {}", state.placed.len()); - } - "HOLD" => { - let secs: u64 = it.next().and_then(|v| v.parse().ok()).unwrap_or(5); - for _ in 0..secs * 10 { - redraw(x, ctx, sel_gc, styles, state); - std::thread::sleep(Duration::from_millis(100)); - } - let _ = writeln!(log, "OK HOLD {}", secs); - } - "LIST" => { - for p in &state.placed { - let _ = writeln!( - log, - "LIST {} {} {} {} {} {}", - p.id, - registry::WIDGETS[p.type_idx].name, - p.x, - p.y, - p.w, - p.h - ); - } - let _ = writeln!(log, "OK LIST {}", state.placed.len()); - } - "QUIT" => { - let _ = writeln!(log, "OK QUIT"); - break; - } - _ => { - log_fail(log, line, "unknown command"); - fails += 1; - } - } - let _ = log.flush(); - } - let _ = writeln!(log, "SCRIPT {} commands, {} failures", cmds, fails); - let _ = log.flush(); - if fails > 0 { - 1 - } else { - 0 - } -} - -fn poll_selection( - x: &X11, - state: &mut State, - ctx: &mut DrawCtx, - sel_gc: Gcontext, - styles: &mut StyleManager, -) { - let mt = match ipc::file_mtime_nanos(&ipc::selection_path()) { - Some(m) => m, - None => return, - }; - if mt == state.sel_mtime { - return; - } - state.sel_mtime = mt; - if let Some((name, idx)) = ipc::read_selection() { - if idx >= 0 { - state.sel_type = idx as i32; - let title = format!("LightGUI Layout — place: {}", name); - let _ = x.set_window_title(ctx.drawable, &title); - // Bring the layout window to the front: the palette tells - // the user to "click in the layout window to place it", so - // the window must be visible — otherwise it sits behind - // the designer and the click lands on the designer's - // canvas, placing nothing. EWMH activation (raise + - // _NET_ACTIVE_WINDOW + focus), mirroring the C++ fix. - let _ = x.activate_window(ctx.drawable); - redraw(x, ctx, sel_gc, styles, state); - } - } -} - -fn run() -> Result> { - let argv: Vec = std::env::args().collect(); - let mut script = String::new(); - let mut logpath = String::new(); - let mut i = 1; - while i < argv.len() { - match argv[i].as_str() { - "--script" => { - i += 1; - script = argv.get(i).cloned().unwrap_or_default(); - } - "--log" => { - i += 1; - logpath = argv.get(i).cloned().unwrap_or_default(); - } - other => return Err(format!("unknown argument: {}", other).into()), - } - i += 1; - } - - let x = X11::connect()?; - let font = x.open_font(&[FONT_DEFAULT, "fixed"])?; - let event_mask = EventMask::EXPOSURE - | EventMask::KEY_PRESS - | EventMask::STRUCTURE_NOTIFY - | EventMask::BUTTON_PRESS - | EventMask::BUTTON_RELEASE - | EventMask::POINTER_MOTION; - let (win, gc) = x.create_window(460, 40, WIN_W, WIN_H, "LightGUI Layout", event_mask)?; - // Dashed selection GC (LineOnOffDash, like the C++ outline). - let sel_gc = x.conn.generate_id()?; - x.conn.create_gc( - sel_gc, - win, - &CreateGCAux::new().line_style(LineStyle::ON_OFF_DASH), - )?; - - let mut styles = StyleManager::new(); - register_styles(&mut styles); - let mut ctx = DrawCtx::new(&x, win, gc, font); - ctx.bind_font(); - // Font metrics for the styles: without them `draw_text_*` draws no - // text at all. Resolving binds the font into the GC via the target. - { - let mut target = CtxTarget::new(&ctx); - if !styles.resolve_font("default", &mut target) && !styles.resolve_font("dark", &mut target) - { - eprintln!("xframe-layout: warning: no font resolved, labels will be blank"); - } - } - let mut state = State::new(); - redraw(&x, &mut ctx, sel_gc, &mut styles, &mut state); - - if !script.is_empty() { - let mut log: Box = if logpath.is_empty() { - Box::new(std::io::stdout()) - } else { - match std::fs::File::create(&logpath) { - Ok(f) => Box::new(f), - Err(_) => Box::new(std::io::stdout()), - } - }; - let rc = run_script( - &x, - &mut ctx, - sel_gc, - win, - &mut styles, - &mut state, - &script, - &mut log, - ); - return Ok(rc); - } - - // Interactive mode. - poll_selection(&x, &mut state, &mut ctx, sel_gc, &mut styles); - let mut dragging = false; - let mut handle_drag = false; - let mut drag_handle = Handle::Se; - let mut grab_dx = 0; - let mut grab_dy = 0; - let mut drag_start_x = 0; - let mut drag_start_y = 0; - let mut last_press_ms: u128 = 0; - let mut last_press_id = -1; - let t0 = Instant::now(); - loop { - let ev = match x.conn.poll_for_event()? { - Some(ev) => ev, - None => { - std::thread::sleep(Duration::from_millis(100)); - poll_selection(&x, &mut state, &mut ctx, sel_gc, &mut styles); - continue; - } - }; - match ev { - Event::Expose(_) => redraw(&x, &mut ctx, sel_gc, &mut styles, &mut state), - Event::ConfigureNotify(ev) => { - state.win_w = ev.width as i32; - state.win_h = ev.height as i32; - redraw(&x, &mut ctx, sel_gc, &mut styles, &mut state); - } - Event::ButtonPress(ev) => { - if ev.detail != 1 { - continue; - } - let (mx, my) = (ev.event_x as i32, ev.event_y as i32); - if let Some(h) = handle_at(&state, mx, my) { - handle_drag = true; - drag_handle = h; - drag_start_x = mx; - drag_start_y = my; - continue; - } - let mut hit: Option = None; - for p in state.placed.iter().rev() { - if mx >= p.x && mx <= p.x + p.w && my >= p.y && my <= p.y + p.h { - hit = Some(p.id); - break; - } - } - let t = t0.elapsed().as_millis(); - if let Some(id) = hit { - let dbl = id == last_press_id && t - last_press_ms < 450; - last_press_ms = t; - last_press_id = id; - if dbl { - state.selected_id = id; - state.handles_on = true; - state.write_state(); - redraw(&x, &mut ctx, sel_gc, &mut styles, &mut state); - continue; - } - state.selected_id = id; - state.handles_on = false; - dragging = true; - let p = state.find_placed_ref(id).unwrap(); - grab_dx = mx - p.x; - grab_dy = my - p.y; - state.write_state(); - redraw(&x, &mut ctx, sel_gc, &mut styles, &mut state); - } else { - last_press_ms = t; - last_press_id = -1; - if state.handles_on || state.selected_id >= 0 { - state.handles_on = false; - state.selected_id = -1; - state.write_state(); - redraw(&x, &mut ctx, sel_gc, &mut styles, &mut state); - } - if state.sel_type >= 0 && my < state.win_h - K_STATUS_H { - let t = state.sel_type as usize; - let w = registry::WIDGETS[t].default_w as i32; - let h = registry::WIDGETS[t].default_h as i32; - if state.place_widget(t, mx - w / 2, my - h / 2, w, h) >= 0 { - redraw(&x, &mut ctx, sel_gc, &mut styles, &mut state); - } - } - } - } - Event::MotionNotify(ev) => { - let (mx, my) = (ev.event_x as i32, ev.event_y as i32); - if handle_drag && state.selected_id >= 0 { - if let Some(p) = state.find_placed(state.selected_id) { - apply_handle_drag(p, drag_handle, mx - drag_start_x, my - drag_start_y); - drag_start_x = mx; - drag_start_y = my; - state.write_state(); - redraw(&x, &mut ctx, sel_gc, &mut styles, &mut state); - } - } else if dragging && state.selected_id >= 0 { - if let Some(p) = state.find_placed(state.selected_id) { - p.x = (mx - grab_dx).max(0); - p.y = (my - grab_dy).max(0); - let (nx, ny, nw, nh) = (p.x, p.y, p.w, p.h); - p.wdg.set_bounds(nx, ny, nw, nh); - state.write_state(); - redraw(&x, &mut ctx, sel_gc, &mut styles, &mut state); - } - } else { - for p in state.placed.iter_mut() { - if p.wdg.contains(mx, my) { - p.wdg.on_motion(mx, my); - } - } - } - } - Event::ButtonRelease(ev) => { - if handle_drag || dragging { - state.write_state(); - redraw(&x, &mut ctx, sel_gc, &mut styles, &mut state); - } - if state.selected_id >= 0 { - if let Some(p) = state.find_placed(state.selected_id) { - p.wdg - .on_button_release(ev.event_x as i32, ev.event_y as i32, 1); - } - } - dragging = false; - handle_drag = false; - } - Event::KeyPress(ev) => { - let keysym = x.keysym_for_keycode(ev.detail); - match keysym { - KEY_DELETE | KEY_BACKSPACE => { - if state.selected_id >= 0 { - state.delete_widget(state.selected_id); - redraw(&x, &mut ctx, sel_gc, &mut styles, &mut state); - } - } - KEY_ESCAPE => { - state.handles_on = false; - state.selected_id = -1; - state.write_state(); - redraw(&x, &mut ctx, sel_gc, &mut styles, &mut state); - } - 0x73 => { - // 's': save layout. - state.save_layout("/tmp/lightgui-layout.txt"); - redraw(&x, &mut ctx, sel_gc, &mut styles, &mut state); - } - 0x71 => break, // 'q' - _ => {} - } - } - Event::ClientMessage(ev) - if ev.type_ == x.wm_protocols && ev.data.as_data32()[0] == x.wm_delete => - { - break; - } - _ => {} - } - poll_selection(&x, &mut state, &mut ctx, sel_gc, &mut styles); - } - Ok(0) -} - -fn main() -> ExitCode { - match run() { - Ok(code) => ExitCode::from(code as u8), - Err(e) => { - eprintln!("xframe-layout: {}", e); - ExitCode::from(1) - } - } -} diff --git a/crates/xframe-layout/tests/script.rs b/crates/xframe-layout/tests/script.rs deleted file mode 100644 index 5b8f2ef..0000000 --- a/crates/xframe-layout/tests/script.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! Layout script-mode test under Xvfb on display :92 (kept clear of -//! the demo :98, palette :93 and runner :91 tests). Exercises the -//! full script command set, including PLACE_ALL (547 stubs) and the -//! GtkInvisible BLANK-EXPECTED CHECKDRAW path. -use std::path::PathBuf; -use std::process::{Child, Command, Stdio}; -use std::time::{Duration, Instant}; - -fn layout_bin() -> PathBuf { - PathBuf::from(env!("CARGO_BIN_EXE_xframe-layout")) -} - -fn start_xvfb(display: &str) -> Option { - // A SIGKILLed Xvfb leaves its socket behind; a stale socket makes - // the wait below return at once and the X client then fails to - // connect. Remove it when no server for this display is alive. - let sock_path = format!("/tmp/.X11-unix/X{}", display.trim_start_matches(':')); - let server_running = Command::new("pgrep") - .args(["-f", &format!("Xvfb {}", display)]) - .output() - .map(|o| o.status.success()) - .unwrap_or(false); - if !server_running && PathBuf::from(&sock_path).exists() { - let _ = std::fs::remove_file(&sock_path); - } - let child = Command::new("Xvfb") - .args([display, "-screen", "0", "1280x1024x24"]) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .spawn() - .ok()?; - let sock = format!("/tmp/.X11-unix/X{}", display.trim_start_matches(':')); - let t0 = Instant::now(); - while !PathBuf::from(&sock).exists() { - if t0.elapsed() > Duration::from_secs(10) { - return None; - } - std::thread::sleep(Duration::from_millis(100)); - } - Some(child) -} - -#[test] -fn layout_script_full_command_set() { - let mut xvfb = match start_xvfb(":92") { - Some(c) => c, - None => { - eprintln!("Xvfb unavailable; skipping X test"); - return; - } - }; - let dir = std::env::temp_dir().join("xframe-layout-test"); - let _ = std::fs::create_dir_all(&dir); - let script = dir.join("cmds.txt"); - let log = dir.join("out.log"); - let saved = dir.join("saved.txt"); - let state = dir.join("layout-state.txt"); - let _ = std::fs::remove_file(&log); - std::fs::write( - &script, - format!( - "# layout script test\nPLACE GtkButton 40 40 340 200\nPLACE GtkInvisible 11 11 10 10\nCHECKDRAW 1\nCHECKDRAW 2\nMOVE 1 10 5\nRESIZE 1 400 220\nSELECT 1\nDBLCLICK 1\nHANDLE se 20 10\nSAVE {}\nDELETE 2\nLOAD {}\nCOUNT\nLIST\nPLACE_ALL\nCOUNT\nQUIT\n", - saved.display(), - saved.display() - ), - ) - .unwrap(); - let out = Command::new(layout_bin()) - .args(["--script"]) - .arg(&script) - .args(["--log"]) - .arg(&log) - .env("DISPLAY", ":92") - .env("LIGHTGUI_LAYOUT_STATE", &state) - .output() - .expect("run layout --script"); - let log_text = std::fs::read_to_string(&log).unwrap_or_default(); - let _ = xvfb.kill(); - let _ = xvfb.wait(); - assert!( - out.status.success(), - "layout script rc={:?}\nlog:\n{}", - out.status.code(), - log_text - ); - assert!( - log_text.contains("OK CHECKDRAW 1 GtkButton nonwhite="), - "log:\n{}", - log_text - ); - assert!( - log_text.contains("BLANK-EXPECTED"), - "GtkInvisible should be BLANK-EXPECTED\nlog:\n{}", - log_text - ); - assert!( - log_text.contains("OK PLACE_ALL 547/547"), - "log:\n{}", - log_text - ); - assert!( - log_text.contains("SCRIPT 17 commands, 0 failures"), - "log:\n{}", - log_text - ); - // State file must hold 2 loaded + 547 PLACE_ALL widgets. - let state_text = std::fs::read_to_string(&state).unwrap_or_default(); - assert_eq!(state_text.lines().count(), 549, "state lines"); - let _ = std::fs::remove_file(&script); - let _ = std::fs::remove_file(&log); - let _ = std::fs::remove_file(&saved); - let _ = std::fs::remove_file(&state); -} diff --git a/flatpak/com.hotconfig.LightGUIRust.yaml b/flatpak/com.hotconfig.LightGUIRust.yaml index de88d56..b309786 100644 --- a/flatpak/com.hotconfig.LightGUIRust.yaml +++ b/flatpak/com.hotconfig.LightGUIRust.yaml @@ -34,7 +34,6 @@ modules: - cargo --offline build --release --verbose - install -Dm755 target/release/lightgui-designer /app/share/lightgui-rust/lightgui-designer - install -Dm755 target/release/xframe-palette /app/share/lightgui-rust/xframe-palette - - install -Dm755 target/release/xframe-layout /app/share/lightgui-rust/xframe-layout - mkdir -p /app/share/lightgui-rust/widgets/icons - cp lightgui-icons/widgets/icons/* /app/share/lightgui-rust/widgets/icons/ - install -Dm755 flatpak/lightgui-rust-launcher /app/bin/lightgui-rust diff --git a/flatpak/lightgui-rust-launcher b/flatpak/lightgui-rust-launcher index adc11c1..a0cb928 100755 --- a/flatpak/lightgui-rust-launcher +++ b/flatpak/lightgui-rust-launcher @@ -1,6 +1,8 @@ #!/bin/sh -# LightGUI Rust Flatpak launcher — start the combined IDE -# (designer + XFrame palette + layout), mirroring the C `ide` script. +# LightGUI Rust Flatpak launcher — start the designer. +# The canvas lives inside the designer now (no separate layout +# process); the XFrame palette is a separate crate but is not +# launched — palette selection happens in-process in the designer. # Binaries and icons live under /app/share/lightgui-rust/. ROOT=/app/share/lightgui-rust export LIGHTGUI_ICONS="$ROOT/widgets/icons" @@ -10,23 +12,4 @@ if [ -z "$DISPLAY" ] && [ -z "$WAYLAND_DISPLAY" ]; then exit 1 fi -PAL_PID="" -LAY_PID="" -cleanup() { - [ -n "$PAL_PID" ] && kill "$PAL_PID" 2>/dev/null - [ -n "$LAY_PID" ] && kill "$LAY_PID" 2>/dev/null -} -trap cleanup EXIT INT TERM - -(cd "$ROOT" && ./xframe-palette) & -PAL_PID=$! -(cd "$ROOT" && ./xframe-layout) & -LAY_PID=$! - -(cd "$ROOT" && ./lightgui-designer) & -DESIGNER_PID=$! -wait "$DESIGNER_PID" -STATUS=$? -cleanup -trap - EXIT INT TERM -exit "$STATUS" +exec "$ROOT/lightgui-designer" "$@"