From d0bb7465f651716959148ec510f1f74569971a1d Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Fri, 30 Oct 2026 23:49:38 -0700 Subject: [PATCH] refactor(mac-bar): delete keyboard.rs and media.rs, which nothing compiles komorebi-for-mac/komorebi-bar/src/widgets/keyboard.rs (177 lines, still written against the windows crate) and media.rs (122 lines) are not declared as modules (their mod lines in widgets/mod.rs are comments), so they are not part of the build; the widget variants that would use them are commented out in widget.rs. The files and the two commented-out mod lines are removed. The macOS bar has no keyboard or media widget; the config types of both live in the Windows bar and move to komorebi-bar-core with the platform seam. No behaviour change, no schema change. Verified: macOS fake-CC cargo check --locked --workspace --all-targets finished, 0 errors (6 bar warnings, unchanged); harness regeneration byte-identical for both. Not verified: rendering. --- .../komorebi-bar/src/widgets/keyboard.rs | 177 ------------------ .../komorebi-bar/src/widgets/media.rs | 122 ------------ .../komorebi-bar/src/widgets/mod.rs | 2 - 3 files changed, 301 deletions(-) delete mode 100644 komorebi-for-mac/komorebi-bar/src/widgets/keyboard.rs delete mode 100644 komorebi-for-mac/komorebi-bar/src/widgets/media.rs diff --git a/komorebi-for-mac/komorebi-bar/src/widgets/keyboard.rs b/komorebi-for-mac/komorebi-bar/src/widgets/keyboard.rs deleted file mode 100644 index 4d24d264..00000000 --- a/komorebi-for-mac/komorebi-bar/src/widgets/keyboard.rs +++ /dev/null @@ -1,177 +0,0 @@ -use crate::config::LabelPrefix; -use crate::render::RenderConfig; -use crate::widgets::widget::BarWidget; -use eframe::egui::Align; -use eframe::egui::Context; -use eframe::egui::Label; -use eframe::egui::TextFormat; -use eframe::egui::Ui; -use eframe::egui::WidgetText; -use eframe::egui::text::LayoutJob; -use serde::Deserialize; -use serde::Serialize; -use std::time::Duration; -use std::time::Instant; -use windows::Win32::Globalization::LCIDToLocaleName; -use windows::Win32::Globalization::LOCALE_ALLOW_NEUTRAL_NAMES; -use windows::Win32::System::SystemServices::LOCALE_NAME_MAX_LENGTH; -use windows::Win32::UI::Input::KeyboardAndMouse::GetKeyboardLayout; -use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow; -use windows::Win32::UI::WindowsAndMessaging::GetWindowThreadProcessId; - -const DEFAULT_DATA_REFRESH_INTERVAL: u64 = 1; -const ERROR_TEXT: &str = "Error"; - -#[derive(Copy, Clone, Debug, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -pub struct KeyboardConfig { - /// Enable the Input widget - pub enable: bool, - /// Data refresh interval in seconds - pub data_refresh_interval: Option, - /// Display label prefix - pub label_prefix: Option, -} - -impl From for Keyboard { - fn from(value: KeyboardConfig) -> Self { - let data_refresh_interval = value - .data_refresh_interval - .unwrap_or(DEFAULT_DATA_REFRESH_INTERVAL); - - Self { - enable: value.enable, - data_refresh_interval, - label_prefix: value.label_prefix.unwrap_or(LabelPrefix::IconAndText), - last_updated: Instant::now(), - lang_name: get_lang(), - } - } -} - -pub struct Keyboard { - pub enable: bool, - data_refresh_interval: u64, - label_prefix: LabelPrefix, - last_updated: Instant, - lang_name: String, -} - -/// Retrieves the name of the active keyboard layout for the current foreground window. -/// -/// This function determines the active keyboard layout by querying the system for the -/// foreground window's thread ID and its associated keyboard layout. It then attempts -/// to retrieve the locale name corresponding to the keyboard layout. -/// -/// # Failure Cases -/// -/// This function can fail in two distinct scenarios: -/// -/// 1. **Failure to Retrieve the Locale Name**: -/// If the system fails to retrieve the locale name (e.g., due to an invalid or unsupported -/// language identifier), the function will return `Err(())`. -/// -/// 2. **Invalid UTF-16 Characters in the Locale Name**: -/// If the retrieved locale name contains invalid UTF-16 sequences, the conversion to a Rust -/// `String` will fail, and the function will return `Err(())`. -/// -/// # Returns -/// -/// - `Ok(String)`: The name of the active keyboard layout as a valid UTF-8 string. -/// - `Err(())`: Indicates that the function failed to retrieve the locale name or encountered -/// invalid UTF-16 characters during conversion. -fn get_active_keyboard_layout() -> Result { - let foreground_window_tid = unsafe { GetWindowThreadProcessId(GetForegroundWindow(), None) }; - let lcid = unsafe { GetKeyboardLayout(foreground_window_tid) }; - - // Extract the low word (language identifier) from the keyboard layout handle. - let lang_id = (lcid.0 as u32) & 0xFFFF; - let mut locale_name_buffer = [0; LOCALE_NAME_MAX_LENGTH as usize]; - let char_count = unsafe { - LCIDToLocaleName( - lang_id, - Some(&mut locale_name_buffer), - LOCALE_ALLOW_NEUTRAL_NAMES, - ) - }; - - match char_count { - 0 => Err(()), - _ => String::from_utf16(&locale_name_buffer[..char_count as usize]).map_err(|_| ()), - } -} - -/// Retrieves the name of the active keyboard layout or a fallback error message. -/// -/// # Behavior -/// -/// - **Success Case**: -/// If [`get_active_keyboard_layout`] succeeds, this function returns the retrieved keyboard -/// layout name as a `String`. -/// -/// - **Failure Case**: -/// If [`get_active_keyboard_layout`] fails, this function returns the value of `ERROR_TEXT` -/// as a fallback message. This ensures that the function always returns a valid `String`, -/// even in error scenarios. -/// -/// # Returns -/// -/// A `String` representing either: -/// - The name of the active keyboard layout, or -/// - The fallback error message (`ERROR_TEXT`) if the layout name cannot be retrieved. -fn get_lang() -> String { - get_active_keyboard_layout() - .map(|l| l.trim_end_matches('\0').to_string()) - .unwrap_or_else(|_| ERROR_TEXT.to_string()) -} - -impl Keyboard { - fn output(&mut self) -> String { - let now = Instant::now(); - if now.duration_since(self.last_updated) > Duration::from_secs(self.data_refresh_interval) { - self.last_updated = now; - self.lang_name = get_lang(); - } - - match self.label_prefix { - LabelPrefix::Text | LabelPrefix::IconAndText => format!("KB: {}", self.lang_name), - LabelPrefix::None | LabelPrefix::Icon => self.lang_name.clone(), - } - } -} - -impl BarWidget for Keyboard { - fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { - if self.enable { - let output = self.output(); - if !output.is_empty() { - let mut layout_job = LayoutJob::simple( - match self.label_prefix { - LabelPrefix::Icon | LabelPrefix::IconAndText => { - egui_phosphor::regular::KEYBOARD.to_string() - } - LabelPrefix::None | LabelPrefix::Text => String::new(), - }, - config.icon_font_id.clone(), - ctx.style().visuals.selection.stroke.color, - 100.0, - ); - - layout_job.append( - &output, - 10.0, - TextFormat { - font_id: config.text_font_id.clone(), - color: ctx.style().visuals.text_color(), - valign: Align::Center, - ..Default::default() - }, - ); - - config.apply_on_widget(true, ui, |ui| { - ui.add(Label::new(WidgetText::LayoutJob(layout_job.clone())).selectable(false)) - }); - } - } - } -} diff --git a/komorebi-for-mac/komorebi-bar/src/widgets/media.rs b/komorebi-for-mac/komorebi-bar/src/widgets/media.rs deleted file mode 100644 index 2428d063..00000000 --- a/komorebi-for-mac/komorebi-bar/src/widgets/media.rs +++ /dev/null @@ -1,122 +0,0 @@ -use crate::MAX_LABEL_WIDTH; -use crate::render::RenderConfig; -use crate::selected_frame::SelectableFrame; -use crate::ui::CustomUi; -use crate::widgets::widget::BarWidget; -use eframe::egui::Align; -use eframe::egui::Context; -use eframe::egui::Label; -use eframe::egui::TextFormat; -use eframe::egui::Ui; -use eframe::egui::Vec2; -use eframe::egui::text::LayoutJob; -use serde::Deserialize; -use serde::Serialize; -use std::sync::atomic::Ordering; -use windows::Media::Control::GlobalSystemMediaTransportControlsSessionManager; - -#[derive(Copy, Clone, Debug, Serialize, Deserialize)] -#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] -pub struct MediaConfig { - /// Enable the Media widget - pub enable: bool, -} - -impl From for Media { - fn from(value: MediaConfig) -> Self { - Self::new(value.enable) - } -} - -#[derive(Clone, Debug)] -pub struct Media { - pub enable: bool, - pub session_manager: GlobalSystemMediaTransportControlsSessionManager, -} - -impl Media { - pub fn new(enable: bool) -> Self { - Self { - enable, - session_manager: GlobalSystemMediaTransportControlsSessionManager::RequestAsync() - .unwrap() - .get() - .unwrap(), - } - } - - pub fn toggle(&self) { - if let Ok(session) = self.session_manager.GetCurrentSession() - && let Ok(op) = session.TryTogglePlayPauseAsync() - { - op.get().unwrap_or_default(); - } - } - - fn output(&mut self) -> String { - if let Ok(session) = self.session_manager.GetCurrentSession() - && let Ok(operation) = session.TryGetMediaPropertiesAsync() - && let Ok(properties) = operation.get() - && let (Ok(artist), Ok(title)) = (properties.Artist(), properties.Title()) - { - if artist.is_empty() { - return format!("{title}"); - } - - if title.is_empty() { - return format!("{artist}"); - } - - return format!("{artist} - {title}"); - } - - String::new() - } -} - -impl BarWidget for Media { - fn render(&mut self, ctx: &Context, ui: &mut Ui, config: &mut RenderConfig) { - if self.enable { - let output = self.output(); - if !output.is_empty() { - let mut layout_job = LayoutJob::simple( - egui_phosphor::regular::HEADPHONES.to_string(), - config.icon_font_id.clone(), - ctx.style().visuals.selection.stroke.color, - 100.0, - ); - - layout_job.append( - &output, - 10.0, - TextFormat { - font_id: config.text_font_id.clone(), - color: ctx.style().visuals.text_color(), - valign: Align::Center, - ..Default::default() - }, - ); - - config.apply_on_widget(false, ui, |ui| { - if SelectableFrame::new(false) - .show(ui, |ui| { - let available_height = ui.available_height(); - let mut custom_ui = CustomUi(ui); - - custom_ui.add_sized_left_to_right( - Vec2::new( - MAX_LABEL_WIDTH.load(Ordering::SeqCst) as f32, - available_height, - ), - Label::new(layout_job).selectable(false).truncate(), - ) - }) - .clicked() - { - self.toggle(); - } - }); - } - } - } -} diff --git a/komorebi-for-mac/komorebi-bar/src/widgets/mod.rs b/komorebi-for-mac/komorebi-bar/src/widgets/mod.rs index ea5a5718..34bbb3a8 100644 --- a/komorebi-for-mac/komorebi-bar/src/widgets/mod.rs +++ b/komorebi-for-mac/komorebi-bar/src/widgets/mod.rs @@ -13,10 +13,8 @@ pub mod applications; pub use komorebi_bar_core::widgets::battery; pub use komorebi_bar_core::widgets::cpu; pub use komorebi_bar_core::widgets::date; -// pub mod keyboard; pub mod komorebi; mod komorebi_layout; -// pub mod media; pub use komorebi_bar_core::widgets::memory; pub mod network; pub mod storage;