Add backlight control to the shell and regenerate WIT bindings
CI / test (push) Canceled after 0s

- Add compositor/shell/backlight.mbt for backlight control in the shell
- Update wit/capabilities.wit and wit/host/plasmoids.wit, then regenerate the component and interface ffi.mbt bindings (mostly export reordering)
- Add world/launcher-widget/README.md
This commit is contained in:
nandi committed 2026-11-28 02:16:07 -08:00
1 parent 2e00009c79
commit 74235cb0ca
84 files changed
+1525 -864

No files matched your search

+151 -9
View File
@@ -439,10 +439,28 @@ def query_camera(path):
os.close(fd)
def list_libcameras():
"""[(libcamera:id, label, '')] for cameras exposed through libcamera."""
try:
import libcamera
except ImportError:
return []
out = []
cm = libcamera.CameraManager.singleton()
loc_names = {0: "Front", 1: "Back", 2: "External"}
for cam in cm.cameras:
props = cam.properties
loc = loc_names.get(props.get(libcamera.properties.Location), "")
model = str(props.get(libcamera.properties.Model) or cam.id)
label = "%s camera (%s)" % (loc, model) if loc else model
out.append(("libcamera:" + cam.id, label, ""))
return out
def list_cameras():
"""[(path, name, why not or "")]: the /dev/v4l/by-id links, then /dev/video* nodes no link
points at."""
out, seen = [], set()
"""[(path, name, why not or '')]: libcamera cameras, /dev/v4l/by-id links, then /dev/video*."""
out = list_libcameras()
seen = set()
for p in sorted(glob.glob("/dev/v4l/by-id/*")):
seen.add(os.path.realpath(p))
out.append((p,) + query_camera(p))
@@ -460,9 +478,19 @@ def cameras_text(cams):
def camera_problem(device):
"""Why the configured camera can't be used, or "" (only checks the node, not streaming)."""
"""Why the configured camera can't be used, or '' (only checks the node, not streaming)."""
if device.startswith("images:"):
return ""
if device.startswith("libcamera:"):
cid = device[len("libcamera:"):]
try:
import libcamera
except ImportError:
return "python-libcamera is not installed (cannot open %s)" % device
cm = libcamera.CameraManager.singleton()
if cm.get(cid) is None:
return "no libcamera camera %s; %s" % (cid, cameras_text(list_cameras()))
return ""
path = "/dev/video" + device if device.isdigit() else device
if not os.path.exists(path):
why = "broken link" if os.path.islink(path) else "not there"
@@ -475,6 +503,112 @@ def camera_problem(device):
return ""
class LibcameraCamera:
"""Capture BGR frames via python-libcamera (MIPI/SoftISP phone cameras)."""
def __init__(self, device):
problem = camera_problem(device)
if problem:
raise Fail(problem, 2)
import cv2
import libcamera
import mmap
import numpy as np
self.cv2, self.libcamera, self.mmap, self.np = cv2, libcamera, mmap, np
cid = device[len("libcamera:"):]
self.cm = libcamera.CameraManager.singleton()
self.cam = self.cm.get(cid)
if self.cam is None:
raise Fail("camera %s disappeared" % device, 2)
self.rot = int(self.cam.properties.get(libcamera.properties.Rotation) or 0)
try:
self.cam.acquire()
except Exception as e:
raise Fail("couldn't acquire camera %s: %s" % (device, e), 2)
try:
cfg = self.cam.generate_configuration([libcamera.StreamRole.Viewfinder])
self.sc = cfg.at(0)
self.sc.size = libcamera.Size(640, 480)
cfg.validate()
self.cam.configure(cfg)
self.alloc = libcamera.FrameBufferAllocator(self.cam)
if self.alloc.allocate(self.sc.stream) <= 0:
raise Fail("couldn't allocate camera buffers for %s" % device, 2)
self.requests = []
for buf in self.alloc.buffers(self.sc.stream):
r = self.cam.create_request()
r.add_buffer(self.sc.stream, buf)
self.requests.append(r)
self.cam.start()
for r in self.requests:
self.cam.queue_request(r)
except Exception as e:
self.close()
if isinstance(e, Fail):
raise
raise Fail("couldn't start libcamera %s: %s" % (device, e), 2)
self._first = True
def _to_bgr(self, buf):
p = buf.planes[0]
w, h, stride = self.sc.size.width, self.sc.size.height, self.sc.stride
fmt = str(self.sc.pixel_format)
with self.mmap.mmap(p.fd, p.offset + p.length, self.mmap.MAP_SHARED, self.mmap.PROT_READ) as mm:
raw = bytes(mm[p.offset:p.offset + p.length])
arr = self.np.frombuffer(raw, dtype=self.np.uint8)
if fmt in ("ABGR8888", "XBGR8888", "ARGB8888", "XRGB8888"):
img = arr[:h * stride].reshape((h, stride // 4, 4))[:, :w, :3]
bgr = self.np.ascontiguousarray(img[:, :, ::-1]) if "BGR" in fmt else self.np.ascontiguousarray(img)
elif fmt in ("RGB888", "BGR888"):
img = arr[:h * stride].reshape((h, stride // 3, 3))[:, :w, :]
bgr = self.np.ascontiguousarray(img[:, :, ::-1]) if fmt == "RGB888" else self.np.ascontiguousarray(img)
else:
raise Fail("unsupported libcamera pixel format %s" % fmt, 2)
if self.rot == 90:
return self.cv2.rotate(bgr, self.cv2.ROTATE_90_CLOCKWISE)
if self.rot == 180:
return self.cv2.rotate(bgr, self.cv2.ROTATE_180)
if self.rot == 270:
return self.cv2.rotate(bgr, self.cv2.ROTATE_90_COUNTERCLOCKWISE)
return bgr
def read(self):
timeout = 3.0 if self._first else 1.5
self._first = False
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
ready = self.cm.get_ready_requests()
if ready:
for old in ready[:-1]:
old.reuse(self.libcamera.Request.ReuseFlag.ReuseBuffers)
self.cam.queue_request(old)
req = ready[-1]
frame = None
try:
if req.status == self.libcamera.Request.Status.Complete:
frame = self._to_bgr(req.buffers[self.sc.stream])
finally:
req.reuse(self.libcamera.Request.ReuseFlag.ReuseBuffers)
self.cam.queue_request(req)
if frame is not None:
return frame
time.sleep(0.01)
return None
def close(self):
try:
self.cam.stop()
except Exception:
pass
self.requests = []
self.alloc = None
try:
self.cam.release()
except Exception:
pass
class V4L2Camera:
def __init__(self, device):
problem = camera_problem(device)
@@ -502,6 +636,8 @@ class V4L2Camera:
def open_camera(cfg, loop=False):
if cfg.device.startswith("images:"):
return ImageCamera(cfg.device, cfg, loop)
if cfg.device.startswith("libcamera:"):
return LibcameraCamera(cfg.device)
return V4L2Camera(cfg.device)
@@ -1008,11 +1144,17 @@ def cmd_cameras(out):
def cmd_set_camera(cfg, path, out):
"""Point face.conf's `device` at `path` (root), after checking it is a camera."""
if not path.startswith("/dev/") or not os.path.exists(path):
raise Fail("no camera at %s" % path)
name, why = query_camera(path)
if why:
raise Fail("%s: %s" % (path, why))
if path.startswith("libcamera:"):
why = camera_problem(path)
if why:
raise Fail(why)
name = next((n for p, n, _ in list_libcameras() if p == path), path)
else:
if not path.startswith("/dev/") or not os.path.exists(path):
raise Fail("no camera at %s" % path)
name, why = query_camera(path)
if why:
raise Fail("%s: %s" % (path, why))
conf = cfg.path
text = open(conf).read() if os.path.exists(conf) else "[face]\n"
lines = text.split("\n")