Repository navigation
feat(gui): pick a custom keyboard lighting color #2666
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,11 +7,15 @@ | |
|
|
||
| use crate::ui::theme::FocusRingStyle as _; | ||
| use gpui::{ | ||
| Context, InteractiveElement, IntoElement, ParentElement, Render, Role, | ||
| StatefulInteractiveElement as _, Styled, Subscription, Toggled, Window, div, px, rgb, | ||
| App, AppContext as _, Context, Entity, Hsla, InteractiveElement, IntoElement, ParentElement, | ||
| Render, Rgba, Role, StatefulInteractiveElement as _, Styled, Subscription, Toggled, Window, | ||
| div, prelude::FluentBuilder as _, px, rgb, | ||
| }; | ||
| use gpui_kit::base::Button as BaseButton; | ||
| use gpui_kit::component::{Selectable as _, h_flex, slider::Slider, v_flex}; | ||
| use gpui_kit::component::color_picker::{ColorPicker, ColorPickerEvent, ColorPickerState}; | ||
| use gpui_kit::component::{ | ||
| IconName, Selectable as _, Sizable as _, Size, h_flex, slider::Slider, v_flex, | ||
| }; | ||
| use openlogi_core::color::Rgb; | ||
| use openlogi_core::config::Lighting; | ||
|
|
||
|
|
@@ -41,13 +45,57 @@ const PALETTE: &[Rgb] = &[ | |
| Rgb::WHITE, | ||
| ]; | ||
|
|
||
| /// The color the custom control stands for: the current color when the | ||
| /// lighting is on and it is none of the presets. | ||
| fn custom_color(current: &Lighting) -> Option<Rgb> { | ||
| (current.enabled && !PALETTE.contains(¤t.color)).then_some(current.color) | ||
| } | ||
|
|
||
| /// A picker color as the 8-bit RGB the keyboard takes. The keys have no | ||
| /// alpha, so a translucent pick lights them at full color. | ||
| fn rgb_of(color: Hsla) -> Rgb { | ||
| #[expect( | ||
| clippy::cast_possible_truncation, | ||
| clippy::cast_sign_loss, | ||
| reason = "clamped to 0.0..=255.0 before the cast" | ||
| )] | ||
| fn channel(value: f32) -> u8 { | ||
| (value.clamp(0., 1.) * 255.).round() as u8 | ||
| } | ||
| let color = Rgba::from(color); | ||
| Rgb::new(channel(color.r), channel(color.g), channel(color.b)) | ||
| } | ||
|
|
||
| /// Light the keys in `color`, unless they already are. | ||
| fn commit_color(color: Rgb, cx: &mut App) { | ||
| let unchanged = AppState::try_read(cx).is_some_and(|state| { | ||
| let lighting = state.lighting(); | ||
| lighting.enabled && lighting.color == color | ||
| }); | ||
| if unchanged { | ||
| return; | ||
| } | ||
| AppState::apply(cx, |state| { | ||
| let mut next = state.lighting(); | ||
| next.enabled = true; | ||
| next.color = color; | ||
| state.commit_lighting(next) | ||
| }); | ||
| } | ||
|
|
||
| pub struct LightingPanel { | ||
| brightness: CommitSlider<u8>, | ||
| /// The picker behind the custom-color control. | ||
| picker: Entity<ColorPickerState>, | ||
| /// The color a slider drag left in the open picker. It is written when | ||
| /// the picker closes, so a drag does not stream writes to the keyboard. | ||
| pending: Option<Rgb>, | ||
| _state_obs: Subscription, | ||
| _picker_subscriptions: [Subscription; 2], | ||
| } | ||
|
|
||
| impl LightingPanel { | ||
| pub fn new(cx: &mut Context<Self>) -> Self { | ||
| pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self { | ||
| let initial = AppState::try_read(cx).map_or(100, |s| s.lighting().brightness); | ||
| // The slider drives the device only on release, to avoid streaming a | ||
| // frame burst to the keyboard for every intermediate drag value. | ||
|
|
@@ -66,11 +114,74 @@ impl LightingPanel { | |
| ); | ||
| let state_obs = | ||
| AppState::repaint_on(cx, |event| matches!(event, StateEvent::LightingChanged(_))); | ||
| let picker = cx.new(|cx| ColorPickerState::new(window, cx)); | ||
| // A palette pick or a hex commit closes the picker before it reports | ||
| // the color, so a closed picker's color is final; a slider drag reports | ||
| // every step while the picker stays open. | ||
| let change = cx.subscribe(&picker, |this, picker, event: &ColorPickerEvent, cx| { | ||
| let ColorPickerEvent::Change(Some(color)) = event else { | ||
| return; | ||
| }; | ||
| let color = rgb_of(*color); | ||
| if picker.read(cx).is_open() { | ||
| this.pending = Some(color); | ||
| } else { | ||
| this.pending = None; | ||
| commit_color(color, cx); | ||
| } | ||
| }); | ||
| let close = cx.observe(&picker, |this, picker, cx| { | ||
| if !picker.read(cx).is_open() | ||
| && let Some(color) = this.pending.take() | ||
| { | ||
| commit_color(color, cx); | ||
| } | ||
| }); | ||
| Self { | ||
| brightness, | ||
| picker, | ||
| pending: None, | ||
| _state_obs: state_obs, | ||
| _picker_subscriptions: [change, close], | ||
| } | ||
| } | ||
|
|
||
| /// The custom-color control: the picker's trigger in a swatch-sized ring. | ||
| /// It shows the current color when that is none of the presets, and a | ||
| /// palette icon otherwise. | ||
| fn custom_control(&self, current: &Lighting, pal: Palette) -> impl IntoElement { | ||
| let custom = custom_color(current); | ||
| let label = match custom { | ||
| Some(color) => format!("{} #{:06X}", tr!("lighting.custom_color"), color.packed()), | ||
| None => tr!("lighting.custom_color").to_string(), | ||
| }; | ||
| let outer = SWATCH_RING + SWATCH_RING_GAP; | ||
| div() | ||
| .flex() | ||
| .items_center() | ||
| .justify_center() | ||
| .size(px(SWATCH + 2. * outer)) | ||
| .p(px(SWATCH_RING_GAP)) | ||
| .rounded(pal.control_radius + px(outer)) | ||
| .border(px(SWATCH_RING)) | ||
| .border_color(if custom.is_some() { | ||
| theme::accent() | ||
| } else { | ||
| gpui::transparent_black() | ||
| }) | ||
| .child( | ||
| ColorPicker::new(&self.picker) | ||
| .with_size(Size::Size(px(SWATCH))) | ||
| .featured_colors( | ||
| PALETTE | ||
| .iter() | ||
| .map(|color| Hsla::from(rgb(color.packed()))) | ||
| .collect(), | ||
| ) | ||
| .accessibility_label(label) | ||
| .when(custom.is_none(), |picker| picker.icon(IconName::Palette)), | ||
|
greptile-apps[bot] marked this conversation as resolved.
Resolved
Comment on lines
+212
to
+221
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The new control never calls Apply it to the picker trigger in both its icon and custom-color states, and add a keyboard-focus test before merging. This is a missing shared style, not a claim that the library draws no focus indicator. Rule Used: Severity: low. Every focusable control calls the shared Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 3f9baa7. The picker's trigger owns the focus handle, so the frame around it draws |
||
| ) | ||
| } | ||
| } | ||
|
|
||
| impl Render for LightingPanel { | ||
|
|
@@ -83,10 +194,20 @@ impl Render for LightingPanel { | |
| // disturbing an in-progress drag. | ||
| self.brightness.sync(lighting.brightness, window, cx); | ||
|
|
||
| // Keep the closed picker on the device's color, so it opens there | ||
| // after a device switch or a preset pick. | ||
| let color = Hsla::from(rgb(lighting.color.packed())); | ||
| let picker = self.picker.read(cx); | ||
| if !picker.is_open() && picker.value() != Some(color) { | ||
| self.picker | ||
| .update(cx, |picker, cx| picker.set_value(color, window, cx)); | ||
| } | ||
|
|
||
| let swatches: Vec<_> = PALETTE | ||
| .iter() | ||
| .map(|&color| swatch(color, &lighting, pal)) | ||
| .collect(); | ||
| let custom = self.custom_control(&lighting, pal); | ||
|
|
||
| v_flex() | ||
| .gap_3() | ||
|
|
@@ -110,7 +231,13 @@ impl Render for LightingPanel { | |
| )) | ||
| // The rings' clear gaps already space the faces; a full gap on top | ||
| // would spread the row. | ||
| .child(h_flex().gap_1().flex_wrap().children(swatches)) | ||
| .child( | ||
| h_flex() | ||
| .gap_1() | ||
| .flex_wrap() | ||
| .children(swatches) | ||
| .child(custom), | ||
| ) | ||
| .child( | ||
| SliderRow::new( | ||
| tr!("camera.brightness"), | ||
|
|
@@ -184,3 +311,6 @@ fn swatch(color: Rgb, current: &Lighting, pal: Palette) -> impl IntoElement { | |
| }); | ||
| }) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests; | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,184 @@ | ||
| use gpui::{Hsla, rgb}; | ||
| use openlogi_core::color::Rgb; | ||
| use openlogi_core::config::Lighting; | ||
|
|
||
| use super::{PALETTE, custom_color, rgb_of}; | ||
|
|
||
| fn lighting(enabled: bool, color: Rgb) -> Lighting { | ||
| Lighting { | ||
| enabled, | ||
| color, | ||
| ..Lighting::default() | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn a_preset_color_is_not_a_custom_color() { | ||
| assert_eq!(custom_color(&lighting(true, PALETTE[0])), None); | ||
| } | ||
|
|
||
| #[test] | ||
| fn an_off_palette_color_is_the_custom_color() { | ||
| let color = Rgb::new(0x00, 0xff, 0xaa); | ||
| assert_eq!(custom_color(&lighting(true, color)), Some(color)); | ||
| } | ||
|
|
||
| #[test] | ||
| fn lighting_off_selects_no_custom_color() { | ||
| assert_eq!( | ||
| custom_color(&lighting(false, Rgb::new(0x00, 0xff, 0xaa))), | ||
| None | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn picker_colors_convert_without_alpha() { | ||
| let translucent = Hsla { | ||
| a: 0.3, | ||
| ..Hsla::from(rgb(0x0000_ffaa)) | ||
| }; | ||
| assert_eq!(rgb_of(translucent), Rgb::new(0x00, 0xff, 0xaa)); | ||
| for &color in PALETTE { | ||
| let hsla = Hsla::from(rgb(color.packed())); | ||
| assert_eq!(rgb_of(hsla), color, "#{:06x}", color.packed()); | ||
| } | ||
| } | ||
|
|
||
| mod picker { | ||
| use std::sync::Arc; | ||
|
|
||
| use gpui::{AppContext as _, Entity, TestAppContext, VisualTestContext, rgb}; | ||
| use gpui_kit::component::color_picker::ColorPickerState; | ||
| use openlogi_core::color::Rgb; | ||
| use openlogi_core::config::Config; | ||
| use openlogi_core::device::{Capabilities, DeviceKind}; | ||
| use tokio::sync::mpsc::UnboundedReceiver; | ||
|
|
||
| use super::super::LightingPanel; | ||
| use crate::services::assets::AssetResolver; | ||
| use crate::services::ipc::Command; | ||
| use crate::state::{AppState, ConfigPersistence, Sources}; | ||
|
|
||
| const CUSTOM: Rgb = Rgb::new(0x00, 0xff, 0xaa); | ||
|
|
||
| /// A lighting keyboard as the selected device, and its panel. | ||
| fn panel( | ||
| cx: &mut TestAppContext, | ||
| ) -> ( | ||
| Entity<LightingPanel>, | ||
| UnboundedReceiver<Command>, | ||
| &mut VisualTestContext, | ||
| ) { | ||
| cx.update(gpui_kit::init); | ||
| let receiver = cx.update(|cx| { | ||
| let (sender, receiver) = tokio::sync::mpsc::unbounded_channel(); | ||
| let mut inventory = crate::state::tests::direct_inventory([1, 2, 3, 4]); | ||
| inventory.paired[0].kind = DeviceKind::Keyboard; | ||
| inventory.paired[0].capabilities = Some(Capabilities { | ||
| lighting: true, | ||
| ..Capabilities::default() | ||
| }); | ||
| let runtime: Arc<dyn swr_core::Runtime> = Arc::new(swr_gpui::GpuiRuntime::new(cx)); | ||
| let client = swr_core::SwrClient::builder().build(runtime.clone()); | ||
| let state = cx.new(|_| { | ||
| let mut state = AppState::new(Sources { | ||
| config: Config::ephemeral(), | ||
| inventories: &[inventory], | ||
| standalone: &[], | ||
| resolver: &AssetResolver::new(), | ||
| cameras: &[], | ||
| persistence: ConfigPersistence::MemoryOnly, | ||
| ipc_commands: sender, | ||
| }); | ||
| state.connect_device_reads(client, runtime); | ||
| state | ||
| }); | ||
| AppState::set_global(state, cx); | ||
| receiver | ||
| }); | ||
| let (panel, cx) = cx.add_window_view(LightingPanel::new); | ||
| cx.run_until_parked(); | ||
| (panel, receiver, cx) | ||
| } | ||
|
|
||
| fn picker_of( | ||
| panel: &Entity<LightingPanel>, | ||
| cx: &mut VisualTestContext, | ||
| ) -> Entity<ColorPickerState> { | ||
| cx.read(|cx| panel.read(cx).picker.clone()) | ||
| } | ||
|
|
||
| fn current(cx: &mut VisualTestContext) -> (bool, Rgb) { | ||
| cx.read(|cx| { | ||
| let lighting = AppState::try_read(cx).unwrap().lighting(); | ||
| (lighting.enabled, lighting.color) | ||
| }) | ||
| } | ||
|
|
||
| fn lighting_writes(receiver: &mut UnboundedReceiver<Command>) -> usize { | ||
| std::iter::from_fn(|| receiver.try_recv().ok()) | ||
| .filter(|command| matches!(command, Command::SetLighting(_))) | ||
| .count() | ||
| } | ||
|
|
||
| #[gpui::test] | ||
| fn a_closed_picker_commits_its_color_at_once(cx: &mut TestAppContext) { | ||
| let _locale = crate::services::i18n::LOCALE_LOCK.lock().unwrap(); | ||
| let (panel, mut receiver, cx) = panel(cx); | ||
| lighting_writes(&mut receiver); | ||
| let picker = picker_of(&panel, cx); | ||
| cx.update(|window, cx| { | ||
| picker.update(cx, |picker, cx| { | ||
| picker.select_color(rgb(CUSTOM.packed()).into(), window, cx); | ||
| }); | ||
| }); | ||
| cx.run_until_parked(); | ||
| assert_eq!(current(cx), (true, CUSTOM)); | ||
| assert_eq!(lighting_writes(&mut receiver), 1); | ||
| } | ||
|
|
||
| #[gpui::test] | ||
| fn an_open_picker_commits_only_when_it_closes(cx: &mut TestAppContext) { | ||
| let _locale = crate::services::i18n::LOCALE_LOCK.lock().unwrap(); | ||
| let (panel, mut receiver, cx) = panel(cx); | ||
| lighting_writes(&mut receiver); | ||
| let before = current(cx); | ||
| let picker = picker_of(&panel, cx); | ||
| cx.update(|window, cx| { | ||
| picker.update(cx, |picker, cx| { | ||
| picker.set_open(true, cx); | ||
| picker.update_color(rgb(0x11_2233).into(), window, cx); | ||
| picker.update_color(rgb(CUSTOM.packed()).into(), window, cx); | ||
| }); | ||
| }); | ||
| cx.run_until_parked(); | ||
| assert_eq!(current(cx), before, "a drag writes nothing"); | ||
| assert_eq!(lighting_writes(&mut receiver), 0); | ||
| cx.update(|_, cx| picker.update(cx, |picker, cx| picker.set_open(false, cx))); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These tests render Before merging, add tests that click the trigger, pick or type a color, drag, and dismiss the picker. Include the required minimum-window check at 125% scale. Rule Used: Severity: medium. A GUI interaction test renders the real view as a window root and drives it the way the user does (click, wheel, focus change) instead of calling the handler. A desktop test that renders localized text or changes the locale holds `L... (source) Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 3f9baa7. The tests now:
gpui-kit v0.8.1 gives the popover's palette swatches and sliders no debug selector, so a test can't target them. The drag test still sends the slider reports through the picker state, but it opens and dismisses the picker with real clicks. The |
||
| cx.run_until_parked(); | ||
| assert_eq!(current(cx), (true, CUSTOM)); | ||
| assert_eq!( | ||
| lighting_writes(&mut receiver), | ||
| 1, | ||
| "closing writes the last color once" | ||
| ); | ||
| } | ||
|
|
||
| #[gpui::test] | ||
| fn closing_an_unchanged_picker_writes_nothing(cx: &mut TestAppContext) { | ||
| let _locale = crate::services::i18n::LOCALE_LOCK.lock().unwrap(); | ||
| let (panel, mut receiver, cx) = panel(cx); | ||
| lighting_writes(&mut receiver); | ||
| let before = current(cx); | ||
| let picker = picker_of(&panel, cx); | ||
| cx.update(|_, cx| { | ||
| picker.update(cx, |picker, cx| { | ||
| picker.set_open(true, cx); | ||
| picker.set_open(false, cx); | ||
| }); | ||
| }); | ||
| cx.run_until_parked(); | ||
| assert_eq!(current(cx), before); | ||
| assert_eq!(lighting_writes(&mut receiver), 0); | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LightingPanel::picker's open status andLightingPanel::pendingtogether encode the edit phase. One callback writespending; another consumes it after checking the open status again. This violates the repository's requirement for one explicit state and transition owner.Replace this coordination with one enum, such as
Closed,OpenClean,OpenDirty(Rgb), andClosing(Rgb), owned by one transition method. Test that it refuses a dirty draft inClosedand changes from an already-finished session. No harmful invalid combination was established as reachable, so the design concern is non-blocking on behavior; the repository requirement still needs resolution before merging.Context Used: Implicit state machines Flag any change that introduces or extends an implicit state machine: a lifecycle, phase, or mode that the code tracks through a combination of independent fields instead of one enum with one transition function. Report it as... (source)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed in 3f9baa7. One
PickerEdit { Closed, Open, Dragged(Rgb) }and onenext(open, color)transition now own the phase, and one handler moves it. Its unit tests cover the cases you named: a finished drag isn't written twice, and closing without a drag writes nothing.