Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/openlogi-desktop/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ impl AppView {
let dpi_panel = cx.new(DpiPanel::new);
let smartshift_panel = cx.new(SmartShiftPanel::new);
let momentum_panel = cx.new(|cx| MomentumPanel::new(MomentumScope::SelectedDevice, cx));
let lighting_panel = cx.new(LightingPanel::new);
let lighting_panel = cx.new(|cx| LightingPanel::new(window, cx));
let camera_preview = cx.new(CameraPreview::new);
let camera_controls = cx.new(CameraControlsPanel::new);
let light_panel = cx.new(LightPanel::new);
Expand Down
140 changes: 135 additions & 5 deletions crates/openlogi-desktop/src/features/lighting/keyboard_rgb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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(&current.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.
Expand All @@ -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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Picker phases have separate writers

LightingPanel::picker's open status and LightingPanel::pending together encode the edit phase. One callback writes pending; 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), and Closing(Rgb), owned by one transition method. Test that it refuses a dirty draft in Closed and 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)

Copy link
Copy Markdown
Author

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 one next(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.

}
});
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)),
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
Comment on lines +212 to +221

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Shared focus style is missing

The new control never calls focus_ring(pal), unlike the neighboring swatches. The repository requires that shared style on every focusable control.

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 focus_ring(pal) from crates/openlogi-desktop/src/ui/theme.rs in all its states, and text painted over accent_tint stays text_primary. A control whose change cannot be applied (device off... (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!

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The 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 focus_ring(pal) under the same keyboard-only rule as focus_visible. The keyboard test focuses it and checks the input modality.

)
}
}

impl Render for LightingPanel {
Expand All @@ -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()
Expand All @@ -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"),
Expand Down Expand Up @@ -184,3 +311,6 @@ fn swatch(color: Rgb, current: &Lighting, pal: Palette) -> impl IntoElement {
});
})
}

#[cfg(test)]
mod tests;
184 changes: 184 additions & 0 deletions crates/openlogi-desktop/src/features/lighting/keyboard_rgb/tests.rs
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)));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Tests bypass picker controls

These tests render LightingPanel but call select_color, update_color, and set_open directly. The repository requires GUI interaction tests to use user actions, not handler calls. A broken trigger, hex-field commit, or outside-click dismissal would leave these tests green.

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!

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 3f9baa7. The tests now:

  • click the control to open the picker
  • type a hex color into its field and press Enter
  • click outside to dismiss it
  • move focus to the control the way Tab does, then Enter opens the picker and Escape closes it
  • check that the control wraps inside a 360 px column at 125%

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 PickerEdit transitions behind it have their own unit tests.

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);
}
}
1 change: 1 addition & 0 deletions crates/openlogi-ui/locales/be.toml
Original file line number Diff line number Diff line change
Expand Up @@ -746,6 +746,7 @@ applying_light_setting = "Прымяненне налады святла…"
auto_on_with_camera = "Аўтаўключэнне з камерай"
camera_light_auto_description = "Уключайце гэта святло, пакуль выкарыстоўваецца якая-небудзь камера, і выключайце, калі камеры перастаюць працаваць."
keyboard_lighting_description = "Ужываецца OpenLogi, пакуль ён працуе, і не захоўваецца ў клавіятуры."
custom_color = "Свой колер"

[action_ring]
actions_ring = "Кола дзеянняў"
Expand Down
Loading