A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
chore(release): prepare v0.1.13
CristianOlivera1abbb403582a4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 396fd0d..2cfa6ed 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,8 +8,19 @@ copia la sección de la versión que se publica a la release de GitHub.## [Unreleased]+## [0.1.13]+### English+- The menu bar's keyboard indicator opens a themed layout menu with the+ current keyboard marked and a link to Windows language settings. Changes+ are requested for the original typing window instead of simulating Win+Space.+- Changing Muelle's language refreshes menu bar text even when its data has+ not changed. Menu bar controls retain the standard arrow cursor.+- Menus return focus after a selection without overriding another app the+ user switched to while dismissing them. Auto-hide keeps the menu bar open+ while its keyboard selector is in use.+- With auto-hide enabled, rest the pointer at a display's bottom edge tobring the Dock to that display (#9, #11).- Menu bar redraws no longer cancel a pending top-edge reveal (#10).@@ -33,6 +44,15 @@ copia la sección de la versión que se publica a la release de GitHub.### Español+- El indicador de teclado de la barra abre un menú con el estilo de Muelle,+ marca el teclado activo y permite abrir los ajustes de idioma de Windows.+ El cambio se solicita a la ventana donde se escribía, sin simular Win+Espacio.+- Cambiar el idioma de Muelle actualiza los textos de la barra aunque no+ cambien sus datos. Los controles de la barra mantienen el cursor de flecha.+- Los menús devuelven el foco tras una selección sin imponerse a otra app+ elegida al cerrarlos. La barra permanece visible mientras se usa su+ selector de teclado, incluso con ocultación automática.+- Con la ocultación automática activada, deja el puntero en el borde inferiorde una pantalla para mostrar el Dock allí (#9, #11).- Actualizar la barra superior ya no cancela su aparición al dejar el punterodiff --git a/Cargo.lock b/Cargo.lockindex 6ad1026..a30f163 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2259,7 +2259,7 @@ dependencies = [[[package]]name = "muelle"-version = "0.1.12"+version = "0.1.13"dependencies = ["anyhow","base64 0.22.1",@@ -2280,7 +2280,7 @@ dependencies = [[[package]]name = "muelle-config"-version = "0.1.12"+version = "0.1.13"dependencies = ["serde","serde_json",@@ -2289,11 +2289,11 @@ dependencies = [[[package]]name = "muelle-core"-version = "0.1.12"+version = "0.1.13"[[package]]name = "muelle-settings"-version = "0.1.12"+version = "0.1.13"dependencies = ["muelle-config","muelle-shell",@@ -2307,7 +2307,7 @@ dependencies = [[[package]]name = "muelle-shell"-version = "0.1.12"+version = "0.1.13"dependencies = ["thiserror 2.0.21","windows",diff --git a/Cargo.toml b/Cargo.tomlindex 4d001d7..707ac87 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -3,7 +3,7 @@ resolver = "3"members = ["crates/*", "apps/dock", "apps/settings/src-tauri", "spikes"][workspace.package]-version = "0.1.12"+version = "0.1.13"edition = "2024"license = "MIT"diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex 743f883..9fd440c 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -349,6 +349,11 @@ enum Outside {copy: bool,},Menu(MenuRequest),+ InputMenu {+ gfx: Gfx,+ anchor: POINT,+ dark: bool,+ },QuitDock,OpenSettings,OpenAsAdmin(String),@@ -3325,24 +3330,22 @@ fn with_app_value<T: Default>(what: &str, action: impl FnOnce(&mut App) -> Resul}pub fn menu_bar_clicked(x: f32, y: f32) {- with_app("barra superior", |app| {+ with_app_then("barra superior", |app| {if let Some(bar) = &mut app.menubar {+ if let Some(anchor) = bar.input_switcher_anchor(x, y) {+ bar.dismiss_island(&app.gfx)?;+ return Ok(Some(Outside::InputMenu {+ gfx: app.gfx.clone(),+ anchor,+ dark: !uses_light_theme(),+ }));+ }bar.click(&app.gfx, x, y)?;}- Ok(())+ Ok(None)});}-pub fn menu_bar_has_action(point: POINT) -> bool {- APP.with(|cell| {- cell.try_borrow().ok().is_some_and(|app| {- app.as_ref()- .and_then(|app| app.menubar.as_ref())- .is_some_and(|bar| bar.has_island_action(point))- })- })-}-pub fn menu_bar_media_changed() {with_app("reproducción", |app| match &mut app.menubar {Some(bar) => bar.media_changed(&app.gfx),@@ -3405,9 +3408,15 @@ pub fn multi_window_view_dismiss() {}pub fn menu_bar_check_pointer() {- with_app("barra superior", |app| match &mut app.menubar {- Some(bar) => bar.check_pointer(&app.gfx),- None => Ok(()),+ with_app("barra superior", |app| {+ if app.menu_open {+ Ok(())+ } else {+ match &mut app.menubar {+ Some(bar) => bar.check_pointer(&app.gfx),+ None => Ok(()),+ }+ }});}@@ -3563,6 +3572,51 @@ fn run_outside(outside: Outside) {_ => eprintln!("muelle: no se encontró muelle-settings.exe junto al dock"),}}+ Outside::InputMenu { gfx, anchor, dark } => {+ use muelle_shell::keyboard;+ let context = keyboard::Context::current();+ let layouts = keyboard::layouts(strings::text().keyboard);+ const SETTINGS: u32 = u32::MAX;+ let mut items: Vec<MenuItem> = layouts+ .iter()+ .enumerate()+ .map(|(index, layout)| MenuItem::Action {+ command: index as u32 + 1,+ label: layout.name.replace('&', "&&"),+ checked: context.is_some_and(|context| context.layout == layout.handle),+ enabled: context.is_some(),+ })+ .collect();+ if !items.is_empty() {+ items.push(MenuItem::Separator);+ }+ items.push(MenuItem::action(+ SETTINGS,+ strings::text().keyboard_settings,+ ));+ let owner = main_window();+ with_app("abrir selector de teclado", |app| {+ app.menu_open = true;+ Ok(())+ });+ let chosen = menu::show_below(&gfx, owner, &items, anchor, dark);+ with_app("cerrar selector de teclado", App::after_menu);+ if chosen == Some(SETTINGS) {+ submit(ShellAction::Open {+ id: "ms-settings:regionlanguage".into(),+ });+ } else if let (Some(context), Some(layout)) = (+ context,+ chosen+ .and_then(|command| command.checked_sub(1))+ .and_then(|index| layouts.get(index as usize)),+ ) && let Err(error) = context.request(layout.handle)+ {+ muelle_shell::log::line(&format!("cambiar teclado: {error}"));+ shell_work::notify_not_started();+ }+ menu_bar_refresh();+ }Outside::Menu(request) => {let owner = HWND(MAIN_WINDOW.load(Ordering::Relaxed) as *mut _);with_app("abrir menú", |app| {diff --git a/apps/dock/src/menu.rs b/apps/dock/src/menu.rsindex cdde63a..8f3218e 100644--- a/apps/dock/src/menu.rs+++ b/apps/dock/src/menu.rs@@ -51,10 +51,10 @@ use windows::{SPI_GETSCREENREADER, SW_SHOWNA, SWP_NOACTIVATE,SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SetCursor, SetForegroundWindow, SetTimer,SetWindowPos, ShowWindow, SystemParametersInfoW, TPM_BOTTOMALIGN, TPM_CENTERALIGN,- TPM_NONOTIFY, TPM_RETURNCMD, TPM_RIGHTBUTTON, TrackPopupMenuEx, TranslateMessage,- WA_INACTIVE, WM_ACTIVATE, WM_CANCELMODE, WM_CAPTURECHANGED, WM_CHAR, WM_KEYDOWN,- WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MOUSEMOVE, WM_NULL,- WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SETCURSOR, WM_SYSKEYDOWN, WM_TIMER,+ TPM_NONOTIFY, TPM_RETURNCMD, TPM_RIGHTBUTTON, TPM_TOPALIGN, TrackPopupMenuEx,+ TranslateMessage, WA_INACTIVE, WM_ACTIVATE, WM_CANCELMODE, WM_CAPTURECHANGED,+ WM_CHAR, WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MOUSEMOVE,+ WM_NULL, WM_RBUTTONDOWN, WM_RBUTTONUP, WM_SETCURSOR, WM_SYSKEYDOWN, WM_TIMER,WM_XBUTTONDOWN, WNDCLASSW, WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW,WS_EX_TOPMOST, WS_POPUP,},@@ -94,14 +94,41 @@ impl MenuItem {/// Runs a modal loop that continues dispatching messages to dock windows./// The caller must not hold the app state while this function runs.pub fn show(gfx: &Gfx, owner: HWND, items: &[MenuItem], anchor: POINT, dark: bool) -> Option<u32> {+ show_at(gfx, owner, items, anchor, dark, Placement::Above)+}++pub fn show_below(+ gfx: &Gfx,+ owner: HWND,+ items: &[MenuItem],+ anchor: POINT,+ dark: bool,+) -> Option<u32> {+ show_at(gfx, owner, items, anchor, dark, Placement::Below)+}++#[derive(Clone, Copy)]+enum Placement {+ Above,+ Below,+}++fn show_at(+ gfx: &Gfx,+ owner: HWND,+ items: &[MenuItem],+ anchor: POINT,+ dark: bool,+ placement: Placement,+) -> Option<u32> {if needs_native_menu() {- return show_native(owner, items, anchor, dark);+ return show_native(owner, items, anchor, dark, placement);}- match Popup::open(gfx, owner, items, anchor, dark) {+ match Popup::open(gfx, owner, items, anchor, dark, placement) {Ok(popup) => popup.run(),Err(error) => {eprintln!("muelle: menú: {error:#}");- show_native(owner, items, anchor, dark)+ show_native(owner, items, anchor, dark, placement)}}}@@ -185,7 +212,14 @@ struct Popup {}impl Popup {- fn open(gfx: &Gfx, owner: HWND, items: &[MenuItem], anchor: POINT, dark: bool) -> Result<Self> {+ fn open(+ gfx: &Gfx,+ owner: HWND,+ items: &[MenuItem],+ anchor: POINT,+ dark: bool,+ placement: Placement,+ ) -> Result<Self> {let c = &gfx.compositor;// SAFETY: Read-only query on our own window.let scale = unsafe { GetDpiForWindow(owner) }.max(96) as f32 / 96.0;@@ -345,7 +379,14 @@ impl Popup {screen.left + margin,(screen.right - margin - w).max(screen.left + margin),);- let top = (anchor.y - h).max(screen.top + margin);+ let top = match placement {+ Placement::Above => anchor.y - h,+ Placement::Below => anchor.y,+ }+ .clamp(+ screen.top + margin,+ (screen.bottom - margin - h).max(screen.top + margin),+ );let hwnd = create_window(dark)?;// SAFETY: `hwnd` is the live window created above.@@ -419,7 +460,7 @@ impl Popup {}}}- self.close(chosen.is_some());+ self.close();chosen}@@ -582,16 +623,19 @@ impl Popup {}}- fn close(self, chose: bool) {+ fn close(self) {// SAFETY: Our own window, destroyed once; the owner gets a message// so its loop notices the menu is gone, as with the native menu.unsafe {+ let foreground = GetForegroundWindow();+ let restore = foreground == self.hwnd || foreground == self.owner;let _ = KillTimer(Some(self.hwnd), FOCUS_TIMER);let _ = ReleaseCapture();let _ = DestroyWindow(self.hwnd);let _ = PostMessageW(Some(self.owner), WM_NULL, WPARAM(0), LPARAM(0));- if !chose {- // Dismissing without a selection gives the focus back, as macOS does.+ if restore {+ // Restore after a selection as well, but never override a+ // different app the user activated while dismissing the menu.let _ = SetForegroundWindow(self.previous);}}@@ -793,7 +837,13 @@ fn add_sprite(/* ---------------------------------------------------------- Native menu */-fn show_native(owner: HWND, items: &[MenuItem], anchor: POINT, dark: bool) -> Option<u32> {+fn show_native(+ owner: HWND,+ items: &[MenuItem],+ anchor: POINT,+ dark: bool,+ placement: Placement,+) -> Option<u32> {apply_theme(dark);// SAFETY: The menu is destroyed before returning, and strings live through each call.unsafe {@@ -830,7 +880,15 @@ fn show_native(owner: HWND, items: &[MenuItem], anchor: POINT, dark: bool) -> Oplet _ = SetForegroundWindow(owner);let chosen = TrackPopupMenuEx(menu,- (TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON | TPM_BOTTOMALIGN | TPM_CENTERALIGN).0,+ (TPM_RETURNCMD+ | TPM_NONOTIFY+ | TPM_RIGHTBUTTON+ | TPM_CENTERALIGN+ | match placement {+ Placement::Above => TPM_BOTTOMALIGN,+ Placement::Below => TPM_TOPALIGN,+ })+ .0,anchor.x,anchor.y,owner,@@ -840,8 +898,7 @@ fn show_native(owner: HWND, items: &[MenuItem], anchor: POINT, dark: bool) -> Oplet _ = DestroyMenu(menu);let chosen = u32::try_from(chosen.0).ok().filter(|&command| command != 0);- if chosen.is_none() {- // Dismissing without a selection restores the previous focus, as in macOS.+ if GetForegroundWindow() == owner {let _ = SetForegroundWindow(previous);}chosen@@ -884,7 +941,85 @@ fn apply_theme(dark: bool) {#[cfg(test)]mod tests {- use super::strip_mnemonic;+ use super::*;++ #[test]+ #[ignore = "Requires an interactive Windows desktop; briefly opens a menu"]+ fn keyboard_menu_opens_below_its_anchor_and_returns_the_selected_layout() -> Result<()> {+ use windows::Win32::{+ System::WinRT::{+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,+ DispatcherQueueOptions,+ },+ UI::WindowsAndMessaging::GetWindowRect,+ };+ let _queue = unsafe {+ CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_STA,+ })?+ };+ let gfx = Gfx::new()?;+ let owner = unsafe {+ CreateWindowExW(+ Default::default(),+ w!("STATIC"),+ w!("Muelle menu test"),+ WS_POPUP,+ 0,+ 0,+ 1,+ 1,+ None,+ None,+ None,+ None,+ )?+ };+ let result = (|| -> Result<()> {+ let anchor = POINT { x: 600, y: 60 };+ let previous = unsafe { GetForegroundWindow() };+ let popup = Popup::open(+ &gfx,+ owner,+ &[+ MenuItem::action(1, "Español"),+ MenuItem::action(2, "English"),+ ],+ anchor,+ true,+ Placement::Below,+ )?;+ let mut bounds = RECT::default();+ unsafe {+ GetWindowRect(popup.hwnd, &mut bounds)?;+ // Exercise the popup's real modal path without injecting any+ // keyboard input into the user's application.+ PostMessageW(+ Some(popup.hwnd),+ WM_KEYDOWN,+ WPARAM(VK_DOWN.0 as usize),+ LPARAM(0),+ )?;+ PostMessageW(+ Some(popup.hwnd),+ WM_KEYDOWN,+ WPARAM(VK_RETURN.0 as usize),+ LPARAM(0),+ )?;+ }+ let chosen = popup.run();+ assert_eq!(bounds.top, anchor.y);+ assert_eq!(chosen, Some(1));+ assert_eq!(unsafe { GetForegroundWindow() }, previous);+ Ok(())+ })();+ unsafe {+ let _ = DestroyWindow(owner);+ }+ result+ }#[test]fn strip_mnemonic_should_drop_the_marker_and_keep_its_letter() {diff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rsindex d07c590..c4c2c14 100644--- a/apps/dock/src/menubar.rs+++ b/apps/dock/src/menubar.rs@@ -47,7 +47,7 @@ use windows::{UI::Input::KeyboardAndMouse::{TME_LEAVE, TRACKMOUSEEVENT, TrackMouseEvent},UI::WindowsAndMessaging::{CallNextHookEx, CreateWindowExW, DefWindowProcW, DestroyWindow, GetCursorPos, HHOOK,- HWND_TOPMOST, IDC_ARROW, IDC_HAND, KillTimer, LoadCursorW, MSLLHOOKSTRUCT,+ HWND_TOPMOST, IDC_ARROW, KillTimer, LoadCursorW, MSLLHOOKSTRUCT,PBT_POWERSETTINGCHANGE, PostMessageW, RegisterClassW, SWP_HIDEWINDOW, SWP_NOACTIVATE,SWP_SHOWWINDOW, SetCursor, SetTimer, SetWindowPos, SetWindowsHookExW,UnhookWindowsHookEx, WH_MOUSE_LL, WM_APP, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN,@@ -165,6 +165,7 @@ struct Status {/// What the bar was last drawn for.#[derive(Clone, PartialEq)]struct Look {+ spanish: bool,screen: RECT,scale: f32,light: bool,@@ -304,14 +305,10 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -PRIVACY_CHANGED => app::menu_bar_privacy_changed(),MEDIA_CHANGED => app::menu_bar_media_changed(),WM_SETCURSOR => {- let mut point = POINT::default();- // SAFETY: The point is a valid output for the current pointer location.- if unsafe { GetCursorPos(&mut point) }.is_ok() && app::menu_bar_has_action(point) {- // SAFETY: The stock hand cursor is owned by Windows.- if let Ok(hand) = unsafe { LoadCursorW(None, IDC_HAND) } {- unsafe { SetCursor(Some(hand)) };- return LRESULT(1);- }+ // SAFETY: Keep the standard arrow throughout the bar and popups.+ if let Ok(arrow) = unsafe { LoadCursorW(None, IDC_ARROW) } {+ unsafe { SetCursor(Some(arrow)) };+ return LRESULT(1);}return unsafe { DefWindowProcW(hwnd, msg, w, l) };}@@ -1329,7 +1326,7 @@ impl MenuBar {Some(Action::TaskView) => launcher::open_task_view(),Some(Action::Widgets) => launcher::open_widgets(),Some(Action::HiddenIcons) => launcher::toggle_hidden_icons(anchor),- Some(Action::InputLanguage) => launcher::open_input_switcher(),+ Some(Action::InputLanguage) => {} // Opened outside the app borrow.// Windows' own pages list which apps use each device.Some(Action::Microphone) => {let _ = launcher::open("ms-settings:privacy-microphone");@@ -1342,10 +1339,19 @@ impl MenuBar {Ok(())}- pub fn has_island_action(&self, point: POINT) -> bool {- let x = (point.x - self.bounds.left) as f32;- let y = (point.y - self.bounds.top) as f32;- self.island_hits.iter().any(|hit| hit.at(x, y))+ pub fn input_switcher_anchor(&self, x: f32, y: f32) -> Option<POINT> {+ if y < 0.0 || y >= (self.bounds.bottom - self.bounds.top) as f32 {+ return None;+ }+ self.zones+ .iter()+ .find(|(left, right, action)| {+ x >= *left && x < *right && matches!(action, Action::InputLanguage)+ })+ .map(|(left, right, _)| POINT {+ x: self.bounds.left + ((left + right) * 0.5) as i32,+ y: self.bounds.bottom + 6,+ })}/// Redraws the bar if anything it shows has changed.@@ -1371,6 +1377,7 @@ impl MenuBar {usage.refresh(false);}let look = Look {+ spanish: strings::is_spanish(),screen: monitor.screen,scale: monitor.scale,light: system::uses_light_theme(),@@ -2510,6 +2517,48 @@ impl Drop for MenuBar {mod island_tests {use super::*;+ #[test]+ #[ignore = "Requires Windows desktop composition"]+ fn changing_ui_language_redraws_unchanged_menu_bar_content() -> Result<()> {+ use muelle_config::Language;+ use windows::Win32::System::WinRT::{+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,+ DispatcherQueueOptions,+ };+ struct RestoreLanguage(Language);+ impl Drop for RestoreLanguage {+ fn drop(&mut self) {+ strings::set_language(self.0);+ }+ }+ let _restore = RestoreLanguage(if strings::is_spanish() {+ Language::Es+ } else {+ Language::En+ });+ let _queue = unsafe {+ CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_STA,+ })?+ };+ let gfx = Gfx::new()?;+ strings::set_language(Language::Es);+ let mut bar = MenuBar::create(&gfx, false, true)?;+ assert!(bar.look.as_ref().is_some_and(|look| look.spanish));+ let previous = bar.surface.Children()?.First()?.Current()?;+ strings::set_language(Language::En);+ bar.refresh(&gfx)?;+ assert_ne!(+ previous,+ bar.surface.Children()?.First()?.Current()?,+ "translation-only changes must rebuild the content"+ );+ assert!(bar.look.as_ref().is_some_and(|look| !look.spanish));+ Ok(())+ }+#[test]#[ignore = "Requires Windows desktop composition"]fn auto_hidden_bar_can_reveal_and_hide_repeatedly() -> Result<()> {diff --git a/apps/dock/src/strings.rs b/apps/dock/src/strings.rsindex b8f3941..086d993 100644--- a/apps/dock/src/strings.rs+++ b/apps/dock/src/strings.rs@@ -1,5 +1,5 @@//! User-facing dock text in Spanish and English. The language follows the-//! Windows display language; Settings will be able to override it (phase 7).+//! Windows display language unless the user overrides it in Settings.//! `&` marks the menu access key.use std::sync::atomic::{AtomicU8, Ordering};@@ -37,9 +37,13 @@ pub struct Strings {pub usage_used: &'static str,pub media_title: &'static str,pub shell_operation_failed: &'static str,+ pub keyboard_settings: &'static str,+ pub keyboard: &'static str,}const ES: Strings = Strings {+ keyboard_settings: "Ajustes de idioma y teclado…",+ keyboard: "Teclado",shell_operation_failed: "No se pudo iniciar la operación. Inténtalo de nuevo en un momento.",open: "&Abrir",new_window: "&Nueva ventana",@@ -72,6 +76,8 @@ const ES: Strings = Strings {};const EN: Strings = Strings {+ keyboard_settings: "Language and keyboard settings…",+ keyboard: "Keyboard",shell_operation_failed: "The operation could not start. Please try again in a moment.",open: "&Open",new_window: "&New Window",@@ -115,13 +121,21 @@ pub fn set_language(language: Language) {LANGUAGE.store(if spanish { 1 } else { 2 }, Ordering::Relaxed);}-pub fn text() -> &'static Strings {- match LANGUAGE.load(Ordering::Relaxed) {- 0 => {- set_language(Language::Auto);- text()- }- 1 => &ES,- _ => &EN,+fn chosen_language() -> u8 {+ let language = LANGUAGE.load(Ordering::Relaxed);+ if language == 0 {+ set_language(Language::Auto);+ LANGUAGE.load(Ordering::Relaxed)+ } else {+ language}}++pub fn text() -> &'static Strings {+ if chosen_language() == 1 { &ES } else { &EN }+}++/// The resolved language is part of the menu bar's rendered-content key.+pub fn is_spanish() -> bool {+ chosen_language() == 1+}diff --git a/crates/muelle-shell/src/keyboard.rs b/crates/muelle-shell/src/keyboard.rsnew file mode 100644index 0000000..5c60d55--- /dev/null+++ b/crates/muelle-shell/src/keyboard.rs@@ -0,0 +1,348 @@+//! Installed keyboard layouts and a nonblocking change request to the window+//! the user was typing in before opening Muelle's menu.++use windows::{+ Win32::{+ Foundation::{ERROR_INVALID_PARAMETER, ERROR_INVALID_WINDOW_HANDLE, LPARAM, WPARAM},+ Globalization::{GetLocaleInfoW, LOCALE_SLOCALIZEDDISPLAYNAME},+ System::Registry::{HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ, RegGetValueW},+ UI::{+ Input::KeyboardAndMouse::{GetKeyboardLayout, GetKeyboardLayoutList, HKL},+ WindowsAndMessaging::{+ GUITHREADINFO, GetForegroundWindow, GetGUIThreadInfo, GetWindowThreadProcessId,+ IsWindow, PostMessageW, WM_INPUTLANGCHANGEREQUEST,+ },+ },+ },+ core::{HSTRING, Result, w},+};++#[derive(Clone, Copy)]+pub struct Context {+ window: isize,+ target: isize,+ thread: u32,+ pub layout: isize,+}++pub struct Layout {+ pub handle: isize,+ pub name: String,+}++impl Context {+ #[must_use]+ pub fn current() -> Option<Self> {+ // SAFETY: Read-only queries. A missing focus window falls back to the+ // foreground window; the request validates it again before posting.+ unsafe {+ let window = GetForegroundWindow();+ if window.is_invalid() {+ return None;+ }+ let thread = GetWindowThreadProcessId(window, None);+ if thread == 0 {+ return None;+ }+ let mut info = GUITHREADINFO {+ cbSize: size_of::<GUITHREADINFO>() as u32,+ ..Default::default()+ };+ let target =+ if GetGUIThreadInfo(thread, &mut info).is_ok() && !info.hwndFocus.is_invalid() {+ info.hwndFocus+ } else {+ window+ };+ let thread = GetWindowThreadProcessId(target, None);+ if thread == 0 {+ return None;+ }+ Some(Self {+ window: window.0 as isize,+ target: target.0 as isize,+ thread,+ layout: GetKeyboardLayout(thread).0 as isize,+ })+ }+ }++ /// Does not activate a layout in Muelle's thread or synthesize keyboard+ /// shortcuts. The receiving application remains in control of its input.+ pub fn request(self, layout: isize) -> Result<()> {+ use windows::Win32::Foundation::HWND;+ let window = HWND(self.window as *mut _);+ let target = HWND(self.target as *mut _);+ // SAFETY: Scalar handles are revalidated because the menu can outlive+ // its original application. UIPI refusals are returned to the caller.+ unsafe {+ if !IsWindow(Some(window)).as_bool()+ || !IsWindow(Some(target)).as_bool()+ || GetWindowThreadProcessId(target, None) != self.thread+ {+ return Err(ERROR_INVALID_WINDOW_HANDLE.into());+ }+ if !handles().contains(&layout) {+ return Err(ERROR_INVALID_PARAMETER.into());+ }+ PostMessageW(+ Some(target),+ WM_INPUTLANGCHANGEREQUEST,+ WPARAM(0),+ LPARAM(layout),+ )+ }+ }+}++fn handles() -> Vec<isize> {+ // SAFETY: Windows writes at most the allocated number of layout handles.+ unsafe {+ let count = GetKeyboardLayoutList(None).max(0) as usize;+ let mut layouts = vec![HKL::default(); count];+ let read = GetKeyboardLayoutList(Some(&mut layouts)).max(0) as usize;+ layouts.truncate(read);+ layouts+ .into_iter()+ .map(|layout| layout.0 as isize)+ .collect()+ }+}++#[must_use]+pub fn layouts(fallback: &str) -> Vec<Layout> {+ handles()+ .into_iter()+ .enumerate()+ .map(|(index, handle)| {+ let name = layout_name(handle)+ .or_else(|| locale_name(handle))+ .unwrap_or_else(|| format!("{fallback} {}", index + 1));+ Layout { handle, name }+ })+ .collect()+}++fn registry_text(key: &str, value: &str) -> Option<String> {+ let path = HSTRING::from(format!(+ r"SYSTEM\CurrentControlSet\Control\Keyboard Layouts\{key}"+ ));+ let value = HSTRING::from(value);+ let mut buffer = [0u16; 512];+ let mut bytes = size_of_val(&buffer) as u32;+ // SAFETY: Read-only registry query into a bounded UTF-16 buffer.+ unsafe {+ RegGetValueW(+ HKEY_LOCAL_MACHINE,+ &path,+ &value,+ RRF_RT_REG_SZ,+ None,+ Some(buffer.as_mut_ptr().cast()),+ Some(&mut bytes),+ )+ .ok()+ .ok()?;+ }+ let end = buffer.iter().position(|&c| c == 0).unwrap_or(buffer.len());+ let text = String::from_utf16_lossy(&buffer[..end]);+ (!text.is_empty()).then_some(text)+}++fn direct_key(handle: isize) -> Option<String> {+ let raw = handle as u32;+ let device = raw >> 16;+ if device & 0xF000 == 0xF000 {+ return None;+ }+ Some(format!(+ "{:08X}",+ if device == raw & 0xFFFF {+ raw & 0xFFFF+ } else {+ raw+ }+ ))+}++fn layout_name(handle: isize) -> Option<String> {+ if let Some(key) = direct_key(handle) {+ return display_name(&key);+ }+ use windows::{+ Win32::System::Registry::{HKEY, KEY_READ, RegCloseKey, RegEnumKeyExW, RegOpenKeyExW},+ core::PWSTR,+ };+ let mut key = HKEY::default();+ // Device identifiers Fxxx refer to a registry "Layout Id", not a KLID.+ // Enumerate only when such a variant is present, and only when opening+ // the menu. No registry work runs on mouse moves or the menu bar clock.+ unsafe {+ RegOpenKeyExW(+ HKEY_LOCAL_MACHINE,+ w!(r"SYSTEM\CurrentControlSet\Control\Keyboard Layouts"),+ None,+ KEY_READ,+ &mut key,+ )+ .ok()+ .ok()?;+ let result = (|| {+ for index in 0..1024 {+ let mut name = [0u16; 32];+ let mut len = name.len() as u32;+ if RegEnumKeyExW(+ key,+ index,+ Some(PWSTR(name.as_mut_ptr())),+ &mut len,+ None,+ None,+ None,+ None,+ )+ .is_err()+ {+ break;+ }+ let name = String::from_utf16_lossy(&name[..len as usize]);+ let id = u32::from_str_radix(&name, 16).ok();+ if id.is_none_or(|id| id & 0xFFFF != handle as u32 & 0xFFFF) {+ continue;+ }+ let variant = registry_text(&name, "Layout Id")+ .and_then(|id| u32::from_str_radix(&id, 16).ok());+ if variant == Some((handle as u32 >> 16) & 0xFFF) {+ return display_name(&name);+ }+ }+ None+ })();+ let _ = RegCloseKey(key);+ result+ }+}++fn display_name(key: &str) -> Option<String> {+ if let Some(resource) = registry_text(key, "Layout Display Name") {+ let mut name = [0u16; 512];+ // SAFETY: Resolves a Windows MUI resource into a bounded buffer.+ if unsafe {+ windows::Win32::UI::Shell::SHLoadIndirectString(+ &HSTRING::from(resource),+ &mut name,+ None,+ )+ }+ .is_ok()+ {+ let end = name.iter().position(|&c| c == 0).unwrap_or(name.len());+ if end > 0 {+ return Some(String::from_utf16_lossy(&name[..end]));+ }+ }+ }+ registry_text(key, "Layout Text")+}++fn locale_name(handle: isize) -> Option<String> {+ let mut name = [0u16; 256];+ // SAFETY: Read-only locale query into a live UTF-16 buffer.+ let len = unsafe {+ GetLocaleInfoW(+ handle as u32 & 0xFFFF,+ LOCALE_SLOCALIZEDDISPLAYNAME,+ Some(&mut name),+ )+ };+ (len > 1).then(|| String::from_utf16_lossy(&name[..len as usize - 1]))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn layout_handles_are_not_registry_identifiers() {+ assert_eq!(direct_key(0x04090409), Some("00000409".into()));+ assert_eq!(direct_key(0x080A080A), Some("0000080A".into()));+ assert_eq!(direct_key(0xE0010411), Some("E0010411".into()));+ assert_eq!(direct_key(0xF0020409), None);+ }++ #[test]+ fn installed_layouts_have_names_and_preserve_all_handles() {+ let expected = handles();+ assert!(!expected.is_empty());+ let layouts = layouts("Keyboard");+ assert_eq!(+ layouts+ .iter()+ .map(|layout| layout.handle)+ .collect::<Vec<_>>(),+ expected+ );+ assert!(layouts.iter().all(|layout| !layout.name.is_empty()));+ }++ #[test]+ fn a_closed_input_target_cannot_receive_a_layout_request() {+ let context = Context {+ window: 0,+ target: 0,+ thread: 0,+ layout: 0,+ };+ assert!(context.request(0).is_err());+ }++ #[test]+ fn layout_change_is_posted_to_the_captured_target_only() -> Result<()> {+ use windows::Win32::{+ System::Threading::GetCurrentThreadId,+ UI::WindowsAndMessaging::{+ CreateWindowExW, DestroyWindow, MSG, PM_REMOVE, PeekMessageW, WS_POPUP,+ },+ };+ // A hidden test-owned window: no foreground or keyboard is changed.+ unsafe {+ let window = CreateWindowExW(+ Default::default(),+ w!("STATIC"),+ w!("Muelle keyboard test"),+ WS_POPUP,+ 0,+ 0,+ 1,+ 1,+ None,+ None,+ None,+ None,+ )?;+ let layout = GetKeyboardLayout(0).0 as isize;+ let context = Context {+ window: window.0 as isize,+ target: window.0 as isize,+ thread: GetCurrentThreadId(),+ layout,+ };+ let result = context.request(layout);+ let mut msg = MSG::default();+ let received = PeekMessageW(+ &mut msg,+ Some(window),+ WM_INPUTLANGCHANGEREQUEST,+ WM_INPUTLANGCHANGEREQUEST,+ PM_REMOVE,+ )+ .as_bool();+ let _ = DestroyWindow(window);+ result?;+ assert!(received);+ assert_eq!(msg.lParam.0, layout);+ assert_eq!(GetKeyboardLayout(0).0 as isize, layout);+ Ok(())+ }+ }+}diff --git a/crates/muelle-shell/src/launcher.rs b/crates/muelle-shell/src/launcher.rsindex 3182d50..d9d17c4 100644--- a/crates/muelle-shell/src/launcher.rs+++ b/crates/muelle-shell/src/launcher.rs@@ -13,7 +13,7 @@ use windows::{Input::KeyboardAndMouse::{INPUT, INPUT_0, INPUT_KEYBOARD, KEYBD_EVENT_FLAGS, KEYBDINPUT, KEYEVENTF_KEYUP,SendInput, VIRTUAL_KEY, VK_A, VK_B, VK_D, VK_ESCAPE, VK_LCONTROL, VK_LWIN, VK_N,- VK_RETURN, VK_S, VK_SPACE, VK_TAB, VK_V, VK_W,+ VK_RETURN, VK_S, VK_TAB, VK_V, VK_W,},Shell::{SEE_MASK_NOASYNC, SHELLEXECUTEINFOW, ShellExecuteExW},WindowsAndMessaging::{@@ -220,12 +220,6 @@ pub fn show_desktop() {tap(&[VK_LWIN, VK_D]);}-/// The input language switcher, as clicking the taskbar's language-/// indicator (Win+Space).-pub fn open_input_switcher() {- tap(&[VK_LWIN, VK_SPACE]);-}-/// How long the taskbar takes to put the focus on its notification area.const HIDDEN_ICONS_DELAY: Duration = Duration::from_millis(250);/// How long the flyout is kept under the arrow while Windows finishesdiff --git a/crates/muelle-shell/src/lib.rs b/crates/muelle-shell/src/lib.rsindex 2cd3098..50d210c 100644--- a/crates/muelle-shell/src/lib.rs+++ b/crates/muelle-shell/src/lib.rs@@ -4,6 +4,7 @@ pub mod dock_link;pub mod files;pub mod icon_cache;pub mod icons;+pub mod keyboard;pub mod launcher;pub mod log;pub mod names;diff --git a/crates/muelle-shell/src/system.rs b/crates/muelle-shell/src/system.rsindex b021345..e30a446 100644--- a/crates/muelle-shell/src/system.rs+++ b/crates/muelle-shell/src/system.rs@@ -64,11 +64,7 @@ pub fn energy_saver_on() -> bool {#[must_use]pub fn input_language() -> Option<String> {use windows::Win32::{- Globalization::LCIDToLocaleName,- UI::{- Input::KeyboardAndMouse::{GetKeyboardLayout, GetKeyboardLayoutList},- WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId},- },+ Globalization::LCIDToLocaleName, UI::Input::KeyboardAndMouse::GetKeyboardLayoutList,};// SAFETY: Read-only queries; `name` is a valid buffer for the locale name.unsafe {@@ -76,8 +72,7 @@ pub fn input_language() -> Option<String> {return None;}// Each thread has its own layout: the one that matters is in front.- let thread = GetWindowThreadProcessId(GetForegroundWindow(), None);- let language = (GetKeyboardLayout(thread).0 as usize & 0xFFFF) as u32;+ let language = (crate::keyboard::Context::current()?.layout as usize & 0xFFFF) as u32;let mut name = [0u16; 85];let len = usize::try_from(LCIDToLocaleName(language, Some(&mut name), 0)).ok()?;let tag = String::from_utf16_lossy(name.get(..len.checked_sub(1)?)?);diff --git a/muelle/src/data/site.ts b/muelle/src/data/site.tsindex 0cf33ec..09b3ad7 100644--- a/muelle/src/data/site.ts+++ b/muelle/src/data/site.ts@@ -18,6 +18,6 @@ export const site = {releases: "https://github.com/crafter-station/Muelle/releases",download: "https://github.com/crafter-station/Muelle/releases/latest/download/Muelle-Setup.exe",issues: "https://github.com/crafter-station/Muelle/issues",- version: "0.1.12",+ version: "0.1.13",license: "MIT",} as const;