From 16efd67210d3cf865c9a91d8a21281692be69ee2 Mon Sep 17 00:00:00 2001 From: sknowledge <216877555+sknowledge1@users.noreply.github.com> Date: Thu, 24 Sep 2026 11:30:50 +0100 Subject: [PATCH 1/5] fix: keep install dialogs compatible with Godot export Preserve the existing install-dialog behavior in the exported build used to validate the new joystick-lighting panel. Assisted-by: OpenAI Codex --- .../components/install_dialog_compat_test.gd | 21 +++++++++++++++++++ .../install_dialog_compat_test.gd.uid | 1 + 2 files changed, 22 insertions(+) create mode 100644 core/ui/components/install_dialog_compat_test.gd create mode 100644 core/ui/components/install_dialog_compat_test.gd.uid diff --git a/core/ui/components/install_dialog_compat_test.gd b/core/ui/components/install_dialog_compat_test.gd new file mode 100644 index 000000000..07e71d5e5 --- /dev/null +++ b/core/ui/components/install_dialog_compat_test.gd @@ -0,0 +1,21 @@ +extends GutTest + +func _check_dialog(path: String) -> void: + var packed := load(path) as PackedScene + assert_not_null(packed) + var dialog := packed.instantiate() as Control + add_child_autofree(dialog) + await wait_frames(2) + assert_eq(dialog.scroll_maximum_size, Vector2i(0, 600), "Keep the existing scroll growth limit") + var container: ScrollContainer = dialog.scroll_container + var child: Control = container.get_child(0) + child.custom_minimum_size.y = 1000 + await wait_frames(3) + dialog._recalculate_minimum_size() + assert_eq(container.custom_minimum_size.y, 600.0) + +func test_install_location_scroll_growth_limit() -> void: + await _check_dialog("res://core/ui/components/install_location_dialog.tscn") + +func test_install_options_scroll_growth_limit() -> void: + await _check_dialog("res://core/ui/components/install_options_dialog.tscn") diff --git a/core/ui/components/install_dialog_compat_test.gd.uid b/core/ui/components/install_dialog_compat_test.gd.uid new file mode 100644 index 000000000..4a0bd9e98 --- /dev/null +++ b/core/ui/components/install_dialog_compat_test.gd.uid @@ -0,0 +1 @@ +uid://fxkc6ld3f4wh From dffbaeccc642e34e11603473cf4f343808e35ff6 Mon Sep 17 00:00:00 2001 From: sknowledge <216877555+sknowledge1@users.noreply.github.com> Date: Thu, 24 Sep 2026 11:31:05 +0100 Subject: [PATCH 2/5] feat: add native joystick lighting controls Read and apply shared LED state through InputPlumber, with a stock gamepad-friendly panel for Off, Solid, Breathing and Colour cycle. InputPlumber remains the settings owner and hardware writer. Assisted-by: OpenAI Codex --- core/systems/input/input_plumber.gd | 3 + core/systems/input/lighting_model.gd | 158 ++++++++ core/systems/input/lighting_model.gd.uid | 1 + core/systems/input/lighting_model.tres | 6 + core/systems/input/lighting_model_test.gd | 232 +++++++++++ core/systems/input/lighting_model_test.gd.uid | 1 + core/systems/input/lighting_render_test.gd | 59 +++ .../systems/input/lighting_render_test.gd.uid | 1 + core/ui/common/quick_bar/lighting_panel.gd | 158 ++++++++ .../ui/common/quick_bar/lighting_panel.gd.uid | 1 + core/ui/common/quick_bar/lighting_panel.tscn | 73 ++++ .../common/quick_bar/quick_settings_menu.tscn | 27 +- docs/lighting.md | 46 +++ extensions/core/src/dbus/inputplumber.rs | 1 + .../core/src/dbus/inputplumber/led_device.rs | 21 + extensions/core/src/input/inputplumber.rs | 74 ++++ .../core/src/input/inputplumber/led_device.rs | 382 ++++++++++++++++++ .../src/input/inputplumber/led_device_test.rs | 283 +++++++++++++ .../src/input/inputplumber/led_discovery.rs | 122 ++++++ 19 files changed, 1644 insertions(+), 5 deletions(-) create mode 100644 core/systems/input/lighting_model.gd create mode 100644 core/systems/input/lighting_model.gd.uid create mode 100644 core/systems/input/lighting_model.tres create mode 100644 core/systems/input/lighting_model_test.gd create mode 100644 core/systems/input/lighting_model_test.gd.uid create mode 100644 core/systems/input/lighting_render_test.gd create mode 100644 core/systems/input/lighting_render_test.gd.uid create mode 100644 core/ui/common/quick_bar/lighting_panel.gd create mode 100644 core/ui/common/quick_bar/lighting_panel.gd.uid create mode 100644 core/ui/common/quick_bar/lighting_panel.tscn create mode 100644 docs/lighting.md create mode 100644 extensions/core/src/dbus/inputplumber/led_device.rs create mode 100644 extensions/core/src/input/inputplumber/led_device.rs create mode 100644 extensions/core/src/input/inputplumber/led_device_test.rs create mode 100644 extensions/core/src/input/inputplumber/led_discovery.rs diff --git a/core/systems/input/input_plumber.gd b/core/systems/input/input_plumber.gd index afd8c6197..93038c3b4 100644 --- a/core/systems/input/input_plumber.gd +++ b/core/systems/input/input_plumber.gd @@ -9,11 +9,14 @@ class_name InputPlumber @export var instance: InputPlumberInstance = load("res://core/systems/input/input_plumber.tres") +const LIGHTING := preload("res://core/systems/input/lighting_model.tres") + # Keep a reference to dbus devices so they are not cleaned up automatically var _dbus_devices := {} func _ready() -> void: + LIGHTING.start(instance) # Add listeners for any new devices var on_device_added := func(device: CompositeDevice): var dbus_devices := device.dbus_devices diff --git a/core/systems/input/lighting_model.gd b/core/systems/input/lighting_model.gd new file mode 100644 index 000000000..5b8a1f000 --- /dev/null +++ b/core/systems/input/lighting_model.gd @@ -0,0 +1,158 @@ +extends Resource +class_name LightingModel +## Shared settings and drafts. Only InputPlumber owns effects or persistence. +signal updated + +const EFFECT_LABELS := {"off": "Off", "solid": "Solid colour", "breathing": "Breathing", "cycle": "Colour cycle"} +const DEFAULT_CONFIG := {"effect": "off", "color": [255, 255, 255], "brightness": 30, "cycle_period_ms": 8000} +var entries: Dictionary = {} +var selected_id: String = "" +var _instance: Object +var _sources: Array = [] + +func start(instance: Object) -> void: + if _instance == instance: + return + if _instance: + _instance.led_device_added.disconnect(_on_device_added) + _instance.led_device_removed.disconnect(_on_device_removed) + _instance = instance + _instance.led_device_added.connect(_on_device_added, CONNECT_DEFERRED) + _instance.led_device_removed.connect(_on_device_removed, CONNECT_DEFERRED) + set_sources(_instance.get_led_devices()) + +func _on_device_added(_device: Object) -> void: + set_sources(_instance.get_led_devices()) + +func _on_device_removed(_path: String) -> void: + set_sources(_instance.get_led_devices()) + +## Injectable source boundary also used by the headless regression tests. +func set_sources(sources: Array) -> void: + for source in _sources: + if source in sources: + continue + source.lighting_changed.disconnect(_on_source_changed.bind(source)) + source.apply_finished.disconnect(_on_apply_finished.bind(source)) + for key in entries: + var entry: Dictionary = entries[key] + if entry.source != source: + continue + entry.source = null + entry.snapshot.available = false + entry.snapshot.error = "Lighting device disconnected." + if entry.busy: + entry.error = "Device disconnected; check the saved settings before retrying." + entry.busy = false + for source in sources: + if source not in _sources: + source.lighting_changed.connect(_on_source_changed.bind(source), CONNECT_DEFERRED) + source.apply_finished.connect(_on_apply_finished.bind(source), CONNECT_DEFERRED) + _sources = sources.duplicate() + for source in _sources: + _on_source_changed(source) + updated.emit() + +func _on_source_changed(source: Object) -> void: + if source not in _sources: + return + var snapshot: Dictionary = source.get_snapshot() + var key: String = snapshot.get("persistent_id", "") + if key.is_empty(): + updated.emit() + return + if not entries.has(key): + entries[key] = {"source": source, "snapshot": snapshot, "draft": DEFAULT_CONFIG.duplicate(true), + "dirty": false, "busy": false, "error": "", "edits": 0, "submitted_edits": -1, "request": 0} + var entry: Dictionary = entries[key] + # Duplicate persistent IDs cannot be safely controlled as one device. + for other in _sources: + if other != source and str(other.get_snapshot().get("persistent_id", "")) == key: + entry.snapshot.available = false + entry.snapshot.error = "More than one lighting device has this identity." + updated.emit() + return + entry.source = source + entry.snapshot = snapshot.duplicate(true) + if not entry.dirty and snapshot.has("config"): + entry.draft = snapshot.config.duplicate(true) + if selected_id.is_empty(): + selected_id = key + updated.emit() + +func select_device(key: String) -> void: + if entries.has(key): + selected_id = key + updated.emit() + +func current() -> Dictionary: + return entries.get(selected_id, {}) + +func edit(field: String, value: Variant) -> void: + var entry := current() + if entry.is_empty() or not DEFAULT_CONFIG.has(field): + return + entry.draft[field] = value.duplicate() if value is Array else value + entry.edits += 1 + entry.dirty = true + entry.error = "" + updated.emit() + +func apply(turn_off: bool = false) -> void: + var entry := current() + if entry.is_empty() or entry.busy or not entry.source or not entry.snapshot.get("available", false): + return + if turn_off: + entry.draft.effect = "off" + entry.edits += 1 + entry.dirty = true + var draft: Dictionary = entry.draft + entry.error = "" + var request: int = entry.source.apply_config(draft.effect, PackedByteArray(draft.color), int(draft.brightness), int(draft.cycle_period_ms)) + if request <= 0: + entry.error = "These lighting settings are unavailable. Refresh and try again." + else: + entry.busy = true + entry.request = request + entry.submitted_edits = entry.edits + updated.emit() + +func _on_apply_finished(request: int, success: bool, error: String, source: Object) -> void: + for key in entries: + var entry: Dictionary = entries[key] + if entry.source != source or not entry.busy or entry.request != request: + continue + entry.busy = false + entry.error = error + if success: + entry.snapshot = source.get_snapshot().duplicate(true) + if entry.edits == entry.submitted_edits: + entry.dirty = false + entry.draft = entry.snapshot.config.duplicate(true) + updated.emit() + return + +func status_text() -> String: + var entry := current() + if entry.is_empty(): + for source in _sources: + var state: Dictionary = source.get_snapshot() + if not str(state.get("error", "")).is_empty(): + return str(state.error) + return "Joystick lighting is unavailable. A supported device and InputPlumber lighting support are required." + if not str(entry.error).is_empty(): + return str(entry.error) + if entry.busy: + return "Saving lighting settings..." + var snapshot: Dictionary = entry.snapshot + if not snapshot.get("available", false): + return str(snapshot.get("error", "Lighting controls are unavailable.")) + if snapshot.status == "failed": + return "Settings are saved, but lighting could not be applied. %s Use Apply lighting to retry." % snapshot.get("error", "") + if snapshot.status == "unavailable": + return "Settings are saved. The lighting device is unavailable. %s" % snapshot.get("error", "") + if snapshot.status == "pending": + return "Settings are saved. Waiting for the lighting device." + if entry.dirty: + return "You have unapplied changes." + return "Lighting settings applied." diff --git a/core/systems/input/lighting_model.gd.uid b/core/systems/input/lighting_model.gd.uid new file mode 100644 index 000000000..64c1398cc --- /dev/null +++ b/core/systems/input/lighting_model.gd.uid @@ -0,0 +1 @@ +uid://psqdk1prlgny diff --git a/core/systems/input/lighting_model.tres b/core/systems/input/lighting_model.tres new file mode 100644 index 000000000..255f15873 --- /dev/null +++ b/core/systems/input/lighting_model.tres @@ -0,0 +1,6 @@ +[gd_resource type="Resource" script_class="LightingModel" load_steps=2 format=3] + +[ext_resource type="Script" path="res://core/systems/input/lighting_model.gd" id="1"] + +[resource] +script = ExtResource("1") diff --git a/core/systems/input/lighting_model_test.gd b/core/systems/input/lighting_model_test.gd new file mode 100644 index 000000000..db8eabfa3 --- /dev/null +++ b/core/systems/input/lighting_model_test.gd @@ -0,0 +1,232 @@ +extends GutTest + +const Model := preload("res://core/systems/input/lighting_model.gd") +const PanelScene := preload("res://core/ui/common/quick_bar/lighting_panel.tscn") + +class FakeSource extends RefCounted: + signal lighting_changed + signal apply_finished(request: int, success: bool, error: String) + var calls: Array = [] + var state: Dictionary = {"available": true, "api_version": 1, "persistent_id": "test-rings", + "effects": ["off", "solid", "breathing", "cycle"], "cycle_min_ms": 2000, "cycle_max_ms": 30000, + "config": {"effect": "off", "color": [255, 255, 255], "brightness": 30, "cycle_period_ms": 8000}, + "revision": "0", "status": "applied", "error": ""} + func get_snapshot() -> Dictionary: + return state.duplicate(true) + func apply_config(effect: String, color: PackedByteArray, brightness: int, period: int) -> int: + calls.append({"effect": effect, "color": Array(color), "brightness": brightness, "cycle_period_ms": period}) + return calls.size() + func complete(success: bool = true, error: String = "") -> void: + if success: + state.config = calls.back().duplicate(true) + state.revision = str(calls.size()) + apply_finished.emit(calls.size(), success, error) + +var model: LightingModel +var source: FakeSource + +func before_each() -> void: + model = Model.new() + source = FakeSource.new() + model.set_sources([source]) + +func after_each() -> void: + model.set_sources([]) + model = null + source = null + +func test_external_state_preserves_dirty_draft() -> void: + source.state.config.effect = "solid" + source.lighting_changed.emit() + await wait_frames(2) + assert_eq(model.current().draft.effect, "solid") + model.edit("brightness", 44) + source.state.config.brightness = 90 + source.lighting_changed.emit() + await wait_frames(2) + assert_eq(model.current().snapshot.config.brightness, 90) + assert_eq(model.current().draft.brightness, 44) + +func test_apply_keeps_new_edits_and_uses_latest_saved_state() -> void: + model.edit("effect", "solid") + model.apply() + model.apply() + assert_eq(source.calls.size(), 1, "Only one request may be in flight") + model.edit("brightness", 63) + source.complete() + await wait_frames(2) + assert_true(model.current().dirty) + assert_eq(model.current().draft.brightness, 63) + model.apply() + source.complete() + await wait_frames(2) + assert_false(model.current().dirty) + assert_eq(model.current().draft.brightness, 63) + +func test_write_error_survives_notifications_and_can_retry() -> void: + model.edit("effect", "cycle") + model.apply() + source.complete(false, "Not authorized") + await wait_frames(2) + source.lighting_changed.emit() + await wait_frames(2) + assert_eq(model.status_text(), "Not authorized") + assert_true(model.current().dirty) + model.apply() + source.complete() + await wait_frames(2) + assert_eq(model.current().error, "") + assert_false(model.current().busy) + +func test_disconnect_restart_preserves_draft_and_ignores_stale_result() -> void: + model.edit("effect", "breathing") + model.apply() + model.set_sources([]) + assert_false(model.current().busy) + assert_false(model.current().snapshot.available) + var replacement := FakeSource.new() + model.set_sources([replacement]) + source.complete() + await wait_frames(2) + assert_eq(model.current().draft.effect, "breathing") + assert_true(model.current().dirty) + assert_true(model.current().snapshot.available) + model.apply() + replacement.complete() + await wait_frames(2) + assert_false(model.current().dirty) + +func test_turn_off_retains_remembered_color_and_brightness() -> void: + model.edit("color", [12, 23, 34]) + model.edit("brightness", 47) + model.apply(true) + assert_eq(source.calls[0], {"effect": "off", "color": [12, 23, 34], "brightness": 47, "cycle_period_ms": 8000}) + source.complete() + await wait_frames(2) + assert_eq(model.current().draft.brightness, 47) + +func test_hardware_failure_is_distinct_from_successful_save() -> void: + model.apply() + source.state.status = "failed" + source.state.error = "Device write failed" + source.complete() + await wait_frames(2) + assert_false(model.current().dirty) + assert_string_contains(model.status_text(), "saved") + assert_string_contains(model.status_text(), "Device write failed") + +func test_multiple_devices_have_separate_drafts() -> void: + var other := FakeSource.new() + other.state.persistent_id = "other-rings" + model.set_sources([source, other]) + model.edit("brightness", 11) + model.select_device("other-rings") + model.edit("brightness", 22) + model.select_device("test-rings") + assert_eq(model.current().draft.brightness, 11) + model.select_device("other-rings") + assert_eq(model.current().draft.brightness, 22) + +func test_duplicate_identity_is_unavailable() -> void: + var other := FakeSource.new() + model.set_sources([source, other]) + source.lighting_changed.emit() + await wait_frames(2) + assert_false(model.current().snapshot.available) + model.apply() + assert_eq(source.calls.size(), 0) + assert_eq(other.calls.size(), 0) + +func _panel() -> Control: + var panel := PanelScene.instantiate() + panel.model = model + panel.connect_backend = false + panel.size = Vector2(420, 1000) + add_child_autofree(panel) + return panel + +func test_panel_retains_draft_request_and_error_across_remount() -> void: + var first := _panel() + await wait_frames(2) + model.edit("effect", "solid") + model.edit("brightness", 69) + model.apply() + first.queue_free() + await wait_frames(2) + var second := _panel() + await wait_frames(2) + assert_eq(second.brightness.value, 69.0) + assert_true(second.apply_button.disabled) + source.complete(false, "Authorization denied") + await wait_frames(2) + assert_false(second.apply_button.disabled) + assert_eq(second.status.text, "Authorization denied") + assert_eq(source.calls.size(), 1, "Closing a panel must never issue Off") + +func test_controls_capabilities_and_focus_follow_effect() -> void: + var panel := _panel() + await wait_frames(2) + model.edit("effect", "cycle") + await wait_frames(2) + assert_true(panel.cycle.visible) + assert_false(panel.red.visible) + assert_false(panel.breathing_note.visible) + var controls: Array[Control] = panel._focus_controls() + assert_eq(controls.size(), 5) + panel.effect.option_button.grab_focus() + assert_eq(panel.effect.option_button.find_valid_focus_neighbor(SIDE_BOTTOM), panel.brightness.slider) + panel.brightness.slider.grab_focus() + assert_eq(panel.brightness.slider.find_valid_focus_neighbor(SIDE_BOTTOM), panel.cycle.slider) + model.edit("effect", "breathing") + await wait_frames(2) + assert_false(panel.cycle.visible) + assert_true(panel.red.visible) + assert_true(panel.breathing_note.visible) + assert_eq(panel._focus_controls().size(), 7) + source.state.effects = ["off", "solid"] + source.lighting_changed.emit() + await wait_frames(2) + assert_true(panel.apply_button.disabled) + assert_false(panel.red.visible) + assert_eq(panel.effect.option_button.item_count, 2) + model.edit("effect", "solid") + await wait_frames(2) + assert_false(panel.apply_button.disabled) + +func test_missing_backend_shows_unavailable_and_no_controls() -> void: + model.set_sources([]) + var panel := _panel() + await wait_frames(2) + assert_false(panel.effect.visible) + assert_false(panel.apply_button.visible) + assert_string_contains(panel.status.text, "disconnected") + +func test_stock_quick_settings_scroll_and_controller_focus() -> void: + var scene := load("res://core/ui/common/quick_bar/quick_settings_menu.tscn") as PackedScene + var menu := scene.instantiate() as Control + # Isolate layout/navigation from the existing audio/backlight integrations. + menu.set_script(null) + menu.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT) + menu.size = Vector2(480, 450) + var panel: Control = menu.get_node("Scroll/QuickVBoxContainer/JoystickLighting") + panel.model = model + panel.connect_backend = false + add_child_autofree(menu) + model.edit("effect", "solid") + await wait_frames(4) + var scroll: ScrollContainer = menu.get_node("Scroll") + var volume: Control = menu.get_node("Scroll/QuickVBoxContainer/VolumeSlider") + var saturation: Control = menu.get_node("Scroll/QuickVBoxContainer/SaturationSlider") + assert_eq(panel.effect.option_button.get_node(panel.effect.option_button.focus_neighbor_top), saturation) + assert_eq(panel.off_button.get_node(panel.off_button.focus_neighbor_bottom), volume) + panel.off_button.grab_focus() + await wait_frames(3) + assert_gt(scroll.scroll_vertical, 0, "Controller focus must scroll the lower controls into view") + var bottom: float = panel.off_button.get_global_rect().end.y + assert_true(bottom <= scroll.get_global_rect().end.y + 1.0) + var event := InputEventAction.new() + event.action = "ui_down" + event.pressed = true + Input.parse_input_event(event) + await wait_frames(2) + assert_eq(get_viewport().gui_get_focus_owner(), volume.slider) diff --git a/core/systems/input/lighting_model_test.gd.uid b/core/systems/input/lighting_model_test.gd.uid new file mode 100644 index 000000000..98327f102 --- /dev/null +++ b/core/systems/input/lighting_model_test.gd.uid @@ -0,0 +1 @@ +uid://cmh17gfuuxdo2 diff --git a/core/systems/input/lighting_render_test.gd b/core/systems/input/lighting_render_test.gd new file mode 100644 index 000000000..4c26dc5e9 --- /dev/null +++ b/core/systems/input/lighting_render_test.gd @@ -0,0 +1,59 @@ +extends SceneTree +const Fixtures := preload("res://core/systems/input/lighting_model_test.gd") +const Scene := preload("res://core/ui/common/quick_bar/lighting_panel.tscn") +var model: LightingModel +var source: Fixtures.FakeSource + +func _initialize() -> void: + _run.call_deferred() + +func _run() -> void: + print("LED_RENDER_START") + OS.low_processor_usage_mode = false + Engine.max_fps = 60 + root.mode = Window.MODE_WINDOWED + root.content_scale_size = Vector2i(480, 800) + model = LightingModel.new() + source = Fixtures.FakeSource.new() + source.state.config.effect = "breathing" + source.state.config.color = [80, 160, 255] + source.state.config.brightness = 30 + model.set_sources([source]) + root.size = Vector2i(480, 800) + var background := ColorRect.new() + background.color = Color("#17191f") + background.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) + root.add_child(background) + var scroll := ScrollContainer.new() + scroll.position = Vector2(20, 20) + scroll.size = Vector2(440, 760) + scroll.follow_focus = true + scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED + root.add_child(scroll) + var panel := Scene.instantiate() + panel.model = model + panel.connect_backend = false + panel.theme = load("res://assets/themes/card_ui-dracula.tres") + scroll.add_child(panel) + for i in 5: + await process_frame + RenderingServer.force_draw() + var image := root.get_texture().get_image() + var result := image.save_png("/work/artifacts/ogui-lighting-breathing.png") + assert(result == OK) + model.edit("effect", "cycle") + for i in 4: + await process_frame + panel.effect.option_button.grab_focus() + RenderingServer.force_draw() + result = root.get_texture().get_image().save_png("/work/artifacts/ogui-lighting-cycle.png") + assert(result == OK) + panel.queue_free() + scroll.queue_free() + background.queue_free() + model.set_sources([]) + await process_frame + model = null + source = null + print("LED_RENDER_OK: breathing and cycle panels at 480x800") + quit(0) diff --git a/core/systems/input/lighting_render_test.gd.uid b/core/systems/input/lighting_render_test.gd.uid new file mode 100644 index 000000000..e6c078d74 --- /dev/null +++ b/core/systems/input/lighting_render_test.gd.uid @@ -0,0 +1 @@ +uid://lm51nklla5h5 diff --git a/core/ui/common/quick_bar/lighting_panel.gd b/core/ui/common/quick_bar/lighting_panel.gd new file mode 100644 index 000000000..3d9bd5553 --- /dev/null +++ b/core/ui/common/quick_bar/lighting_panel.gd @@ -0,0 +1,158 @@ +extends VBoxContainer +## The shared resource keeps drafts and requests alive across quick-menu remounts. +@export var model: LightingModel = preload("res://core/systems/input/lighting_model.tres") +@export var connect_backend := true +var _updating := false +var _effects: Array[String] = [] +var _ids: Array = [] +var _last_focus: Control + +@onready var device: Dropdown = $Device +@onready var effect: Dropdown = $Effect +@onready var red: ValueSlider = $Red +@onready var green: ValueSlider = $Green +@onready var blue: ValueSlider = $Blue +@onready var brightness: ValueSlider = $Brightness +@onready var cycle: ValueSlider = $Cycle +@onready var apply_button: Button = $Apply +@onready var off_button: Button = $Off +@onready var status: Label = $Status +@onready var breathing_note: Label = $BreathingNote + +func _ready() -> void: + if connect_backend: + model.start(load("res://core/systems/input/input_plumber.tres")) + model.updated.connect(_refresh) + device.item_selected.connect(_select_device) + effect.item_selected.connect(_select_effect) + red.value_changed.connect(_edit_color.bind(0)) + green.value_changed.connect(_edit_color.bind(1)) + blue.value_changed.connect(_edit_color.bind(2)) + brightness.value_changed.connect(_edit_number.bind("brightness", 1)) + cycle.value_changed.connect(_edit_number.bind("cycle_period_ms", 1000)) + apply_button.pressed.connect(model.apply) + off_button.pressed.connect(model.apply.bind(true)) + focus_entered.connect(_grab_inner_focus) + visibility_changed.connect(_update_focus) + _refresh() + +func _exit_tree() -> void: + if model.updated.is_connected(_refresh): + model.updated.disconnect(_refresh) + +func _select_device(index: int) -> void: + if not _updating and index >= 0 and index < _ids.size(): + model.select_device(str(_ids[index])) + +func _select_effect(index: int) -> void: + if not _updating and index >= 0 and index < _effects.size(): + model.edit("effect", _effects[index]) + +func _edit_color(value: float, index: int) -> void: + if _updating or model.current().is_empty(): + return + var color: Array = model.current().draft.color.duplicate() + color[index] = int(value) + model.edit("color", color) + +func _edit_number(value: float, field: String, factor: int) -> void: + if not _updating: + model.edit(field, int(value * factor)) + +func _refresh() -> void: + if not is_node_ready(): + return + _updating = true + var entry := model.current() + var available: bool = not entry.is_empty() and entry.snapshot.get("available", false) + var busy: bool = not entry.is_empty() and entry.busy + status.text = model.status_text() + _ids = model.entries.keys() + device.visible = _ids.size() > 1 + device.clear() + for key in _ids: + device.add_item(str(key).replace("-", " ").capitalize()) + device.select(_ids.find(model.selected_id)) + device.disabled = busy + _effects.clear() + if available: + for name in entry.snapshot.effects: + if LightingModel.EFFECT_LABELS.has(name): + _effects.append(name) + effect.clear() + for name in _effects: + effect.add_item(LightingModel.EFFECT_LABELS[name]) + effect.visible = available + effect.disabled = busy + var draft: Dictionary = entry.get("draft", LightingModel.DEFAULT_CONFIG) + var supported := str(draft.effect) in _effects + effect.select(_effects.find(str(draft.effect))) + var colored: bool = available and supported and draft.effect in ["solid", "breathing"] + for slider in [red, green, blue]: + slider.visible = colored + slider.editable = not busy + red.value = int(draft.color[0]) + green.value = int(draft.color[1]) + blue.value = int(draft.color[2]) + brightness.visible = available and supported and draft.effect != "off" + brightness.editable = not busy + brightness.value = int(draft.brightness) + cycle.visible = available and supported and draft.effect == "cycle" + cycle.editable = not busy + cycle.min_value = float(entry.get("snapshot", {}).get("cycle_min_ms", 2000)) / 1000.0 + cycle.max_value = float(entry.get("snapshot", {}).get("cycle_max_ms", 30000)) / 1000.0 + cycle.value = float(draft.cycle_period_ms) / 1000.0 + breathing_note.visible = available and supported and draft.effect == "breathing" + apply_button.visible = available + off_button.visible = available and "off" in _effects + apply_button.disabled = busy or not supported + off_button.disabled = busy + _updating = false + _update_focus.call_deferred() + +func _focus_controls() -> Array[Control]: + var controls: Array[Control] = [] + if device.visible and not device.disabled: + controls.append(device.option_button) + if effect.visible and not effect.disabled: + controls.append(effect.option_button) + for slider in [red, green, blue, brightness, cycle]: + if slider.visible and slider.editable: + controls.append(slider.slider) + for button in [apply_button, off_button]: + if button.visible and not button.disabled: + controls.append(button) + return controls + +func _update_focus() -> void: + if not is_node_ready() or not is_inside_tree(): + return + var controls := _focus_controls() + for i in controls.size(): + var control := controls[i] + var previous: NodePath = controls[i - 1].get_path() if i > 0 else focus_neighbor_top + var next: NodePath = controls[i + 1].get_path() if i + 1 < controls.size() else focus_neighbor_bottom + control.focus_neighbor_top = previous + control.focus_previous = previous + control.focus_neighbor_bottom = next + control.focus_next = next + if not control.focus_entered.is_connected(_remember_focus.bind(control)): + control.focus_entered.connect(_remember_focus.bind(control)) + if is_instance_valid(_last_focus) and not _last_focus in controls and _last_focus.has_focus(): + _grab_inner_focus() + +func _remember_focus(control: Control) -> void: + _last_focus = control + +func _grab_inner_focus() -> void: + var controls := _focus_controls() + if is_instance_valid(_last_focus) and _last_focus in controls: + _last_focus.grab_focus() + elif not controls.is_empty(): + controls[0].grab_focus() + +# FocusGroup updates the wrapper after it has entered the tree. +func _set(property: StringName, _value: Variant) -> bool: + if property.begins_with("focus_") and is_node_ready(): + _update_focus.call_deferred() + return false diff --git a/core/ui/common/quick_bar/lighting_panel.gd.uid b/core/ui/common/quick_bar/lighting_panel.gd.uid new file mode 100644 index 000000000..9d26f2528 --- /dev/null +++ b/core/ui/common/quick_bar/lighting_panel.gd.uid @@ -0,0 +1 @@ +uid://dxmalh76og4qv diff --git a/core/ui/common/quick_bar/lighting_panel.tscn b/core/ui/common/quick_bar/lighting_panel.tscn new file mode 100644 index 000000000..f6b960cd7 --- /dev/null +++ b/core/ui/common/quick_bar/lighting_panel.tscn @@ -0,0 +1,73 @@ +[gd_scene load_steps=6 format=3] + +[ext_resource type="Script" path="res://core/ui/common/quick_bar/lighting_panel.gd" id="1"] +[ext_resource type="PackedScene" path="res://core/ui/components/dropdown.tscn" id="2"] +[ext_resource type="PackedScene" path="res://core/ui/components/slider.tscn" id="3"] +[ext_resource type="PackedScene" path="res://core/ui/components/button.tscn" id="4"] +[ext_resource type="PackedScene" path="res://core/ui/components/section_label.tscn" id="5"] + +[node name="JoystickLighting" type="VBoxContainer"] +layout_mode = 2 +size_flags_horizontal = 3 +focus_mode = 2 +theme_override_constants/separation = 10 +script = ExtResource("1") + +[node name="Title" parent="." instance=ExtResource("5")] +layout_mode = 2 +text = "Joystick lighting" + +[node name="Status" type="Label" parent="."] +layout_mode = 2 +size_flags_horizontal = 3 +autowrap_mode = 3 +text = "Lighting controls are loading." + +[node name="Device" parent="." instance=ExtResource("2")] +layout_mode = 2 +title = "Lighting device" +description = "" + +[node name="Effect" parent="." instance=ExtResource("2")] +layout_mode = 2 +title = "Effect" +description = "" + +[node name="Red" parent="." instance=ExtResource("3")] +layout_mode = 2 +text = "Red" +max_value = 255.0 + +[node name="Green" parent="." instance=ExtResource("3")] +layout_mode = 2 +text = "Green" +max_value = 255.0 + +[node name="Blue" parent="." instance=ExtResource("3")] +layout_mode = 2 +text = "Blue" +max_value = 255.0 + +[node name="Brightness" parent="." instance=ExtResource("3")] +layout_mode = 2 +text = "Lighting brightness (%)" + +[node name="Cycle" parent="." instance=ExtResource("3")] +layout_mode = 2 +text = "Colour cycle (seconds)" +min_value = 2.0 +max_value = 30.0 +value = 8.0 + +[node name="BreathingNote" type="Label" parent="."] +layout_mode = 2 +autowrap_mode = 3 +text = "Breathing speed is fixed by the device." + +[node name="Apply" parent="." instance=ExtResource("4")] +layout_mode = 2 +text = "Apply lighting" + +[node name="Off" parent="." instance=ExtResource("4")] +layout_mode = 2 +text = "Turn off" diff --git a/core/ui/common/quick_bar/quick_settings_menu.tscn b/core/ui/common/quick_bar/quick_settings_menu.tscn index 3bc71621f..42e59126f 100644 --- a/core/ui/common/quick_bar/quick_settings_menu.tscn +++ b/core/ui/common/quick_bar/quick_settings_menu.tscn @@ -5,6 +5,8 @@ [ext_resource type="PackedScene" uid="uid://cemxrvvjgm4g" path="res://core/ui/components/slider.tscn" id="2_v67rd"] [ext_resource type="Resource" uid="uid://dpc1o781f43ef" path="res://core/ui/card_ui/quick_bar/quick_bar_menu_focus.tres" id="3_ljj2w"] +[ext_resource type="PackedScene" path="res://core/ui/common/quick_bar/lighting_panel.tscn" id="6_lighting"] + [node name="QuickSettingsMenu" type="Control" unique_id=127986489] layout_mode = 3 anchors_preset = 15 @@ -16,7 +18,17 @@ size_flags_horizontal = 3 size_flags_vertical = 3 script = ExtResource("1_gwnsx") -[node name="QuickVBoxContainer" type="VBoxContainer" parent="." unique_id=367667494] +[node name="Scroll" type="ScrollContainer" parent="."] +layout_mode = 1 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 +follow_focus = true +horizontal_scroll_mode = 0 + +[node name="QuickVBoxContainer" type="VBoxContainer" parent="Scroll" unique_id=367667494] layout_mode = 1 anchors_preset = 15 anchor_right = 1.0 @@ -24,26 +36,31 @@ anchor_bottom = 1.0 grow_horizontal = 2 grow_vertical = 2 -[node name="FocusGroup" parent="QuickVBoxContainer" unique_id=1117910552 node_paths=PackedStringArray("current_focus") instance=ExtResource("2_2f2tv")] +size_flags_horizontal = 3 + +[node name="FocusGroup" parent="Scroll/QuickVBoxContainer" unique_id=1117910552 node_paths=PackedStringArray("current_focus") instance=ExtResource("2_2f2tv")] unique_name_in_owner = true current_focus = NodePath("../VolumeSlider") focus_stack = ExtResource("3_ljj2w") -[node name="VolumeSlider" parent="QuickVBoxContainer" unique_id=185484119 instance=ExtResource("2_v67rd")] +[node name="VolumeSlider" parent="Scroll/QuickVBoxContainer" unique_id=185484119 instance=ExtResource("2_v67rd")] unique_name_in_owner = true layout_mode = 2 text = "Volume" -[node name="BrightnessSlider" parent="QuickVBoxContainer" unique_id=2142893004 instance=ExtResource("2_v67rd")] +[node name="BrightnessSlider" parent="Scroll/QuickVBoxContainer" unique_id=2142893004 instance=ExtResource("2_v67rd")] unique_name_in_owner = true layout_mode = 2 text = "Brightness" step = 3.0 -[node name="SaturationSlider" parent="QuickVBoxContainer" unique_id=1840954089 instance=ExtResource("2_v67rd")] +[node name="SaturationSlider" parent="Scroll/QuickVBoxContainer" unique_id=1840954089 instance=ExtResource("2_v67rd")] unique_name_in_owner = true layout_mode = 2 text = "Saturation" value = 100.0 max_value = 400.0 step = 5.0 + +[node name="JoystickLighting" parent="Scroll/QuickVBoxContainer" instance=ExtResource("6_lighting")] +layout_mode = 2 diff --git a/docs/lighting.md b/docs/lighting.md new file mode 100644 index 000000000..352496fa8 --- /dev/null +++ b/docs/lighting.md @@ -0,0 +1,46 @@ +# Joystick lighting + +The stock quick-settings menu includes lighting controls when InputPlumber +exposes LED API version 1. InputPlumber owns persistence and effects; closing OGUI +does not turn lighting off. Decky can configure the same settings independently. + +The controls offer only advertised effects: Off, Solid, fixed-tempo hardware +Breathing, and Colour cycle. RGB is remembered for Solid/Breathing; cycle period +is 2–30 seconds and brightness is independent. Off preserves the other values. +Apply saves a complete configuration. The status distinguishes saved settings +from pending, applied, unavailable, and failed hardware state. + +The shared LightingModel retains each identity's dirty draft and in-flight +request across quick-menu remounts. A backend notification updates clean drafts; +it never overwrites pending edits. A duplicate persistent identity is ambiguous +and cannot be configured. A missing/older backend leaves the rest of quick +settings usable. + +Native LED resources use bounded asynchronous requests, unique D-Bus owner pins, +coalesced snapshots, PropertiesChanged notifications, and explicit reconnect. +No sysfs, private service, or effect loop exists in the frontend. Native signals +are deferred before GDScript reads a resource to avoid reentrant mutable borrows. +The API wire types are documented in the companion InputPlumber change. + +## Verification + +From extensions/, run: +```sh +cargo test --locked -p opengamepadui-core led -- --test-threads=1 +cargo clippy --locked -p opengamepadui-core --all-targets +cargo build --locked --release +``` + +Use the project's GUT runner for +core/systems/input/lighting_model_test.gd. Require 12 collected tests, no failures +or skips, and no SCRIPT ERROR; a GUT process exit of zero alone is insufficient. +The tests cover lifecycle, multi-device isolation, stale replies, dirty drafts, +errors, capability controls, and stock quick-settings focus/scroll behavior. +lighting_render_test.gd renders fixture panels without a physical LED device. +Native tests start a private bus and fake services. + +The pinned Godot 4.7.1 baseline also needs the independent install-dialog +scroll_maximum_size compatibility fix before a clean application export. +Existing upstream Rust lint findings are documented separately in the review +handoff; this change does not suppress them. Physical controller interaction, +visible LED output, and real session permissions require device validation. diff --git a/extensions/core/src/dbus/inputplumber.rs b/extensions/core/src/dbus/inputplumber.rs index c4647b77f..800c31087 100644 --- a/extensions/core/src/dbus/inputplumber.rs +++ b/extensions/core/src/dbus/inputplumber.rs @@ -4,5 +4,6 @@ pub mod event_device; pub mod gamepad; pub mod input_manager; pub mod keyboard; +pub mod led_device; pub mod mouse; pub mod target; diff --git a/extensions/core/src/dbus/inputplumber/led_device.rs b/extensions/core/src/dbus/inputplumber/led_device.rs new file mode 100644 index 000000000..5d6e2f631 --- /dev/null +++ b/extensions/core/src/dbus/inputplumber/led_device.rs @@ -0,0 +1,21 @@ +//! InputPlumber's versioned, whole-configuration LED interface. +use zbus::proxy; + +pub const LED_INTERFACE: &str = "org.shadowblip.Input.Source.LEDDevice"; +pub type LedConfiguration = (String, Vec, u32, u32); +pub type LedCapabilities = (u32, String, Vec, u32, u32); +pub type LedState = (u64, LedConfiguration, String, String); + +#[proxy( + interface = "org.shadowblip.Input.Source.LEDDevice", + default_service = "org.shadowblip.InputPlumber" +)] +pub trait LedDevice { + #[zbus(property)] + fn id(&self) -> zbus::Result; + #[zbus(property)] + fn capabilities(&self) -> zbus::Result; + #[zbus(property)] + fn state(&self) -> zbus::Result; + fn set_config(&self, config: LedConfiguration) -> zbus::Result; +} diff --git a/extensions/core/src/input/inputplumber.rs b/extensions/core/src/input/inputplumber.rs index f55bf6c6f..f3949cba6 100644 --- a/extensions/core/src/input/inputplumber.rs +++ b/extensions/core/src/input/inputplumber.rs @@ -1,3 +1,6 @@ +pub mod led_device; +mod led_discovery; +use led_device::LedDevice; pub mod composite_device; pub mod dbus_device; pub mod event_device; @@ -95,6 +98,10 @@ pub struct InputPlumberInstance { /// Map of DBus path to dbus device resource. E.g. /// {"/org/shadowblip/InputPlumber/target/dbus0": } dbus_devices: HashMap>, + led_devices: HashMap>, + led_discovery: Option>, + led_task: Option>, + led_owner: String, /// The current intercept mode set for all devices #[var(get = get_intercept_mode, set = set_intercept_mode)] intercept_mode: i64, @@ -135,6 +142,17 @@ impl InputPlumberInstance { #[signal] fn composite_device_removed(dbus_path: GString); + #[signal] + fn led_device_added(device: Gd); + #[signal] + fn led_device_removed(dbus_path: GString); + + /// Cached LED resources; discovery and state requests never block a frame. + #[func] + fn get_led_devices(&self) -> Array> { + self.led_devices.values().cloned().collect() + } + /// Returns true if the InputPlumber service is currently running #[func] fn is_running(&self) -> bool { @@ -279,6 +297,11 @@ impl InputPlumberInstance { self.process_signal(signal); } + self.process_led_discovery(); + for device in self.led_devices.values_mut() { + device.bind_mut().process(); + } + // Process signals from tracked devices for (_, device) in self.dbus_devices.iter_mut() { device.bind_mut().process(); @@ -288,6 +311,39 @@ impl InputPlumberInstance { } } + fn process_led_discovery(&mut self) { + let Some(updates) = self.led_discovery.as_mut() else { + return; + }; + if !updates.has_changed().unwrap_or(true) { + return; + } + let discovery = updates.borrow_and_update().clone(); + let removed: Vec<_> = self + .led_devices + .keys() + .filter(|path| self.led_owner != discovery.owner || !discovery.paths.contains(*path)) + .cloned() + .collect(); + for path in removed { + if let Some(mut device) = self.led_devices.remove(&path) { + device.bind_mut().disconnect_device(); + } + self.base_mut() + .emit_signal("led_device_removed", &[path.to_variant()]); + } + self.led_owner = discovery.owner.clone(); + for path in discovery.paths { + if self.led_devices.contains_key(&path) { + continue; + } + let device = LedDevice::new(path.clone(), discovery.owner.clone()); + self.led_devices.insert(path, device.clone()); + self.base_mut() + .emit_signal("led_device_added", &[device.to_variant()]); + } + } + /// Gets whether or not InputPlumber should automatically manage all supported devices #[func] fn get_manage_all_devices(&self) -> bool { @@ -451,6 +507,10 @@ impl IResource for InputPlumberInstance { rx, conn, proxy: None, + led_devices: HashMap::new(), + led_discovery: None, + led_task: None, + led_owner: String::new(), composite_devices: Default::default(), dbus_devices: Default::default(), intercept_mode: Default::default(), @@ -474,12 +534,18 @@ impl IResource for InputPlumberInstance { None }; + let (led_updates, led_task) = led_discovery::start(); + // Create a new InputPlumber instance let mut instance = Self { base, rx, conn, proxy, + led_devices: HashMap::new(), + led_discovery: Some(led_updates), + led_task: Some(led_task), + led_owner: String::new(), composite_devices: HashMap::new(), dbus_devices: HashMap::new(), intercept_mode: 0, @@ -600,3 +666,11 @@ async fn run(tx: Sender) -> Result<(), RunError> { Ok(()) } + +impl Drop for InputPlumberInstance { + fn drop(&mut self) { + if let Some(task) = self.led_task.take() { + task.abort(); + } + } +} diff --git a/extensions/core/src/input/inputplumber/led_device.rs b/extensions/core/src/input/inputplumber/led_device.rs new file mode 100644 index 000000000..06ef4f1f9 --- /dev/null +++ b/extensions/core/src/input/inputplumber/led_device.rs @@ -0,0 +1,382 @@ +//! Nonblocking Godot resource for a single persistent LED source. +use crate::dbus::inputplumber::led_device::{ + LedCapabilities, LedConfiguration, LedDeviceProxy, LedState, +}; +use crate::{get_dbus_system, RUNTIME}; +use futures_util::StreamExt; +use godot::prelude::*; +use std::time::Duration; +use tokio::{ + sync::{mpsc, watch}, + task::JoinHandle, +}; + +const TIMEOUT: Duration = Duration::from_secs(3); + +#[derive(Clone, Debug, PartialEq)] +struct Snapshot { + capabilities: LedCapabilities, + state: LedState, + connected: bool, + error: String, +} +impl Default for Snapshot { + fn default() -> Self { + Self { + capabilities: (0, String::new(), vec![], 2000, 30000), + state: ( + 0, + ("off".into(), vec![255; 3], 30, 8000), + "unavailable".into(), + String::new(), + ), + connected: false, + error: "Lighting controls are loading.".into(), + } + } +} +impl Snapshot { + fn compatible(&self) -> bool { + self.connected + && self.capabilities.0 == 1 + && !self.capabilities.1.is_empty() + && !self.capabilities.2.is_empty() + && self.capabilities.3 >= 2000 + && self.capabilities.4 <= 30000 + && self.capabilities.3 <= self.capabilities.4 + } + fn accepts(&self, config: &LedConfiguration) -> bool { + self.compatible() + && self.capabilities.2.contains(&config.0) + && config.1.len() == 3 + && config.2 <= 100 + && (self.capabilities.3..=self.capabilities.4).contains(&config.3) + } +} +#[derive(Clone, Debug, Default)] +struct ApplyResult { + request: i64, + success: bool, + error: String, +} +struct Apply { + request: i64, + config: LedConfiguration, +} + +/// Its properties are cached. All D-Bus work runs on the shared Tokio runtime; +/// closing an OGUI panel never stops or modifies InputPlumber's lighting worker. +#[derive(GodotClass)] +#[class(no_init, base=Resource)] +pub struct LedDevice { + base: Base, + path: String, + snapshot: Snapshot, + updates: watch::Receiver, + results: watch::Receiver, + requests: mpsc::Sender, + next_request: i64, + last_result: i64, + pending: Option, + task: JoinHandle<()>, +} +#[godot_api] +impl LedDevice { + #[signal] + fn lighting_changed(); + #[signal] + fn apply_finished(request: i64, success: bool, error: GString); + + pub fn new(path: String, owner: String) -> Gd { + let (tx, updates) = watch::channel(Snapshot::default()); + let (result_tx, results) = watch::channel(ApplyResult::default()); + let (requests, rx) = mpsc::channel(8); + let device_path = path.clone(); + let task = RUNTIME.spawn(async move { + if let Err(error) = run(device_path, owner, tx.clone(), result_tx, rx).await { + tx.send_modify(|snapshot| { + snapshot.connected = false; + snapshot.error = error; + }); + } + }); + Gd::from_init_fn(|base| Self { + base, + path, + snapshot: Snapshot::default(), + updates, + results, + requests, + next_request: 0, + last_result: 0, + pending: None, + task, + }) + } + #[func] + pub fn get_dbus_path(&self) -> GString { + self.path.as_str().into() + } + #[func] + pub fn get_snapshot(&self) -> VarDictionary { + let caps = &self.snapshot.capabilities; + let state = &self.snapshot.state; + let effects: PackedStringArray = caps.2.iter().map(GString::from).collect(); + let color: Array = state.1 .1.iter().map(|c| i64::from(*c)).collect(); + let config = vdict! { "effect": state.1.0.as_str(), "color": color, "brightness": i64::from(state.1.2), "cycle_period_ms": i64::from(state.1.3) }; + let error = if self.snapshot.error.is_empty() { + state.3.as_str() + } else { + self.snapshot.error.as_str() + }; + vdict! { "available": self.snapshot.compatible(), "api_version": i64::from(caps.0), + "persistent_id": caps.1.as_str(), "effects": effects, + "cycle_min_ms": i64::from(caps.3), "cycle_max_ms": i64::from(caps.4), + "config": config, "revision": state.0.to_string(), "status": state.2.as_str(), "error": error } + } + /// Returns a local request ID, or zero if unavailable/invalid/busy. The + /// apply_finished signal distinguishes persistence acceptance from failure; + /// lighting_changed/State report actual hardware application separately. + #[func] + pub fn apply_config( + &mut self, + effect: GString, + color: PackedByteArray, + brightness: i64, + cycle_period_ms: i64, + ) -> i64 { + if !(0..=100).contains(&brightness) || !(2000..=30000).contains(&cycle_period_ms) { + return 0; + } + let config = ( + effect.to_string(), + color.to_vec(), + brightness as u32, + cycle_period_ms as u32, + ); + if self.pending.is_some() || !self.snapshot.accepts(&config) { + return 0; + } + let Some(request) = self.next_request.checked_add(1) else { + return 0; + }; + if self.requests.try_send(Apply { request, config }).is_err() { + return 0; + } + self.next_request = request; + self.pending = Some(request); + request + } + pub fn process(&mut self) { + // A closed watch channel may still contain an unread final failure. + if self.updates.has_changed().unwrap_or(true) { + let snapshot = self.updates.borrow_and_update().clone(); + if self.snapshot != snapshot { + self.snapshot = snapshot; + self.base_mut().emit_signal("lighting_changed", &[]); + } + } + if self.results.has_changed().unwrap_or(true) { + let result = self.results.borrow_and_update().clone(); + if result.request > self.last_result { + self.last_result = result.request; + if self.pending == Some(result.request) { + self.pending = None; + } + self.base_mut().emit_signal( + "apply_finished", + &[ + result.request.to_variant(), + result.success.to_variant(), + result.error.to_variant(), + ], + ); + } + } + if !self.snapshot.connected && self.task.is_finished() { + if let Some(request) = self.pending.take() { + self.base_mut().emit_signal( + "apply_finished", + &[ + request.to_variant(), + false.to_variant(), + "Lighting connection ended; refresh state before retrying.".to_variant(), + ], + ); + } + } + } + + pub fn disconnect_device(&mut self) { + self.task.abort(); + self.snapshot.connected = false; + self.snapshot.error = "Lighting device disconnected.".into(); + self.base_mut().emit_signal("lighting_changed", &[]); + if let Some(request) = self.pending.take() { + self.base_mut().emit_signal( + "apply_finished", + &[ + request.to_variant(), + false.to_variant(), + "Device disconnected; refresh state before retrying.".to_variant(), + ], + ); + } + } +} +impl Drop for LedDevice { + fn drop(&mut self) { + self.task.abort(); + } +} + +async fn read_snapshot(proxy: &LedDeviceProxy<'_>) -> Result { + let result = tokio::time::timeout(TIMEOUT, async { + // Read after SetConfig must not reuse a property value cached before + // its notification arrived. Keep the subscription proxy separately. + let fresh = LedDeviceProxy::builder(proxy.inner().connection()) + .destination(proxy.inner().destination().to_owned())? + .path(proxy.inner().path().to_owned())? + .cache_properties(zbus::proxy::CacheProperties::No) + .build() + .await?; + let (caps, state) = tokio::join!(fresh.capabilities(), fresh.state()); + Ok::<_, zbus::Error>(Snapshot { + capabilities: caps?, + state: state?, + connected: true, + error: String::new(), + }) + }) + .await + .map_err(|_| "Lighting state request timed out")? + .map_err(|e| format!("InputPlumber lighting controls are unavailable: {e}"))?; + if result.capabilities.0 != 1 { + return Err("This InputPlumber lighting API version is unsupported. Update OpenGamepadUI and InputPlumber together.".into()); + } + if result.state.1 .1.len() != 3 + || result.state.1 .2 > 100 + || !(2000..=30000).contains(&result.state.1 .3) + { + return Err("InputPlumber returned invalid lighting settings.".into()); + } + Ok(result) +} +async fn refresh( + proxy: &LedDeviceProxy<'_>, + snapshots: &watch::Sender, +) -> Result<(), String> { + match read_snapshot(proxy).await { + Ok(snapshot) => { + snapshots.send_replace(snapshot); + Ok(()) + } + Err(error) => { + snapshots.send_modify(|snapshot| { + snapshot.connected = false; + snapshot.error = error.clone(); + }); + Err(error) + } + } +} + +async fn run( + path: String, + owner: String, + snapshots: watch::Sender, + results: watch::Sender, + requests: mpsc::Receiver, +) -> Result<(), String> { + let connection = tokio::time::timeout(TIMEOUT, get_dbus_system()) + .await + .map_err(|_| "Lighting connection timed out")? + .map_err(|e| e.to_string())?; + run_on_connection(connection, path, owner, snapshots, results, requests).await +} + +async fn run_on_connection( + connection: zbus::Connection, + path: String, + owner: String, + snapshots: watch::Sender, + results: watch::Sender, + mut requests: mpsc::Receiver, +) -> Result<(), String> { + let proxy = LedDeviceProxy::builder(&connection) + .destination(owner) + .map_err(|e| e.to_string())? + .path(path) + .map_err(|e| e.to_string())? + .build() + .await + .map_err(|e| e.to_string())?; + // Subscribe before fetching initial state; startup/hotplug changes cannot be missed. + let mut states = proxy.receive_state_changed().await; + let mut capabilities = proxy.receive_capabilities_changed().await; + let _ = refresh(&proxy, &snapshots).await; + let mut retry = tokio::time::interval(Duration::from_secs(5)); + retry.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + retry.reset(); + loop { + tokio::select! { + command = requests.recv() => { + let Some(command) = command else { return Ok(()); }; + let response = tokio::time::timeout(TIMEOUT, proxy.set_config(command.config)).await; + let outcome = match response { + Ok(Ok(_)) => match refresh(&proxy, &snapshots).await { + Ok(()) => Ok(()), + Err(error) => Err(format!("Settings were accepted, but state could not be refreshed: {error}")), + }, + Ok(Err(error)) => Err(error.to_string()), + Err(_) => Err("Lighting request timed out; refresh state before retrying.".into()), + }; + results.send_replace(ApplyResult { request: command.request, success: outcome.is_ok(), error: outcome.err().unwrap_or_default() }); + }, + _ = retry.tick(), if !snapshots.borrow().connected => { + let _ = refresh(&proxy, &snapshots).await; + }, + event = states.next() => { + if event.is_none() { return Err("Lighting state subscription ended.".into()); } + let _ = refresh(&proxy, &snapshots).await; + }, + event = capabilities.next() => { + if event.is_none() { return Err("Lighting capabilities subscription ended.".into()); } + let _ = refresh(&proxy, &snapshots).await; + }, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn compatible_snapshot_requires_supported_version_and_complete_configuration() { + let mut snapshot = Snapshot { + connected: true, + capabilities: ( + 1, + "ayaneo-3-joystick-rings".into(), + vec!["off".into(), "solid".into()], + 2000, + 30000, + ), + ..Snapshot::default() + }; + let config = ("solid".into(), vec![1, 2, 3], 30, 8000); + assert!(snapshot.accepts(&config)); + assert!(!snapshot.accepts(&("cycle".into(), vec![1, 2, 3], 30, 8000))); + assert!(!snapshot.accepts(&("solid".into(), vec![1, 2], 30, 8000))); + assert!(!snapshot.accepts(&("solid".into(), vec![1, 2, 3], 101, 8000))); + snapshot.capabilities.0 = 2; + assert!(!snapshot.accepts(&config)); + snapshot.capabilities.0 = 1; + snapshot.connected = false; + assert!(!snapshot.accepts(&config)); + } +} + +#[cfg(test)] +#[path = "led_device_test.rs"] +mod wire; diff --git a/extensions/core/src/input/inputplumber/led_device_test.rs b/extensions/core/src/input/inputplumber/led_device_test.rs new file mode 100644 index 000000000..23fdf83d0 --- /dev/null +++ b/extensions/core/src/input/inputplumber/led_device_test.rs @@ -0,0 +1,283 @@ +use super::*; +#[cfg(test)] +mod wire_tests { + use super::*; + use crate::input::inputplumber::{led_discovery, INPUT_PLUMBER_BUS, INPUT_PLUMBER_PATH}; + use std::{ + io::{BufRead, BufReader}, + process::{Child, Command, Stdio}, + sync::{Arc, Mutex}, + }; + + struct Bus { + child: Child, + address: String, + } + impl Bus { + fn new() -> Self { + let mut child = Command::new("dbus-daemon") + .args(["--session", "--nofork", "--print-address=1"]) + .stdout(Stdio::piped()) + .spawn() + .expect("private dbus-daemon is required"); + let mut address = String::new(); + BufReader::new(child.stdout.take().unwrap()) + .read_line(&mut address) + .unwrap(); + Self { + child, + address: address.trim().into(), + } + } + async fn connection(&self) -> zbus::Connection { + zbus::connection::Builder::address(self.address.as_str()) + .unwrap() + .build() + .await + .unwrap() + } + } + impl Drop for Bus { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } + } + + struct FakeLed { + state: Arc>, + version: u32, + } + #[zbus::interface(name = "org.shadowblip.Input.Source.LEDDevice")] + impl FakeLed { + #[zbus(property)] + fn capabilities(&self) -> LedCapabilities { + ( + self.version, + "test-rings".into(), + vec!["off".into(), "solid".into(), "cycle".into()], + 2000, + 30000, + ) + } + #[zbus(property)] + fn state(&self) -> zbus::fdo::Result { + let state = self.state.lock().unwrap(); + if state.3 == "read-error" { + return Err(zbus::fdo::Error::Failed( + "Transient state read failure".into(), + )); + } + Ok(state.clone()) + } + fn set_config(&self, config: LedConfiguration) -> zbus::fdo::Result { + if config.2 == 13 { + return Err(zbus::fdo::Error::AccessDenied( + "Test authorization denied".into(), + )); + } + let mut state = self.state.lock().unwrap(); + state.0 += 1; + state.1 = config; + state.2 = "pending".into(); + if state.1 .2 == 12 { + state.3 = "read-error".into(); + } + Ok(state.0) + } + } + const PATH: &str = "/org/shadowblip/InputPlumber/devices/source/vendor_rings"; + fn state() -> Arc> { + Arc::new(Mutex::new(( + 0, + ("off".into(), vec![255; 3], 30, 8000), + "applied".into(), + String::new(), + ))) + } + async fn server(bus: &Bus, state: Arc>, version: u32) -> zbus::Connection { + zbus::connection::Builder::address(bus.address.as_str()) + .unwrap() + .serve_at(INPUT_PLUMBER_PATH, zbus::fdo::ObjectManager) + .unwrap() + .serve_at(PATH, FakeLed { state, version }) + .unwrap() + .name(INPUT_PLUMBER_BUS) + .unwrap() + .build() + .await + .unwrap() + } + async fn wait_discovery( + rx: &mut watch::Receiver, + owner: &str, + present: bool, + ) { + tokio::time::timeout( + Duration::from_secs(4), + rx.wait_for(|state| state.owner == owner && state.paths.contains(PATH) == present), + ) + .await + .unwrap() + .unwrap(); + } + + #[tokio::test] + async fn discovery_follows_interface_hotplug_and_fast_unique_owner_replacement() { + let bus = Bus::new(); + let connection = bus.connection().await; + let (tx, mut updates) = watch::channel(led_discovery::Discovery::default()); + let task = tokio::spawn(async move { led_discovery::run(&connection, &tx).await }); + let first = server(&bus, state(), 1).await; + let first_owner = first.unique_name().unwrap().to_string(); + wait_discovery(&mut updates, &first_owner, true).await; + first + .object_server() + .remove::(PATH) + .await + .unwrap(); + wait_discovery(&mut updates, &first_owner, false).await; + first + .object_server() + .at( + PATH, + FakeLed { + state: state(), + version: 1, + }, + ) + .await + .unwrap(); + wait_discovery(&mut updates, &first_owner, true).await; + first.release_name(INPUT_PLUMBER_BUS).await.unwrap(); + let second = server(&bus, state(), 1).await; + let second_owner = second.unique_name().unwrap().to_string(); + assert_ne!(first_owner, second_owner); + wait_discovery(&mut updates, &second_owner, true).await; + task.abort(); + let _ = task.await; + } + + #[tokio::test] + async fn worker_uses_real_tuples_fresh_reads_notifications_and_authorization_errors() { + let bus = Bus::new(); + let hardware = state(); + let server = server(&bus, hardware.clone(), 1).await; + let owner = server.unique_name().unwrap().to_string(); + let client = bus.connection().await; + let (tx, mut updates) = watch::channel(Snapshot::default()); + let (results_tx, mut results) = watch::channel(ApplyResult::default()); + let (requests, rx) = mpsc::channel(8); + let task = tokio::spawn(run_on_connection( + client, + PATH.into(), + owner, + tx, + results_tx, + rx, + )); + tokio::time::timeout(TIMEOUT, updates.wait_for(|s| s.connected)) + .await + .unwrap() + .unwrap(); + let config = ("solid".into(), vec![12, 34, 56], 47, 8000); + requests + .send(Apply { + request: 1, + config: config.clone(), + }) + .await + .unwrap(); + tokio::time::timeout(TIMEOUT, results.wait_for(|r| r.request == 1)) + .await + .unwrap() + .unwrap(); + assert!(results.borrow().success); + // Fake setter deliberately sends no notification. The reply must use a + // fresh Get rather than the subscription proxy's old property cache. + assert_eq!(updates.borrow().state.1, config); + assert_eq!(updates.borrow().state.2, "pending"); + hardware.lock().unwrap().2 = "failed".into(); + hardware.lock().unwrap().3 = "Device write failed".into(); + let iface = server + .object_server() + .interface::<_, FakeLed>(PATH) + .await + .unwrap(); + iface + .get() + .await + .state_changed(iface.signal_emitter()) + .await + .unwrap(); + tokio::time::timeout(TIMEOUT, updates.wait_for(|s| s.state.2 == "failed")) + .await + .unwrap() + .unwrap(); + requests + .send(Apply { + request: 2, + config: ("off".into(), vec![1, 2, 3], 13, 8000), + }) + .await + .unwrap(); + tokio::time::timeout(TIMEOUT, results.wait_for(|r| r.request == 2)) + .await + .unwrap() + .unwrap(); + assert!(!results.borrow().success); + assert!(results.borrow().error.contains("denied")); + assert_eq!(hardware.lock().unwrap().1, config); + let recovered_config = ("solid".into(), vec![4, 5, 6], 12, 8000); + requests + .send(Apply { + request: 3, + config: recovered_config.clone(), + }) + .await + .unwrap(); + tokio::time::timeout(TIMEOUT, results.wait_for(|r| r.request == 3)) + .await + .unwrap() + .unwrap(); + assert!(!results.borrow().success); + assert!(results.borrow().error.contains("accepted")); + assert!(!updates.borrow().connected); + hardware.lock().unwrap().3.clear(); + tokio::time::timeout(Duration::from_secs(8), updates.wait_for(|s| s.connected)) + .await + .unwrap() + .unwrap(); + assert_eq!(updates.borrow().state.1, recovered_config); + drop(requests); + tokio::time::timeout(TIMEOUT, task) + .await + .unwrap() + .unwrap() + .unwrap(); + assert_eq!( + hardware.lock().unwrap().1, + recovered_config, + "Client exit must not turn lighting off" + ); + } + + #[tokio::test] + async fn future_protocol_is_unavailable_instead_of_writable() { + let bus = Bus::new(); + let server = server(&bus, state(), 2).await; + let client = bus.connection().await; + let proxy = LedDeviceProxy::builder(&client) + .destination(server.unique_name().unwrap().clone()) + .unwrap() + .path(PATH) + .unwrap() + .build() + .await + .unwrap(); + assert!(read_snapshot(&proxy) + .await + .unwrap_err() + .contains("unsupported")); + } +} diff --git a/extensions/core/src/input/inputplumber/led_discovery.rs b/extensions/core/src/input/inputplumber/led_discovery.rs new file mode 100644 index 000000000..4785e8785 --- /dev/null +++ b/extensions/core/src/input/inputplumber/led_discovery.rs @@ -0,0 +1,122 @@ +//! Owner-pinned LED discovery. Updates are coalesced, never queued per frame. +use super::{INPUT_PLUMBER_BUS, INPUT_PLUMBER_PATH}; +use crate::{dbus::inputplumber::led_device::LED_INTERFACE, get_dbus_system, RUNTIME}; +use futures_util::StreamExt; +use std::{collections::BTreeSet, time::Duration}; +use tokio::{sync::watch, task::JoinHandle}; +use zbus::{ + fdo::{DBusProxy, ObjectManagerProxy}, + names::BusName, + Connection, +}; + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Discovery { + pub owner: String, + pub paths: BTreeSet, +} +const TIMEOUT: Duration = Duration::from_secs(3); + +pub fn start() -> (watch::Receiver, JoinHandle<()>) { + let (tx, rx) = watch::channel(Discovery::default()); + let task = RUNTIME.spawn(async move { + loop { + if tx.is_closed() { + return; + } + let result = match get_dbus_system().await { + Ok(connection) => run(&connection, &tx).await, + Err(error) => Err(error.to_string()), + }; + if tx.is_closed() { + return; + } + tx.send_replace(Discovery::default()); + if let Err(error) = result { + log::warn!("LED discovery unavailable: {error}"); + } + tokio::time::sleep(Duration::from_secs(5)).await; + } + }); + (rx, task) +} + +pub(super) async fn run( + connection: &Connection, + tx: &watch::Sender, +) -> Result<(), String> { + let dbus = DBusProxy::new(connection) + .await + .map_err(|e| e.to_string())?; + let mut owners = dbus + .receive_name_owner_changed_with_args(&[(0, INPUT_PLUMBER_BUS)]) + .await + .map_err(|e| e.to_string())?; + let bus = BusName::from_static_str(INPUT_PLUMBER_BUS).unwrap(); + loop { + let owner = match tokio::time::timeout(TIMEOUT, dbus.get_name_owner(bus.clone())).await { + Ok(Ok(owner)) => owner.to_string(), + Ok(Err(zbus::fdo::Error::NameHasNoOwner(_))) => { + tx.send_replace(Discovery::default()); + tokio::select! { + _ = tx.closed() => return Ok(()), + event = owners.next() => { if event.is_none() { return Err("Owner subscription ended".into()); } } + } + continue; + } + Ok(Err(error)) => return Err(error.to_string()), + Err(_) => return Err("LED discovery timed out".into()), + }; + // Pin this generation to the unique owner. A fast daemon restart must + // not leave an old resource addressing the new service at the same path. + let proxy = ObjectManagerProxy::builder(connection) + .destination(owner.clone()) + .map_err(|e| e.to_string())? + .path(INPUT_PLUMBER_PATH) + .map_err(|e| e.to_string())? + .build() + .await + .map_err(|e| e.to_string())?; + let mut added = proxy + .receive_interfaces_added() + .await + .map_err(|e| e.to_string())?; + let mut removed = proxy + .receive_interfaces_removed() + .await + .map_err(|e| e.to_string())?; + let objects = tokio::time::timeout(TIMEOUT, proxy.get_managed_objects()) + .await + .map_err(|_| "LED discovery timed out")? + .map_err(|e| e.to_string())?; + let paths = objects + .into_iter() + .filter(|(_, interfaces)| interfaces.keys().any(|name| name.as_str() == LED_INTERFACE)) + .map(|(path, _)| path.to_string()) + .collect(); + let mut discovery = Discovery { owner, paths }; + tx.send_replace(discovery.clone()); + loop { + tokio::select! { + _ = tx.closed() => return Ok(()), + event = owners.next() => { + if event.is_none() { return Err("Owner subscription ended".into()); } + // Re-read the owner rather than trusting queued transitions. + break; + }, + event = added.next() => { + let Some(event) = event else { return Err("LED discovery subscription ended".into()); }; + let args = event.args().map_err(|e| e.to_string())?; + if args.interfaces_and_properties.keys().any(|name| name.as_str() == LED_INTERFACE) + && discovery.paths.insert(args.object_path.to_string()) { tx.send_replace(discovery.clone()); } + }, + event = removed.next() => { + let Some(event) = event else { return Err("LED discovery subscription ended".into()); }; + let args = event.args().map_err(|e| e.to_string())?; + if args.interfaces.iter().any(|name| name.as_str() == LED_INTERFACE) + && discovery.paths.remove(args.object_path.as_str()) { tx.send_replace(discovery.clone()); } + }, + } + } + } +} From 0336b9528aa0558bd370bbe083bfa5510467ef3d Mon Sep 17 00:00:00 2001 From: sknowledge <216877555+sknowledge1@users.noreply.github.com> Date: Thu, 24 Sep 2026 11:31:20 +0100 Subject: [PATCH 3/5] fix: include lighting resources in clean exports Keep the new Godot resources available in a fresh exported build. Assisted-by: OpenAI Codex --- core/ui/card_ui/navigation/running_game_card.gd | 4 +++- export_presets.cfg | 6 +++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/core/ui/card_ui/navigation/running_game_card.gd b/core/ui/card_ui/navigation/running_game_card.gd index b93861051..810f671f5 100644 --- a/core/ui/card_ui/navigation/running_game_card.gd +++ b/core/ui/card_ui/navigation/running_game_card.gd @@ -241,5 +241,7 @@ func _on_gampad_button_pressed() -> void: func _notification(what: int) -> void: - if what == NOTIFICATION_PREDELETE: + if what != NOTIFICATION_PREDELETE or not is_instance_valid(_xwayland): + return + if _xwayland.focusable_windows_updated.is_connected(_on_focusable_windows_changed): _xwayland.focusable_windows_updated.disconnect(_on_focusable_windows_changed) diff --git a/export_presets.cfg b/export_presets.cfg index fb9c02525..05a897bc1 100644 --- a/export_presets.cfg +++ b/export_presets.cfg @@ -7,7 +7,7 @@ dedicated_server=false custom_features="" export_filter="all_resources" include_filter="*.ini,*.profile,*.pub" -exclude_filter="rootfs,sandbox,plugins,*_test.tscn,*_test.gd,*.key,addons/gut/*,node_modules/*" +exclude_filter="rootfs,sandbox,plugins,*_test*.tscn,*_test.gd,*.key,addons/gut/*,node_modules/*" export_path="build/opengamepad-ui.x86_64" patches=PackedStringArray() patch_delta_encoding=false @@ -59,7 +59,7 @@ dedicated_server=false custom_features="" export_filter="all_resources" include_filter="*.ini,*.profile,*.pub" -exclude_filter="rootfs,sandbox,plugins,*_test.tscn,*_test.gd,*.key" +exclude_filter="rootfs,sandbox,plugins,*_test*.tscn,*_test.gd,*.key" export_path="" patches=PackedStringArray() patch_delta_encoding=false @@ -163,7 +163,7 @@ dedicated_server=false custom_features="" export_filter="all_resources" include_filter="*.ini,*.profile,*.pub" -exclude_filter="rootfs,sandbox,plugins,*_test.tscn,*_test.gd,*.key,addons/gut/*,node_modules/*" +exclude_filter="rootfs,sandbox,plugins,*_test*.tscn,*_test.gd,*.key,addons/gut/*,node_modules/*" export_path="build/opengamepad-ui.aarch64" patches=PackedStringArray() patch_delta_encoding=false From 88c64770df7ea99d3de35eea99f25148681ffeea Mon Sep 17 00:00:00 2001 From: sknowledge <216877555+sknowledge1@users.noreply.github.com> Date: Thu, 24 Sep 2026 11:31:33 +0100 Subject: [PATCH 4/5] feat: show AYANEO native cycle as fixed tempo When InputPlumber reports firmware-timed cycling, show a fixed-tempo note and no adjustable speed control. Retain the saved period for compatibility with the shared LED setting format. Assisted-by: OpenAI Codex --- core/systems/input/lighting_model_test.gd | 29 +++++++++++++++ core/ui/common/quick_bar/lighting_panel.gd | 12 ++++--- docs/lighting.md | 9 +++-- .../core/src/input/inputplumber/led_device.rs | 14 +++++--- .../src/input/inputplumber/led_device_test.rs | 35 +++++++++++++++++++ 5 files changed, 88 insertions(+), 11 deletions(-) diff --git a/core/systems/input/lighting_model_test.gd b/core/systems/input/lighting_model_test.gd index db8eabfa3..da62ffd59 100644 --- a/core/systems/input/lighting_model_test.gd +++ b/core/systems/input/lighting_model_test.gd @@ -230,3 +230,32 @@ func test_stock_quick_settings_scroll_and_controller_focus() -> void: Input.parse_input_event(event) await wait_frames(2) assert_eq(get_viewport().gui_get_focus_owner(), volume.slider) + +func test_native_cycle_hides_speed_preserves_period_and_keeps_gamepad_focus() -> void: + source.state.cycle_min_ms = 0 + source.state.cycle_max_ms = 0 + source.state.config.effect = "cycle" + source.state.config.cycle_period_ms = 17000 + source.lighting_changed.emit() + await wait_frames(2) + var panel := _panel() + await wait_frames(2) + assert_false(panel.cycle.visible) + assert_true(panel.breathing_note.visible) + assert_eq(panel.breathing_note.text, "Colour cycle speed is fixed by the device.") + assert_eq(panel._focus_controls().size(), 4) + panel.brightness.slider.grab_focus() + assert_eq(panel.brightness.slider.find_valid_focus_neighbor(SIDE_BOTTOM), panel.apply_button) + model.edit("brightness", 60) + model.apply() + assert_eq(source.calls.size(), 1) + assert_eq(source.calls[0].cycle_period_ms, 17000) + source.complete() + await wait_frames(2) + source.state.cycle_min_ms = 2000 + source.state.cycle_max_ms = 30000 + source.lighting_changed.emit() + await wait_frames(2) + assert_true(panel.cycle.visible) + assert_eq(panel.cycle.value, 17.0) + assert_false(panel.breathing_note.visible) diff --git a/core/ui/common/quick_bar/lighting_panel.gd b/core/ui/common/quick_bar/lighting_panel.gd index 3d9bd5553..66d80279a 100644 --- a/core/ui/common/quick_bar/lighting_panel.gd +++ b/core/ui/common/quick_bar/lighting_panel.gd @@ -97,12 +97,16 @@ func _refresh() -> void: brightness.visible = available and supported and draft.effect != "off" brightness.editable = not busy brightness.value = int(draft.brightness) - cycle.visible = available and supported and draft.effect == "cycle" + var snapshot: Dictionary = entry.get("snapshot", {}) + var fixed_cycle: bool = snapshot.get("cycle_min_ms", 2000) == 0 and snapshot.get("cycle_max_ms", 30000) == 0 + cycle.visible = available and supported and draft.effect == "cycle" and not fixed_cycle cycle.editable = not busy - cycle.min_value = float(entry.get("snapshot", {}).get("cycle_min_ms", 2000)) / 1000.0 - cycle.max_value = float(entry.get("snapshot", {}).get("cycle_max_ms", 30000)) / 1000.0 + if not fixed_cycle: + cycle.min_value = float(snapshot.get("cycle_min_ms", 2000)) / 1000.0 + cycle.max_value = float(snapshot.get("cycle_max_ms", 30000)) / 1000.0 cycle.value = float(draft.cycle_period_ms) / 1000.0 - breathing_note.visible = available and supported and draft.effect == "breathing" + breathing_note.visible = available and supported and (draft.effect == "breathing" or (draft.effect == "cycle" and fixed_cycle)) + breathing_note.text = tr("Colour cycle speed is fixed by the device.") if draft.effect == "cycle" else tr("Breathing speed is fixed by the device.") apply_button.visible = available off_button.visible = available and "off" in _effects apply_button.disabled = busy or not supported diff --git a/docs/lighting.md b/docs/lighting.md index 352496fa8..19b40aec9 100644 --- a/docs/lighting.md +++ b/docs/lighting.md @@ -5,8 +5,11 @@ exposes LED API version 1. InputPlumber owns persistence and effects; closing OG does not turn lighting off. Decky can configure the same settings independently. The controls offer only advertised effects: Off, Solid, fixed-tempo hardware -Breathing, and Colour cycle. RGB is remembered for Solid/Breathing; cycle period -is 2–30 seconds and brightness is independent. Off preserves the other values. +Breathing, and Colour cycle. RGB is remembered for Solid/Breathing and brightness +is independent. Native cycling has fixed tempo: both cycle bounds are zero and +the panel shows a fixed-speed note instead of a slider. Software-capable devices +offer a 2–30 second period. The saved period remains unchanged on native hardware; +Off preserves the other values. Apply saves a complete configuration. The status distinguishes saved settings from pending, applied, unavailable, and failed hardware state. @@ -32,7 +35,7 @@ cargo build --locked --release ``` Use the project's GUT runner for -core/systems/input/lighting_model_test.gd. Require 12 collected tests, no failures +core/systems/input/lighting_model_test.gd. Require 13 collected tests, no failures or skips, and no SCRIPT ERROR; a GUT process exit of zero alone is insufficient. The tests cover lifecycle, multi-device isolation, stale replies, dirty drafts, errors, capability controls, and stock quick-settings focus/scroll behavior. diff --git a/extensions/core/src/input/inputplumber/led_device.rs b/extensions/core/src/input/inputplumber/led_device.rs index 06ef4f1f9..353795575 100644 --- a/extensions/core/src/input/inputplumber/led_device.rs +++ b/extensions/core/src/input/inputplumber/led_device.rs @@ -36,21 +36,27 @@ impl Default for Snapshot { } } impl Snapshot { + fn fixed_cycle(&self) -> bool { + self.capabilities.3 == 0 && self.capabilities.4 == 0 + } fn compatible(&self) -> bool { self.connected && self.capabilities.0 == 1 && !self.capabilities.1.is_empty() && !self.capabilities.2.is_empty() - && self.capabilities.3 >= 2000 - && self.capabilities.4 <= 30000 - && self.capabilities.3 <= self.capabilities.4 + && (self.fixed_cycle() + || (self.capabilities.3 >= 2000 + && self.capabilities.4 <= 30000 + && self.capabilities.3 <= self.capabilities.4)) } fn accepts(&self, config: &LedConfiguration) -> bool { self.compatible() && self.capabilities.2.contains(&config.0) && config.1.len() == 3 && config.2 <= 100 - && (self.capabilities.3..=self.capabilities.4).contains(&config.3) + && (2000..=30000).contains(&config.3) + && (self.fixed_cycle() + || (self.capabilities.3..=self.capabilities.4).contains(&config.3)) } } #[derive(Clone, Debug, Default)] diff --git a/extensions/core/src/input/inputplumber/led_device_test.rs b/extensions/core/src/input/inputplumber/led_device_test.rs index 23fdf83d0..0232ed12c 100644 --- a/extensions/core/src/input/inputplumber/led_device_test.rs +++ b/extensions/core/src/input/inputplumber/led_device_test.rs @@ -281,3 +281,38 @@ mod wire_tests { .contains("unsupported")); } } + +#[test] +fn led_fixed_cycle_capability_preserves_saved_period_and_rejects_malformed_bounds() { + let mut snapshot = Snapshot { + connected: true, + capabilities: ( + 1, + "native-rings".into(), + vec![ + "off".into(), + "solid".into(), + "breathing".into(), + "cycle".into(), + ], + 0, + 0, + ), + ..Snapshot::default() + }; + assert!(snapshot.compatible()); + for effect in ["off", "solid", "breathing", "cycle"] { + for period in [2000, 17000, 30000] { + assert!(snapshot.accepts(&(effect.into(), vec![19, 61, 127], 60, period))); + } + } + for period in [0, 1999, 30001, u32::MAX] { + assert!(!snapshot.accepts(&("cycle".into(), vec![255; 3], 60, period))); + } + for bounds in [(0, 2000), (2000, 0), (1, 1), (30000, 2000), (2000, 30001)] { + snapshot.capabilities.3 = bounds.0; + snapshot.capabilities.4 = bounds.1; + assert!(!snapshot.compatible()); + assert!(!snapshot.accepts(&("cycle".into(), vec![255; 3], 60, 8000))); + } +} From a88b6c6880d671ecf8129a585554c274808fb6f8 Mon Sep 17 00:00:00 2001 From: sknowledge1 <216877555+sknowledge1@users.noreply.github.com> Date: Thu, 15 Oct 2026 15:39:35 +0100 Subject: [PATCH 5/5] fix: preserve unconfigured lighting until explicit apply --- core/systems/input/lighting_model.gd | 4 +++- core/systems/input/lighting_model_test.gd | 23 +++++++++++++++++++++- core/ui/common/quick_bar/lighting_panel.gd | 2 +- docs/lighting.md | 13 +++++++----- 4 files changed, 34 insertions(+), 8 deletions(-) diff --git a/core/systems/input/lighting_model.gd b/core/systems/input/lighting_model.gd index 5b8a1f000..770082fe4 100644 --- a/core/systems/input/lighting_model.gd +++ b/core/systems/input/lighting_model.gd @@ -3,7 +3,7 @@ class_name LightingModel ## Shared settings and drafts. Only InputPlumber owns effects or persistence. signal updated -const EFFECT_LABELS := {"off": "Off", "solid": "Solid colour", "breathing": "Breathing", "cycle": "Colour cycle"} +const EFFECT_LABELS := {"off": "Off", "solid": "Solid colour", "breathing": "Breathing", "cycle": "Rainbow"} const DEFAULT_CONFIG := {"effect": "off", "color": [255, 255, 255], "brightness": 30, "cycle_period_ms": 8000} var entries: Dictionary = {} var selected_id: String = "" @@ -155,4 +155,6 @@ func status_text() -> String: return "Settings are saved. Waiting for the lighting device." if entry.dirty: return "You have unapplied changes." + if snapshot.status == "unconfigured": + return "No lighting settings are saved. Choose an effect and apply it; lighting stays unchanged until then." return "Lighting settings applied." diff --git a/core/systems/input/lighting_model_test.gd b/core/systems/input/lighting_model_test.gd index da62ffd59..20738ad1e 100644 --- a/core/systems/input/lighting_model_test.gd +++ b/core/systems/input/lighting_model_test.gd @@ -20,6 +20,8 @@ class FakeSource extends RefCounted: if success: state.config = calls.back().duplicate(true) state.revision = str(calls.size()) + if state.status == "unconfigured": + state.status = "applied" apply_finished.emit(calls.size(), success, error) var model: LightingModel @@ -47,6 +49,25 @@ func test_external_state_preserves_dirty_draft() -> void: assert_eq(model.current().snapshot.config.brightness, 90) assert_eq(model.current().draft.brightness, 44) +func test_first_use_stays_untouched_until_explicit_apply() -> void: + source.state.status = "unconfigured" + source.lighting_changed.emit() + await wait_frames(2) + assert_string_contains(model.status_text(), "No lighting settings are saved") + assert_eq(source.calls.size(), 0) + var panel := _panel() + await wait_frames(2) + assert_string_contains(panel.status.text, "lighting stays unchanged") + assert_eq(source.calls.size(), 0, "Opening the panel must not apply placeholder Off") + model.edit("effect", "solid") + assert_eq(model.status_text(), "You have unapplied changes.") + assert_eq(source.calls.size(), 0) + model.apply() + source.complete() + await wait_frames(2) + assert_eq(source.calls.size(), 1) + assert_eq(model.status_text(), "Lighting settings applied.") + func test_apply_keeps_new_edits_and_uses_latest_saved_state() -> void: model.edit("effect", "solid") model.apply() @@ -242,7 +263,7 @@ func test_native_cycle_hides_speed_preserves_period_and_keeps_gamepad_focus() -> await wait_frames(2) assert_false(panel.cycle.visible) assert_true(panel.breathing_note.visible) - assert_eq(panel.breathing_note.text, "Colour cycle speed is fixed by the device.") + assert_eq(panel.breathing_note.text, "Rainbow speed is fixed by the device.") assert_eq(panel._focus_controls().size(), 4) panel.brightness.slider.grab_focus() assert_eq(panel.brightness.slider.find_valid_focus_neighbor(SIDE_BOTTOM), panel.apply_button) diff --git a/core/ui/common/quick_bar/lighting_panel.gd b/core/ui/common/quick_bar/lighting_panel.gd index 66d80279a..8c0e1b97a 100644 --- a/core/ui/common/quick_bar/lighting_panel.gd +++ b/core/ui/common/quick_bar/lighting_panel.gd @@ -106,7 +106,7 @@ func _refresh() -> void: cycle.max_value = float(snapshot.get("cycle_max_ms", 30000)) / 1000.0 cycle.value = float(draft.cycle_period_ms) / 1000.0 breathing_note.visible = available and supported and (draft.effect == "breathing" or (draft.effect == "cycle" and fixed_cycle)) - breathing_note.text = tr("Colour cycle speed is fixed by the device.") if draft.effect == "cycle" else tr("Breathing speed is fixed by the device.") + breathing_note.text = tr("Rainbow speed is fixed by the device.") if draft.effect == "cycle" else tr("Breathing speed is fixed by the device.") apply_button.visible = available off_button.visible = available and "off" in _effects apply_button.disabled = busy or not supported diff --git a/docs/lighting.md b/docs/lighting.md index 19b40aec9..ceebb9b05 100644 --- a/docs/lighting.md +++ b/docs/lighting.md @@ -5,13 +5,16 @@ exposes LED API version 1. InputPlumber owns persistence and effects; closing OG does not turn lighting off. Decky can configure the same settings independently. The controls offer only advertised effects: Off, Solid, fixed-tempo hardware -Breathing, and Colour cycle. RGB is remembered for Solid/Breathing and brightness +Breathing, and Rainbow (the API's `cycle` effect). RGB is remembered for Solid/Breathing and brightness is independent. Native cycling has fixed tempo: both cycle bounds are zero and the panel shows a fixed-speed note instead of a slider. Software-capable devices offer a 2–30 second period. The saved period remains unchanged on native hardware; Off preserves the other values. Apply saves a complete configuration. The status distinguishes saved settings -from pending, applied, unavailable, and failed hardware state. +from unconfigured, pending, applied, unavailable, and failed hardware state. +An unconfigured device has no saved selection. Opening or closing the panel +leaves its existing lighting untouched; the placeholder Off value is applied +only after an explicit user request. The shared LightingModel retains each identity's dirty draft and in-flight request across quick-menu remounts. A backend notification updates clean drafts; @@ -35,15 +38,15 @@ cargo build --locked --release ``` Use the project's GUT runner for -core/systems/input/lighting_model_test.gd. Require 13 collected tests, no failures +core/systems/input/lighting_model_test.gd. Require 14 collected tests, no failures or skips, and no SCRIPT ERROR; a GUT process exit of zero alone is insufficient. The tests cover lifecycle, multi-device isolation, stale replies, dirty drafts, errors, capability controls, and stock quick-settings focus/scroll behavior. lighting_render_test.gd renders fixture panels without a physical LED device. Native tests start a private bus and fake services. -The pinned Godot 4.7.1 baseline also needs the independent install-dialog -scroll_maximum_size compatibility fix before a clean application export. +The branch includes regression tests for the install-dialog compatibility fix +already present in the current Godot 4.7.1 baseline. Existing upstream Rust lint findings are documented separately in the review handoff; this change does not suppress them. Physical controller interaction, visible LED output, and real session permissions require device validation.