From 006b362f411997da8653cadd546ef4e0ba002b65 Mon Sep 17 00:00:00 2001 From: Hironobu Sano <7529745+sanohiro@users.noreply.github.com> Date: Sat, 26 Sep 2026 10:19:52 +0900 Subject: [PATCH 1/4] feat: add display rotation and restore keypad navigation --- docs/configuration.ja.md | 27 +++++ docs/configuration.md | 27 +++++ docs/installation.ja.md | 9 +- docs/installation.md | 7 +- docs/keybinds.ja.md | 8 ++ docs/keybinds.md | 8 ++ src/config/mod.rs | 100 +++++++++++++++++- src/drm/display.rs | 48 +++++++++ src/font/lcd_atlas.rs | 53 ++++++++-- src/gpu/emoji_renderer.rs | 16 ++- src/gpu/fbo.rs | 12 ++- src/gpu/image_renderer.rs | 16 ++- src/gpu/lcd_renderer_instanced.rs | 9 +- src/gpu/renderer.rs | 9 +- src/gpu/shader.rs | 166 +++++++++++++++++++++++++----- src/gpu/ui_renderer.rs | 11 +- src/input/evdev.rs | 161 +++++++++++++++++++++++++---- src/main.rs | 90 +++++++++++++--- src/terminal/kitty.rs | 20 +++- 19 files changed, 710 insertions(+), 87 deletions(-) diff --git a/docs/configuration.ja.md b/docs/configuration.ja.md index 24860f4..3e848c6 100644 --- a/docs/configuration.ja.md +++ b/docs/configuration.ja.md @@ -65,6 +65,32 @@ bcon --init-config=~/foo.toml,vim # ファイル生成 BCON_CONFIG=~/foo.toml bcon # そのファイルだけを読み込み起動 ``` +## 画面の回転 + +タブレットや縦置きモニターでは、設定に次を追加します。 + +```toml +[display] +rotation = 90 + +[font] +render_mode = "grayscale" +``` + +`rotation` は時計回りに `0`(既定)、`90`、`180`、`270` 度を指定します。 +変更後は bcon を再起動してください。90/270 度では端末の論理的な幅と高さが +入れ替わり、文字・画像・UI・ポインター座標に同じ回転が適用されます。 +対応していない正の角度は警告を出し、`0` に戻ります。 + +グレースケールにすると、回転後の文字とパネルのサブピクセル配列が合わない +場合の色にじみを避けられます。LCD 描画を使う場合は、回転後の配列に合わせて +`lcd_subpixel`(`rgb`、`bgr`、`vrgb`、`vbgr`)を選んでください。 +描画モードやサブピクセル配列の変更後も再起動が必要です。 + +`bcon@tty2.service` を使う場合は `/etc/bcon/config.toml` を編集し、 +`sudo systemctl restart bcon@tty2` の後に `Ctrl+Alt+F2` で tty2 に切り替えます。 +rootless セッションでは `~/.config/bcon/config.toml` を使えます。 + ## 利用可能なプリセット | プリセット | 説明 | @@ -107,6 +133,7 @@ speed = 1.0 # カーソル速度倍率 (デフォルト: 1.0、 [display] prefer_external = true # 外部モニター優先 (HDMI/DP > 内蔵) auto_switch = true # ホットプラグ時に自動切り替え +rotation = 0 # 時計回り: 0、90、180、270 度。変更後は再起動が必要 [drm] device = "auto" # "auto" は各 GPU を probe して接続中のディスプレイを自動選択 diff --git a/docs/configuration.md b/docs/configuration.md index 8180eb4..bfe0f67 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -66,6 +66,32 @@ bcon --init-config=~/foo.toml,vim # generate the file BCON_CONFIG=~/foo.toml bcon # load it exclusively ``` +## Display rotation + +For tablets or portrait monitors, add this to your configuration: + +```toml +[display] +rotation = 90 + +[font] +render_mode = "grayscale" +``` + +`rotation` accepts `0` (default), `90`, `180`, or `270`, clockwise. Restart +bcon after changing it. Quarter turns swap the terminal's logical width and +height; text, images, UI, and pointer coordinates use the same rotation. +Invalid positive angles fall back to `0` with a warning. + +Grayscale avoids color fringes when the rotated content no longer matches the +panel's subpixel layout. To retain LCD rendering, choose `lcd_subpixel` for the +rotated layout (`rgb`, `bgr`, `vrgb`, or `vbgr`). Restart after changing the font +rendering mode or subpixel layout as well. + +For `bcon@tty2.service`, edit `/etc/bcon/config.toml` and restart with +`sudo systemctl restart bcon@tty2`, then switch to tty2 with `Ctrl+Alt+F2`. +Rootless sessions can use `~/.config/bcon/config.toml`. + ## Available Presets | Preset | Description | @@ -109,6 +135,7 @@ speed = 1.0 # Cursor speed multiplier (default: 1.0) [display] prefer_external = true # Prefer external monitors (HDMI/DP) over internal auto_switch = true # Auto-switch on hotplug connect/disconnect +rotation = 0 # Clockwise degrees: 0, 90, 180, or 270; restart to apply [drm] device = "auto" # "auto" probes each GPU and selects one with a connected display diff --git a/docs/installation.ja.md b/docs/installation.ja.md index 7e9ea8c..6347c3d 100644 --- a/docs/installation.ja.md +++ b/docs/installation.ja.md @@ -146,6 +146,14 @@ bcon はデフォルトで libseat 対応。以下が可能: 同じバイナリが `sudo` でもユーザーセッションでも動作します。 +rootless で試す場合は空いているテキスト VT(GNOME では通常 +`Ctrl+Alt+F3`)に切り替え、 +そこでログインしてから `bcon --backend=seatd` を実行します。この対話的な +起動では getty を停止する必要はありません。ログイン後は getty から +ログインセッションへ VT が引き継がれています。システムサービスから +VT 上で bcon を直接起動する場合は、同じ VT の競合を避けるため +その VT の getty を停止してください。 + ## Arch Linux ユーザー向け Debian/Ubuntu と比べていくつか違いがあります。 @@ -191,4 +199,3 @@ yay -S bcon 4. ユーザーログインセッション セッションファイル (`bcon-session`, `bcon.desktop`) は AUR パッケージが最終配置先に直接インストールするため、手動コピーは不要です。 - diff --git a/docs/installation.md b/docs/installation.md index 7ee362a..dda1bf6 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -147,6 +147,12 @@ bcon includes libseat support by default, enabling: The same binary works both with `sudo` and as a user session. +For a rootless run, switch to an unused text VT (often `Ctrl+Alt+F3` on +GNOME), log in there, and run `bcon --backend=seatd` from that login shell. +You do not need to disable getty for this interactive setup: getty has already +handed the VT to your login session. If a system service starts bcon directly +on a VT instead, disable that VT's getty so the two services do not own it. + ## For Arch Linux Users There are some differences compared to Debian/Ubuntu. @@ -192,4 +198,3 @@ yay -S bcon 4. User Login Session Session files (`bcon-session`, `bcon.desktop`) are installed in their final locations by the AUR package, so no manual deployment is needed. - diff --git a/docs/keybinds.ja.md b/docs/keybinds.ja.md index 405a1a9..f93a894 100644 --- a/docs/keybinds.ja.md +++ b/docs/keybinds.ja.md @@ -29,6 +29,14 @@ | 次のタブ | `Ctrl+Shift+PageDown` | 同左 | 同左 | 次のタブに切替 | | 前のタブ | `Ctrl+Shift+PageUp` | 同左 | 同左 | 前のタブに切替 | +## テンキー + +NumLock が OFF のとき、テンキーの矢印・Home・End・PageUp・PageDown・Insert・Delete +は独立した同名のキーと同じように動作し、bcon のキーバインドにも使えます。 +NumLock が ON のときは数字を入力します。追加設定は不要です。 +動作は XKB レイアウトが選ぶキーシンボルに従います。レイアウトによっては +Shift を押すと NumLock の動作が一時的に反転します。 + ## カスタムキーバインド 1つのアクションに複数のキーを割り当て可能: diff --git a/docs/keybinds.md b/docs/keybinds.md index 3c4cf42..2b0dce4 100644 --- a/docs/keybinds.md +++ b/docs/keybinds.md @@ -29,6 +29,14 @@ English | **[Japanese](keybinds.ja.md)** | Next Tab | `Ctrl+Shift+PageDown` | same | same | Switch to next tab | | Prev Tab | `Ctrl+Shift+PageUp` | same | same | Switch to previous tab | +## Numeric keypad + +With NumLock off, keypad arrows, Home, End, PageUp, PageDown, Insert, and Delete +work like the dedicated navigation keys, including bcon keybinds. With NumLock +on, the keypad continues to enter digits. No extra configuration is required. +The keysym selected by your XKB layout determines the behavior; some layouts +make Shift temporarily reverse NumLock. + ## Custom Keybinds Multiple keys can be assigned to a single action in config: diff --git a/src/config/mod.rs b/src/config/mod.rs index 7960757..48dc20f 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -272,6 +272,11 @@ pub struct DisplayOutputConfig { /// Auto-switch to external monitor when connected /// When true, automatically switch display on hotplug connect pub auto_switch: bool, + /// Display rotation in clockwise degrees: 0, 90, 180, or 270 + /// Useful for tablets and portrait monitors where the panel reports + /// a fixed native orientation different from how the user holds it. + /// Implemented via a GL projection-matrix transform (no hardware dependency). + pub rotation: u32, } impl Default for DisplayOutputConfig { @@ -279,6 +284,24 @@ impl Default for DisplayOutputConfig { Self { prefer_external: true, auto_switch: true, + rotation: 0, + } + } +} + +impl DisplayOutputConfig { + /// Returns the rotation clamped to one of the valid values (0/90/180/270). + /// Logs a warning for invalid input and falls back to 0. + pub fn normalized_rotation(&self) -> u32 { + match self.rotation { + 0 | 90 | 180 | 270 => self.rotation, + other => { + warn!( + "Invalid display.rotation = {} (must be 0, 90, 180, or 270). Using 0.", + other + ); + 0 + } } } } @@ -1368,6 +1391,16 @@ ime_disabled_apps = ["vim", "nvim", "vi", "vimdiff", "emacs", "nano", "less", "m # [display] # prefer_external = true # Prefer external monitors (HDMI/DP) over internal (eDP) # auto_switch = true # Auto-switch to external monitor on hotplug connect +# rotation = 0 # Display rotation in clockwise degrees: 0, 90, 180, 270 +# # For tablets / portrait monitors whose panel ships +# # in a different physical orientation than expected. +# # 0 = no rotation (default). Applied via GL projection +# # transform (no hardware dependency). +# # Caveat: LCD subpixel rendering assumes the panel's +# # physical subpixel layout, so when rotation is 90/270 +# # switch font.render_mode to "grayscale" or set +# # font.lcd_subpixel = "vrgb"/"vbgr" to match. +# # Changing this at runtime requires a restart. # # Connector priority (when prefer_external = true): # HDMI > DisplayPort > DVI > VGA > eDP (internal) @@ -1599,9 +1632,23 @@ impl ConfigWatcher { /// Start watching config file pub fn new(config_path: &Path) -> Result { let (tx, rx) = mpsc::channel(); + // notify emits absolute paths, including when BCON_CONFIG was relative. + // Preserve symlink names so atomic replacement still matches this path. + let config_path = if config_path.is_absolute() { + config_path.to_path_buf() + } else { + std::env::current_dir()?.join(config_path) + }; + let watched_config = config_path.clone(); let mut watcher = notify::recommended_watcher(move |res: Result| { if let Ok(event) = res { + // The parent directory is watched to catch atomic renames, but + // changes to sibling files must not reload the config. In + // particular, a log in that directory would feed back forever. + if !event.paths.iter().any(|path| path == &watched_config) { + return; + } // Detect Modify, Create, and Rename events // (editors often save by writing to temp file then rename) use notify::EventKind; @@ -1615,7 +1662,7 @@ impl ConfigWatcher { })?; // Watch the parent directory to catch rename operations - let watch_path = config_path.parent().unwrap_or(config_path); + let watch_path = config_path.parent().unwrap_or(&config_path); watcher.watch(watch_path, RecursiveMode::NonRecursive)?; Ok(Self { @@ -1626,7 +1673,11 @@ impl ConfigWatcher { /// Check if config file was modified (non-blocking) pub fn check_reload(&self) -> bool { - self.rx.try_recv().is_ok() + let mut changed = false; + while self.rx.try_recv().is_ok() { + changed = true; + } + changed } } @@ -1698,6 +1749,51 @@ pub fn detect_nerd_font_path() -> Option { mod tests { use super::*; + #[cfg(target_os = "linux")] + #[test] + fn config_watcher_detects_relative_path_and_atomic_replace() { + let cwd = std::env::current_dir().unwrap(); + let dir = tempfile::tempdir_in(&cwd).unwrap(); + let config_path = dir.path().join("config.toml"); + std::fs::write(&config_path, "[display]\nrotation = 0\n").unwrap(); + let watcher = ConfigWatcher::new(config_path.strip_prefix(&cwd).unwrap()).unwrap(); + + let replacement = dir.path().join("replacement.toml"); + std::fs::write(&replacement, "[display]\nrotation = 90\n").unwrap(); + std::fs::rename(&replacement, &config_path).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while !watcher.check_reload() { + assert!( + std::time::Instant::now() < deadline, + "atomic save of relative config was not detected" + ); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + } + + #[cfg(target_os = "linux")] + #[test] + fn config_watcher_ignores_sibling_log_updates() { + let dir = tempfile::tempdir().unwrap(); + let config_path = dir.path().join("config.toml"); + let log_path = dir.path().join("bcon.log"); + std::fs::write(&config_path, "[display]\nrotation = 0\n").unwrap(); + let watcher = ConfigWatcher::new(&config_path).unwrap(); + + std::fs::write(&log_path, "first log line\n").unwrap(); + std::thread::sleep(std::time::Duration::from_millis(150)); + assert!(!watcher.check_reload(), "a sibling log triggered config reload"); + + std::fs::write(&config_path, "[display]\nrotation = 90\n").unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + let mut detected = watcher.check_reload(); + while !detected && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(10)); + detected = watcher.check_reload(); + } + assert!(detected, "config edit was not detected"); + } + #[test] fn test_parse_color() { let color = parse_color("ff0000"); diff --git a/src/drm/display.rs b/src/drm/display.rs index 05b7dc0..b1e4e66 100644 --- a/src/drm/display.rs +++ b/src/drm/display.rs @@ -16,10 +16,57 @@ pub struct DisplayConfig { pub connector_handle: connector::Handle, pub crtc_handle: crtc::Handle, pub mode: Mode, + /// Physical framebuffer dimensions (always panel native, never swapped). pub width: u32, pub height: u32, /// HDR capabilities detected from display EDID pub hdr: HdrCapabilities, + /// Rotation applied to user-facing content in clockwise degrees: 0/90/180/270. + /// Set from the configured `display.rotation`. Does NOT change the framebuffer + /// or DRM mode — it only affects the projection matrix and input coordinates. + pub rotation: u32, +} + +impl DisplayConfig { + /// Logical width seen by the application (rendering, terminal grid, layout, input). + /// For 0/180 it equals the physical width; for 90/270 it equals the physical height. + pub fn logical_width(&self) -> u32 { + match self.rotation { + 90 | 270 => self.height, + _ => self.width, + } + } + + /// Logical height seen by the application. + /// For 0/180 it equals the physical height; for 90/270 it equals the physical width. + pub fn logical_height(&self) -> u32 { + match self.rotation { + 90 | 270 => self.width, + _ => self.height, + } + } + + /// Map a logical pointer position to the physical cursor plane. + pub fn cursor_position(&self, x: f64, y: f64) -> (f64, f64) { + logical_to_physical_cursor(x, y, self.width, self.height, self.rotation) + } +} + +pub(crate) fn logical_to_physical_cursor( + x: f64, + y: f64, + width: u32, + height: u32, + rotation: u32, +) -> (f64, f64) { + let w = width as f64 - 1.0; + let h = height as f64 - 1.0; + match rotation { + 90 => (w - y, x), + 180 => (w - x, h - y), + 270 => (y, h - x), + _ => (x, y), + } } impl DisplayConfig { @@ -83,6 +130,7 @@ impl DisplayConfig { width: width as u32, height: height as u32, hdr, + rotation: 0, }) } diff --git a/src/font/lcd_atlas.rs b/src/font/lcd_atlas.rs index f5bea8e..73348ce 100644 --- a/src/font/lcd_atlas.rs +++ b/src/font/lcd_atlas.rs @@ -242,12 +242,12 @@ impl LcdGlyphAtlas { // Copy RGB bitmap for y in 0..bh { for x in 0..bw { - let src_idx = ((y * bw + x) * 3) as usize; + let pixel_idx = (y * bw + x) as usize; let dst_idx = (((y0 + y) * atlas_width + (x0 + x)) * 3) as usize; - if src_idx + 2 < ft_glyph.bitmap.len() && dst_idx + 2 < atlas_data.len() { - atlas_data[dst_idx] = ft_glyph.bitmap[src_idx]; - atlas_data[dst_idx + 1] = ft_glyph.bitmap[src_idx + 1]; - atlas_data[dst_idx + 2] = ft_glyph.bitmap[src_idx + 2]; + if let Some(rgb) = glyph_pixel_rgb(&ft_glyph.bitmap, pixel_idx, lcd_mode) { + if dst_idx + 2 < atlas_data.len() { + atlas_data[dst_idx..dst_idx + 3].copy_from_slice(&rgb); + } } } } @@ -532,12 +532,12 @@ impl LcdGlyphAtlas { for y in 0..bh { for x in 0..bw { - let src_idx = ((y * bw + x) * 3) as usize; + let pixel_idx = (y * bw + x) as usize; let dst_idx = (((y0 + y) * self.atlas_width + (x0 + x)) * 3) as usize; - if src_idx + 2 < glyph.bitmap.len() && dst_idx + 2 < self.atlas_data.len() { - self.atlas_data[dst_idx] = glyph.bitmap[src_idx]; - self.atlas_data[dst_idx + 1] = glyph.bitmap[src_idx + 1]; - self.atlas_data[dst_idx + 2] = glyph.bitmap[src_idx + 2]; + if let Some(rgb) = glyph_pixel_rgb(&glyph.bitmap, pixel_idx, self.lcd_mode) { + if dst_idx + 2 < self.atlas_data.len() { + self.atlas_data[dst_idx..dst_idx + 3].copy_from_slice(&rgb); + } } } } @@ -993,3 +993,36 @@ impl LcdGlyphAtlas { (self.cell_width, self.cell_height) } } + +// The GPU atlas always uses RGB8, while FreeType grayscale glyphs contain R8. +fn glyph_pixel_rgb(bitmap: &[u8], pixel: usize, mode: LcdMode) -> Option<[u8; 3]> { + if mode == LcdMode::Grayscale { + bitmap.get(pixel).map(|&coverage| [coverage; 3]) + } else { + let start = pixel * 3; + bitmap + .get(start..start + 3) + .map(|rgb| [rgb[0], rgb[1], rgb[2]]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn grayscale_glyph_pixels_expand_without_color_or_truncation() { + let coverage = [0, 64, 128, 255]; + let rgb: Vec = (0..coverage.len()) + .flat_map(|pixel| glyph_pixel_rgb(&coverage, pixel, LcdMode::Grayscale).unwrap()) + .collect(); + assert_eq!(rgb, [0, 0, 0, 64, 64, 64, 128, 128, 128, 255, 255, 255]); + assert_eq!(glyph_pixel_rgb(&coverage, 4, LcdMode::Grayscale), None); + for mode in [LcdMode::LcdHorizontal, LcdMode::LcdVertical] { + assert_eq!( + glyph_pixel_rgb(&[10, 20, 30, 40, 50, 60], 1, mode), + Some([40, 50, 60]) + ); + } + } +} diff --git a/src/gpu/emoji_renderer.rs b/src/gpu/emoji_renderer.rs index 098522e..d415950 100644 --- a/src/gpu/emoji_renderer.rs +++ b/src/gpu/emoji_renderer.rs @@ -8,8 +8,6 @@ use log::info; use crate::font::emoji::EmojiAtlas; -use super::shader::ortho_projection; - /// Vertex shader for emoji rendering (GLSL ES 3.00) const EMOJI_VERTEX_SHADER: &str = r#"#version 300 es precision mediump float; @@ -133,6 +131,7 @@ pub struct EmojiRenderer { vertices: Vec, /// Current character count in buffer glyph_count: usize, + rotation: u32, } impl EmojiRenderer { @@ -197,10 +196,15 @@ impl EmojiRenderer { ebo, vertices: Vec::with_capacity(MAX_EMOJI * VERTICES_PER_QUAD * VERTEX_FLOATS), glyph_count: 0, + rotation: 0, }) } } + pub fn set_rotation(&mut self, rotation: u32) { + self.rotation = rotation; + } + /// Clear buffer pub fn begin(&mut self) { self.vertices.clear(); @@ -271,8 +275,12 @@ impl EmojiRenderer { // Bind shader self.shader.bind(gl); - // Set orthographic projection matrix - let projection = ortho_projection(screen_width as f32, screen_height as f32); + // Set orthographic projection matrix (rotation-aware) + let projection = super::shader::ortho_projection_rotated( + screen_width as f32, + screen_height as f32, + self.rotation, + ); self.shader.set_projection(gl, &projection); self.shader.set_texture_unit(gl, 0); diff --git a/src/gpu/fbo.rs b/src/gpu/fbo.rs index 7aa422a..1102fda 100644 --- a/src/gpu/fbo.rs +++ b/src/gpu/fbo.rs @@ -168,6 +168,7 @@ impl Fbo { end_row: usize, cell_height: f32, margin_y: f32, + rotation: u32, r: f32, g: f32, b: f32, @@ -179,9 +180,14 @@ impl Fbo { let y = (margin_y + start_row as f32 * cell_height) as i32; let height = ((end_row - start_row + 1) as f32 * cell_height) as i32; - // OpenGL scissor Y is from bottom, need to flip - let flipped_y = self.height as i32 - y - height; - gl.scissor(0, flipped_y, self.width as i32, height); + // Convert the logical row strip to physical framebuffer coordinates. + // OpenGL scissor coordinates start at the bottom left. + match rotation { + 90 => gl.scissor(self.width as i32 - y - height, 0, height, self.height as i32), + 180 => gl.scissor(0, y, self.width as i32, height), + 270 => gl.scissor(y, 0, height, self.height as i32), + _ => gl.scissor(0, self.height as i32 - y - height, self.width as i32, height), + } gl.clear_color(r, g, b, 1.0); gl.clear(glow::COLOR_BUFFER_BIT); diff --git a/src/gpu/image_renderer.rs b/src/gpu/image_renderer.rs index 09b5579..6f9e9dc 100644 --- a/src/gpu/image_renderer.rs +++ b/src/gpu/image_renderer.rs @@ -10,8 +10,6 @@ use log::info; use crate::terminal::TerminalImage; -use super::shader::ortho_projection; - /// Image drawing vertex shader (GLSL ES 3.00) const IMAGE_VERTEX_SHADER: &str = r#"#version 300 es precision mediump float; @@ -139,6 +137,7 @@ pub struct ImageRenderer { generation: u64, /// Draw queue draw_queue: Vec, + rotation: u32, } /// Generate a unique texture key from pane ID and image ID. @@ -210,10 +209,15 @@ impl ImageRenderer { textures: HashMap::new(), generation: 0, draw_queue: Vec::new(), + rotation: 0, }) } } + pub fn set_rotation(&mut self, rotation: u32) { + self.rotation = rotation; + } + /// Upload image texture with explicit key. /// Use `image_key(pane_id, image_id)` to generate the key. pub fn upload_image(&mut self, gl: &glow::Context, key: u64, image: &TerminalImage) { @@ -336,8 +340,12 @@ impl ImageRenderer { // Bind shader self.shader.bind(gl); - // Set orthographic projection matrix - let projection = ortho_projection(screen_width as f32, screen_height as f32); + // Set orthographic projection matrix (rotation-aware) + let projection = super::shader::ortho_projection_rotated( + screen_width as f32, + screen_height as f32, + self.rotation, + ); self.shader.set_projection(gl, &projection); self.shader.set_image_unit(gl, 0); diff --git a/src/gpu/lcd_renderer_instanced.rs b/src/gpu/lcd_renderer_instanced.rs index d2641a2..3442a0d 100644 --- a/src/gpu/lcd_renderer_instanced.rs +++ b/src/gpu/lcd_renderer_instanced.rs @@ -262,6 +262,7 @@ pub struct LcdTextRendererInstanced { stem_darkening: f32, contrast: f32, fringe_reduction: f32, + rotation: u32, } impl LcdTextRendererInstanced { @@ -324,10 +325,15 @@ impl LcdTextRendererInstanced { stem_darkening: 0.0, contrast: LCD_DEFAULT_CONTRAST, fringe_reduction: 0.1, + rotation: 0, }) } } + pub fn set_rotation(&mut self, rotation: u32) { + self.rotation = rotation; + } + pub fn set_bg_color(&mut self, r: f32, g: f32, b: f32) { self.default_bg = [r, g, b]; } @@ -690,7 +696,8 @@ impl LcdTextRendererInstanced { self.shader.bind(gl); - let projection = shader::ortho_projection(width as f32, height as f32); + let projection = + shader::ortho_projection_rotated(width as f32, height as f32, self.rotation); self.shader.set_projection(gl, &projection); self.shader.set_gamma(gl, self.gamma); self.shader.set_stem_darkening(gl, self.stem_darkening); diff --git a/src/gpu/renderer.rs b/src/gpu/renderer.rs index 7376e7e..4789612 100644 --- a/src/gpu/renderer.rs +++ b/src/gpu/renderer.rs @@ -387,6 +387,7 @@ pub struct CurlyRenderer { ebo: glow::Buffer, vertices: Vec, run_count: usize, + rotation: u32, } impl CurlyRenderer { @@ -453,10 +454,15 @@ impl CurlyRenderer { ebo, vertices: Vec::with_capacity(CURLY_MAX_RUNS * 4 * CURLY_VERTEX_FLOATS), run_count: 0, + rotation: 0, }) } } + pub fn set_rotation(&mut self, rotation: u32) { + self.rotation = rotation; + } + pub fn begin(&mut self) { self.vertices.clear(); self.run_count = 0; @@ -520,7 +526,8 @@ impl CurlyRenderer { self.shader.bind(gl); - let projection = shader::ortho_projection(width as f32, height as f32); + let projection = + shader::ortho_projection_rotated(width as f32, height as f32, self.rotation); self.shader.set_projection(gl, &projection); gl.bind_vertex_array(Some(self.vao)); diff --git a/src/gpu/shader.rs b/src/gpu/shader.rs index 7df727e..62e6586 100644 --- a/src/gpu/shader.rs +++ b/src/gpu/shader.rs @@ -456,31 +456,42 @@ impl UiShader { /// Map pixel coordinates (0,0)-(width,height) /// to NDC (-1,-1)-(1,1) pub fn ortho_projection(width: f32, height: f32) -> [f32; 16] { - let l = 0.0_f32; - let r = width; - let t = 0.0_f32; // top - let b = height; // bottom - let n = -1.0_f32; - let f = 1.0_f32; - - // Column-major (OpenGL convention) + ortho_projection_rotated(width, height, 0) +} + +/// Orthographic projection with display rotation applied. +/// +/// Renderers draw in *logical* coordinates spanning (0,0)-(logical_w,logical_h). +/// `rotation` (0/90/180/270 clockwise) twists the resulting NDC so that the +/// content lands correctly on the underlying *physical* framebuffer. +/// +/// At rotation = 0 the matrix matches the original `ortho_projection`. +/// For 90/270, callers should pass the *logical* (post-swap) width/height — +/// `DisplayConfig::logical_width()` / `logical_height()` are the canonical source. +pub fn ortho_projection_rotated(logical_w: f32, logical_h: f32, rotation: u32) -> [f32; 16] { + // Column-major (OpenGL convention). + // For rotation r, NDC_x and NDC_y as linear functions of (x, y) in + // logical pixel space. z/w identity columns are shared. + // + // 0° : NDC_x = (2/lw)·x - 1, NDC_y = -(2/lh)·y + 1 + // 90° : NDC_x = -(2/lh)·y + 1, NDC_y = -(2/lw)·x + 1 + // 180°: NDC_x = -(2/lw)·x + 1, NDC_y = (2/lh)·y - 1 + // 270°: NDC_x = (2/lh)·y - 1, NDC_y = (2/lw)·x - 1 + let inv_lw = 2.0 / logical_w; + let inv_lh = 2.0 / logical_h; + + let (m0, m1, m4, m5, m12, m13) = match rotation { + 90 => (0.0, -inv_lw, -inv_lh, 0.0, 1.0, 1.0), + 180 => (-inv_lw, 0.0, 0.0, inv_lh, 1.0, -1.0), + 270 => (0.0, inv_lw, inv_lh, 0.0, -1.0, -1.0), + _ => (inv_lw, 0.0, 0.0, -inv_lh, -1.0, 1.0), + }; + [ - 2.0 / (r - l), - 0.0, - 0.0, - 0.0, - 0.0, - 2.0 / (t - b), - 0.0, - 0.0, - 0.0, - 0.0, - -2.0 / (f - n), - 0.0, - -(r + l) / (r - l), - -(t + b) / (t - b), - -(f + n) / (f - n), - 1.0, + m0, m1, 0.0, 0.0, // column 0 + m4, m5, 0.0, 0.0, // column 1 + 0.0, 0.0, -1.0, 0.0, // column 2 (z) + m12, m13, 0.0, 1.0, // column 3 (translation) ] } @@ -542,3 +553,110 @@ fn compile_shader(gl: &glow::Context, shader_type: u32, source: &str) -> Result< Ok(shader) } } + +#[cfg(test)] +mod rotation_tests { + use super::ortho_projection_rotated; + use crate::drm::display::logical_to_physical_cursor; + use crate::input::evdev::physical_to_logical_point; + + /// Apply a column-major 4x4 matrix to a 2D point with z=0, w=1. + /// Returns (NDC_x, NDC_y). + fn apply(m: &[f32; 16], x: f32, y: f32) -> (f32, f32) { + // column-major: m[col * 4 + row] + let ndc_x = m[0] * x + m[4] * y + m[8] * 0.0 + m[12]; + let ndc_y = m[1] * x + m[5] * y + m[9] * 0.0 + m[13]; + (ndc_x, ndc_y) + } + + fn close(a: f32, b: f32) -> bool { + (a - b).abs() < 1e-4 + } + + #[test] + fn rotation_0_top_left_to_minus_one_one() { + let m = ortho_projection_rotated(100.0, 50.0, 0); + let (x, y) = apply(&m, 0.0, 0.0); + assert!(close(x, -1.0) && close(y, 1.0), "got ({}, {})", x, y); + let (x, y) = apply(&m, 100.0, 50.0); + assert!(close(x, 1.0) && close(y, -1.0), "got ({}, {})", x, y); + } + + #[test] + fn rotation_90_top_left_to_physical_top_right() { + // Logical (0, 0) should land at physical top-right corner -> NDC (1, 1). + let m = ortho_projection_rotated(100.0, 50.0, 90); + let (x, y) = apply(&m, 0.0, 0.0); + assert!(close(x, 1.0) && close(y, 1.0), "got ({}, {})", x, y); + let (x, y) = apply(&m, 100.0, 50.0); + assert!(close(x, -1.0) && close(y, -1.0), "got ({}, {})", x, y); + } + + #[test] + fn rotation_180_top_left_to_physical_bottom_right() { + let m = ortho_projection_rotated(100.0, 50.0, 180); + let (x, y) = apply(&m, 0.0, 0.0); + assert!(close(x, 1.0) && close(y, -1.0), "got ({}, {})", x, y); + let (x, y) = apply(&m, 100.0, 50.0); + assert!(close(x, -1.0) && close(y, 1.0), "got ({}, {})", x, y); + } + + #[test] + fn rotation_270_top_left_to_physical_bottom_left() { + let m = ortho_projection_rotated(100.0, 50.0, 270); + let (x, y) = apply(&m, 0.0, 0.0); + assert!(close(x, -1.0) && close(y, -1.0), "got ({}, {})", x, y); + let (x, y) = apply(&m, 100.0, 50.0); + assert!(close(x, 1.0) && close(y, 1.0), "got ({}, {})", x, y); + } + + #[test] + fn rendered_pixels_pointer_input_and_hardware_cursor_agree() { + let (physical_w, physical_h) = (320_u32, 200_u32); + for rotation in [0, 90, 180, 270] { + let (logical_w, logical_h) = if rotation == 90 || rotation == 270 { + (physical_h, physical_w) + } else { + (physical_w, physical_h) + }; + let matrix = ortho_projection_rotated(logical_w as f32, logical_h as f32, rotation); + for (x, y) in [ + (0.0, 0.0), + ((logical_w - 1) as f64, (logical_h - 1) as f64), + ((logical_w / 3) as f64, (logical_h / 4) as f64), + ] { + let (cursor_x, cursor_y) = + logical_to_physical_cursor(x, y, physical_w, physical_h, rotation); + let (ndc_x, ndc_y) = apply(&matrix, (x + 0.5) as f32, (y + 0.5) as f32); + let drawn_x = (ndc_x as f64 + 1.0) * physical_w as f64 / 2.0; + let drawn_y = (1.0 - ndc_y as f64) * physical_h as f64 / 2.0; + assert!((drawn_x - cursor_x - 0.5).abs() < 0.001); + assert!((drawn_y - cursor_y - 0.5).abs() < 0.001); + let (input_x, input_y) = physical_to_logical_point( + cursor_x, + cursor_y, + physical_w as f64, + physical_h as f64, + rotation, + ); + assert_eq!((input_x, input_y), (x, y)); + } + } + } + + #[test] + fn absolute_pointer_stays_inside_rotated_screen() { + for rotation in [0, 90, 180, 270] { + let (w, h) = if matches!(rotation, 90 | 270) { + (200.0, 320.0) + } else { + (320.0, 200.0) + }; + for (px, py) in [(-10.0, -10.0), (320.0, 200.0), (330.0, 210.0)] { + let (x, y) = physical_to_logical_point(px, py, 320.0, 200.0, rotation); + assert!((0.0..w).contains(&x), "rotation={rotation}, x={x}"); + assert!((0.0..h).contains(&y), "rotation={rotation}, y={y}"); + } + } + } +} diff --git a/src/gpu/ui_renderer.rs b/src/gpu/ui_renderer.rs index 7d8ba9b..746b2ac 100644 --- a/src/gpu/ui_renderer.rs +++ b/src/gpu/ui_renderer.rs @@ -26,6 +26,7 @@ pub struct UiRenderer { vertices: Vec, /// Current number of rectangles in buffer rect_count: usize, + rotation: u32, } impl UiRenderer { @@ -102,10 +103,15 @@ impl UiRenderer { ebo, vertices: Vec::with_capacity(MAX_RECTS * VERTICES_PER_QUAD * VERTEX_FLOATS), rect_count: 0, + rotation: 0, }) } } + pub fn set_rotation(&mut self, rotation: u32) { + self.rotation = rotation; + } + /// Clear draw buffer pub fn begin(&mut self) { self.vertices.clear(); @@ -186,8 +192,9 @@ impl UiRenderer { // Bind shader self.shader.bind(gl); - // Set orthographic projection matrix - let projection = shader::ortho_projection(width as f32, height as f32); + // Set orthographic projection matrix (rotation-aware) + let projection = + shader::ortho_projection_rotated(width as f32, height as f32, self.rotation); self.shader.set_projection(gl, &projection); // Bind VAO and upload vertex data diff --git a/src/input/evdev.rs b/src/input/evdev.rs index a420df7..aa6b41c 100644 --- a/src/input/evdev.rs +++ b/src/input/evdev.rs @@ -229,6 +229,11 @@ pub struct EvdevKeyboard { gesture_pinch_scale: f64, /// Mouse/touchpad configuration, retained to apply to hotplugged devices mouse_config: MouseConfig, + /// Display rotation in clockwise degrees (0/90/180/270). + /// `mouse_x`/`mouse_y` are kept in *physical* framebuffer coordinates + /// (libinput delivers events that way), and are transformed to *logical* + /// coordinates at the moment events are emitted. + rotation: u32, } impl EvdevKeyboard { @@ -344,6 +349,7 @@ impl EvdevKeyboard { gesture_swipe_fingers: 0, gesture_pinch_scale: 1.0, mouse_config: mouse_config.clone(), + rotation: 0, }) } @@ -456,6 +462,7 @@ impl EvdevKeyboard { gesture_swipe_dy: 0.0, gesture_swipe_fingers: 0, gesture_pinch_scale: 1.0, + rotation: 0, }) } @@ -465,6 +472,37 @@ impl EvdevKeyboard { self.fd } + /// Update the display rotation (0/90/180/270 clockwise). + /// Affects how internal physical mouse coords are transformed before they + /// are exposed to consumers via `MouseEvent`. + pub fn set_rotation(&mut self, rotation: u32) { + self.rotation = rotation; + } + + /// Transform a physical (framebuffer-space) point to logical + /// (application-space) coordinates according to `self.rotation`. + /// + /// Inverse of the rotation applied by the projection matrix in + /// `gpu::shader::ortho_projection_rotated`, so a click at physical (px, py) + /// lands on the same logical cell that the renderer drew there. + #[inline] + fn physical_to_logical(&self, px: f64, py: f64) -> (f64, f64) { + physical_to_logical_point( + px, + py, + self.screen_width, + self.screen_height, + self.rotation, + ) + } + + /// Convenience wrapper that returns the current mouse position in logical + /// coordinates. + #[inline] + fn logical_mouse(&self) -> (f64, f64) { + self.physical_to_logical(self.mouse_x, self.mouse_y) + } + /// Process events and return bytes to forward to PTY #[allow(dead_code)] pub fn process_events(&mut self) -> Vec { @@ -569,7 +607,7 @@ impl EvdevKeyboard { KeyState::Released => KeyAction::Release, }; let raw_event = RawKeyEvent { - keysym: sym.raw(), + keysym: normalize_keypad_navigation(sym.raw()), keycode: evdev_code, xkb_state: mods, utf8, @@ -613,10 +651,8 @@ impl EvdevKeyboard { // Clamp to screen bounds self.mouse_x = self.mouse_x.clamp(0.0, self.screen_width - 1.0); self.mouse_y = self.mouse_y.clamp(0.0, self.screen_height - 1.0); - mouse_events.push(MouseEvent::Move { - x: self.mouse_x, - y: self.mouse_y, - }); + let (x, y) = self.logical_mouse(); + mouse_events.push(MouseEvent::Move { x, y }); } PointerEvent::MotionAbsolute(m) => { // Absolute coordinates (touchpad, tablet, etc.) @@ -624,26 +660,25 @@ impl EvdevKeyboard { m.absolute_x_transformed(self.screen_width as u32) as f64; self.mouse_y = m.absolute_y_transformed(self.screen_height as u32) as f64; - mouse_events.push(MouseEvent::Move { - x: self.mouse_x, - y: self.mouse_y, - }); + let (x, y) = self.logical_mouse(); + mouse_events.push(MouseEvent::Move { x, y }); } PointerEvent::Button(b) => { let button = b.button(); + let (x, y) = self.logical_mouse(); match b.button_state() { ButtonState::Pressed => { mouse_events.push(MouseEvent::ButtonPress { button, - x: self.mouse_x, - y: self.mouse_y, + x, + y, }); } ButtonState::Released => { mouse_events.push(MouseEvent::ButtonRelease { button, - x: self.mouse_x, - y: self.mouse_y, + x, + y, }); } } @@ -766,10 +801,11 @@ impl EvdevKeyboard { // Emit accumulated scroll as event (even small values for smoothness) if self.scroll_accum.abs() >= 0.1 { + let (x, y) = self.logical_mouse(); mouse_events.push(MouseEvent::Scroll { delta: self.scroll_accum, - x: self.mouse_x, - y: self.mouse_y, + x, + y, }); self.scroll_accum = 0.0; } @@ -798,7 +834,7 @@ impl EvdevKeyboard { /// Get current mouse position #[allow(dead_code)] pub fn mouse_position(&self) -> (f64, f64) { - (self.mouse_x, self.mouse_y) + self.logical_mouse() } /// Suspend libinput (call when VT switches away) @@ -825,6 +861,25 @@ impl EvdevKeyboard { } } +pub(crate) fn physical_to_logical_point( + px: f64, + py: f64, + width: f64, + height: f64, + rotation: u32, +) -> (f64, f64) { + // Absolute devices can report the outer edge or coordinates outside the + // active area. Clamp before rotation so the inverse never becomes negative. + let px = px.clamp(0.0, (width - 1.0).max(0.0)); + let py = py.clamp(0.0, (height - 1.0).max(0.0)); + match rotation { + 90 => (py, width - 1.0 - px), + 180 => (width - 1.0 - px, height - 1.0 - py), + 270 => (height - 1.0 - py, px), + _ => (px, py), + } +} + // evdev keycodes for F1-F12 const KEY_F1: u32 = 59; const KEY_F2: u32 = 60; @@ -865,9 +920,27 @@ pub fn check_vt_switch(event: &RawKeyEvent) -> Option { } } +/// NumLock-off keypad keys have distinct XKB keysyms, but their navigation +/// behavior should match the dedicated keys in bcon and in terminal apps. +fn normalize_keypad_navigation(raw: u32) -> u32 { + match raw { + keysyms::KEY_KP_Up => keysyms::KEY_Up, + keysyms::KEY_KP_Down => keysyms::KEY_Down, + keysyms::KEY_KP_Left => keysyms::KEY_Left, + keysyms::KEY_KP_Right => keysyms::KEY_Right, + keysyms::KEY_KP_Home => keysyms::KEY_Home, + keysyms::KEY_KP_End => keysyms::KEY_End, + keysyms::KEY_KP_Prior => keysyms::KEY_Page_Up, + keysyms::KEY_KP_Next => keysyms::KEY_Page_Down, + keysyms::KEY_KP_Insert => keysyms::KEY_Insert, + keysyms::KEY_KP_Delete => keysyms::KEY_Delete, + _ => raw, + } +} + /// Convert keysym to terminal escape sequence pub fn keysym_to_bytes(sym: xkb::Keysym, utf8: &str) -> Vec { - let raw = sym.raw(); + let raw = normalize_keypad_navigation(sym.raw()); match raw { // Control keys _ if raw == keysyms::KEY_Return || raw == keysyms::KEY_KP_Enter => vec![b'\r'], @@ -997,7 +1070,8 @@ pub fn keysym_to_bytes_with_mods( shift: bool, config: &KeyboardConfig, ) -> Vec { - let raw = sym.raw(); + let raw = normalize_keypad_navigation(sym.raw()); + let sym = xkb::Keysym::new(raw); let has_mods = ctrl || alt || shift; let mod_code = modifier_code(ctrl, alt, shift); @@ -1308,3 +1382,54 @@ fn encode_kitty_keyboard( // Not handled by Kitty protocol - fall back to legacy encoding None } + +#[cfg(test)] +mod keypad_navigation_tests { + use super::*; + + #[test] + fn keypad_navigation_matches_dedicated_keys_in_terminal_modes() { + let pairs = [ + (keysyms::KEY_KP_Up, keysyms::KEY_Up), + (keysyms::KEY_KP_Down, keysyms::KEY_Down), + (keysyms::KEY_KP_Left, keysyms::KEY_Left), + (keysyms::KEY_KP_Right, keysyms::KEY_Right), + (keysyms::KEY_KP_Home, keysyms::KEY_Home), + (keysyms::KEY_KP_End, keysyms::KEY_End), + (keysyms::KEY_KP_Prior, keysyms::KEY_Page_Up), + (keysyms::KEY_KP_Next, keysyms::KEY_Page_Down), + (keysyms::KEY_KP_Insert, keysyms::KEY_Insert), + (keysyms::KEY_KP_Delete, keysyms::KEY_Delete), + ]; + for config in [ + KeyboardConfig::default(), + KeyboardConfig { + application_cursor_keys: true, + ..KeyboardConfig::default() + }, + KeyboardConfig { + kitty_flags: 8, + ..KeyboardConfig::default() + }, + ] { + for (keypad, dedicated) in pairs { + let keypad = xkb::Keysym::new(keypad); + let dedicated = xkb::Keysym::new(dedicated); + assert_eq!( + keysym_to_bytes_with_mods(keypad, "", false, false, false, &config), + keysym_to_bytes_with_mods(dedicated, "", false, false, false, &config), + "keypad key {:?} differs with config {:?}", + keypad, + config + ); + } + } + } + + #[test] + fn keypad_digits_keep_their_numeric_output() { + let key = xkb::Keysym::new(keysyms::KEY_KP_9); + assert_eq!(normalize_keypad_navigation(key.raw()), key.raw()); + assert_eq!(keysym_to_bytes(key, "9"), b"9"); + } +} diff --git a/src/main.rs b/src/main.rs index 084a7fe..e86d3c1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1577,12 +1577,14 @@ Make sure seatd/logind is running and you're on an active VT." let mut display_config = drm::DisplayConfig::detect_with_preference(&drm_device, cfg.display.prefer_external) .context("Failed to detect display configuration")?; + display_config.rotation = cfg.display.normalized_rotation(); info!( - "Display: {}x{} (external: {})", + "Display: {}x{} (external: {}, rotation: {}°)", display_config.width, display_config.height, - display_config.is_external(&drm_device) + display_config.is_external(&drm_device), + display_config.rotation, ); // Initialize DRM hotplug monitor (Linux only) @@ -1740,7 +1742,11 @@ Make sure seatd/logind is running and you're on an active VT." // LCD filter settings (from config) let lcd_filter = font::freetype::LcdFilterMode::from_str(&cfg.font.lcd_filter); let lcd_subpixel = font::freetype::LcdSubpixel::from_str(&cfg.font.lcd_subpixel); - let lcd_mode = lcd_subpixel.to_lcd_mode(); + let lcd_mode = if cfg.font.render_mode.eq_ignore_ascii_case("grayscale") { + font::freetype::LcdMode::Grayscale + } else { + lcd_subpixel.to_lcd_mode() + }; let subpixel_bgr = lcd_subpixel.is_bgr(); let hinting_mode = font::freetype::HintingMode::from_str(&cfg.font.lcd_hinting); @@ -1847,6 +1853,16 @@ Make sure seatd/logind is running and you're on an active VT." let mut curly_renderer = gpu::CurlyRenderer::new(gl).context("Failed to initialize curly renderer")?; + // Propagate display rotation to all renderers (used by their projection matrix). + { + let rot = display_config.rotation; + text_renderer.set_rotation(rot); + ui_renderer.set_rotation(rot); + image_renderer.set_rotation(rot); + emoji_renderer.set_rotation(rot); + curly_renderer.set_rotation(rot); + } + // Create FBO for cached rendering (enables partial updates) let fbo = gpu::Fbo::new(gl, display_config.width, display_config.height) .context("Failed to initialize FBO")?; @@ -1856,8 +1872,11 @@ Make sure seatd/logind is running and you're on an active VT." // Phase 3: Terminal initialization info!("Phase 3: terminal/PTY..."); - let screen_w = display_config.width; - let screen_h = display_config.height; + // Logical screen dimensions used by the renderer/grid/layout/input layers. + // When `display.rotation` is 90/270, these are the physical dims swapped. + // The framebuffer, DRM mode, and GL viewport keep the *physical* values. + let screen_w = display_config.logical_width(); + let screen_h = display_config.logical_height(); // Cell dimensions from font metrics (always positive, but guard against edge cases) let mut cell_w = glyph_atlas.cell_width.max(1.0); let mut cell_h = glyph_atlas.cell_height.max(1.0); @@ -2042,6 +2061,11 @@ Make sure seatd/logind is running and you're on an active VT." anyhow::bail!("No input method available (both TTY keyboard and evdev failed)"); } + // Propagate display rotation to evdev so mouse coords land in logical space. + if let Some(ref mut kb) = evdev_keyboard { + kb.set_rotation(display_config.rotation); + } + info!("Phase 4 initialization complete"); info!("Phase 4 complete"); @@ -2416,7 +2440,8 @@ Make sure seatd/logind is running and you're on an active VT." // Restore hardware cursor after VT switch if let Some(ref hc) = hw_cursor { hc.show(); - hc.move_to(mouse_x, mouse_y); + let (x, y) = display_config.cursor_position(mouse_x, mouse_y); + hc.move_to(x, y); } } } @@ -2560,6 +2585,15 @@ Make sure seatd/logind is running and you're on an active VT." term.notifications_enabled = new_cfg.notifications.enabled; term.allow_kitty_remote = new_cfg.security.allow_kitty_remote; + // Display rotation is captured at startup; changing it requires a restart. + if new_cfg.display.normalized_rotation() != display_config.rotation { + log::warn!( + "display.rotation changed ({}° -> {}°). Restart bcon to apply.", + display_config.rotation, + new_cfg.display.normalized_rotation() + ); + } + // Update IME disable app list cfg = new_cfg; @@ -2595,7 +2629,11 @@ Make sure seatd/logind is running and you're on an active VT." &drm_device, cfg.display.prefer_external, ) { - Ok(new_config) => { + Ok(mut new_config) => { + // Rotation is fixed for this process because every + // renderer and the input transform were configured + // at startup. + new_config.rotation = display_config.rotation; if new_config.connector_handle != display_config.connector_handle { @@ -3330,7 +3368,8 @@ Make sure seatd/logind is running and you're on an active VT." mouse_x = *x; mouse_y = *y; if let Some(ref hc) = hw_cursor { - hc.move_to(mouse_x, mouse_y); + let (x, y) = display_config.cursor_position(mouse_x, mouse_y); + hc.move_to(x, y); } else { needs_redraw = true; } @@ -3502,7 +3541,8 @@ Make sure seatd/logind is running and you're on an active VT." mouse_y = *y; // Hardware cursor: update position directly (no frame render needed) if let Some(ref hc) = hw_cursor { - hc.move_to(mouse_x, mouse_y); + let (x, y) = display_config.cursor_position(mouse_x, mouse_y); + hc.move_to(x, y); } else { needs_redraw = true; } @@ -4004,7 +4044,8 @@ Make sure seatd/logind is running and you're on an active VT." for row in 0..term.grid.rows() { if term.grid.is_row_dirty(row) { fbo.clear_rows( - gl, row, row, cell_h, margin_y, bg_color.0, bg_color.1, bg_color.2, + gl, row, row, cell_h, margin_y, display_config.rotation, + bg_color.0, bg_color.1, bg_color.2, ); } } @@ -6247,8 +6288,8 @@ Make sure seatd/logind is running and you're on an active VT." let user_home = term.user_home_dir(); if let Err(e) = save_screenshot( gl, - screen_w, - screen_h, + display_config.width, + display_config.height, &cfg.paths.screenshot_dir, user_home.as_deref(), ) { @@ -6273,7 +6314,7 @@ Make sure seatd/logind is running and you're on an active VT." // Unbind FBO and blit to screen fbo.unbind(gl); - fbo.blit_to_screen(gl, screen_w, screen_h); + fbo.blit_to_screen(gl, display_config.width, display_config.height); // === Tab bar (drawn directly to screen, outside FBO) === // Drawn every frame to avoid FBO caching artifacts @@ -6765,8 +6806,27 @@ Make sure seatd/logind is running and you're on an active VT." let sy = cursor_y.floor() as i32; let sw = cell_w.ceil() as i32; let sh = cell_h.ceil() as i32; - let flipped_y = screen_h as i32 - sy - sh; - gl.scissor(sx, flipped_y, sw, sh); + match display_config.rotation { + 90 => gl.scissor( + display_config.width as i32 - sy - sh, + display_config.height as i32 - sx - sw, + sh, + sw, + ), + 180 => gl.scissor( + display_config.width as i32 - sx - sw, + sy, + sw, + sh, + ), + 270 => gl.scissor(sy, sx, sh, sw), + _ => gl.scissor( + sx, + display_config.height as i32 - sy - sh, + sw, + sh, + ), + } } text_renderer.flush(gl, &glyph_atlas, screen_w, screen_h); unsafe { diff --git a/src/terminal/kitty.rs b/src/terminal/kitty.rs index c3ed43f..b11b165 100644 --- a/src/terminal/kitty.rs +++ b/src/terminal/kitty.rs @@ -361,7 +361,10 @@ impl KittyDecoder { self.parse_params(params_str); self.first_chunk = false; } else { - // For subsequent chunks, only update m parameter + // The continuation flag belongs to this chunk. An omitted m on + // the final chunk means m=0, even when preceding chunks had m=1. + self.params.more = false; + // For subsequent chunks, only update m parameter. for part in params_str.split(',') { if let Some((key, value)) = part.split_once('=') { if key == "m" { @@ -1090,6 +1093,21 @@ mod tests { } } + #[test] + fn final_chunk_without_m_completes_kitten_transmission() { + let rgba = [0x10, 0x20, 0x30, 0xff]; + let mut decoder = KittyDecoder::new(); + let first = format!("a=T,f=32,s=1,v=1,m=1;{}", b64_encode(&rgba[..2])); + assert!(!decoder.process(first.as_bytes()).0); + let last = format!("a=T;{}", b64_encode(&rgba[2..])); + assert!(decoder.process(last.as_bytes()).0); + + match decoder.finish(1, false).expect("decode") { + KittyDecodeResult::Image(image) => assert_eq!(image.data, rgba), + _ => panic!("expected Image result"), + } + } + /// Reproduces the mpv v0.40.0 bug from issue #7: RGB data is slightly /// short of expected w*h*3 (720 bytes / 240 pixels missing). bcon must /// pad with zeros instead of rejecting the frame. From f3da1160c9d3ee565a0841baaa153620067e45f5 Mon Sep 17 00:00:00 2001 From: Hironobu Sano <7529745+sanohiro@users.noreply.github.com> Date: Sat, 26 Sep 2026 10:19:52 +0900 Subject: [PATCH 2/4] test: add rendering, rotation, and keyboard smoke checks --- tests/README.md | 57 +++++++++ tests/input-stress-uinput.c | 194 +++++++++++++++++++++++++++++ tests/keypad-uinput-check.c | 164 +++++++++++++++++++++++++ tests/rootless-stress.py | 216 +++++++++++++++++++++++++++++++++ tests/rotation-mouse-check.py | 83 +++++++++++++ tests/visual-smoke.sh | 221 ++++++++++++++++++++++++++++++++++ 6 files changed, 935 insertions(+) create mode 100644 tests/README.md create mode 100644 tests/input-stress-uinput.c create mode 100644 tests/keypad-uinput-check.c create mode 100644 tests/rootless-stress.py create mode 100644 tests/rotation-mouse-check.py create mode 100644 tests/visual-smoke.sh diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..c68da00 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,57 @@ +# Interactive checks + +Run these inside bcon on a text VT, including a session started through +`bcon@tty2.service`. A terminal window or SSH session alone cannot verify bcon's +rendering or local keyboard handling. Stop a test before switching VTs when it +injects virtual keyboard events. + +## Rendering smoke check + +```bash +bash tests/visual-smoke.sh +``` + +Requires Bash and Python 3. `img2sixel` is optional; its absence records a skip. +Ten pages cover text/emoji, colors/attributes, box drawing and the right edge, +scrolling, Sixel, Kitty chunked/file transfers, partial updates, alternate screen +restoration, and cursor/VT restoration. Enter records OK, `n` records NG and a +note, `s` skips, and `q` stops. Results are saved to `~/bcon-visual-*.log`. +Screenshots record static results; watch the animations and actually switch +away/back on the final page to check flicker and VT restoration. + +## Rotation and pointer coordinates + +Set `[display] rotation` to each of `0`, `90`, `180`, and `270`, restart bcon, +and run the rendering check followed by: + +```bash +python3 tests/rotation-mouse-check.py +``` + +Click the five highlighted targets. The visible pointer and reported click +should agree, including near the edges. `q` or Ctrl+C stops the check. + +## Keypad navigation + +```bash +cc -O2 -Wall -Wextra -o /tmp/bcon-keypad-check tests/keypad-uinput-check.c +sudo /tmp/bcon-keypad-check +``` + +Requires Linux `/dev/uinput` and libinput device hotplug. It creates a temporary +virtual keypad and checks the resulting bytes in the current bcon PTY. Run at +the shell prompt, with no other keys held; it expects normal cursor-key mode. + +## Bounded stress checks + +```bash +python3 tests/rootless-stress.py 20 +cc -O2 -Wall -Wextra -o /tmp/bcon-input-stress tests/input-stress-uinput.c +sudo /tmp/bcon-input-stress 10 +``` + +Run the commands separately. Durations are in minutes. Despite its filename, +the rendering stress script also works in systemd-launched bcon. It writes +`~/bcon-stress-*.log`; virtual-keyboard stress writes `/var/tmp/bcon-input-stress-*`. +Both accept `q` or Ctrl+C to stop. A completed stress run without a reproduction +does not by itself prove an intermittent issue is fixed. diff --git a/tests/input-stress-uinput.c b/tests/input-stress-uinput.c new file mode 100644 index 0000000..ff7a0c6 --- /dev/null +++ b/tests/input-stress-uinput.c @@ -0,0 +1,194 @@ +// Bounded end-to-end keyboard stress test. Run inside bcon via sudo. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const struct { + int code; + const char *name; + const char *expect; +} keys[] = { + {KEY_A, "a", "a"}, {KEY_Z, "z", "z"}, {KEY_SPACE, "space", " "}, + {KEY_UP, "Up", "\033[A"}, {KEY_DOWN, "Down", "\033[B"}, + {KEY_LEFT, "Left", "\033[D"}, {KEY_RIGHT, "Right", "\033[C"}, + {KEY_KP8, "KP8/Up", "\033[A"}, {KEY_KP2, "KP2/Down", "\033[B"}, + {KEY_KP4, "KP4/Left", "\033[D"}, {KEY_KP6, "KP6/Right", "\033[C"}, + {KEY_KP7, "KP7/Home", "\033[H"}, {KEY_KP1, "KP1/End", "\033[F"}, + {KEY_KP9, "KP9/PageUp", "\033[5~"}, {KEY_KP3, "KP3/PageDown", "\033[6~"}, + {KEY_KP0, "KP0/Insert", "\033[2~"}, {KEY_KPDOT, "KP./Delete", "\033[3~"}, +}; + +static volatile sig_atomic_t stop_requested; + +static void on_signal(int number) { (void)number; stop_requested = 1; } + +static double seconds_now(void) { + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + return now.tv_sec + now.tv_nsec / 1000000000.0; +} + +static int emit(int fd, unsigned short type, unsigned short code, int value) { + struct input_event event = {.type = type, .code = code, .value = value}; + return write(fd, &event, sizeof(event)) == sizeof(event) ? 0 : -1; +} + +static int press(int fd, int code) { + if (emit(fd, EV_KEY, code, 1) || emit(fd, EV_SYN, SYN_REPORT, 0)) return -1; + usleep(25000); + if (emit(fd, EV_KEY, code, 0) || emit(fd, EV_SYN, SYN_REPORT, 0)) return -1; + return 0; +} + +static int receive(char *buffer, size_t size, int timeout_ms) { + int used = 0; + while (used + 1 < (int)size && !stop_requested) { + struct pollfd pfd = {.fd = STDIN_FILENO, .events = POLLIN}; + if (poll(&pfd, 1, timeout_ms) <= 0) break; + ssize_t count = read(STDIN_FILENO, buffer + used, size - used - 1); + if (count <= 0) break; + used += (int)count; + timeout_ms = 15; + } + buffer[used] = '\0'; + if (memchr(buffer, 'q', used) || memchr(buffer, 3, used)) stop_requested = 1; + return used; +} + +static void show_status(double elapsed, int minutes, unsigned long total, unsigned long errors, + const char *last_key) { + printf("\033[2J\033[HKeyboard stress: %.0f / %d seconds\r\n", elapsed, minutes * 60); + printf("Keys: %lu mismatches: %lu last: %s\r\n", total, errors, last_key); + printf("Sending letters, arrows and keypad keys. q or Ctrl+C: stop.\r\n\r\n"); + for (int row = 0; row < 10; ++row) { + for (int col = 0; col < 25; ++col) { + int red = (total + row * 11 + col * 7) % 256; + int blue = (total * 2 + row * 5 + col * 13) % 256; + printf("\033[48;2;%d;50;%dm ", red, blue); + } + printf("\033[0m\r\n"); + } + fflush(stdout); +} + +int main(int argc, char **argv) { + char *end = NULL; + long minutes = argc > 1 ? strtol(argv[1], &end, 10) : 10; + if ((argc > 1 && (!end || *end)) || minutes < 1 || minutes > 60) { + fprintf(stderr, "Usage: binputstress [1..60 minutes]\n"); + return 2; + } + int fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK); + if (fd < 0) { perror("/dev/uinput (sudo required)"); return 2; } + if (ioctl(fd, UI_SET_EVBIT, EV_KEY) < 0 || ioctl(fd, UI_SET_EVBIT, EV_SYN) < 0) { + perror("UI_SET_EVBIT"); close(fd); return 2; + } + for (size_t i = 0; i < sizeof(keys) / sizeof(keys[0]); ++i) { + if (ioctl(fd, UI_SET_KEYBIT, keys[i].code) < 0) { + perror("UI_SET_KEYBIT"); close(fd); return 2; + } + } + ioctl(fd, UI_SET_KEYBIT, KEY_NUMLOCK); + struct uinput_setup setup = {.id = {.bustype = BUS_USB, .vendor = 0x1234, .product = 0x5679}}; + snprintf(setup.name, sizeof(setup.name), "bcon temporary keyboard stress"); + if (ioctl(fd, UI_DEV_SETUP, &setup) < 0 || ioctl(fd, UI_DEV_CREATE) < 0) { + perror("UI_DEV_SETUP/CREATE"); close(fd); return 2; + } + char log_name[] = "/var/tmp/bcon-input-stress-XXXXXX"; + int log_fd = mkstemp(log_name); + if (log_fd >= 0) { + fchmod(log_fd, 0644); + dprintf(log_fd, "START duration=%ldm\n", minutes); + fsync(log_fd); + } + printf("Virtual keyboard ready. Log: %s\n", log_name); + fflush(stdout); + sleep(2); + + struct termios old, raw; + if (tcgetattr(STDIN_FILENO, &old) < 0) { + perror("tcgetattr"); ioctl(fd, UI_DEV_DESTROY); close(fd); return 2; + } + raw = old; + cfmakeraw(&raw); + tcsetattr(STDIN_FILENO, TCSANOW, &raw); + signal(SIGTERM, on_signal); + signal(SIGINT, on_signal); + printf("\033[?1049h\033[?25l"); + fflush(stdout); + char got[128]; + receive(got, sizeof(got), 10); + press(fd, KEY_KP8); + int length = receive(got, sizeof(got), 500); + bool changed_numlock = false; + if (length == 1 && got[0] == '8') { + press(fd, KEY_NUMLOCK); + changed_numlock = true; + receive(got, sizeof(got), 100); + press(fd, KEY_KP8); + length = receive(got, sizeof(got), 500); + } + unsigned long total = 0, errors = 0; + if (length != 3 || memcmp(got, "\033[A", 3) != 0) { + errors++; + stop_requested = 1; + if (log_fd >= 0) dprintf(log_fd, "ERROR virtual keyboard not reaching bcon\n"); + } + double start = seconds_now(); + const char *last_key = "ready"; + while (!stop_requested && seconds_now() - start < minutes * 60.0) { + size_t index = total % (sizeof(keys) / sizeof(keys[0])); + receive(got, sizeof(got), 1); + if (press(fd, keys[index].code) < 0) { + errors++; + break; + } + length = receive(got, sizeof(got), 500); + if (stop_requested) break; + total++; + last_key = keys[index].name; + size_t expected = strlen(keys[index].expect); + if ((size_t)length != expected || memcmp(got, keys[index].expect, expected) != 0) { + errors++; + if (log_fd >= 0) { + dprintf(log_fd, "MISMATCH key=%s length=%d bytes=", last_key, length); + for (int i = 0; i < length; ++i) dprintf(log_fd, "%02X", (unsigned char)got[i]); + dprintf(log_fd, "\n"); + } + } + if (total % 50 == 0) { + show_status(seconds_now() - start, (int)minutes, total, errors, last_key); + if (log_fd >= 0) { + dprintf(log_fd, "PROGRESS elapsed=%.1fs keys=%lu errors=%lu\n", + seconds_now() - start, total, errors); + fsync(log_fd); + } + } + } + double elapsed = seconds_now() - start; + if (changed_numlock) press(fd, KEY_NUMLOCK); + printf("\033[0m\033[?25h\033[?1049l"); + fflush(stdout); + tcsetattr(STDIN_FILENO, TCSADRAIN, &old); + ioctl(fd, UI_DEV_DESTROY); + close(fd); + if (log_fd >= 0) { + dprintf(log_fd, "%s elapsed=%.1fs keys=%lu errors=%lu\n", + stop_requested ? "STOPPED" : "COMPLETE", elapsed, total, errors); + fsync(log_fd); + close(log_fd); + } + printf("Keyboard stress: %.1fs, %lu keys, %lu mismatches. Log: %s\n", + elapsed, total, errors, log_name); + return errors ? 1 : 0; +} diff --git a/tests/keypad-uinput-check.c b/tests/keypad-uinput-check.c new file mode 100644 index 0000000..15e1e40 --- /dev/null +++ b/tests/keypad-uinput-check.c @@ -0,0 +1,164 @@ +// Inject a temporary virtual keypad and verify bcon's PTY key sequences. +// Build: cc -O2 -Wall -Wextra -o /tmp/bcon-keypad-check tests/keypad-uinput-check.c +// Run inside bcon: sudo /tmp/bcon-keypad-check +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const struct { + int code; + const char *name; + const char *expected; +} cases[] = { + {KEY_KP8, "KP8 / Up", "\033[A"}, + {KEY_KP2, "KP2 / Down", "\033[B"}, + {KEY_KP6, "KP6 / Right", "\033[C"}, + {KEY_KP4, "KP4 / Left", "\033[D"}, + {KEY_KP7, "KP7 / Home", "\033[H"}, + {KEY_KP1, "KP1 / End", "\033[F"}, + {KEY_KP9, "KP9 / PageUp", "\033[5~"}, + {KEY_KP3, "KP3 / PageDown", "\033[6~"}, + {KEY_KP0, "KP0 / Insert", "\033[2~"}, + {KEY_KPDOT, "KP. / Delete", "\033[3~"}, +}; + +static int send_event(int fd, unsigned short type, unsigned short code, int value) { + struct input_event event = {.type = type, .code = code, .value = value}; + return write(fd, &event, sizeof(event)) == sizeof(event) ? 0 : -1; +} + +static int send_key(int fd, int code) { + if (send_event(fd, EV_KEY, code, 1) || send_event(fd, EV_SYN, SYN_REPORT, 0)) return -1; + usleep(30000); + if (send_event(fd, EV_KEY, code, 0) || send_event(fd, EV_SYN, SYN_REPORT, 0)) return -1; + return 0; +} + +static int collect(char *out, size_t capacity, int timeout_ms) { + size_t used = 0; + while (used + 1 < capacity) { + struct pollfd pfd = {.fd = STDIN_FILENO, .events = POLLIN}; + int ready = poll(&pfd, 1, timeout_ms); + if (ready <= 0) break; + ssize_t count = read(STDIN_FILENO, out + used, capacity - used - 1); + if (count <= 0) break; + used += (size_t)count; + timeout_ms = 40; + } + out[used] = '\0'; + return (int)used; +} + +static void show_bytes(const char *bytes, int length) { + for (int i = 0; i < length; ++i) printf(" %02X", (unsigned char)bytes[i]); +} + +int main(void) { + int fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK); + if (fd < 0) { + perror("open /dev/uinput (sudo required)"); + return 2; + } + int keys[] = {KEY_A, KEY_Z, KEY_SPACE, KEY_ENTER, KEY_NUMLOCK, + KEY_KP0, KEY_KP1, KEY_KP2, KEY_KP3, KEY_KP4, KEY_KP5, + KEY_KP6, KEY_KP7, KEY_KP8, KEY_KP9, KEY_KPDOT}; + if (ioctl(fd, UI_SET_EVBIT, EV_KEY) < 0 || ioctl(fd, UI_SET_EVBIT, EV_SYN) < 0) { + perror("UI_SET_EVBIT"); + close(fd); + return 2; + } + for (size_t i = 0; i < sizeof(keys) / sizeof(keys[0]); ++i) { + if (ioctl(fd, UI_SET_KEYBIT, keys[i]) < 0) { + perror("UI_SET_KEYBIT"); + close(fd); + return 2; + } + } + struct uinput_setup setup = {.id = {.bustype = BUS_USB, .vendor = 0x1234, .product = 0x5678}}; + snprintf(setup.name, sizeof(setup.name), "bcon temporary keypad test"); + if (ioctl(fd, UI_DEV_SETUP, &setup) < 0 || ioctl(fd, UI_DEV_CREATE) < 0) { + perror("UI_DEV_SETUP/CREATE"); + close(fd); + return 2; + } + printf("Virtual keypad ready; waiting for libinput...\r\n"); + fflush(stdout); + sleep(2); + + struct termios old, raw; + if (tcgetattr(STDIN_FILENO, &old) < 0) { + perror("tcgetattr"); + ioctl(fd, UI_DEV_DESTROY); + close(fd); + return 2; + } + raw = old; + cfmakeraw(&raw); + tcsetattr(STDIN_FILENO, TCSANOW, &raw); + char received[128]; + collect(received, sizeof(received), 10); + + // A fresh XKB state starts with NumLock off. Toggle once if it was on. + send_key(fd, KEY_KP8); + int length = collect(received, sizeof(received), 600); + bool initially_numlock_on = length == 1 && received[0] == '8'; + if (initially_numlock_on) { + send_key(fd, KEY_NUMLOCK); + collect(received, sizeof(received), 100); + send_key(fd, KEY_KP8); + length = collect(received, sizeof(received), 600); + } + int passed = 0; + int failed = 0; + if (length == 3 && memcmp(received, "\033[A", 3) == 0) { + printf("PASS KP8 / Up (NumLock off)\r\n"); + passed++; + } else { + printf("FAIL KP8 / Up: got"); + show_bytes(received, length); + printf("\r\n"); + failed++; + } + for (size_t i = 1; i < sizeof(cases) / sizeof(cases[0]); ++i) { + collect(received, sizeof(received), 10); + send_key(fd, cases[i].code); + length = collect(received, sizeof(received), 600); + size_t expected_length = strlen(cases[i].expected); + if ((size_t)length == expected_length && memcmp(received, cases[i].expected, expected_length) == 0) { + printf("PASS %s\r\n", cases[i].name); + passed++; + } else { + printf("FAIL %s: got", cases[i].name); + show_bytes(received, length); + printf("\r\n"); + failed++; + } + fflush(stdout); + } + send_key(fd, KEY_NUMLOCK); + collect(received, sizeof(received), 100); + send_key(fd, KEY_KP8); + length = collect(received, sizeof(received), 600); + if (length == 1 && received[0] == '8') { + printf("PASS KP8 / digit (NumLock on)\r\n"); + passed++; + } else { + printf("FAIL KP8 / digit: got"); + show_bytes(received, length); + printf("\r\n"); + failed++; + } + if (!initially_numlock_on) send_key(fd, KEY_NUMLOCK); // Restore the original state. + tcsetattr(STDIN_FILENO, TCSANOW, &old); + ioctl(fd, UI_DEV_DESTROY); + close(fd); + printf("Result: %d passed, %d failed\n", passed, failed); + return failed ? 1 : 0; +} diff --git a/tests/rootless-stress.py b/tests/rootless-stress.py new file mode 100644 index 0000000..28c9c23 --- /dev/null +++ b/tests/rootless-stress.py @@ -0,0 +1,216 @@ +#!/usr/bin/env python3 +"""Bounded interactive rendering stress test for bcon rootless sessions.""" + +import base64 +import datetime as dt +import os +import select +import shutil +import struct +import subprocess +import sys +import tempfile +import termios +import time +import tty +import zlib +from pathlib import Path + +PHASES = ("text", "scroll", "sixel", "kitty-inline", "kitty-file") +PHASE_SECONDS = 15 +FRAME_INTERVAL = {"text": 0.12, "scroll": 0.12, "sixel": 0.30, + "kitty-inline": 0.25, "kitty-file": 0.25} + + +def log(path, message): + line = f"{dt.datetime.now().astimezone().isoformat(timespec='seconds')} {message}\n" + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644) + try: + os.write(fd, line.encode()) + os.fsync(fd) + finally: + os.close(fd) + + +def watch(path, parent): + while True: + try: + os.kill(parent, 0) + except ProcessLookupError: + log(path, "WATCH parent exited") + return + log(path, "WATCH host heartbeat") + time.sleep(5) + + +def png_bytes(variant): + width = height = 192 + rows = [] + colors = ((240, 35, 35), (30, 215, 65), (40, 85, 245), (245, 215, 25)) + for y in range(height): + row = bytearray([0]) + for x in range(width): + quadrant = (y // 96) * 2 + x // 96 + r, g, b = colors[(quadrant + variant) % 4] + shade = (x * 2 + y + variant * 19) % 64 + row.extend((max(0, r - shade), max(0, g - shade), max(0, b - shade))) + rows.append(row) + + def chunk(kind, body): + data = kind + body + return struct.pack(">I", len(body)) + data + struct.pack(">I", zlib.crc32(data)) + + return (b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(b"".join(rows))) + + chunk(b"IEND", b"")) + + +def kitty_inline(data, image_id): + encoded = base64.b64encode(data) + chunks = [encoded[i:i + 4096] for i in range(0, len(encoded), 4096)] + packets = [] + for index, chunk in enumerate(chunks): + if index == 0: + params = f"a=T,t=d,f=100,i={image_id},q=2".encode() + else: + params = b"" + if index + 1 < len(chunks): + params += b",m=1" if params else b"m=1" + packets.append(b"\x1b_G" + params + b";" + chunk + b"\x1b\\") + return b"".join(packets) + + +def frame(phase, elapsed, duration, count, images, sixels, paths): + size = shutil.get_terminal_size() + width = max(25, size.columns) + height = max(12, size.lines) + title = (f"bcon rootless stress | {phase} | {elapsed:4.0f}/{duration:.0f}s " + f"| frame {count} | q/Ctrl+C: stop") + prefix = b"\x1b_Ga=d,d=A,q=2\x1b\\\x1b[2J\x1b[H" + output = bytearray(prefix + title[:width].encode() + b"\r\n") + output.extend(("=" * min(width, 72) + "\r\n").encode()) + variant = count % len(images) + + if phase in ("text", "scroll"): + lines = height - 4 if phase == "text" else height + 9 + for row in range(lines): + red = (count * 11 + row * 7) % 256 + green = (count * 5 + row * 13) % 256 + blue = (count * 3 + row * 17) % 256 + line = (f"\x1b[38;2;{red};{green};{blue}m{count:05d} / {row:02d} " + "ABC 123 日本語 かな カナ 😀 ─── 画面更新\x1b[0m\r\n") + output.extend(line.encode()) + elif phase == "sixel" and sixels: + output.extend("Sixel 192x192 / 赤 緑 青 黄\r\n".encode()) + output.extend(sixels[variant]) + elif phase == "kitty-inline": + output.extend("Kitty inline chunks / PNG 192x192\r\n".encode()) + output.extend(kitty_inline(images[variant], 100 + count % 64)) + elif phase == "kitty-file": + output.extend("Kitty file path / PNG 192x192\r\n".encode()) + path = base64.b64encode(str(paths[variant]).encode()) + output.extend(b"\x1b_Ga=T,t=f,f=100,i=1,q=2;" + path + b"\x1b\\") + return output + + +def run(minutes, end_wall=None): + if not sys.stdin.isatty() or not sys.stdout.isatty(): + raise SystemExit("bcon の端末内で実行してください") + duration = minutes * 60 + started = dt.datetime.now().strftime("%Y%m%d-%H%M%S") + log_path = Path.home() / f"bcon-stress-{started}.log" + latest = Path.home() / "bcon-stress-last.log" + latest.unlink(missing_ok=True) + latest.symlink_to(log_path) + log(log_path, f"START duration={duration}s pid={os.getpid()} TERM={os.getenv('TERM')} " + f"TERM_PROGRAM={os.getenv('TERM_PROGRAM')}") + watcher = subprocess.Popen([sys.executable, __file__, "--watch", str(log_path), str(os.getpid())], + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True) + fd = sys.stdin.fileno() + old = termios.tcgetattr(fd) + image_dir = tempfile.TemporaryDirectory(prefix="bcon-stress-") + try: + paths = [] + images = [] + sixels = [] + for variant in range(4): + path = Path(image_dir.name) / f"frame-{variant}.png" + image = png_bytes(variant) + path.write_bytes(image) + paths.append(path) + images.append(image) + if shutil.which("img2sixel"): + sixels.append(subprocess.run(["img2sixel", str(path)], + check=True, stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL).stdout) + log(log_path, f"FIXTURES png_bytes={[len(i) for i in images]} sixel={bool(sixels)}") + tty.setraw(fd) + sys.stdout.buffer.write(b"\x1b[?1049h\x1b[?25l") + sys.stdout.buffer.flush() + begin = time.monotonic() + count = 0 + last_progress = -10 + phase = None + stopped = False + while True: + elapsed = time.monotonic() - begin + if elapsed >= duration or (end_wall is not None and time.time() >= end_wall): + break + next_phase = PHASES[int(elapsed // PHASE_SECONDS) % len(PHASES)] + if next_phase != phase: + phase = next_phase + log(log_path, f"PHASE {phase} elapsed={elapsed:.1f}s") + if elapsed - last_progress >= 10: + log(log_path, f"PROGRESS elapsed={elapsed:.1f}s frames={count} phase={phase}") + last_progress = elapsed + sys.stdout.buffer.write(frame(phase, elapsed, duration, count, images, sixels, paths)) + sys.stdout.buffer.flush() + count += 1 + if select.select([fd], [], [], FRAME_INTERVAL[phase])[0]: + keys = os.read(fd, 1024) + if b"q" in keys or b"\x03" in keys: + stopped = True + break + elapsed = time.monotonic() - begin + log(log_path, f"{'STOPPED' if stopped else 'COMPLETE'} elapsed={elapsed:.1f}s frames={count}") + except Exception as error: + log(log_path, f"ERROR {type(error).__name__}: {error}") + raise + finally: + sys.stdout.buffer.write(b"\x1b_Ga=d,d=A,q=2\x1b\\\x1b[0m\x1b[?25h\x1b[?1049l") + sys.stdout.buffer.flush() + termios.tcsetattr(fd, termios.TCSADRAIN, old) + watcher.terminate() + try: + watcher.wait(timeout=2) + except subprocess.TimeoutExpired: + watcher.kill() + image_dir.cleanup() + print(f"bcon stress: {elapsed:.1f}s, {count} frames. Log: {log_path}") + + +if __name__ == "__main__": + if len(sys.argv) > 1 and sys.argv[1] == "--watch": + watch(sys.argv[2], int(sys.argv[3])) + else: + end_wall = None + if len(sys.argv) == 3 and sys.argv[1] == "--until": + try: + hour, minute = map(int, sys.argv[2].split(":")) + if not (0 <= hour < 24 and 0 <= minute < 60): + raise ValueError + except ValueError: + raise SystemExit("use --until HH:MM (local time)") + now = dt.datetime.now().astimezone() + target = now.replace(hour=hour, minute=minute, second=0, microsecond=0) + if target <= now: + target += dt.timedelta(days=1) + end_wall = target.timestamp() + minutes = (end_wall - time.time()) / 60 + else: + minutes = int(sys.argv[1]) if len(sys.argv) > 1 else 20 + if not 1 <= minutes <= 1440: + raise SystemExit("duration must be 1..1440 minutes") + run(minutes, end_wall) diff --git a/tests/rotation-mouse-check.py b/tests/rotation-mouse-check.py new file mode 100644 index 0000000..f85d542 --- /dev/null +++ b/tests/rotation-mouse-check.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Check that clicks land on visible targets with a rotated bcon display.""" + +import os +import re +import select +import shutil +import sys +import termios +import tty + +EVENT = re.compile(rb"\x1b\[<([0-9]+);([0-9]+);([0-9]+)([Mm])") +OUT = sys.stdout.buffer + + +def emit(data): + OUT.write(data.encode() if isinstance(data, str) else data) + OUT.flush() + + +def draw(targets, active, result=""): + emit("\x1b[2J\x1b[H") + emit("マウス位置テスト: 緑の [番号] の中央をクリックしてください。q で終了。\n") + emit("カーソルの見た目とクリック位置が一致するかも確認してください。") + for index, (x, y) in enumerate(targets): + color = "\x1b[32;1m" if index == active else "\x1b[90m" + emit(f"\x1b[{y};{x}H{color}[ {index + 1} ]\x1b[0m") + rows = shutil.get_terminal_size().lines + emit(f"\x1b[{rows - 1};1H\x1b[2K{result}") + emit(f"\x1b[{rows};1H\x1b[2K{active + 1}/{len(targets)} をクリック") + + +def main(): + size = shutil.get_terminal_size() + if size.columns < 25 or size.lines < 12: + raise SystemExit("端末が小さすぎます") + targets = [ + (5, 5), + (size.columns - 8, 5), + (size.columns - 8, size.lines - 5), + (5, size.lines - 5), + (size.columns // 2, size.lines // 2), + ] + fd = sys.stdin.fileno() + old = termios.tcgetattr(fd) + buffer = b"" + active = 0 + try: + tty.setraw(fd) + emit("\x1b[?1000h\x1b[?1006h\x1b[?25h") + draw(targets, active) + while active < len(targets): + if not select.select([fd], [], [], 1)[0]: + continue + chunk = os.read(fd, 1024) + if not chunk: + break + buffer += chunk + if b"q" in buffer or b"\x03" in buffer: + break + match = EVENT.search(buffer) + while match: + button, x, y, edge = match.groups() + buffer = buffer[match.end():] + if edge == b"M" and int(button) & 3 == 0: + tx, ty = targets[active] + if abs(int(x) - tx - 2) <= 3 and abs(int(y) - ty) <= 1: + active += 1 + if active == len(targets): + break + draw(targets, active, f"OK: {x.decode()},{y.decode()}") + else: + draw(targets, active, f"ずれ: click={x.decode()},{y.decode()} target={tx + 2},{ty}") + match = EVENT.search(buffer) + buffer = buffer[-100:] + finally: + emit("\x1b[?1000l\x1b[?1006l\x1b[0m\x1b[2J\x1b[H") + termios.tcsetattr(fd, termios.TCSADRAIN, old) + print(f"マウス位置: {active}/{len(targets)} 成功") + + +if __name__ == "__main__": + main() diff --git a/tests/visual-smoke.sh b/tests/visual-smoke.sh new file mode 100644 index 0000000..9923828 --- /dev/null +++ b/tests/visual-smoke.sh @@ -0,0 +1,221 @@ +#!/usr/bin/env bash +# Interactive rendering check. Run inside bcon and capture each numbered screen. +set -eu + +if [[ ${1:-} == --help ]]; then + printf 'Usage: bash tests/visual-smoke.sh\nRun inside bcon. Enter=OK, n=NG, s=skip, q=quit. Results: ~/bcon-visual-*.log\n' + exit 0 +fi +if [[ ! -t 0 || ! -t 1 ]]; then + printf 'bcon の端末内で実行してください。\n' >&2 + exit 1 +fi +command -v python3 >/dev/null || { printf 'python3 が必要です。\n' >&2; exit 1; } + +tmp_dir=$(mktemp -d) +image_path=$tmp_dir/check.png +log_path=$(mktemp "$HOME/bcon-visual-$(date +%Y%m%d-%H%M%S)-XXXXXX.log") +printf 'START %s TERM=%s TERM_PROGRAM=%s\n' "$(date -Is)" "${TERM:-}" "${TERM_PROGRAM:-}" > "$log_path" +bad=() +skipped=() +passed=() +completed=false +in_alternate=false +title='' + +cleanup() { + local status=$? + if $in_alternate; then printf '\033[?1049l'; fi + printf '\033_Ga=d,d=A,q=2\033\\\033[0m\033[?25h' + rm -rf -- "$tmp_dir" + printf 'END completed=%s exit=%s OK=%s NG=%s SKIP=%s\n' "$completed" "$status" "${#passed[@]}" "${#bad[@]}" "${#skipped[@]}" >> "$log_path" + printf '\n結果: OK %s / NG %s / スキップ %s(全10項目)\nログ: %s\n' "${#passed[@]}" "${#bad[@]}" "${#skipped[@]}" "$log_path" +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM + +python3 - "$image_path" <<'PY' +import struct +import sys +import zlib + +width = height = 96 +rows = [] +for y in range(height): + row = bytearray([0]) + for x in range(width): + if x < 48 and y < 48: + rgb = (255, 40, 40) + elif x >= 48 and y < 48: + rgb = (40, 220, 60) + elif x < 48: + rgb = (40, 90, 255) + else: + rgb = (255, 220, 30) + row.extend(rgb) + rows.append(row) + +def chunk(kind, data): + body = kind + data + return struct.pack('>I', len(data)) + body + struct.pack('>I', zlib.crc32(body)) + +with open(sys.argv[1], 'wb') as output: + output.write(b'\x89PNG\r\n\x1a\n') + output.write(chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0))) + output.write(chunk(b'IDAT', zlib.compress(b''.join(rows)))) + output.write(chunk(b'IEND', b'')) +PY + +page() { + title=$2 + printf '\033_Ga=d,d=A,q=2\033\\\033[0m\033[2J\033[H' + printf 'bcon 描画チェック %s/10: %s\n' "$1" "$2" + printf '%s\n\n' '────────────────────────────────────────' +} + +check() { + local answer result note='' + while true; do + printf '\n必要なら画面を撮影 → Enter: OK / n: NG / s: スキップ / q: 終了 > ' + IFS= read -r answer ' + IFS= read -r note > "$log_path"; return 1 ;; + esac + done + printf '%s %s %s %s\n' "$1" "$result" "$title" "$note" >> "$log_path" + return 0 +} + +page 1 '文字と幅' +printf 'ASCII: ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789\n' +printf '日本語: こんにちは、世界。漢字・かな・カナ\n' +printf '全角と半角: |A|あ|B|界|C| 縦線がずれないか\n' +printf '結合文字: e\u0301 / é 記号: ┌─┬─┐ │ └─┘\n' +printf '絵文字: 😀 🚀 🎉 ❤️ 🇯🇵 表示と幅を確認\n' +printf '期待: 欠け・重なり・文字化けがない\n' +check 1 || exit 0 + +page 2 '色と文字属性' +printf '通常 \033[1m太字\033[22m \033[3m斜体\033[23m \033[4m下線\033[24m \033[9m取消線\033[29m\n' +printf '\033[7m反転表示\033[27m \033[2m淡い文字\033[22m\n' +printf 'ANSI: ' +for color in {0..7}; do printf '\033[4%sm %s \033[0m' "$color" "$color"; done +printf '\n256色: ' +for color in {16..27}; do printf '\033[48;5;%sm \033[0m' "$color"; done +printf '\n24bit: ' +for step in {0..23}; do + red=$((step * 255 / 23)) + blue=$((255 - red)) + printf '\033[48;2;%s;40;%sm \033[0m' "$red" "$blue" +done +printf '\n期待: 属性と色の階調が見える\n' +check 2 || exit 0 + +page 3 '位置と罫線' +printf '下の枠が四角くつながり、中の文字が枠内に収まるか\n\n' +printf '┌──────────────────────────────┐\n' +printf '│ %-28s │\n' 'left center right' +printf '│ %-28s │\n' '1234567890 ABCDEFGHIJKLMNO' +printf '└──────────────────────────────┘\n\n' +printf '行末テスト: 次の行の X が右端にあるか\n' +cols=$(tput cols 2>/dev/null || printf 80) +if (( cols > 20 )); then + printf '%*s' "$cols" X + printf '\n' +fi +printf '期待: 行末の X と次の行が正常\n' +check 3 || exit 0 + +page 4 'スクロール' +printf '連続行を表示します。最後に 51〜60 が順番に見えるか\n' +for number in {1..60}; do printf '行 %02d ABC 日本語 123\n' "$number"; done +check 4 || exit 0 + +page 5 'Sixel 画像' +if command -v img2sixel >/dev/null 2>&1; then + printf '期待: 赤・緑・青・黄の 4 色の正方形が出る\n\n' + if img2sixel "$image_path"; then + check 5 || exit 0 + else + bad+=(5) + printf '5 NG Sixel encoder failed\n' >> "$log_path" + fi +else + printf 'img2sixel がないためスキップ\n' + skipped+=(5) + printf '5 SKIP img2sixel unavailable\n' >> "$log_path" +fi + +page 6 'Kitty 画像(分割転送)' +printf '期待: 左上=赤、右上=緑、左下=青、右下=黄の正方形\n\n' +# Force multiple chunks even for this small PNG; omit m on the final chunk. +python3 - "$image_path" <<'PY' +import base64 +import pathlib +import sys +data = base64.b64encode(pathlib.Path(sys.argv[1]).read_bytes()) +for offset in range(0, len(data), 64): + params = 'a=T,t=d,f=100,q=2' if offset == 0 else '' + if offset + 64 < len(data): + params += ',m=1' if params else 'm=1' + sys.stdout.buffer.write(b'\x1b_G' + params.encode() + b';' + data[offset:offset + 64] + b'\x1b\\') +PY +check 6 || exit 0 + +page 7 'Kitty 画像(ファイル転送)' +printf '期待: 同じ 4 色の正方形が出る。casty が使う転送方式\n\n' +encoded_path=$(printf '%s' "$image_path" | base64 -w0) +printf '\033_Ga=T,t=f,f=100,q=2;%s\033\\' "$encoded_path" +printf '\n' +check 7 || exit 0 + +page 8 '部分更新・残像(約3秒)' +printf '期待: 固定行は動かず、更新行の右端に古い文字や背景が残らない\n' +printf '\033[6;1H固定行: ABC 日本語 ──────────' +for frame in {1..24}; do + printf '\033[8;1H\033[2K' + if (( frame % 2 )); then + printf '\033[44;97m長い更新行 ABCDEFGHIJKLMNOPQRSTUVWXYZ 日本語\033[0m' + else + printf '\033[41;97m短い行\033[0m' + fi + sleep 0.12 +done +printf '\033[10;1H' +check 8 || exit 0 + +page 9 '代替画面からの復帰' +printf '復帰確認: この文字と見出しが戻れば OK\n' +printf 'Enter で代替画面へ > ' +IFS= read -r _ ' +IFS= read -r _ Date: Sat, 26 Sep 2026 10:19:52 +0900 Subject: [PATCH 3/4] docs: share agent instructions and record release handoff --- AGENTS.md | 7 +++++++ CLAUDE.md | 13 ++++++++++-- HANDOFF.md | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 AGENTS.md create mode 100644 HANDOFF.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..b401ca3 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,7 @@ +# Agent Instructions + +Read and follow [CLAUDE.md](./CLAUDE.md) for this repository's architecture, coding conventions, testing guidance, and release rules. It is the shared source of truth for Claude Code and Codex. + +Read [HANDOFF.md](./HANDOFF.md) for any active task handoff, and follow the handoff instructions in `CLAUDE.md` when passing work to another agent. + +In particular, do not run `git push` or `git tag` without an explicit user instruction. diff --git a/CLAUDE.md b/CLAUDE.md index e70126e..ea96781 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -220,10 +220,19 @@ Reference: https://vt100.net/emu/dec_ansi_parser - Keep unsafe blocks minimal and well-documented - Module structure: one file per major component +## Agent Handoff + +Claude Code and Codex share [HANDOFF.md](./HANDOFF.md) as the current task handoff. + +- At the start of a task, read the handoff and check `git status`; verify its notes against the working tree before relying on them. +- When the user asks to hand work to another agent, update the handoff with the goal, completed work, next steps, test results, blockers, and uncommitted files. Keep it brief and specific. +- Treat the handoff as task state, not as a replacement for this file or the user's instructions. Do not overwrite another agent's uncommitted work. +- When a task is complete, mark the handoff as having no active task so stale steps are not followed later. + ## Language Guidelines Use **English** for wider adoption: -- README.md, CLAUDE.md +- README.md, CLAUDE.md, AGENTS.md, HANDOFF.md - Release notes / CHANGELOG - Commit messages - GitHub Issues/PR titles @@ -264,7 +273,7 @@ img2sixel test.png - **kmscon** (C): https://github.com/dvdhrm/kmscon - **alacritty** (Rust): https://github.com/alacritty/alacritty -## Commands for Claude Code +## Commands for Coding Agents When implementing, prefer: - Small, focused commits diff --git a/HANDOFF.md b/HANDOFF.md new file mode 100644 index 0000000..bbd4d58 --- /dev/null +++ b/HANDOFF.md @@ -0,0 +1,58 @@ +# Agent Handoff + +Status: Active — review complete; v1.5.0 merge and release pending. + +## Goal + +Merge the reviewed display rotation (#17), NumLock-off keypad navigation (#18), +and related rendering/config fixes. The user authorized merging and necessary +documentation updates. The user also explicitly authorized a release. Use v1.5.0 because rotation adds +a feature. All commit, PR, release, and issue messages must be English. +Leave issue #19 unchanged. +After release, reply to #17 and #18 in English, briefly apologizing for the slow reply +(as requested by the user). Do not send those replies before release. + +## Completed + +- Reviewed all application, documentation, and test-tool changes. +- Fixed review findings: relative-path config watch filtering, grayscale mode + selection and R8-to-RGB atlas upload, and out-of-bounds absolute pointer input + after rotation. Added regression coverage. +- Fixed final-target handling in the interactive pointer check and NumLock + restoration in the keypad check. +- Updated English/Japanese configuration, keybind, and installation docs; + added an Unreleased changelog section and tests/README.md. +- Earlier systemd visual smoke run: 12 screenshots showed correct text, colors, + Sixel, both Kitty transfers, partial update cleanup, and alternate-screen + restoration. Service had zero restarts during that run. This predates the + additional code-review fixes; screenshots do not verify all rotation angles + or VT switching animations. + +## Verification + +- `cargo test --locked`: 65 passed, 1 hardware-dependent seatd test ignored. +- `cargo test --locked --no-default-features`: passed. +- `cargo build --release --locked`: passed after the review fixes. +- Shell/Python parsing and both C test utilities' strict syntax checks passed. +- Relative-config atomic-save regression failed before the fix and passed after. +- User reports overnight stress did not reproduce issue #19; not proof of a fix. + +## Next steps + +- Publish the reviewed branch/PR, verify CI, merge, tag v1.5.0, and verify the + release artifacts. Then reply to issues #17 and #18 in English with a brief + apology for the slow reply. Update this handoff once complete. +- Update this file after merge so future agents do not repeat stale work. + +## Uncommitted files and blockers + +- Changes are being prepared on a dedicated review branch. Check git status and + the PR before resuming. No application restart is needed for GitHub operations. +- The development share is CIFS and reports every file as executable. Preserve + existing Git modes; ignore mode-only differences when reviewing/staging. +- Privileged deployment requires the user's sudo interaction. The user offered + to execute commands themselves; never request their password. + +- CIFS rejected writing loose Git objects during staging. A local review clone + is recorded in /tmp/bcon-review-path; it has the same reviewed file contents + and preserves repository file modes. Use it for publication if needed. From 03ff90559180551af64e840a47beb7726297d155 Mon Sep 17 00:00:00 2001 From: Hironobu Sano <7529745+sanohiro@users.noreply.github.com> Date: Sat, 26 Sep 2026 10:19:52 +0900 Subject: [PATCH 4/4] release: prepare v1.5.0 --- CHANGELOG.md | 13 +++++++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f98ace2..e3a106d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,19 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [1.5.0] - 2026-09-26 + +### Added +- Clockwise display rotation (`0`, `90`, `180`, `270`) for tablets and portrait monitors, including rendering, pointer coordinates, and framebuffer updates ([#17](https://github.com/sanohiro/bcon/issues/17)). +- Interactive rendering and rotated-pointer checks, plus bounded rendering and virtual-keyboard stress tools in `tests/`. +- Shared agent instructions and task handoff documentation. + +### Fixed +- NumLock-off keypad navigation now works like dedicated arrow, Home, End, PageUp, PageDown, Insert, and Delete keys ([#18](https://github.com/sanohiro/bcon/issues/18)). +- Kitty image transfers finish when the last chunk omits `m`. +- Config watching ignores sibling files, coalesces pending events, and supports relative config paths and atomic saves. +- Honor `font.render_mode = "grayscale"` when initializing the glyph atlas. + ## [1.3.1] - 2026-04-04 ### Added diff --git a/Cargo.lock b/Cargo.lock index ca11820..35b9a8e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -187,7 +187,7 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "bcon" -version = "1.4.0" +version = "1.5.0" dependencies = [ "anyhow", "bitflags 2.10.0", diff --git a/Cargo.toml b/Cargo.toml index b54f5f2..1b9c031 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "bcon" -version = "1.4.0" +version = "1.5.0" edition = "2021" authors = ["Hironobu Sano"] description = "GPU-accelerated terminal emulator for Linux console"