Files
community-plugins/ds4-color/panel.luau
T
5fb0e0f279 Add DS4 Color plugin (Hy4ri/ds4-color) (#52)
* feat: add PS4 Colors plugin (DS4 lightbar control)

Wraps the ps4-colors CLI (github.com/Hy4ri/ps4-colors) as a Noctalia
plugin: bar button + color panel (native picker, hex field, presets)
that sets the DualShock 4 lightbar via the ps4-colors binary.

NOTE: thumbnail.webp still pending (generated in noctalia thumbnail
generator) — CI will flag the missing asset until added.

* fix: add PS4 Colors thumbnail (solid crimson card)

960x540 WebP, deep crimson (#990000) to match the plugin accent.

* feat: left-click applies saved color, panel adds Save button

- widget: left-click applies the saved color via service; right-click opens panel
- service: add 'save' IPC (persist without touching controller)
- panel: Save (persist) + Apply (set now) buttons
- translations: add 'save' key

* refactor: implement DS4 protocol in pure Lua (drop C dependency)

The plugin now writes the HID output report to /dev/hidrawN directly via
noctalia.writeFile. USB report 0x05 (32B) and Bluetooth report 0x11 (78B)
with CRC32 are built and the CRC verified against the kernel algorithm.
Device detection scans /sys/class/hidraw uevent for Sony DS4 PIDs.
No external binary or library required.

* fix: panel renders black box (ipairs(nil) at script load)

Move preset-click handler registration into onOpen (after presets are
loaded) instead of module top-level, where ipairs(nil) threw and aborted
the whole panel entry. Guard presets with 'or {}'. Replace unsupported
width='100%' string with a numeric width on the swatch.

* fix: match color_picker panel schema exactly (drop invented props)

Remove border='primary' (unknown value -> whole tree abort) and wrap=true.
Swatch now uses border='outline' + borderWidth to show selection, mirroring
oldirtty/color_picker. Aligns every ui.* node with a known-good panel.

* fix: service dead on load (pluginDataDir nil concat) + real device write

- Resolve pluginDataDir lazily + nil-guard lastFile() so the service entry
  actually loads (top-level concat on nil threw -> no onIpc -> no apply ->
  no notification, which is why the color never changed).
- setLightbar tries noctalia.writeFile, falls back to a python3 O_WRONLY
  binary write for the /dev/hidrawN char device (writeFile is file-oriented).

* fix: replace Luau bitwise ops (&/|/~/>>) with math-only helpers

Noctalia's Lua is strict (PUC-Rio semantic), not Luau: '&', '|', '~', '>>'
are syntax errors -> service failed to load at crc32_init -> no apply.
Added band/rshift/bxor/bnot32 math helpers; CRC32 + BT report now use them
and still produce the verified CRC 523bce6f.

* fix: panel black box (readonly _G) — use static onPreset1..9 globals

Noctalia's _G is immutable at runtime, so assigning _G['onPreset'..i] in
onOpen threw 'attempt to modify a readonly table' and aborted the panel.
Presets are a fixed list, so define onPreset1..9 as plain module globals
calling a shared applyPreset(i). Remove dead makePresetHandler.

* fix: drop unsupported textAlign prop on ui.input (ui-tree warning)

'textAlign' is a label prop, not an input prop; Noctalia ignored it with a
[WRN] ui-tree log line. Input defaults to left align anyway.

* fix: use device-gamepad-2 icon for catalog + bar glyph

'controller' glyph was missing; swap to device-gamepad-2 for both the
plugin catalog icon and the bar widget default glyph.

* rename: PS4 Colors -> DS4 Color (id Hy4ri/ds4-color, dir ds4-color/)

Rename plugin id, display name, bar glyph default, translation key
(ps4_colors -> ds4_color) and all internal IPC references. Drop the stale
ps4_colors_missing string (plugin has no external binary dependency).
Keep accurate comments crediting the original ps4-colors C source.

* ui: shorten panel (height 520->400, tighter gaps/padding, smaller swatch)

Save/Apply buttons were already the last row (bottom of the column); this
just compacts the overall panel height.

* art: use panel screenshot as thumbnail (960x540 webp, crimson bg)

* fix: lowercase author in id (CI validate: author must match ^[a-z0-9][a-z0-9._-]*$)

'Hy4ri' -> 'hy4ri' in id, author, and all internal IPC references.

* fix: thumbnail

* fix(review): declare python3 dependency + document hidraw fallback

Reviewer flagged: plugin declared dependencies=[] but the hidraw write fallback
invokes python3, so systems without Python cannot apply the color if the
direct writeFile fails. Declare 'python3' in dependencies, note it in the
manifest description, and document the requirement in README Requirements.

* security(review): validate color as 6-hex at every trust boundary

Reviewer flagged: last.json value entered shared state unvalidated, then got
single-quote-interpolated into /bin/sh -c via runAsync -> shell injection.

- Add isHex6() (exactly ^[0-9a-fA-F]{6}$) and enforce it at: loadLast
  (poisoned last.json), onSubmitHex, onApply/onSave (from state), onIpc
  apply/save, and the apply()/save() service funcs.
- Since only 6 hex chars can reach runAsync, the single-quote interpolation
  is provably safe (no quote-breaker / metachar can survive).
- Also fixes a latent bug: the old %x regex captured only 5 hex, rejecting
  valid 6-char colors like 990000.

* Update plugin description for clarity

Removed mention of 'hidraw write fallback' from the description.

---------

Co-authored-by: M57 <hy4ri@users.noreply.github.com>
Co-authored-by: Lemmy <studio@quadbyte.net>
2026-07-19 08:39:42 -04:00

154 lines
4.3 KiB
Luau

--!nonstrict
--!nocheck
--!nolint UnknownGlobal
local tr = noctalia.tr("ds4_color")
local SERVICE = "hy4ri/ds4-color:service"
-- Validate a color is exactly 6 hex chars (no metachars / quote-breakers can
-- survive this, so it is safe to interpolate into the runAsync shell string).
local function isHex6(s)
return type(s) == "string" and s:match("^[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]$") ~= nil
end
local function sendToService(event, payload)
local cmd = "noctalia msg plugin " .. SERVICE .. " all " .. event
if payload ~= nil then cmd = cmd .. " '" .. payload .. "'" end
noctalia.runAsync(cmd, function() end)
end
local function currentColor()
return noctalia.state.get("lastColor") or "990000"
end
local function render()
local color = currentColor()
local presets = noctalia.state.get("presets") or {}
local presetRow = {}
for i, p in ipairs(presets) do
local selected = (p.hex:lower() == color:lower())
table.insert(presetRow, ui.box({
width = 34,
height = 34,
fill = "#" .. p.hex,
radius = 8,
border = "outline",
borderWidth = selected and 3 or 1,
onClick = "onPreset" .. i,
}))
end
panel.render(ui.column({ gap = 10, padding = 12 }, {
ui.row({ align = "center", justify = "space_between" }, {
ui.label({ text = tr, fontSize = 18, fontWeight = "bold", color = "primary", flexGrow = 1 }),
ui.button({ glyph = "close", onClick = "onCloseClicked" }),
}),
-- Live swatch preview
ui.box({
width = 200,
height = 72,
fill = "#" .. color,
radius = 12,
border = "outline",
borderWidth = 2,
onClick = "onNativePicker",
}),
-- Hex field + native picker button
ui.row({ gap = 8, align = "center" }, {
ui.input({
key = "hex-input",
value = "#" .. color,
flexGrow = 1,
onSubmit = "onSubmitHex",
}),
ui.button({ glyph = "color-picker", variant = "ghost", onClick = "onNativePicker" }),
}),
ui.label({ text = noctalia.tr("presets"), fontSize = 13, color = "on_surface_variant" }),
ui.row({ gap = 8, align = "center" }, presetRow),
ui.row({ gap = 8 }, {
ui.button({
text = noctalia.tr("save"),
variant = "ghost",
onClick = "onSave",
flexGrow = 1,
}),
ui.button({
text = noctalia.tr("apply"),
variant = "primary",
onClick = "onApply",
flexGrow = 1,
}),
}),
}))
end
--==== callbacks ====
function onApply()
local c = currentColor()
if isHex6(c) then sendToService("apply", c) end
end
function onSave()
local c = currentColor()
if isHex6(c) then sendToService("save", c) end
end
function onSubmitHex(text)
local hex = text:match("^#?([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])$")
or text:match("^0x([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])$")
if hex == nil or not isHex6(hex) then
noctalia.notifyError(tr, noctalia.tr("bad_color"))
return
end
noctalia.state.set("lastColor", hex:upper())
render()
end
function onNativePicker()
noctalia.openColorPicker("#" .. currentColor(), function(color)
if color == nil then return end
local hex = color:match("#?(%x%x%x%x%x%x)")
if hex ~= nil then
noctalia.state.set("lastColor", hex:upper())
render()
end
end)
end
function onCloseClicked()
panel.close()
end
function onClose()
end
-- Presets are a fixed list, so define one global handler per index at module
-- load (Noctalia's _G is read-only at runtime — no dynamic _G["onPreset"..i]
-- assignment, which throws "attempt to modify a readonly table" in onOpen).
local function applyPreset(i)
local presets = noctalia.state.get("presets") or {}
local p = presets[i]
if p == nil then return end
noctalia.state.set("lastColor", p.hex:upper())
render()
end
function onPreset1() applyPreset(1) end
function onPreset2() applyPreset(2) end
function onPreset3() applyPreset(3) end
function onPreset4() applyPreset(4) end
function onPreset5() applyPreset(5) end
function onPreset6() applyPreset(6) end
function onPreset7() applyPreset(7) end
function onPreset8() applyPreset(8) end
function onPreset9() applyPreset(9) end
function onOpen(context)
noctalia.state.watch("lastColor", function() render() end)
render()
end