From 2321d06af150735f76576af9035cc073c52773911dccb11c28dc17675b274341 Mon Sep 17 00:00:00 2001 From: kira Date: Thu, 3 Dec 2026 00:28:16 +0100 Subject: [PATCH] Implemented keyboard layout testing by forking text_input and using libxkbcommon --- Cargo.lock | 177 +--- Cargo.toml | 8 +- src/kira_system.rs | 64 +- src/kira_text_input/cursor.rs | 189 ++++ src/kira_text_input/editor.rs | 70 ++ src/kira_text_input/mod.rs | 1767 +++++++++++++++++++++++++++++++++ src/kira_text_input/value.rs | 136 +++ src/kira_xkb.rs | 209 ++++ src/main.rs | 45 +- src/stages/keyboard/mod.rs | 95 +- 10 files changed, 2552 insertions(+), 208 deletions(-) create mode 100644 src/kira_text_input/cursor.rs create mode 100644 src/kira_text_input/editor.rs create mode 100644 src/kira_text_input/mod.rs create mode 100644 src/kira_text_input/value.rs create mode 100644 src/kira_xkb.rs diff --git a/Cargo.lock b/Cargo.lock index 5466462..69b2b55 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -88,9 +88,9 @@ checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" [[package]] name = "anyhow" -version = "1.0.104" +version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" [[package]] name = "arbitrary" @@ -132,9 +132,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" -version = "0.7.8" +version = "0.7.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" +checksum = "47a64a0fd06e123e9e3cf3ad01432af17dcab8185e8023edcf184fe696f9675d" [[package]] name = "as-raw-xcb-connection" @@ -514,9 +514,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.11.3" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +checksum = "95e45cf2980b2d467be49a9ed942c9179b701063a7ca3d037de7ee9bd67f8d66" dependencies = [ "find-msvc-tools", "jobserver", @@ -701,9 +701,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.5" +version = "1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" dependencies = [ "cfg-if", ] @@ -989,9 +989,9 @@ dependencies = [ [[package]] name = "find-msvc-tools" -version = "0.1.15" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8" [[package]] name = "flate2" @@ -1237,9 +1237,9 @@ checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" [[package]] name = "globset" -version = "0.4.21" +version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f98b0d85522dc0a824cfebbc9594ff4a9b289c568bea0370319dfbdf20ccdd2d" +checksum = "71217a07f20b48b4938c14203b77b610f8a7fa6762c3f75394a10c5f31e5aee0" dependencies = [ "aho-corasick", "bstr", @@ -1315,9 +1315,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.17.1" +version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" [[package]] name = "hermit-abi" @@ -1553,9 +1553,9 @@ dependencies = [ [[package]] name = "ignore" -version = "0.4.34" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "484be5657551d7868d67587df967fb4fcbe9d266a761cc855aaa148fda0b3cc7" +checksum = "df0a7d5f105e76bda602bed0a44af048542d3c9af12ec35aaf16f106c6f34270" dependencies = [ "crossbeam-deque", "globset", @@ -1614,7 +1614,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", - "hashbrown 0.17.1", + "hashbrown 0.17.2", ] [[package]] @@ -1753,9 +1753,9 @@ dependencies = [ "rust-i18n", "serde", "serde_json", - "smol", "time-format", - "zbus 6.5.0", + "unicode-segmentation", + "xkbcommon", ] [[package]] @@ -1847,9 +1847,9 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "litrs" -version = "1.0.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" +checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175" [[package]] name = "lock_api" @@ -1995,7 +1995,7 @@ dependencies = [ "wasm-bindgen-futures", "web-sys", "windows", - "zbus 5.19.0", + "zbus", ] [[package]] @@ -2706,7 +2706,7 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit 0.25.19+spec-1.1.0", + "toml_edit 0.25.21+spec-1.1.0", ] [[package]] @@ -2827,9 +2827,9 @@ checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" [[package]] name = "rangemap" -version = "1.8.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" +checksum = "f2d43a8c8c74056248124068fde0df374d1ddf9039e747d190f01c36faeaab08" [[package]] name = "rav1e" @@ -3251,12 +3251,9 @@ dependencies = [ [[package]] name = "simd_helpers" -version = "0.1.0" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" -dependencies = [ - "quote", -] +checksum = "f48ea32978b7ad365bd1ecce83827746d5d50dc006a8c85112b7acc3c716e3e7" [[package]] name = "simdutf8" @@ -3337,16 +3334,6 @@ dependencies = [ "serde", ] -[[package]] -name = "socket2" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - [[package]] name = "softbuffer" version = "0.4.8" @@ -3618,9 +3605,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.25.19+spec-1.1.0" +version = "0.25.21+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4" dependencies = [ "indexmap", "toml_datetime 1.1.3+spec-1.1.0", @@ -3630,9 +3617,9 @@ dependencies = [ [[package]] name = "toml_parser" -version = "1.1.5+spec-1.1.0" +version = "1.1.7+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" dependencies = [ "winnow 1.0.5", ] @@ -3771,9 +3758,9 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "walkdir" -version = "2.5.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" dependencies = [ "same-file", "winapi-util", @@ -4302,6 +4289,17 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "xkbcommon" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a974f48060a14e95705c01f24ad9c3345022f4d97441b8a36beb7ed5c4a02d" +dependencies = [ + "libc", + "memmap2", + "xkeysym", +] + [[package]] name = "xkbcommon-dl" version = "0.4.2" @@ -4363,38 +4361,11 @@ dependencies = [ "uuid", "windows-sys 0.61.2", "winnow 1.0.5", - "zbus_macros 5.19.0", + "zbus_macros", "zbus_names", "zvariant", ] -[[package]] -name = "zbus" -version = "6.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a7f9f5dd97fa527c1202ba1cb35d48e07f77d4de8542317c854f7aef22b0668" -dependencies = [ - "async-trait", - "bitflags 2.13.2", - "endi", - "futures-core", - "hex", - "libc", - "ordered-stream", - "rustix 1.1.6", - "serde", - "serde_repr", - "socket2", - "uds_windows", - "uuid", - "windows-sys 0.61.2", - "winnow 1.0.5", - "zbus_macros 6.5.0", - "zbus_utils", - "zcheapstr", - "zruntime", -] - [[package]] name = "zbus_macros" version = "5.19.0" @@ -4410,18 +4381,6 @@ dependencies = [ "zvariant_utils", ] -[[package]] -name = "zbus_macros" -version = "6.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f5aa7f2c4ea81b7ccfb26bafefdb4d1a44dd9d4f82c8426173a3727311743e4" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.10", - "zbus_utils", -] - [[package]] name = "zbus_names" version = "4.3.5" @@ -4433,24 +4392,11 @@ dependencies = [ "zvariant", ] -[[package]] -name = "zbus_utils" -version = "6.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "syn 3.0.10", - "winnow 1.0.5", -] - [[package]] name = "zcheapstr" -version = "1.3.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2347b6f50c4f669a282af57bf950debeacb9ce86de21b5b12932178dda691315" +checksum = "2da34e7164b75d803c3197b86e6cf61b874106fbd472c5082575a8bc5fbd0907" dependencies = [ "serde", ] @@ -4463,18 +4409,18 @@ checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" [[package]] name = "zerocopy" -version = "0.8.63" +version = "0.8.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.63" +version = "0.8.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" dependencies = [ "proc-macro2", "quote", @@ -4483,9 +4429,9 @@ dependencies = [ [[package]] name = "zlib-rs" -version = "0.6.8" +version = "0.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" [[package]] name = "zmij" @@ -4493,24 +4439,11 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" -[[package]] -name = "zruntime" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac67096b97c00742108c4674db6bb6178adb78c4b66a506b0e4a7a9593aa5d9e" -dependencies = [ - "futures-core", - "futures-io", - "rustix 1.1.6", - "socket2", - "windows-sys 0.61.2", -] - [[package]] name = "zune-core" -version = "0.5.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +checksum = "c1a65ee146f41cb456b005bc898af3ab1495ded4ee61ac3637103f40ccacac18" [[package]] name = "zune-inflate" diff --git a/Cargo.toml b/Cargo.toml index 07b0e51..14b67c1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,10 +8,11 @@ edition = "2024" [dependencies] blocking = "1.6" -smol = "2" -iced = { version = "0.14", default-features = false, features = ["crisp", "linux-theme-detection", "tiny-skia", "x11", "smol", "image"] } +# smol = "2" +unicode-segmentation = "1" +iced = { version = "0.14", default-features = false, features = ["crisp", "linux-theme-detection", "tiny-skia", "x11", "smol", "image", "advanced"] } #iced = { git = "https://github.com/iced-rs/iced", branch = "vello_cpu", default-features = false, features = ["crisp", "linux-theme-detection", "vello-cpu", "x11", "smol", "image"]} -zbus = { version = "6", default-features = false, features = ["default-rt", "comms"] } +# zbus = { version = "6", default-features = false, features = ["default-rt", "comms"] } iced_moving_picture = "0" log = "0.4" rust-i18n = "4" @@ -19,6 +20,7 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" time-format = "1.2" regex-lite = "0.1" +xkbcommon = { version = "0.9.0" } [dev-dependencies] diff --git a/src/kira_system.rs b/src/kira_system.rs index 60b1aa8..6017c8d 100644 --- a/src/kira_system.rs +++ b/src/kira_system.rs @@ -525,38 +525,38 @@ pub fn set_root_passwd(chroot_dir: &str, root_passwd: &str) -> Result<(), ExecCo ) } -/// -/// Sends Dbus message locale1 to change input method -/// SetX11Keyboard(layout: s, model: s, variant: s, options: s, convert: b, interactive: b) -/// -pub async fn set_input_method( - layout: &str, - model: &str, - variant: &str, - options: &str, -) -> zbus::Result<()> { - use zbus::Connection; +// / +// / Sends Dbus message locale1 to change input method +// / SetX11Keyboard(layout: s, model: s, variant: s, options: s, convert: b, interactive: b) +// / +// pub async fn set_input_method( +// layout: &str, +// model: &str, +// variant: &str, +// options: &str, +// ) -> zbus::Result<()> { +// use zbus::Connection; - let conn = Connection::system().await?; - log::info!("Sending dbus message to change layout"); - log::info!( - "layout: {}, model: {}, variant: {}, options: {}", - layout, - model, - variant, - options - ); - let resp = conn - .call_method( - Some("org.freedesktop.locale1"), - "/org/freedesktop/locale1", - Some("org.freedesktop.locale1"), - "SetX11Keyboard", - &(layout, model, variant, options, true, false), - ) - .await?; +// let conn = Connection::system().await?; +// log::info!("Sending dbus message to change layout"); +// log::info!( +// "layout: {}, model: {}, variant: {}, options: {}", +// layout, +// model, +// variant, +// options +// ); +// let resp = conn +// .call_method( +// Some("org.freedesktop.locale1"), +// "/org/freedesktop/locale1", +// Some("org.freedesktop.locale1"), +// "SetX11Keyboard", +// &(layout, model, variant, options, true, false), +// ) +// .await?; - log::info!("Dbus response: {}", resp.to_string()); +// log::info!("Dbus response: {}", resp.to_string()); - Ok(()) -} +// Ok(()) +// } diff --git a/src/kira_text_input/cursor.rs b/src/kira_text_input/cursor.rs new file mode 100644 index 0000000..5f14807 --- /dev/null +++ b/src/kira_text_input/cursor.rs @@ -0,0 +1,189 @@ +//! Track the cursor of a text input. +use crate::kira_text_input::Value; + +/// The cursor of a text input. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct Cursor { + state: State, +} + +/// The state of a [`Cursor`]. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum State { + /// Cursor without a selection + Index(usize), + + /// Cursor selecting a range of text + Selection { + /// The start of the selection + start: usize, + /// The end of the selection + end: usize, + }, +} + +impl Default for Cursor { + fn default() -> Self { + Cursor { + state: State::Index(0), + } + } +} + +impl Cursor { + /// Returns the [`State`] of the [`Cursor`]. + pub fn state(&self, value: &Value) -> State { + match self.state { + State::Index(index) => State::Index(index.min(value.len())), + State::Selection { start, end } => { + let start = start.min(value.len()); + let end = end.min(value.len()); + + if start == end { + State::Index(start) + } else { + State::Selection { start, end } + } + } + } + } + + /// Returns the current selection of the [`Cursor`] for the given [`Value`]. + /// + /// `start` is guaranteed to be <= than `end`. + pub fn selection(&self, value: &Value) -> Option<(usize, usize)> { + match self.state(value) { + State::Selection { start, end } => { + Some((start.min(end), start.max(end))) + } + State::Index(_) => None, + } + } + + pub(crate) fn move_to(&mut self, position: usize) { + self.state = State::Index(position); + } + + pub(crate) fn move_right(&mut self, value: &Value) { + self.move_right_by_amount(value, 1); + } + + pub(crate) fn move_right_by_words(&mut self, value: &Value) { + self.move_to(value.next_end_of_word(self.right(value))); + } + + pub(crate) fn move_right_by_amount( + &mut self, + value: &Value, + amount: usize, + ) { + match self.state(value) { + State::Index(index) => { + self.move_to(index.saturating_add(amount).min(value.len())); + } + State::Selection { start, end } => self.move_to(end.max(start)), + } + } + + pub(crate) fn move_left(&mut self, value: &Value) { + match self.state(value) { + State::Index(index) if index > 0 => self.move_to(index - 1), + State::Selection { start, end } => self.move_to(start.min(end)), + State::Index(_) => self.move_to(0), + } + } + + pub(crate) fn move_left_by_words(&mut self, value: &Value) { + self.move_to(value.previous_start_of_word(self.left(value))); + } + + pub(crate) fn select_range(&mut self, start: usize, end: usize) { + if start == end { + self.state = State::Index(start); + } else { + self.state = State::Selection { start, end }; + } + } + + pub(crate) fn select_left(&mut self, value: &Value) { + match self.state(value) { + State::Index(index) if index > 0 => { + self.select_range(index, index - 1); + } + State::Selection { start, end } if end > 0 => { + self.select_range(start, end - 1); + } + _ => {} + } + } + + pub(crate) fn select_right(&mut self, value: &Value) { + match self.state(value) { + State::Index(index) if index < value.len() => { + self.select_range(index, index + 1); + } + State::Selection { start, end } if end < value.len() => { + self.select_range(start, end + 1); + } + _ => {} + } + } + + pub(crate) fn select_left_by_words(&mut self, value: &Value) { + match self.state(value) { + State::Index(index) => { + self.select_range(index, value.previous_start_of_word(index)); + } + State::Selection { start, end } => { + self.select_range(start, value.previous_start_of_word(end)); + } + } + } + + pub(crate) fn select_right_by_words(&mut self, value: &Value) { + match self.state(value) { + State::Index(index) => { + self.select_range(index, value.next_end_of_word(index)); + } + State::Selection { start, end } => { + self.select_range(start, value.next_end_of_word(end)); + } + } + } + + pub(crate) fn select_all(&mut self, value: &Value) { + self.select_range(0, value.len()); + } + + pub(crate) fn start(&self, value: &Value) -> usize { + let start = match self.state { + State::Index(index) => index, + State::Selection { start, .. } => start, + }; + + start.min(value.len()) + } + + pub(crate) fn end(&self, value: &Value) -> usize { + let end = match self.state { + State::Index(index) => index, + State::Selection { end, .. } => end, + }; + + end.min(value.len()) + } + + fn left(&self, value: &Value) -> usize { + match self.state(value) { + State::Index(index) => index, + State::Selection { start, end } => start.min(end), + } + } + + fn right(&self, value: &Value) -> usize { + match self.state(value) { + State::Index(index) => index, + State::Selection { start, end } => start.max(end), + } + } +} diff --git a/src/kira_text_input/editor.rs b/src/kira_text_input/editor.rs new file mode 100644 index 0000000..ed2f356 --- /dev/null +++ b/src/kira_text_input/editor.rs @@ -0,0 +1,70 @@ +use crate::kira_text_input::{Cursor, Value}; + +pub struct Editor<'a> { + value: &'a mut Value, + cursor: &'a mut Cursor, +} + +impl<'a> Editor<'a> { + pub fn new(value: &'a mut Value, cursor: &'a mut Cursor) -> Editor<'a> { + Editor { value, cursor } + } + + pub fn contents(&self) -> String { + self.value.to_string() + } + + pub fn insert(&mut self, character: char) { + if let Some((left, right)) = self.cursor.selection(self.value) { + self.cursor.move_left(self.value); + self.value.remove_many(left, right); + } + + self.value.insert(self.cursor.end(self.value), character); + self.cursor.move_right(self.value); + } + + pub fn paste(&mut self, content: Value) { + let length = content.len(); + if let Some((left, right)) = self.cursor.selection(self.value) { + self.cursor.move_left(self.value); + self.value.remove_many(left, right); + } + + self.value.insert_many(self.cursor.end(self.value), content); + + self.cursor.move_right_by_amount(self.value, length); + } + + pub fn backspace(&mut self) { + match self.cursor.selection(self.value) { + Some((start, end)) => { + self.cursor.move_left(self.value); + self.value.remove_many(start, end); + } + None => { + let start = self.cursor.start(self.value); + + if start > 0 { + self.cursor.move_left(self.value); + self.value.remove(start - 1); + } + } + } + } + + pub fn delete(&mut self) { + match self.cursor.selection(self.value) { + Some(_) => { + self.backspace(); + } + None => { + let end = self.cursor.end(self.value); + + if end < self.value.len() { + self.value.remove(end); + } + } + } + } +} diff --git a/src/kira_text_input/mod.rs b/src/kira_text_input/mod.rs new file mode 100644 index 0000000..036709b --- /dev/null +++ b/src/kira_text_input/mod.rs @@ -0,0 +1,1767 @@ +//! Text inputs display fields that can be filled with text. +//! +//! # Example +//! ```no_run +//! # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } +//! # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; +//! # +//! use iced::widget::text_input; +//! +//! struct State { +//! content: String, +//! } +//! +//! #[derive(Debug, Clone)] +//! enum Message { +//! ContentChanged(String) +//! } +//! +//! fn view(state: &State) -> Element<'_, Message> { +//! text_input("Type something here...", &state.content) +//! .on_input(Message::ContentChanged) +//! .into() +//! } +//! +//! fn update(state: &mut State, message: Message) { +//! match message { +//! Message::ContentChanged(content) => { +//! state.content = content; +//! } +//! } +//! } +//! ``` +mod editor; +mod value; + +pub mod cursor; + +pub use cursor::Cursor; +use iced::keyboard::key::Physical; +pub use value::Value; + +use editor::Editor; +use iced::advanced::InputMethod; +use iced::advanced::Layout; +use iced::advanced::Shell; +use iced::advanced::Widget; +use iced::advanced::clipboard::{self, Clipboard}; +use iced::advanced::input_method; +use iced::advanced::layout; +use iced::advanced::mouse::{self, click}; +use iced::advanced::renderer; +use iced::advanced::text::paragraph::{self, Paragraph as _}; +use iced::advanced::text::{self, Text}; +use iced::advanced::widget; +use iced::advanced::widget::operation::{self, Operation}; +use iced::advanced::widget::tree::{self, Tree}; +use iced::alignment; +use iced::keyboard; +use iced::keyboard::key; +use iced::time::{Duration, Instant}; +use iced::touch; +use iced::window; +use iced::{ + Alignment, Background, Border, Color, Element, Event, Length, Padding, Pixels, Point, + Rectangle, Size, Theme, Vector, +}; + +use crate::kira_xkb; +use xkbcommon::xkb; +/// A field that can be filled with text. +/// +/// # Example +/// ```no_run +/// # mod iced { pub mod widget { pub use iced_widget::*; } pub use iced_widget::Renderer; pub use iced_widget::core::*; } +/// # pub type Element<'a, Message> = iced_widget::core::Element<'a, Message, iced_widget::Theme, iced_widget::Renderer>; +/// # +/// use iced::widget::text_input; +/// +/// struct State { +/// content: String, +/// } +/// +/// #[derive(Debug, Clone)] +/// enum Message { +/// ContentChanged(String) +/// } +/// +/// fn view(state: &State) -> Element<'_, Message> { +/// text_input("Type something here...", &state.content) +/// .on_input(Message::ContentChanged) +/// .into() +/// } +/// +/// fn update(state: &mut State, message: Message) { +/// match message { +/// Message::ContentChanged(content) => { +/// state.content = content; +/// } +/// } +/// } +/// ``` +pub struct TextInput<'a, Message, Theme = iced::Theme, Renderer = iced::Renderer> +where + Theme: Catalog, + Renderer: text::Renderer, +{ + id: Option, + placeholder: String, + value: Value, + is_secure: bool, + font: Option, + width: Length, + padding: Padding, + size: Option, + line_height: text::LineHeight, + alignment: alignment::Horizontal, + on_input: Option Message + 'a>>, + on_paste: Option Message + 'a>>, + on_submit: Option, + icon: Option>, + class: Theme::Class<'a>, + last_status: Option, + xkb_keymap: Option, + xkb_state: Option, +} + +/// The default [`Padding`] of a [`TextInput`]. +pub const DEFAULT_PADDING: Padding = Padding::new(5.0); + +impl<'a, Message, Theme, Renderer> TextInput<'a, Message, Theme, Renderer> +where + Message: Clone, + Theme: Catalog, + Renderer: text::Renderer, +{ + /// Creates a new [`TextInput`] with the given placeholder and + /// its current value. + pub fn new(placeholder: &str, value: &str) -> Self { + TextInput { + id: None, + placeholder: String::from(placeholder), + value: Value::new(value), + is_secure: false, + font: None, + width: Length::Fill, + padding: DEFAULT_PADDING, + size: None, + line_height: text::LineHeight::default(), + alignment: alignment::Horizontal::Left, + on_input: None, + on_paste: None, + on_submit: None, + icon: None, + class: Theme::default(), + last_status: None, + xkb_keymap: None, + xkb_state: None, + } + } + + /// Sets key mapping to use + pub fn keymap(mut self, xkb_keymap: Option) -> Self { + self.xkb_keymap = xkb_keymap; + if let Some(kmref) = self.xkb_keymap.as_ref() { + self.xkb_state = Some(xkb::State::new(kmref)); + } + self + } + + // fn translate_key(&self, keycode: u32, modifiers: &Modifiers) -> Option { + // if let Some(state) = self.xkb_state { + // // Update modifier state from iced's modifiers + // update_xkb_modifiers(&mut state, modifiers); + + // // Update key state (pressed/released) + // state + + // // Get keysym + // let keysym = state.key_get_one_sym(keycode); + + // // Convert keysym to UTF-8 + // let mut buf = [0u8; 8]; + // let len = keysym_to_utf8(keysym, buf.as_mut_ptr()); + + // if len > 0 { + // Some(String::from_utf8_lossy(&buf[..len]).to_string()) + // } else { + // None + // } + // } + // None + // } + + /// Sets the [`widget::Id`] of the [`TextInput`]. + pub fn id(mut self, id: impl Into) -> Self { + self.id = Some(id.into()); + self + } + + /// Converts the [`TextInput`] into a secure password input. + pub fn secure(mut self, is_secure: bool) -> Self { + self.is_secure = is_secure; + self + } + + /// Sets the message that should be produced when some text is typed into + /// the [`TextInput`]. + /// + /// If this method is not called, the [`TextInput`] will be disabled. + pub fn on_input(mut self, on_input: impl Fn(String) -> Message + 'a) -> Self { + self.on_input = Some(Box::new(on_input)); + self + } + + /// Sets the message that should be produced when some text is typed into + /// the [`TextInput`], if `Some`. + /// + /// If `None`, the [`TextInput`] will be disabled. + pub fn on_input_maybe(mut self, on_input: Option Message + 'a>) -> Self { + self.on_input = on_input.map(|f| Box::new(f) as _); + self + } + + /// Sets the message that should be produced when the [`TextInput`] is + /// focused and the enter key is pressed. + pub fn on_submit(mut self, message: Message) -> Self { + self.on_submit = Some(message); + self + } + + /// Sets the message that should be produced when the [`TextInput`] is + /// focused and the enter key is pressed, if `Some`. + pub fn on_submit_maybe(mut self, on_submit: Option) -> Self { + self.on_submit = on_submit; + self + } + + /// Sets the message that should be produced when some text is pasted into + /// the [`TextInput`]. + pub fn on_paste(mut self, on_paste: impl Fn(String) -> Message + 'a) -> Self { + self.on_paste = Some(Box::new(on_paste)); + self + } + + /// Sets the message that should be produced when some text is pasted into + /// the [`TextInput`], if `Some`. + pub fn on_paste_maybe(mut self, on_paste: Option Message + 'a>) -> Self { + self.on_paste = on_paste.map(|f| Box::new(f) as _); + self + } + + /// Sets the [`Font`] of the [`TextInput`]. + /// + /// [`Font`]: text::Renderer::Font + pub fn font(mut self, font: Renderer::Font) -> Self { + self.font = Some(font); + self + } + + /// Sets the [`Icon`] of the [`TextInput`]. + pub fn icon(mut self, icon: Icon) -> Self { + self.icon = Some(icon); + self + } + + /// Sets the width of the [`TextInput`]. + pub fn width(mut self, width: impl Into) -> Self { + self.width = width.into(); + self + } + + /// Sets the [`Padding`] of the [`TextInput`]. + pub fn padding>(mut self, padding: P) -> Self { + self.padding = padding.into(); + self + } + + /// Sets the text size of the [`TextInput`]. + pub fn size(mut self, size: impl Into) -> Self { + self.size = Some(size.into()); + self + } + + /// Sets the [`text::LineHeight`] of the [`TextInput`]. + pub fn line_height(mut self, line_height: impl Into) -> Self { + self.line_height = line_height.into(); + self + } + + /// Sets the horizontal alignment of the [`TextInput`]. + pub fn align_x(mut self, alignment: impl Into) -> Self { + self.alignment = alignment.into(); + self + } + + /// Sets the style of the [`TextInput`]. + #[must_use] + pub fn style(mut self, style: impl Fn(&Theme, Status) -> Style + 'a) -> Self + where + Theme::Class<'a>: From>, + { + self.class = (Box::new(style) as StyleFn<'a, Theme>).into(); + self + } + + /// Sets the style class of the [`TextInput`]. + #[must_use] + pub fn class(mut self, class: impl Into>) -> Self { + self.class = class.into(); + self + } + + /// Lays out the [`TextInput`], overriding its [`Value`] if provided. + /// + /// [`Renderer`]: text::Renderer + pub fn layout( + &mut self, + tree: &mut Tree, + renderer: &Renderer, + limits: &layout::Limits, + value: Option<&Value>, + ) -> layout::Node { + let state = tree.state.downcast_mut::>(); + let value = value.unwrap_or(&self.value); + + let font = self.font.unwrap_or_else(|| renderer.default_font()); + let text_size = self.size.unwrap_or_else(|| renderer.default_size()); + let padding = self.padding.fit(Size::ZERO, limits.max()); + let height = self.line_height.to_absolute(text_size); + + let limits = limits.width(self.width).shrink(padding); + let text_bounds = limits.resolve(self.width, height, Size::ZERO); + + let placeholder_text = Text { + font, + line_height: self.line_height, + content: self.placeholder.as_str(), + bounds: Size::new(f32::INFINITY, text_bounds.height), + size: text_size, + align_x: text::Alignment::Default, + align_y: alignment::Vertical::Center, + shaping: text::Shaping::Advanced, + wrapping: text::Wrapping::default(), + }; + + let _ = state.placeholder.update(placeholder_text); + + let secure_value = self.is_secure.then(|| value.secure()); + let value = secure_value.as_ref().unwrap_or(value); + + let _ = state.value.update(Text { + content: &value.to_string(), + ..placeholder_text + }); + + if let Some(icon) = &self.icon { + let mut content = [0; 4]; + + let icon_text = Text { + line_height: self.line_height, + content: icon.code_point.encode_utf8(&mut content) as &_, + font: icon.font, + size: icon.size.unwrap_or_else(|| renderer.default_size()), + bounds: Size::new(f32::INFINITY, text_bounds.height), + align_x: text::Alignment::Center, + align_y: alignment::Vertical::Center, + shaping: text::Shaping::Advanced, + wrapping: text::Wrapping::default(), + }; + + let _ = state.icon.update(icon_text); + + let icon_width = state.icon.min_width(); + + let (text_position, icon_position) = match icon.side { + Side::Left => ( + Point::new(padding.left + icon_width + icon.spacing, padding.top), + Point::new(padding.left, padding.top), + ), + Side::Right => ( + Point::new(padding.left, padding.top), + Point::new(padding.left + text_bounds.width - icon_width, padding.top), + ), + }; + + let text_node = + layout::Node::new(text_bounds - Size::new(icon_width + icon.spacing, 0.0)) + .move_to(text_position); + + let icon_node = + layout::Node::new(Size::new(icon_width, text_bounds.height)).move_to(icon_position); + + layout::Node::with_children(text_bounds.expand(padding), vec![text_node, icon_node]) + } else { + let text = + layout::Node::new(text_bounds).move_to(Point::new(padding.left, padding.top)); + + layout::Node::with_children(text_bounds.expand(padding), vec![text]) + } + } + + fn input_method<'b>( + &self, + state: &'b State, + layout: Layout<'_>, + value: &Value, + ) -> InputMethod<&'b str> { + let Some(Focus { + is_window_focused: true, + .. + }) = &state.is_focused + else { + return InputMethod::Disabled; + }; + + let secure_value = self.is_secure.then(|| value.secure()); + let value = secure_value.as_ref().unwrap_or(value); + + let text_bounds = layout.children().next().unwrap().bounds(); + + let caret_index = match state.cursor.state(value) { + cursor::State::Index(position) => position, + cursor::State::Selection { start, end } => start.min(end), + }; + + let text = state.value.raw(); + let (cursor_x, scroll_offset) = + measure_cursor_and_scroll_offset(text, text_bounds, caret_index); + + let alignment_offset = + alignment_offset(text_bounds.width, text.min_width(), self.alignment); + + let x = (text_bounds.x + cursor_x).floor() - scroll_offset + alignment_offset; + + InputMethod::Enabled { + cursor: Rectangle::new( + Point::new(x, text_bounds.y), + Size::new(1.0, text_bounds.height), + ), + purpose: if self.is_secure { + input_method::Purpose::Secure + } else { + input_method::Purpose::Normal + }, + preedit: state.preedit.as_ref().map(input_method::Preedit::as_ref), + } + } + + /// Draws the [`TextInput`] with the given [`Renderer`], overriding its + /// [`Value`] if provided. + /// + /// [`Renderer`]: text::Renderer + pub fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + layout: Layout<'_>, + _cursor: mouse::Cursor, + value: Option<&Value>, + viewport: &Rectangle, + ) { + let state = tree.state.downcast_ref::>(); + let value = value.unwrap_or(&self.value); + let is_disabled = self.on_input.is_none(); + + let secure_value = self.is_secure.then(|| value.secure()); + let value = secure_value.as_ref().unwrap_or(value); + + let bounds = layout.bounds(); + + let mut children_layout = layout.children(); + let text_bounds = children_layout.next().unwrap().bounds(); + + let style = theme.style(&self.class, self.last_status.unwrap_or(Status::Disabled)); + + renderer.fill_quad( + renderer::Quad { + bounds, + border: style.border, + ..renderer::Quad::default() + }, + style.background, + ); + + if self.icon.is_some() { + let icon_layout = children_layout.next().unwrap(); + + let icon = state.icon.raw(); + + renderer.fill_paragraph( + icon, + icon_layout.bounds().anchor( + icon.min_bounds(), + Alignment::Center, + Alignment::Center, + ), + style.icon, + *viewport, + ); + } + + let text = value.to_string(); + + let (cursor, offset, is_selecting) = if let Some(focus) = state + .is_focused + .as_ref() + .filter(|focus| focus.is_window_focused) + { + match state.cursor.state(value) { + cursor::State::Index(position) => { + let (text_value_width, offset) = + measure_cursor_and_scroll_offset(state.value.raw(), text_bounds, position); + + let is_cursor_visible = !is_disabled + && ((focus.now - focus.updated_at).as_millis() + / CURSOR_BLINK_INTERVAL_MILLIS) + .is_multiple_of(2); + + let cursor = if is_cursor_visible { + Some(( + renderer::Quad { + bounds: Rectangle { + x: (text_bounds.x + text_value_width).floor(), + y: text_bounds.y, + width: 1.0, + height: text_bounds.height, + }, + ..renderer::Quad::default() + }, + style.value, + )) + } else { + None + }; + + (cursor, offset, false) + } + cursor::State::Selection { start, end } => { + let left = start.min(end); + let right = end.max(start); + + let (left_position, left_offset) = + measure_cursor_and_scroll_offset(state.value.raw(), text_bounds, left); + + let (right_position, right_offset) = + measure_cursor_and_scroll_offset(state.value.raw(), text_bounds, right); + + let width = right_position - left_position; + + ( + Some(( + renderer::Quad { + bounds: Rectangle { + x: text_bounds.x + left_position, + y: text_bounds.y, + width, + height: text_bounds.height, + }, + ..renderer::Quad::default() + }, + style.selection, + )), + if end == right { + right_offset + } else { + left_offset + }, + true, + ) + } + } + } else { + (None, 0.0, false) + }; + + let draw = |renderer: &mut Renderer, viewport| { + let paragraph = if text.is_empty() + && state + .preedit + .as_ref() + .map(|preedit| preedit.content.is_empty()) + .unwrap_or(true) + { + state.placeholder.raw() + } else { + state.value.raw() + }; + + let alignment_offset = + alignment_offset(text_bounds.width, paragraph.min_width(), self.alignment); + + if let Some((cursor, color)) = cursor { + renderer.with_translation( + Vector::new(alignment_offset - offset, 0.0), + |renderer| { + renderer.fill_quad(cursor, color); + }, + ); + } else { + renderer.with_translation(Vector::ZERO, |_| {}); + } + + renderer.fill_paragraph( + paragraph, + text_bounds.anchor(paragraph.min_bounds(), Alignment::Start, Alignment::Center) + + Vector::new(alignment_offset - offset, 0.0), + if text.is_empty() { + style.placeholder + } else { + style.value + }, + viewport, + ); + }; + + if is_selecting { + renderer.with_layer(text_bounds, |renderer| draw(renderer, *viewport)); + } else { + draw(renderer, text_bounds); + } + } +} + +impl Widget + for TextInput<'_, Message, Theme, Renderer> +where + Message: Clone, + Theme: Catalog, + Renderer: text::Renderer, +{ + fn tag(&self) -> tree::Tag { + tree::Tag::of::>() + } + + fn state(&self) -> tree::State { + tree::State::new(State::::new()) + } + + fn diff(&self, tree: &mut Tree) { + let state = tree.state.downcast_mut::>(); + + // Stop pasting if input becomes disabled + if self.on_input.is_none() { + state.is_pasting = None; + } + } + + fn size(&self) -> Size { + Size { + width: self.width, + height: Length::Shrink, + } + } + + fn layout( + &mut self, + tree: &mut Tree, + renderer: &Renderer, + limits: &layout::Limits, + ) -> layout::Node { + self.layout(tree, renderer, limits, None) + } + + fn operate( + &mut self, + tree: &mut Tree, + layout: Layout<'_>, + _renderer: &Renderer, + operation: &mut dyn Operation, + ) { + let state = tree.state.downcast_mut::>(); + + operation.text_input(self.id.as_ref(), layout.bounds(), state); + operation.focusable(self.id.as_ref(), layout.bounds(), state); + } + + fn update( + &mut self, + tree: &mut Tree, + event: &Event, + layout: Layout<'_>, + cursor: mouse::Cursor, + renderer: &Renderer, + clipboard: &mut dyn Clipboard, + shell: &mut Shell<'_, Message>, + _viewport: &Rectangle, + ) { + let update_cache = |state, value| { + replace_paragraph( + renderer, + state, + layout, + value, + self.font, + self.size, + self.line_height, + ); + }; + + match &event { + Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerPressed { .. }) => { + let state = state::(tree); + let cursor_before = state.cursor; + + let click_position = cursor.position_over(layout.bounds()); + + state.is_focused = if click_position.is_some() { + let now = Instant::now(); + + Some(Focus { + updated_at: now, + now, + is_window_focused: true, + }) + } else { + None + }; + + if let Some(cursor_position) = click_position { + let text_layout = layout.children().next().unwrap(); + + let target = { + let text_bounds = text_layout.bounds(); + + let alignment_offset = alignment_offset( + text_bounds.width, + state.value.raw().min_width(), + self.alignment, + ); + + cursor_position.x - text_bounds.x - alignment_offset + }; + + let click = + mouse::Click::new(cursor_position, mouse::Button::Left, state.last_click); + + match click.kind() { + click::Kind::Single => { + let position = if target > 0.0 { + let value = if self.is_secure { + self.value.secure() + } else { + self.value.clone() + }; + + find_cursor_position(text_layout.bounds(), &value, state, target) + } else { + None + } + .unwrap_or(0); + + if state.keyboard_modifiers.shift() { + state + .cursor + .select_range(state.cursor.start(&self.value), position); + } else { + state.cursor.move_to(position); + } + + state.is_dragging = Some(Drag::Select); + } + click::Kind::Double => { + if self.is_secure { + state.cursor.select_all(&self.value); + + state.is_dragging = None; + } else { + let position = find_cursor_position( + text_layout.bounds(), + &self.value, + state, + target, + ) + .unwrap_or(0); + + state.cursor.select_range( + self.value.previous_start_of_word(position), + self.value.next_end_of_word(position), + ); + + state.is_dragging = Some(Drag::SelectWords { anchor: position }); + } + } + click::Kind::Triple => { + state.cursor.select_all(&self.value); + state.is_dragging = None; + } + } + + state.last_click = Some(click); + + if cursor_before != state.cursor { + shell.request_redraw(); + } + + shell.capture_event(); + } + } + Event::Mouse(mouse::Event::ButtonReleased(mouse::Button::Left)) + | Event::Touch(touch::Event::FingerLifted { .. }) + | Event::Touch(touch::Event::FingerLost { .. }) => { + state::(tree).is_dragging = None; + } + Event::Mouse(mouse::Event::CursorMoved { position }) + | Event::Touch(touch::Event::FingerMoved { position, .. }) => { + let state = state::(tree); + + if let Some(is_dragging) = &state.is_dragging { + let text_layout = layout.children().next().unwrap(); + + let target = { + let text_bounds = text_layout.bounds(); + + let alignment_offset = alignment_offset( + text_bounds.width, + state.value.raw().min_width(), + self.alignment, + ); + + position.x - text_bounds.x - alignment_offset + }; + + let value = if self.is_secure { + self.value.secure() + } else { + self.value.clone() + }; + + let position = + find_cursor_position(text_layout.bounds(), &value, state, target) + .unwrap_or(0); + + let selection_before = state.cursor.selection(&value); + + match is_dragging { + Drag::Select => { + state + .cursor + .select_range(state.cursor.start(&value), position); + } + Drag::SelectWords { anchor } => { + if position < *anchor { + state.cursor.select_range( + self.value.previous_start_of_word(position), + self.value.next_end_of_word(*anchor), + ); + } else { + state.cursor.select_range( + self.value.previous_start_of_word(*anchor), + self.value.next_end_of_word(position), + ); + } + } + } + + if let Some(focus) = &mut state.is_focused { + focus.updated_at = Instant::now(); + } + + if selection_before != state.cursor.selection(&value) { + shell.request_redraw(); + } + + shell.capture_event(); + } + } + Event::Keyboard(keyboard::Event::KeyPressed { + key, + text, + modified_key, + physical_key, + .. + }) => { + let state = state::(tree); + + if let Some(focus) = &mut state.is_focused { + let modifiers = state.keyboard_modifiers; + + // getting input according to selected layout + // XKB + // + let mut xkb_sym: Option = None; + if let Some(st) = self.xkb_state.as_mut() { + if let Some(xkb_code) = kira_xkb::physical_to_xkb_keycode(physical_key) { + let k_c = xkb::Keycode::new(xkb_code); + + let sym = st.key_get_utf8(k_c); + if sym.len() > 0 { + xkb_sym = Some(sym); + } + + st.update_key(k_c, xkb::KeyDirection::Down); + } + } + + match key.to_latin(*physical_key) { + Some('c') if state.keyboard_modifiers.command() && !self.is_secure => { + if let Some((start, end)) = state.cursor.selection(&self.value) { + clipboard.write( + clipboard::Kind::Standard, + self.value.select(start, end).to_string(), + ); + } + + shell.capture_event(); + return; + } + Some('x') if state.keyboard_modifiers.command() && !self.is_secure => { + let Some(on_input) = &self.on_input else { + return; + }; + + if let Some((start, end)) = state.cursor.selection(&self.value) { + clipboard.write( + clipboard::Kind::Standard, + self.value.select(start, end).to_string(), + ); + } + + let mut editor = Editor::new(&mut self.value, &mut state.cursor); + editor.delete(); + + let message = (on_input)(editor.contents()); + shell.publish(message); + shell.capture_event(); + + focus.updated_at = Instant::now(); + update_cache(state, &self.value); + return; + } + Some('v') + if state.keyboard_modifiers.command() + && !state.keyboard_modifiers.alt() => + { + let Some(on_input) = &self.on_input else { + return; + }; + + let content = match state.is_pasting.take() { + Some(content) => content, + None => { + let content: String = clipboard + .read(clipboard::Kind::Standard) + .unwrap_or_default() + .chars() + .filter(|c| !c.is_control()) + .collect(); + + Value::new(&content) + } + }; + + let mut editor = Editor::new(&mut self.value, &mut state.cursor); + editor.paste(content.clone()); + + let message = if let Some(paste) = &self.on_paste { + (paste)(editor.contents()) + } else { + (on_input)(editor.contents()) + }; + shell.publish(message); + shell.capture_event(); + + state.is_pasting = Some(content); + focus.updated_at = Instant::now(); + update_cache(state, &self.value); + return; + } + Some('a') if state.keyboard_modifiers.command() => { + let cursor_before = state.cursor; + + state.cursor.select_all(&self.value); + + if cursor_before != state.cursor { + focus.updated_at = Instant::now(); + + shell.request_redraw(); + } + + shell.capture_event(); + return; + } + _ => {} + } + + // if we have layout translated XKB input + if let Some(xkb_text) = xkb_sym { + let Some(on_input) = &self.on_input else { + return; + }; + + state.is_pasting = None; + + if let Some(c) = xkb_text.chars().next().filter(|c| !c.is_control()) { + let mut editor = Editor::new(&mut self.value, &mut state.cursor); + + editor.insert(c); + + let message = (on_input)(editor.contents()); + shell.publish(message); + shell.capture_event(); + + focus.updated_at = Instant::now(); + update_cache(state, &self.value); + return; + } + } else if let Some(text) = text { + let Some(on_input) = &self.on_input else { + return; + }; + + state.is_pasting = None; + + if let Some(c) = text.chars().next().filter(|c| !c.is_control()) { + let mut editor = Editor::new(&mut self.value, &mut state.cursor); + + editor.insert(c); + + let message = (on_input)(editor.contents()); + shell.publish(message); + shell.capture_event(); + + focus.updated_at = Instant::now(); + update_cache(state, &self.value); + return; + } + } + + #[cfg(target_os = "macos")] + let macos_shortcut = crate::text_editor::convert_macos_shortcut(key, modifiers); + + #[cfg(target_os = "macos")] + let modified_key = macos_shortcut.as_ref().unwrap_or(modified_key); + + match modified_key.as_ref() { + keyboard::Key::Named(key::Named::Enter) => { + if let Some(on_submit) = self.on_submit.clone() { + shell.publish(on_submit); + shell.capture_event(); + } + } + keyboard::Key::Named(key::Named::Backspace) => { + let Some(on_input) = &self.on_input else { + return; + }; + + if state.cursor.selection(&self.value).is_none() { + if (self.is_secure && modifiers.jump()) || modifiers.macos_command() + { + state + .cursor + .select_range(state.cursor.start(&self.value), 0); + } else if modifiers.jump() { + state.cursor.select_left_by_words(&self.value); + } + } + + let mut editor = Editor::new(&mut self.value, &mut state.cursor); + editor.backspace(); + + let message = (on_input)(editor.contents()); + shell.publish(message); + shell.capture_event(); + + focus.updated_at = Instant::now(); + update_cache(state, &self.value); + } + keyboard::Key::Named(key::Named::Delete) => { + let Some(on_input) = &self.on_input else { + return; + }; + + if state.cursor.selection(&self.value).is_none() { + if (self.is_secure && modifiers.jump()) || modifiers.macos_command() + { + state.cursor.select_range( + state.cursor.start(&self.value), + self.value.len(), + ); + } else if modifiers.jump() { + state.cursor.select_right_by_words(&self.value); + } + } + + let mut editor = Editor::new(&mut self.value, &mut state.cursor); + editor.delete(); + + let message = (on_input)(editor.contents()); + shell.publish(message); + shell.capture_event(); + + focus.updated_at = Instant::now(); + update_cache(state, &self.value); + } + keyboard::Key::Named(key::Named::Home) => { + let cursor_before = state.cursor; + + if modifiers.shift() { + state + .cursor + .select_range(state.cursor.start(&self.value), 0); + } else { + state.cursor.move_to(0); + } + + if cursor_before != state.cursor { + focus.updated_at = Instant::now(); + + shell.request_redraw(); + } + + shell.capture_event(); + } + keyboard::Key::Named(key::Named::End) => { + let cursor_before = state.cursor; + + if modifiers.shift() { + state.cursor.select_range( + state.cursor.start(&self.value), + self.value.len(), + ); + } else { + state.cursor.move_to(self.value.len()); + } + + if cursor_before != state.cursor { + focus.updated_at = Instant::now(); + + shell.request_redraw(); + } + + shell.capture_event(); + } + keyboard::Key::Named(key::Named::ArrowLeft) => { + let cursor_before = state.cursor; + + if (self.is_secure && modifiers.jump()) || modifiers.macos_command() { + if modifiers.shift() { + state + .cursor + .select_range(state.cursor.start(&self.value), 0); + } else { + state.cursor.move_to(0); + } + } else if modifiers.jump() { + if modifiers.shift() { + state.cursor.select_left_by_words(&self.value); + } else { + state.cursor.move_left_by_words(&self.value); + } + } else if modifiers.shift() { + state.cursor.select_left(&self.value); + } else { + state.cursor.move_left(&self.value); + } + + if cursor_before != state.cursor { + focus.updated_at = Instant::now(); + + shell.request_redraw(); + } + + shell.capture_event(); + } + keyboard::Key::Named(key::Named::ArrowRight) => { + let cursor_before = state.cursor; + + if (self.is_secure && modifiers.jump()) || modifiers.macos_command() { + if modifiers.shift() { + state.cursor.select_range( + state.cursor.start(&self.value), + self.value.len(), + ); + } else { + state.cursor.move_to(self.value.len()); + } + } else if modifiers.jump() { + if modifiers.shift() { + state.cursor.select_right_by_words(&self.value); + } else { + state.cursor.move_right_by_words(&self.value); + } + } else if modifiers.shift() { + state.cursor.select_right(&self.value); + } else { + state.cursor.move_right(&self.value); + } + + if cursor_before != state.cursor { + focus.updated_at = Instant::now(); + + shell.request_redraw(); + } + + shell.capture_event(); + } + keyboard::Key::Named(key::Named::Escape) => { + state.is_focused = None; + state.is_dragging = None; + state.is_pasting = None; + + state.keyboard_modifiers = keyboard::Modifiers::default(); + + shell.capture_event(); + } + _ => {} + } + } + } + Event::Keyboard(keyboard::Event::KeyReleased { + key, physical_key, .. + }) => { + let state = state::(tree); + + // XKB state + if state.is_focused.is_some() { + if let Some(st) = self.xkb_state.as_mut() { + if let Some(xkb_code) = kira_xkb::physical_to_xkb_keycode(physical_key) { + let k_c = xkb::Keycode::new(xkb_code); + st.update_key(k_c, xkb::KeyDirection::Up); + } + } + } + + if state.is_focused.is_some() + && let keyboard::Key::Character("v") = key.as_ref() + { + state.is_pasting = None; + + shell.capture_event(); + } + + state.is_pasting = None; + } + Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => { + let state = state::(tree); + + state.keyboard_modifiers = *modifiers; + } + Event::InputMethod(event) => match event { + input_method::Event::Opened | input_method::Event::Closed => { + let state = state::(tree); + + state.preedit = matches!(event, input_method::Event::Opened) + .then(input_method::Preedit::new); + + shell.request_redraw(); + } + input_method::Event::Preedit(content, selection) => { + let state = state::(tree); + + if state.is_focused.is_some() { + state.preedit = Some(input_method::Preedit { + content: content.to_owned(), + selection: selection.clone(), + text_size: self.size, + }); + + shell.request_redraw(); + } + } + input_method::Event::Commit(text) => { + let state = state::(tree); + + if let Some(focus) = &mut state.is_focused { + let Some(on_input) = &self.on_input else { + return; + }; + + let mut editor = Editor::new(&mut self.value, &mut state.cursor); + editor.paste(Value::new(text)); + + focus.updated_at = Instant::now(); + state.is_pasting = None; + + let message = (on_input)(editor.contents()); + shell.publish(message); + shell.capture_event(); + + update_cache(state, &self.value); + } + } + }, + Event::Window(window::Event::Unfocused) => { + let state = state::(tree); + + if let Some(focus) = &mut state.is_focused { + focus.is_window_focused = false; + } + } + Event::Window(window::Event::Focused) => { + let state = state::(tree); + + if let Some(focus) = &mut state.is_focused { + focus.is_window_focused = true; + focus.updated_at = Instant::now(); + + shell.request_redraw(); + } + } + Event::Window(window::Event::RedrawRequested(now)) => { + let state = state::(tree); + + if let Some(focus) = &mut state.is_focused + && focus.is_window_focused + { + if matches!(state.cursor.state(&self.value), cursor::State::Index(_)) { + focus.now = *now; + + let millis_until_redraw = CURSOR_BLINK_INTERVAL_MILLIS + - (*now - focus.updated_at).as_millis() % CURSOR_BLINK_INTERVAL_MILLIS; + + shell.request_redraw_at( + *now + Duration::from_millis(millis_until_redraw as u64), + ); + } + + shell.request_input_method(&self.input_method(state, layout, &self.value)); + } + } + _ => {} + } + + let state = state::(tree); + let is_disabled = self.on_input.is_none(); + + let status = if is_disabled { + Status::Disabled + } else if state.is_focused() { + Status::Focused { + is_hovered: cursor.is_over(layout.bounds()), + } + } else if cursor.is_over(layout.bounds()) { + Status::Hovered + } else { + Status::Active + }; + + if let Event::Window(window::Event::RedrawRequested(_now)) = event { + self.last_status = Some(status); + } else if self + .last_status + .is_some_and(|last_status| status != last_status) + { + shell.request_redraw(); + } + } + + fn draw( + &self, + tree: &Tree, + renderer: &mut Renderer, + theme: &Theme, + _style: &renderer::Style, + layout: Layout<'_>, + cursor: mouse::Cursor, + viewport: &Rectangle, + ) { + self.draw(tree, renderer, theme, layout, cursor, None, viewport); + } + + fn mouse_interaction( + &self, + _tree: &Tree, + layout: Layout<'_>, + cursor: mouse::Cursor, + _viewport: &Rectangle, + _renderer: &Renderer, + ) -> mouse::Interaction { + if cursor.is_over(layout.bounds()) { + if self.on_input.is_none() { + mouse::Interaction::Idle + } else { + mouse::Interaction::Text + } + } else { + mouse::Interaction::default() + } + } +} + +impl<'a, Message, Theme, Renderer> From> + for Element<'a, Message, Theme, Renderer> +where + Message: Clone + 'a, + Theme: Catalog + 'a, + Renderer: text::Renderer + 'a, +{ + fn from( + text_input: TextInput<'a, Message, Theme, Renderer>, + ) -> Element<'a, Message, Theme, Renderer> { + Element::new(text_input) + } +} + +/// The content of the [`Icon`]. +#[derive(Debug, Clone)] +pub struct Icon { + /// The font that will be used to display the `code_point`. + pub font: Font, + /// The unicode code point that will be used as the icon. + pub code_point: char, + /// The font size of the content. + pub size: Option, + /// The spacing between the [`Icon`] and the text in a [`TextInput`]. + pub spacing: f32, + /// The side of a [`TextInput`] where to display the [`Icon`]. + pub side: Side, +} + +/// The side of a [`TextInput`]. +#[derive(Debug, Clone)] +pub enum Side { + /// The left side of a [`TextInput`]. + Left, + /// The right side of a [`TextInput`]. + Right, +} + +/// The state of a [`TextInput`]. +#[derive(Debug, Default, Clone)] +pub struct State { + value: paragraph::Plain

, + placeholder: paragraph::Plain

, + icon: paragraph::Plain

, + is_focused: Option, + is_dragging: Option, + is_pasting: Option, + preedit: Option, + last_click: Option, + cursor: Cursor, + keyboard_modifiers: keyboard::Modifiers, + // TODO: Add stateful horizontal scrolling offset +} + +fn state(tree: &mut Tree) -> &mut State { + tree.state.downcast_mut::>() +} + +#[derive(Debug, Clone)] +struct Focus { + updated_at: Instant, + now: Instant, + is_window_focused: bool, +} + +#[derive(Debug, Clone)] +enum Drag { + Select, + SelectWords { anchor: usize }, +} + +impl State

{ + /// Creates a new [`State`], representing an unfocused [`TextInput`]. + pub fn new() -> Self { + Self::default() + } + + /// Returns whether the [`TextInput`] is currently focused or not. + pub fn is_focused(&self) -> bool { + self.is_focused.is_some() + } + + /// Returns the [`Cursor`] of the [`TextInput`]. + pub fn cursor(&self) -> Cursor { + self.cursor + } + + /// Focuses the [`TextInput`]. + pub fn focus(&mut self) { + let now = Instant::now(); + + self.is_focused = Some(Focus { + updated_at: now, + now, + is_window_focused: true, + }); + + self.move_cursor_to_end(); + } + + /// Unfocuses the [`TextInput`]. + pub fn unfocus(&mut self) { + self.is_focused = None; + } + + /// Moves the [`Cursor`] of the [`TextInput`] to the front of the input text. + pub fn move_cursor_to_front(&mut self) { + self.cursor.move_to(0); + } + + /// Moves the [`Cursor`] of the [`TextInput`] to the end of the input text. + pub fn move_cursor_to_end(&mut self) { + self.cursor.move_to(usize::MAX); + } + + /// Moves the [`Cursor`] of the [`TextInput`] to an arbitrary location. + pub fn move_cursor_to(&mut self, position: usize) { + self.cursor.move_to(position); + } + + /// Selects all the content of the [`TextInput`]. + pub fn select_all(&mut self) { + self.cursor.select_range(0, usize::MAX); + } + + /// Selects the given range of the content of the [`TextInput`]. + pub fn select_range(&mut self, start: usize, end: usize) { + self.cursor.select_range(start, end); + } +} + +impl operation::Focusable for State

{ + fn is_focused(&self) -> bool { + State::is_focused(self) + } + + fn focus(&mut self) { + State::focus(self); + } + + fn unfocus(&mut self) { + State::unfocus(self); + } +} + +impl operation::TextInput for State

{ + fn text(&self) -> &str { + if self.value.content().is_empty() { + self.placeholder.content() + } else { + self.value.content() + } + } + + fn move_cursor_to_front(&mut self) { + State::move_cursor_to_front(self); + } + + fn move_cursor_to_end(&mut self) { + State::move_cursor_to_end(self); + } + + fn move_cursor_to(&mut self, position: usize) { + State::move_cursor_to(self, position); + } + + fn select_all(&mut self) { + State::select_all(self); + } + + fn select_range(&mut self, start: usize, end: usize) { + State::select_range(self, start, end); + } +} + +fn offset(text_bounds: Rectangle, value: &Value, state: &State

) -> f32 { + if state.is_focused() { + let cursor = state.cursor(); + + let focus_position = match cursor.state(value) { + cursor::State::Index(i) => i, + cursor::State::Selection { end, .. } => end, + }; + + let (_, offset) = + measure_cursor_and_scroll_offset(state.value.raw(), text_bounds, focus_position); + + offset + } else { + 0.0 + } +} + +fn measure_cursor_and_scroll_offset( + paragraph: &impl text::Paragraph, + text_bounds: Rectangle, + cursor_index: usize, +) -> (f32, f32) { + let grapheme_position = paragraph + .grapheme_position(0, cursor_index) + .unwrap_or(Point::ORIGIN); + + let offset = ((grapheme_position.x + 5.0) - text_bounds.width).max(0.0); + + (grapheme_position.x, offset) +} + +/// Computes the position of the text cursor at the given X coordinate of +/// a [`TextInput`]. +fn find_cursor_position( + text_bounds: Rectangle, + value: &Value, + state: &State

, + x: f32, +) -> Option { + let offset = offset(text_bounds, value, state); + let value = value.to_string(); + + let char_offset = state + .value + .raw() + .hit_test(Point::new(x + offset, text_bounds.height / 2.0)) + .map(text::Hit::cursor)?; + + Some( + unicode_segmentation::UnicodeSegmentation::graphemes( + &value[..char_offset.min(value.len())], + true, + ) + .count(), + ) +} + +fn replace_paragraph( + renderer: &Renderer, + state: &mut State, + layout: Layout<'_>, + value: &Value, + font: Option, + text_size: Option, + line_height: text::LineHeight, +) where + Renderer: text::Renderer, +{ + let font = font.unwrap_or_else(|| renderer.default_font()); + let text_size = text_size.unwrap_or_else(|| renderer.default_size()); + + let mut children_layout = layout.children(); + let text_bounds = children_layout.next().unwrap().bounds(); + + state.value = paragraph::Plain::new(Text { + font, + line_height, + content: value.to_string(), + bounds: Size::new(f32::INFINITY, text_bounds.height), + size: text_size, + align_x: text::Alignment::Default, + align_y: alignment::Vertical::Center, + shaping: text::Shaping::Advanced, + wrapping: text::Wrapping::default(), + }); +} + +const CURSOR_BLINK_INTERVAL_MILLIS: u128 = 500; + +/// The possible status of a [`TextInput`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Status { + /// The [`TextInput`] can be interacted with. + Active, + /// The [`TextInput`] is being hovered. + Hovered, + /// The [`TextInput`] is focused. + Focused { + /// Whether the [`TextInput`] is hovered, while focused. + is_hovered: bool, + }, + /// The [`TextInput`] cannot be interacted with. + Disabled, +} + +/// The appearance of a text input. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Style { + /// The [`Background`] of the text input. + pub background: Background, + /// The [`Border`] of the text input. + pub border: Border, + /// The [`Color`] of the icon of the text input. + pub icon: Color, + /// The [`Color`] of the placeholder of the text input. + pub placeholder: Color, + /// The [`Color`] of the value of the text input. + pub value: Color, + /// The [`Color`] of the selection of the text input. + pub selection: Color, +} + +/// The theme catalog of a [`TextInput`]. +pub trait Catalog: Sized { + /// The item class of the [`Catalog`]. + type Class<'a>; + + /// The default class produced by the [`Catalog`]. + fn default<'a>() -> Self::Class<'a>; + + /// The [`Style`] of a class with the given status. + fn style(&self, class: &Self::Class<'_>, status: Status) -> Style; +} + +/// A styling function for a [`TextInput`]. +/// +/// This is just a boxed closure: `Fn(&Theme, Status) -> Style`. +pub type StyleFn<'a, Theme> = Box Style + 'a>; + +impl Catalog for Theme { + type Class<'a> = StyleFn<'a, Self>; + + fn default<'a>() -> Self::Class<'a> { + Box::new(default) + } + + fn style(&self, class: &Self::Class<'_>, status: Status) -> Style { + class(self, status) + } +} + +/// The default style of a [`TextInput`]. +pub fn default(theme: &Theme, status: Status) -> Style { + let palette = theme.extended_palette(); + + let active = Style { + background: Background::Color(palette.background.base.color), + border: Border { + radius: 2.0.into(), + width: 1.0, + color: palette.background.strong.color, + }, + icon: palette.background.weak.text, + placeholder: palette.secondary.base.color, + value: palette.background.base.text, + selection: palette.primary.weak.color, + }; + + match status { + Status::Active => active, + Status::Hovered => Style { + border: Border { + color: palette.background.base.text, + ..active.border + }, + ..active + }, + Status::Focused { .. } => Style { + border: Border { + color: palette.primary.strong.color, + ..active.border + }, + ..active + }, + Status::Disabled => Style { + background: Background::Color(palette.background.weak.color), + value: active.placeholder, + placeholder: palette.background.strongest.color, + ..active + }, + } +} + +fn alignment_offset( + text_bounds_width: f32, + text_min_width: f32, + alignment: alignment::Horizontal, +) -> f32 { + if text_min_width > text_bounds_width { + 0.0 + } else { + match alignment { + alignment::Horizontal::Left => 0.0, + alignment::Horizontal::Center => (text_bounds_width - text_min_width) / 2.0, + alignment::Horizontal::Right => text_bounds_width - text_min_width, + } + } +} diff --git a/src/kira_text_input/value.rs b/src/kira_text_input/value.rs new file mode 100644 index 0000000..b5cf7aa --- /dev/null +++ b/src/kira_text_input/value.rs @@ -0,0 +1,136 @@ +use unicode_segmentation::UnicodeSegmentation; + +/// The value of a [`TextInput`]. +/// +/// [`TextInput`]: super::TextInput +// TODO: Reduce allocations, cache results (?) +#[derive(Debug, Clone)] +pub struct Value { + graphemes: Vec, +} + +impl Value { + /// Creates a new [`Value`] from a string slice. + pub fn new(string: &str) -> Self { + let graphemes = UnicodeSegmentation::graphemes(string, true) + .map(String::from) + .collect(); + + Self { graphemes } + } + + /// Returns whether the [`Value`] is empty or not. + /// + /// A [`Value`] is empty when it contains no graphemes. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Returns the total amount of graphemes in the [`Value`]. + pub fn len(&self) -> usize { + self.graphemes.len() + } + + /// Returns the position of the previous start of a word from the given + /// grapheme `index`. + pub fn previous_start_of_word(&self, index: usize) -> usize { + let previous_string = + &self.graphemes[..index.min(self.graphemes.len())].concat(); + + UnicodeSegmentation::split_word_bound_indices(previous_string as &str) + .filter(|(_, word)| !word.trim_start().is_empty()) + .next_back() + .map(|(i, previous_word)| { + index + - UnicodeSegmentation::graphemes(previous_word, true) + .count() + - UnicodeSegmentation::graphemes( + &previous_string[i + previous_word.len()..] as &str, + true, + ) + .count() + }) + .unwrap_or(0) + } + + /// Returns the position of the next end of a word from the given grapheme + /// `index`. + pub fn next_end_of_word(&self, index: usize) -> usize { + let next_string = &self.graphemes[index..].concat(); + + UnicodeSegmentation::split_word_bound_indices(next_string as &str) + .find(|(_, word)| !word.trim_start().is_empty()) + .map(|(i, next_word)| { + index + + UnicodeSegmentation::graphemes(next_word, true).count() + + UnicodeSegmentation::graphemes( + &next_string[..i] as &str, + true, + ) + .count() + }) + .unwrap_or(self.len()) + } + + /// Returns a new [`Value`] containing the graphemes from `start` until the + /// given `end`. + pub fn select(&self, start: usize, end: usize) -> Self { + let graphemes = + self.graphemes[start.min(self.len())..end.min(self.len())].to_vec(); + + Self { graphemes } + } + + /// Returns a new [`Value`] containing the graphemes until the given + /// `index`. + pub fn until(&self, index: usize) -> Self { + let graphemes = self.graphemes[..index.min(self.len())].to_vec(); + + Self { graphemes } + } + + /// Inserts a new `char` at the given grapheme `index`. + pub fn insert(&mut self, index: usize, c: char) { + self.graphemes.insert(index, c.to_string()); + + self.graphemes = + UnicodeSegmentation::graphemes(&self.to_string() as &str, true) + .map(String::from) + .collect(); + } + + /// Inserts a bunch of graphemes at the given grapheme `index`. + pub fn insert_many(&mut self, index: usize, mut value: Value) { + let _ = self + .graphemes + .splice(index..index, value.graphemes.drain(..)); + } + + /// Removes the grapheme at the given `index`. + pub fn remove(&mut self, index: usize) { + let _ = self.graphemes.remove(index); + } + + /// Removes the graphemes from `start` to `end`. + pub fn remove_many(&mut self, start: usize, end: usize) { + let _ = self.graphemes.splice(start..end, std::iter::empty()); + } + + /// Returns a new [`Value`] with all its graphemes replaced with the + /// dot ('•') character. + pub fn secure(&self) -> Self { + Self { + graphemes: std::iter::repeat_n( + String::from("•"), + self.graphemes.len(), + ) + .collect(), + } + } +} + +impl std::fmt::Display for Value { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.graphemes.concat()) + } +} \ No newline at end of file diff --git a/src/kira_xkb.rs b/src/kira_xkb.rs new file mode 100644 index 0000000..1324134 --- /dev/null +++ b/src/kira_xkb.rs @@ -0,0 +1,209 @@ +// We need this file because wayland broke Linux desktop. + +use iced::keyboard::key::{Code, NativeCode, Physical}; + +const XKB_OFFSET: u32 = 8; + +/// +/// Converts iced key::Physical to xkb numeric keycode +/// +pub fn physical_to_xkb_keycode(physical: &Physical) -> Option { + match physical { + Physical::Unidentified(NativeCode::Xkb(code)) => Some(code.clone()), + Physical::Unidentified(_) => None, + Physical::Code(code) => code_to_xkb(code), + } +} + +/// +/// Converts iced key::Code to xkb numeric keycode +/// +pub fn code_to_xkb(code: &Code) -> Option { + let evdev: u32 = match code { + // Alphanumeric & main typing block + Code::Backquote => 41, + Code::Backslash => 43, + Code::BracketLeft => 26, + Code::BracketRight => 27, + Code::Comma => 51, + Code::Digit0 => 11, + Code::Digit1 => 2, + Code::Digit2 => 3, + Code::Digit3 => 4, + Code::Digit4 => 5, + Code::Digit5 => 6, + Code::Digit6 => 7, + Code::Digit7 => 8, + Code::Digit8 => 9, + Code::Digit9 => 10, + Code::Equal => 13, + Code::IntlBackslash => 86, // KEY_102ND + Code::IntlRo => 89, // KEY_RO + Code::IntlYen => 124, // KEY_YEN + Code::KeyA => 30, + Code::KeyB => 48, + Code::KeyC => 46, + Code::KeyD => 32, + Code::KeyE => 18, + Code::KeyF => 33, + Code::KeyG => 34, + Code::KeyH => 35, + Code::KeyI => 23, + Code::KeyJ => 36, + Code::KeyK => 37, + Code::KeyL => 38, + Code::KeyM => 50, + Code::KeyN => 49, + Code::KeyO => 24, + Code::KeyP => 25, + Code::KeyQ => 16, + Code::KeyR => 19, + Code::KeyS => 31, + Code::KeyT => 20, + Code::KeyU => 22, + Code::KeyV => 47, + Code::KeyW => 17, + Code::KeyX => 45, + Code::KeyY => 21, + Code::KeyZ => 44, + Code::Minus => 12, + Code::Period => 52, + Code::Quote => 40, + Code::Semicolon => 39, + Code::Slash => 53, + + // Modifiers, whitespace & editing + Code::AltLeft => 56, + Code::AltRight => 100, + Code::Backspace => 14, + Code::CapsLock => 58, + Code::ContextMenu => 139, // KEY_MENU + Code::ControlLeft => 29, + Code::ControlRight => 97, + Code::Enter => 28, + Code::SuperLeft => 125, // KEY_LEFTMETA + Code::SuperRight => 126, // KEY_RIGHTMETA + Code::ShiftLeft => 42, + Code::ShiftRight => 54, + Code::Space => 57, + Code::Tab => 15, + + // CJK / IME keys + Code::Convert => 92, // KEY_HENKAN + Code::KanaMode => 93, // KEY_KATAKANAHIRAGANA + Code::Lang1 => 122, // KEY_HANGEUL / KEY_HANGUEL + Code::Lang2 => 123, // KEY_HANJA + Code::Lang3 => 90, // KEY_KATAKANA + Code::Lang4 => 91, // KEY_HIRAGANA + Code::Lang5 => 93, // KEY_KATAKANAHIRAGANA + Code::NonConvert => 94, // KEY_MUHENKAN + Code::Hiragana => 91, // KEY_HIRAGANA + Code::Katakana => 90, // KEY_KATAKANA + + // Navigation & cluster + Code::Delete => 111, + Code::End => 107, + Code::Help => 138, // KEY_HELP + Code::Home => 102, + Code::Insert => 110, + Code::PageDown => 109, + Code::PageUp => 104, + Code::ArrowDown => 108, + Code::ArrowLeft => 105, + Code::ArrowRight => 106, + Code::ArrowUp => 103, + + // Numpad + Code::NumLock => 69, + Code::Numpad0 => 82, + Code::Numpad1 => 79, + Code::Numpad2 => 80, + Code::Numpad3 => 81, + Code::Numpad4 => 75, + Code::Numpad5 => 76, + Code::Numpad6 => 77, + Code::Numpad7 => 71, + Code::Numpad8 => 72, + Code::Numpad9 => 73, + Code::NumpadAdd => 78, + Code::NumpadComma => 121, // KEY_KPCOMMA + Code::NumpadDecimal => 83, + Code::NumpadDivide => 98, + Code::NumpadEnter => 96, + Code::NumpadEqual => 117, // KEY_KPEQUAL + Code::NumpadMultiply => 55, + Code::NumpadParenLeft => 179, // KEY_KPLEFTPAREN + Code::NumpadParenRight => 180, // KEY_KPRIGHTPAREN + Code::NumpadSubtract => 74, + + // System, lock & media keys + Code::Escape => 1, + Code::PrintScreen => 99, + Code::ScrollLock => 70, + Code::Pause => 119, + Code::BrowserBack => 158, // KEY_BACK + Code::BrowserFavorites => 156, // KEY_BOOKMARKS + Code::BrowserForward => 159, // KEY_FORWARD + Code::BrowserHome => 172, // KEY_HOMEPAGE + Code::BrowserRefresh => 173, // KEY_REFRESH + Code::BrowserSearch => 217, // KEY_SEARCH + Code::BrowserStop => 128, // KEY_STOP + Code::Eject => 161, // KEY_EJECTCD + Code::LaunchApp1 => 157, // KEY_COMPUTER + Code::LaunchApp2 => 140, // KEY_CALC + Code::LaunchMail => 155, // KEY_MAIL + Code::MediaPlayPause => 164, // KEY_PLAYPAUSE + Code::MediaSelect => 179, // varies by device; None is safer if ambiguous + Code::MediaStop => 166, // KEY_STOPCD + Code::MediaTrackNext => 163, // KEY_NEXTSONG + Code::MediaTrackPrevious => 165, // KEY_PREVIOUSSONG + Code::Power => 116, // KEY_POWER + Code::Sleep => 142, // KEY_SLEEP + Code::AudioVolumeDown => 114, // KEY_VOLUMEDOWN + Code::AudioVolumeMute => 113, // KEY_MUTE + Code::AudioVolumeUp => 115, // KEY_VOLUMEUP + Code::WakeUp => 143, // KEY_WAKEUP + + Code::Suspend => 205, // KEY_SUSPEND + Code::Again => 129, // KEY_AGAIN + Code::Copy => 133, // KEY_COPY + Code::Cut => 137, // KEY_CUT + Code::Find => 136, // KEY_FIND + Code::Open => 134, // KEY_OPEN + Code::Paste => 135, // KEY_PASTE + Code::Props => 130, // KEY_PROPS + Code::Select => 353, // KEY_SELECT (0x161) + Code::Undo => 131, // KEY_UNDO + + // Function keys F1–F35 + Code::F1 => 59, + Code::F2 => 60, + Code::F3 => 61, + Code::F4 => 62, + Code::F5 => 63, + Code::F6 => 64, + Code::F7 => 65, + Code::F8 => 66, + Code::F9 => 67, + Code::F10 => 68, + Code::F11 => 87, + Code::F12 => 88, + Code::F13 => 183, // KEY_F13 + Code::F14 => 184, // KEY_F14 + Code::F15 => 185, // KEY_F15 + Code::F16 => 186, // KEY_F16 + Code::F17 => 187, + Code::F18 => 188, + Code::F19 => 189, + Code::F20 => 190, + Code::F21 => 191, + Code::F22 => 192, + Code::F23 => 193, + Code::F24 => 194, // KEY_F24 + + // Catch-all in case your `iced_core::keyboard::key::Code` has additional variants + _ => return None, + }; + + Some(evdev + XKB_OFFSET) +} diff --git a/src/main.rs b/src/main.rs index c92407c..3358357 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,7 +20,7 @@ stages loading, switching between stages, and stuff. */ -use iced::{keyboard, widget}; +use iced::widget; use log; use std::process::ExitCode; @@ -41,7 +41,9 @@ mod kira_scroll_list; mod kira_size; mod kira_sysinfo; mod kira_system; +mod kira_text_input; mod kira_theming; +mod kira_xkb; mod stage; mod stages; @@ -251,30 +253,27 @@ fn update(k_state: &mut KiraState, message: Message) -> Task { Message::Keyboard(keyboard_msg) => { if let Views::Keyboard(keyboard_view) = &mut k_state.current_view { match keyboard_view.update(keyboard_msg) { - stages::keyboard::Update::Task(t) => t.map(Message::Keyboard), - stages::keyboard::Update::StgAct(action) => match action { - StageAction::Next(keyboard_res) => { - k_state.k_config = keyboard_res; - match stages::partition::PartitionStage::new(k_state.k_config.clone()) { - Ok(part_stage) => { - let s_state = std::mem::replace( - &mut k_state.current_view, - Views::Partition(part_stage), - ); - k_state.stages_save.push(s_state); - } - Err(ex) => { - log::error!("Error, cannot init partition stage: {}", ex); - } + StageAction::Next(keyboard_res) => { + k_state.k_config = keyboard_res; + match stages::partition::PartitionStage::new(k_state.k_config.clone()) { + Ok(part_stage) => { + let s_state = std::mem::replace( + &mut k_state.current_view, + Views::Partition(part_stage), + ); + k_state.stages_save.push(s_state); + } + Err(ex) => { + log::error!("Error, cannot init partition stage: {}", ex); } - Task::none() } - StageAction::Back => { - k_state.current_view = k_state.stages_save.pop().unwrap(); - Task::none() - } - _ => Task::none(), - }, + Task::none() + } + StageAction::Back => { + k_state.current_view = k_state.stages_save.pop().unwrap(); + Task::none() + } + _ => Task::none(), } } else { Task::none() diff --git a/src/stages/keyboard/mod.rs b/src/stages/keyboard/mod.rs index 6bcb62c..e51f652 100644 --- a/src/stages/keyboard/mod.rs +++ b/src/stages/keyboard/mod.rs @@ -20,11 +20,13 @@ use crate::kira_scroll_list::{self, ListViewMessage}; use crate::kira_system; +use crate::kira_text_input; use crate::stage::{KiraConfig, StageAction}; use iced::{Alignment, Length, Task, widget}; use log; use rust_i18n::t; use std::collections::HashMap; +use xkbcommon::xkb; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Layout { @@ -127,7 +129,7 @@ impl std::fmt::Display for KeyboarLayout { } } -#[derive(Debug, Clone)] +#[derive(Clone)] pub struct KeyboardStage { models: Vec, model: Option, @@ -140,6 +142,7 @@ pub struct KeyboardStage { // selected_kbd_layout_id: Option, k_config: KiraConfig, test_text: String, + xkb_keymap: Option, } #[derive(Debug, Clone, PartialEq)] @@ -206,7 +209,6 @@ pub enum Message { SelectLayout(kira_scroll_list::ListViewMessage), SelectVariant(kira_scroll_list::ListViewMessage), TestTextChange(String), - SysLayoutChanged, // AddLayout(usize), // RemoveLayout(usize), @@ -215,11 +217,6 @@ pub enum Message { Back, } -pub enum Update { - StgAct(StageAction), - Task(Task), -} - const XKB_RULES_FILE_NAME: &str = "/usr/share/X11/xkb/rules/evdev.lst"; /// Getting list of awailable keyboard layouts from from xkb/rules/evdev.lst file. @@ -337,6 +334,7 @@ impl KeyboardStage { keyboard_layout: keyboard_layout, k_config: k_config, test_text: String::new(), + xkb_keymap: None, } } Err(ex) => { @@ -355,13 +353,36 @@ impl KeyboardStage { keyboard_layout: None, k_config: k_config, test_text: String::new(), + xkb_keymap: None, } } } } - fn set_input_method(&self) -> Task { - log::info!("Preparing task!"); + // fn set_input_method(&self) -> Task { + // log::info!("Preparing task!"); + // let (layout, variant) = if let Some(kb_layout) = &self.keyboard_layout { + // (kb_layout.xkb_layout(), kb_layout.xkb_variant()) + // } else { + // (String::new(), String::new()) + // }; + // let model = if let Some(kb_model) = &self.model { + // kb_model.xkb_model() + // } else { + // String::new() + // }; + // log::info!("Task perform!"); + // Task::perform( + // async move { + // let a = kira_system::set_input_method(&layout, &model, &variant, "").await; + // log::info!("Result: {:?}", a); + // }, + // |_| Message::SysLayoutChanged, + // ) + // }s + + fn gen_keymap(&mut self) -> () { + log::debug!("Generating keyboard keymap!"); let (layout, variant) = if let Some(kb_layout) = &self.keyboard_layout { (kb_layout.xkb_layout(), kb_layout.xkb_variant()) } else { @@ -372,14 +393,29 @@ impl KeyboardStage { } else { String::new() }; - log::info!("Task perform!"); - Task::perform( - async move { - let a = kira_system::set_input_method(&layout, &model, &variant, "").await; - log::info!("Result: {:?}", a); - }, - |_| Message::SysLayoutChanged, - ) + log::debug!( + "model:{:?}, layout:{:?}, variant:{:?}", + model, + layout, + variant + ); + + // create context + let ctx = xkb::Context::new(xkb::CONTEXT_NO_FLAGS); + let xkb_keymap = xkb::Keymap::new_from_names( + &ctx, + "evdev", + &model, + &layout, + &variant, + None, + xkb::COMPILE_NO_FLAGS, + ); + if xkb_keymap.is_none() { + log::error!("Cannot compile XKB keymap!"); + } else { + self.xkb_keymap = xkb_keymap; + } } fn gen_result(&mut self) -> KiraConfig { @@ -393,7 +429,7 @@ impl KeyboardStage { self.k_config.clone() } - pub fn update(&mut self, message: Message) -> Update { + pub fn update(&mut self, message: Message) -> StageAction { match message { Message::SelectLayout(ListViewMessage::Select(l_id)) => { if let Some(current_l_id) = self.layout @@ -411,10 +447,9 @@ impl KeyboardStage { variant: variant, }); - Update::Task(self.set_input_method()) - } else { - Update::StgAct(StageAction::None) + self.gen_keymap(); } + StageAction::None } Message::SelectVariant(ListViewMessage::Select(v_id)) => { self.variant = Some(v_id); @@ -422,21 +457,22 @@ impl KeyboardStage { layout: self.layouts[self.layout.unwrap()].clone(), variant: self.variants[v_id].clone(), }); - Update::Task(self.set_input_method()) + self.gen_keymap(); + StageAction::None } Message::SelectKeyboardModel(k_m) => { self.model = Some(k_m); - Update::Task(self.set_input_method()) + self.gen_keymap(); + StageAction::None } Message::TestTextChange(test_text) => { let mut res: String = test_text; res.retain(|c: char| !c.is_control()); self.test_text = res; - Update::StgAct(StageAction::None) + StageAction::None } - Message::SysLayoutChanged => Update::StgAct(StageAction::None), - Message::Next => Update::StgAct(StageAction::Next(self.gen_result())), - Message::Back => Update::StgAct(StageAction::Back), + Message::Next => StageAction::Next(self.gen_result()), + Message::Back => StageAction::Back, } } @@ -482,7 +518,10 @@ impl KeyboardStage { .height(Length::Fill), widget::row![ widget::text("Test Keyboard:"), - widget::text_input("", &self.test_text).on_input(Message::TestTextChange), + //widget::text_input("", &self.test_text).on_input(Message::TestTextChange), + kira_text_input::TextInput::new("", &self.test_text) + .keymap(self.xkb_keymap.clone()) + .on_input(Message::TestTextChange), ] .spacing(2) .align_y(Alignment::Center)