diff --git a/camera/chandra-camera b/camera/chandra-camera new file mode 100755 index 0000000..4604868 --- /dev/null +++ b/camera/chandra-camera @@ -0,0 +1,1881 @@ +#!/usr/bin/env python3 +"""chandra-camera: mobile Wayland camera app for Chandra using libcamera / V4L2.""" + +import argparse +from dataclasses import dataclass +import datetime +import mmap +import os +import queue +import shutil +import signal +import subprocess +import sys +import threading +import time + +os.environ.setdefault("LIBCAMERA_LOG_LEVELS", "*:ERROR") + +APP_ID = "chandra-camera" +APP_TITLE = "Camera" +PICTURE_DIR = os.path.expanduser("~/Pictures/Camera") +VIDEO_DIR = os.path.expanduser("~/Videos/Camera") +FLASH_LED_PATH = "/sys/class/leds/white:flash/brightness" +IMAGE_EXTS = (".jpg", ".jpeg", ".png", ".webp") +VIDEO_EXTS = (".mp4", ".mkv", ".webm") + +# Fallback resolutions when a camera reports no enumerated StillCapture sizes. +DEFAULT_VIEWFINDER_SIZE = (1280, 960) +PREFERRED_STILL_SIZES = [ + (4648, 3496), + (3840, 2160), + (2584, 1940), + (2320, 1740), + (1920, 1440), + (1280, 960), +] + + +@dataclass +class CameraInfo: + """Descriptor for one discovered libcamera or V4L2 camera.""" + + cid: str + backend: str # "libcamera" or "v4l2" + model: str + location: int # 0=Front, 1=Back, 2=External + rotation: int + label: str + max_pixels: int = 0 + + @property + def is_front(self): + return self.location == 0 + + @property + def is_back(self): + return self.location == 1 + + +def _import_libcamera(): + """Import libcamera after silencing non-error C++ log noise.""" + os.environ.setdefault("LIBCAMERA_LOG_LEVELS", "*:ERROR") + import libcamera + return libcamera + + +def _short_model_name(raw_model, fallback_id): + """Turn a libcamera Model property or device path into a compact sensor label.""" + if raw_model: + s = str(raw_model).strip() + if "/" in s: + s = s.rsplit("/", 1)[-1] + if s: + return s + tail = fallback_id.rsplit("/", 1)[-1] + return tail or fallback_id + + +def sort_and_label_cameras(raw_items): + """Sort cameras (primary Back first, then Front, then extra Back/External) and assign unique labels. + + Each item in raw_items is a tuple: + (cid, backend, model, location, rotation, max_pixels) + """ + loc_word = {0: "Front", 1: "Back", 2: "External"} + + back_items = [it for it in raw_items if it[3] == 1] + primary_back_cid = None + if back_items: + best_back = min( + back_items, + key=lambda it: (0 if "imx519" in it[2].lower() else 1, -it[5], it[0]), + ) + primary_back_cid = best_back[0] + + def sort_key(item): + cid, _backend, model, loc, _rot, max_px = item + if loc == 1: + group = 0 if cid == primary_back_cid else 2 + elif loc == 0: + group = 1 + else: + group = 3 + return (group, -max_px, cid) + + ordered = sorted(raw_items, key=sort_key) + counts_by_loc = {} + for item in ordered: + loc = item[3] + counts_by_loc[loc] = counts_by_loc.get(loc, 0) + 1 + + seen_by_loc = {} + out = [] + for cid, backend, model, loc, rot, max_px in ordered: + idx = seen_by_loc.get(loc, 0) + 1 + seen_by_loc[loc] = idx + prefix = loc_word.get(loc, "Camera") + if counts_by_loc.get(loc, 0) > 1 and idx > 1: + tag = "%s %d" % (prefix, idx) + else: + tag = prefix + short = _short_model_name(model, cid) + label = "%s · %s" % (tag, short) if short else tag + out.append( + CameraInfo( + cid=cid, + backend=backend, + model=short, + location=loc, + rotation=int(rot or 0), + label=label, + max_pixels=int(max_px or 0), + ) + ) + return out + + +def discover_cameras(): + """Return sorted CameraInfo list from libcamera, falling back to V4L2.""" + raw = [] + try: + libcamera = _import_libcamera() + cm = libcamera.CameraManager.singleton() + for cam in cm.cameras: + props = cam.properties + loc = props.get(libcamera.properties.Location) + if loc is None: + loc = 2 + rot = props.get(libcamera.properties.Rotation) or 0 + model = str(props.get(libcamera.properties.Model) or _short_model_name("", cam.id)) + max_px = 0 + try: + pa = props.get(libcamera.properties.PixelArraySize) + if pa is not None: + max_px = int(pa.width) * int(pa.height) + except Exception: + max_px = 0 + raw.append((cam.id, "libcamera", model, int(loc), int(rot), max_px)) + except ImportError: + raw = [] + except Exception: + raw = [] + + if raw: + return sort_and_label_cameras(raw) + + # V4L2 fallback for desktops without libcamera sensors. + import glob + v4l2 = [] + for idx in range(10): + path = "/dev/video%d" % idx + if not os.path.exists(path): + continue + sys_name = "/sys/class/video4linux/video%d/name" % idx + name = "Camera %d" % idx + if os.path.exists(sys_name): + try: + name = open(sys_name).read().strip() or name + except OSError: + pass + if "metadata" in name.lower() or "decoder" in name.lower() or "encoder" in name.lower(): + continue + v4l2.append((path, "v4l2", name, 2, 0, 0)) + if not v4l2: + for path in sorted(glob.glob("/dev/v4l/by-id/*-video-index0")): + v4l2.append((path, "v4l2", os.path.basename(path), 2, 0, 0)) + return sort_and_label_cameras(v4l2) + + +def select_initial_camera(cameras, spec): + """Pick camera index matching `--camera` spec ('back', 'front', index, or substring).""" + if not cameras: + return 0 + if not spec: + return 0 + q = spec.strip().lower() + if q.isdigit(): + idx = int(q) + if 0 <= idx < len(cameras): + return idx + if q in ("back", "rear"): + for i, c in enumerate(cameras): + if c.is_back: + return i + if q in ("front", "selfie"): + for i, c in enumerate(cameras): + if c.is_front: + return i + for i, c in enumerate(cameras): + if q in c.cid.lower() or q in c.model.lower() or q in c.label.lower(): + return i + return 0 + + +def convert_frame(raw, width, height, stride, fmt, rot=0, cv2_mod=None, np_mod=None): + """Convert raw camera buffer bytes into a contiguous upright uint8 BGR image.""" + if np_mod is None: + import numpy as np_mod + if cv2_mod is None: + import cv2 as cv2_mod + + arr = np_mod.frombuffer(raw, dtype=np_mod.uint8) + fmt_u = str(fmt).upper() + if fmt_u in ("ABGR8888", "XBGR8888", "ARGB8888", "XRGB8888"): + row_px = stride // 4 + img = arr[:height * stride].reshape((height, row_px, 4))[:, :width, :3] + if "BGR" in fmt_u: + bgr = np_mod.ascontiguousarray(img[:, :, ::-1]) + else: + bgr = np_mod.ascontiguousarray(img) + elif fmt_u in ("RGB888", "BGR888"): + row_px = stride // 3 + img = arr[:height * stride].reshape((height, row_px, 3))[:, :width, :] + if fmt_u == "RGB888": + bgr = np_mod.ascontiguousarray(img[:, :, ::-1]) + else: + bgr = np_mod.ascontiguousarray(img) + else: + raise RuntimeError("unsupported pixel format %s" % fmt) + + rot_i = int(rot) % 360 + if rot_i == 90: + return np_mod.ascontiguousarray(cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_CLOCKWISE)) + if rot_i == 180: + return np_mod.ascontiguousarray(cv2_mod.rotate(bgr, cv2_mod.ROTATE_180)) + if rot_i == 270: + return np_mod.ascontiguousarray(cv2_mod.rotate(bgr, cv2_mod.ROTATE_90_COUNTERCLOCKWISE)) + return bgr + + +def bgr_to_cairo_argb32(bgr, np_mod=None): + """Convert contiguous (H, W, 3) uint8 BGR frame into (H, W, 4) BGRA for Cairo FORMAT_RGB24.""" + if np_mod is None: + import numpy as np_mod + h, w, _ = bgr.shape + buf = np_mod.empty((h, w, 4), dtype=np_mod.uint8) + buf[:, :, :3] = bgr + buf[:, :, 3] = 255 + return np_mod.ascontiguousarray(buf) + + +def set_flash_led(on, brightness=96): + """Toggle the rear white torch LED via logind SetBrightness (fallback to sysfs).""" + if not os.path.exists(FLASH_LED_PATH): + return False + val = int(brightness) if on else 0 + if val < 0: + val = 0 + if val > 255: + val = 255 + + # Prefer direct sysfs write when permitted, else logind session D-Bus helper. + try: + with open(FLASH_LED_PATH, "w") as f: + f.write(str(val)) + return True + except OSError: + pass + + sid = os.environ.get("XDG_SESSION_ID", "").strip() + if not sid: + try: + r = subprocess.run( + ["loginctl", "list-sessions", "--no-legend"], + capture_output=True, + text=True, + timeout=2, + check=False, + ) + uid_s = str(os.getuid()) + for line in r.stdout.splitlines(): + parts = line.split() + if len(parts) >= 2 and parts[1] == uid_s: + sid = parts[0] + break + except Exception: + sid = "" + if not sid: + sid = "auto" + + try: + r = subprocess.run( + [ + "busctl", + "call", + "org.freedesktop.login1", + "/org/freedesktop/login1/session/" + sid, + "org.freedesktop.login1.Session", + "SetBrightness", + "ssu", + "leds", + "white:flash", + str(val), + ], + capture_output=True, + text=True, + timeout=3, + check=False, + ) + return r.returncode == 0 + except Exception: + return False + + +def ensure_even_frame(bgr): + """Crop at most 1 pixel from bottom/right edge so width and height are even for H.264.""" + h, w = bgr.shape[:2] + ew = w & ~1 + eh = h & ~1 + if ew == w and eh == h: + return bgr + return bgr[:eh, :ew] + + +class CameraEngine: + """Thread-safe libcamera/V4L2 streaming, photo capture, and H.264 recording engine.""" + + def __init__(self, cameras, initial_index=0, on_frame=None, on_error=None, on_camera_changed=None): + import cv2 + import numpy as np + + self.cv2 = cv2 + self.np = np + self.libcamera = None + self.cm = None + self.cameras = cameras + self.active_index = initial_index if cameras else -1 + self.on_frame = on_frame + self.on_error = on_error + self.on_camera_changed = on_camera_changed + + self._lock = threading.Lock() + self._stop_event = threading.Event() + self._thread = None + + self._cam = None + self._sc = None + self._alloc = None + self._requests = [] + self._v4l2 = None + self._started = False + self._reuse_arg = None + + self._latest_bgr = None + self._latest_seq = 0 + self._want_switch = None + self._still_request = None + self._still_done = threading.Event() + self._still_result = (None, None) + + self._rec_lock = threading.Lock() + self._rec_proc = None + self._rec_queue = None + self._rec_thread = None + self._rec_path = None + self._rec_start_mono = 0.0 + self._rec_frames = 0 + self._rec_size = None + + @property + def active_camera(self): + if 0 <= self.active_index < len(self.cameras): + return self.cameras[self.active_index] + return None + + def latest_frame(self): + with self._lock: + return self._latest_bgr, self._latest_seq + + def is_recording(self): + with self._rec_lock: + return self._rec_proc is not None + + def recording_elapsed(self): + with self._rec_lock: + if self._rec_proc is None: + return 0.0 + return max(0.0, time.monotonic() - self._rec_start_mono) + + def start(self): + if self._thread is not None or not self.cameras: + return + self._stop_event.clear() + self._thread = threading.Thread(target=self._run_loop, name="chandra-cam-worker", daemon=True) + self._thread.start() + + def stop(self): + self.stop_video() + self._stop_event.set() + if self._thread is not None: + self._thread.join(timeout=6.0) + self._thread = None + set_flash_led(False) + + def switch_camera(self, index): + if not self.cameras: + return + target = index % len(self.cameras) + self.stop_video() + if self.cameras[target].is_front: + set_flash_led(False) + with self._lock: + self._want_switch = target + + def cycle_camera(self): + if len(self.cameras) <= 1: + return + self.switch_camera((self.active_index + 1) % len(self.cameras)) + + def _requeue(self, req): + if self._reuse_arg is not None: + try: + req.reuse(self._reuse_arg) + except TypeError: + self._reuse_arg = None + req.reuse() + else: + req.reuse() + self._cam.queue_request(req) + + def _open_camera(self, info, role_name="viewfinder", target_sizes=None): + if info.backend == "v4l2": + dev = int(info.cid) if info.cid.isdigit() else info.cid + cap = self.cv2.VideoCapture(dev, self.cv2.CAP_V4L2) + if not cap.isOpened(): + cap = self.cv2.VideoCapture(dev) + if not cap.isOpened(): + raise RuntimeError("failed to open V4L2 camera %s" % info.cid) + cap.set(self.cv2.CAP_PROP_FRAME_WIDTH, 1280) + cap.set(self.cv2.CAP_PROP_FRAME_HEIGHT, 960) + self._v4l2 = cap + return + + libcamera = _import_libcamera() + self.libcamera = libcamera + self.cm = libcamera.CameraManager.singleton() + reuse_enum = getattr(libcamera.Request, "Reuse", None) or getattr(libcamera.Request, "ReuseFlag", None) + self._reuse_arg = getattr(reuse_enum, "ReuseBuffers", None) if reuse_enum is not None else None + + cam = self.cm.get(info.cid) + if cam is None: + raise RuntimeError("camera %s disappeared" % info.cid) + cam.acquire() + self._cam = cam + try: + role = libcamera.StreamRole.StillCapture if role_name == "still" else libcamera.StreamRole.Viewfinder + sizes = target_sizes or ([DEFAULT_VIEWFINDER_SIZE] if role_name == "viewfinder" else PREFERRED_STILL_SIZES) + chosen_exc = None + configured = False + for w, h in sizes: + try: + cfg = cam.generate_configuration([role]) + sc = cfg.at(0) + sc.size = libcamera.Size(w, h) + cfg.validate() + cam.configure(cfg) + self._sc = sc + configured = True + break + except Exception as exc: + chosen_exc = exc + if not configured: + raise RuntimeError("failed to configure %s: %s" % (info.label, chosen_exc)) + + alloc = libcamera.FrameBufferAllocator(cam) + if alloc.allocate(self._sc.stream) <= 0: + raise RuntimeError("failed to allocate camera buffers for %s" % info.label) + self._alloc = alloc + reqs = [] + for buf in alloc.buffers(self._sc.stream): + r = cam.create_request() + r.add_buffer(self._sc.stream, buf) + reqs.append(r) + self._requests = reqs + # Drain any stale completed requests before starting the newly acquired sensor. + self.cm.get_ready_requests() + cam.start() + self._started = True + for r in self._requests: + cam.queue_request(r) + except Exception: + self._close_camera() + raise + + def _close_camera(self): + if self._v4l2 is not None: + try: + self._v4l2.release() + except Exception: + pass + self._v4l2 = None + + if self._cam is not None: + try: + if self._started: + self._cam.stop() + except Exception: + pass + self._started = False + if self.cm is not None: + try: + self.cm.get_ready_requests() + except Exception: + pass + self._requests = [] + self._alloc = None + self._sc = None + try: + self._cam.release() + except Exception: + pass + self._cam = None + + def _read_libcamera_frame(self, cam_info): + ready = self.cm.get_ready_requests() + if not ready: + return None + frame = None + for req in ready: + if self._sc is not None and self._sc.stream in req.buffers: + if req.status == self.libcamera.Request.Status.Complete: + buf = req.buffers[self._sc.stream] + plane = buf.planes[0] + w = self._sc.size.width + h = self._sc.size.height + stride = self._sc.stride + fmt = str(self._sc.pixel_format) + with mmap.mmap(plane.fd, plane.offset + plane.length, mmap.MAP_SHARED, mmap.PROT_READ) as mm: + raw = mm[plane.offset:plane.offset + plane.length] + frame = convert_frame( + raw, + w, + h, + stride, + fmt, + rot=cam_info.rotation, + cv2_mod=self.cv2, + np_mod=self.np, + ) + self._requeue(req) + return frame + + def _run_loop(self): + try: + self._open_camera(self.active_camera) + except Exception as exc: + if self.on_error: + self.on_error(str(exc)) + return + + try: + while not self._stop_event.is_set(): + # 1. Pending camera switch? + switch_to = None + with self._lock: + if self._want_switch is not None: + switch_to = self._want_switch + self._want_switch = None + if switch_to is not None and switch_to != self.active_index: + self._close_camera() + self.active_index = switch_to + try: + self._open_camera(self.active_camera) + if self.on_camera_changed: + self.on_camera_changed() + except Exception as exc: + if self.on_error: + self.on_error("Switch failed: %s" % exc) + break + + # 2. Pending full-resolution still capture? + still_out = None + with self._lock: + if self._still_request is not None: + still_out = self._still_request + self._still_request = None + if still_out is not None: + self._perform_still_capture(still_out) + + info = self.active_camera + if info is None: + time.sleep(0.05) + continue + + # 3. Capture next live frame. + frame = None + if info.backend == "v4l2": + if self._v4l2 is not None: + ok, f = self._v4l2.read() + if ok and f is not None: + frame = self.np.ascontiguousarray(f) + else: + time.sleep(0.02) + else: + frame = self._read_libcamera_frame(info) + if frame is None: + time.sleep(0.008) + + if frame is not None: + with self._lock: + self._latest_bgr = frame + self._latest_seq += 1 + self._push_video_frame(frame) + if self.on_frame: + self.on_frame() + finally: + self.stop_video() + self._close_camera() + + def _perform_still_capture(self, dst_path): + info = self.active_camera + try: + if info.backend == "libcamera": + self._close_camera() + self._open_camera(info, role_name="still", target_sizes=PREFERRED_STILL_SIZES) + captured = None + deadline = time.monotonic() + 5.0 + warmup = 0 + while time.monotonic() < deadline and not self._stop_event.is_set(): + f = self._read_libcamera_frame(info) + if f is not None: + captured = f + warmup += 1 + if warmup >= 6: + break + else: + time.sleep(0.01) + self._close_camera() + self._open_camera(info, role_name="viewfinder", target_sizes=[DEFAULT_VIEWFINDER_SIZE]) + if captured is None: + raise RuntimeError("still capture timed out") + os.makedirs(os.path.dirname(dst_path), exist_ok=True) + ok = self.cv2.imwrite(dst_path, captured, [self.cv2.IMWRITE_JPEG_QUALITY, 95]) + if not ok: + raise RuntimeError("failed to write %s" % dst_path) + self._still_result = (dst_path, None) + else: + frame, _ = self.latest_frame() + if frame is None: + raise RuntimeError("no frame yet") + os.makedirs(os.path.dirname(dst_path), exist_ok=True) + ok = self.cv2.imwrite(dst_path, frame, [self.cv2.IMWRITE_JPEG_QUALITY, 95]) + if not ok: + raise RuntimeError("failed to write %s" % dst_path) + self._still_result = (dst_path, None) + except Exception as exc: + self._still_result = (None, str(exc)) + # Recover viewfinder if still capture interrupted it. + if self._cam is None and self._v4l2 is None and info is not None: + try: + self._open_camera(info, role_name="viewfinder", target_sizes=[DEFAULT_VIEWFINDER_SIZE]) + except Exception: + pass + finally: + self._still_done.set() + + def capture_photo(self, high_res=False, dst_path=None): + """Save a JPEG photo into ~/Pictures/Camera (or dst_path) and return its path.""" + if dst_path is None: + os.makedirs(PICTURE_DIR, exist_ok=True) + stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + dst_path = os.path.join(PICTURE_DIR, "IMG_%s.jpg" % stamp) + suffix = 1 + while os.path.exists(dst_path): + dst_path = os.path.join(PICTURE_DIR, "IMG_%s_%d.jpg" % (stamp, suffix)) + suffix += 1 + + if not high_res: + frame, _ = self.latest_frame() + if frame is None: + raise RuntimeError("camera is still warming up") + os.makedirs(os.path.dirname(dst_path), exist_ok=True) + if not self.cv2.imwrite(dst_path, frame, [self.cv2.IMWRITE_JPEG_QUALITY, 95]): + raise RuntimeError("failed to save %s" % dst_path) + return dst_path + + self._still_done.clear() + self._still_result = (None, None) + with self._lock: + self._still_request = dst_path + if not self._still_done.wait(timeout=12.0): + raise RuntimeError("high-res capture timed out") + saved, err = self._still_result + if err: + raise RuntimeError(err) + return saved + + def start_video(self, dst_path=None): + """Start recording H.264 MP4 from upright viewfinder frames via ffmpeg.""" + if shutil.which("ffmpeg") is None: + raise RuntimeError("ffmpeg is not installed") + frame, _ = self.latest_frame() + if frame is None: + raise RuntimeError("camera is still warming up") + even = ensure_even_frame(frame) + h, w = even.shape[:2] + + if dst_path is None: + os.makedirs(VIDEO_DIR, exist_ok=True) + stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + dst_path = os.path.join(VIDEO_DIR, "VID_%s.mp4" % stamp) + suffix = 1 + while os.path.exists(dst_path): + dst_path = os.path.join(VIDEO_DIR, "VID_%s_%d.mp4" % (stamp, suffix)) + suffix += 1 + else: + os.makedirs(os.path.dirname(dst_path) or ".", exist_ok=True) + + cmd = [ + "ffmpeg", + "-y", + "-loglevel", + "error", + "-f", + "rawvideo", + "-pix_fmt", + "bgr24", + "-s", + "%dx%d" % (w, h), + "-r", + "20", + "-i", + "-", + "-c:v", + "libx264", + "-preset", + "ultrafast", + "-tune", + "zerolatency", + "-pix_fmt", + "yuv420p", + "-movflags", + "+faststart", + dst_path, + ] + proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE) + q = queue.Queue(maxsize=6) + + def writer(): + try: + while True: + item = q.get() + if item is None: + break + if proc.stdin is not None: + proc.stdin.write(item) + except Exception: + pass + finally: + try: + if proc.stdin is not None: + proc.stdin.close() + except Exception: + pass + + wt = threading.Thread(target=writer, name="chandra-cam-rec", daemon=True) + with self._rec_lock: + self._rec_proc = proc + self._rec_queue = q + self._rec_thread = wt + self._rec_path = dst_path + self._rec_start_mono = time.monotonic() + self._rec_frames = 0 + self._rec_size = (w, h) + wt.start() + self._push_video_frame(frame) + return dst_path + + def _push_video_frame(self, frame): + with self._rec_lock: + q = self._rec_queue + proc = self._rec_proc + target_size = self._rec_size + if q is None or proc is None or proc.poll() is not None: + return + even = ensure_even_frame(frame) + h, w = even.shape[:2] + if target_size and (w, h) != target_size: + even = self.cv2.resize(even, target_size) + raw = even.tobytes() + try: + q.put_nowait(raw) + with self._rec_lock: + self._rec_frames += 1 + except queue.Full: + # Drop oldest queued frame so live preview remains responsive. + try: + q.get_nowait() + except queue.Empty: + pass + try: + q.put_nowait(raw) + with self._rec_lock: + self._rec_frames += 1 + except queue.Full: + pass + + def stop_video(self): + """Stop video recording and finalize the MP4 container cleanly.""" + with self._rec_lock: + proc = self._rec_proc + q = self._rec_queue + wt = self._rec_thread + path = self._rec_path + frames = self._rec_frames + self._rec_proc = None + self._rec_queue = None + self._rec_thread = None + self._rec_path = None + self._rec_frames = 0 + self._rec_size = None + + if proc is None: + return None, 0 + if q is not None: + try: + while not q.empty(): + try: + q.get_nowait() + except queue.Empty: + break + q.put_nowait(None) + except Exception: + pass + if wt is not None: + wt.join(timeout=5.0) + rc = proc.wait(timeout=10.0) + if rc != 0 and proc.stderr is not None: + err = proc.stderr.read().decode("utf-8", "replace").strip() + if err and self.on_error: + self.on_error("Video encode error: " + err) + return path, frames + + +def list_gallery_photos(): + """Return newest-first list of saved photos in ~/Pictures/Camera.""" + if not os.path.isdir(PICTURE_DIR): + return [] + files = [] + for name in os.listdir(PICTURE_DIR): + if name.lower().endswith(IMAGE_EXTS): + p = os.path.join(PICTURE_DIR, name) + if os.path.isfile(p): + files.append(p) + files.sort(key=lambda p: (os.path.getmtime(p), p), reverse=True) + return files + + +def run_gui(cameras, initial_index, open_gallery=False): + """Launch the GTK3 + Cairo mobile camera interface on Wayland.""" + os.environ.setdefault("GDK_BACKEND", "wayland") + import cairo + import cv2 + import gi + gi.require_version("Gtk", "3.0") + from gi.repository import Gdk, GLib, Gtk + + GLib.set_prgname(APP_ID) + GLib.set_application_name(APP_TITLE) + + css = b""" + window, .cam-root { + background-color: #0b0d14; + color: #f4f6fc; + } + .cam-pill { + background-color: rgba(14, 18, 30, 0.74); + color: #f4f6fc; + border: 1px solid rgba(255, 255, 255, 0.16); + border-radius: 18px; + padding: 5px 12px; + font-size: 13px; + font-weight: 600; + min-height: 24px; + } + .cam-pill:hover { + background-color: rgba(30, 38, 60, 0.88); + } + .cam-pill-active { + background-color: rgba(110, 140, 255, 0.88); + color: #090d16; + border-color: rgba(180, 200, 255, 0.9); + } + .cam-pill-danger { + background-color: rgba(239, 68, 68, 0.88); + color: #ffffff; + border-color: rgba(255, 180, 180, 0.8); + } + .cam-dock { + background-color: rgba(10, 12, 20, 0.86); + border-top: 1px solid rgba(255, 255, 255, 0.10); + padding: 10px 16px 14px 16px; + } + .cam-mode-bar { + background-color: rgba(255, 255, 255, 0.08); + border-radius: 18px; + padding: 3px; + } + .cam-mode-btn { + background-color: transparent; + color: #c2cadc; + border: none; + border-radius: 15px; + padding: 4px 18px; + font-size: 13px; + font-weight: 600; + min-height: 22px; + } + .cam-mode-selected { + background-color: #6e8cff; + color: #0b0d14; + } + .cam-mode-selected-video { + background-color: #ef4444; + color: #ffffff; + } + .cam-rec-badge { + background-color: rgba(239, 68, 68, 0.90); + color: #ffffff; + border-radius: 12px; + padding: 2px 10px; + font-size: 12px; + font-weight: 700; + } + .cam-icon-btn { + background-color: transparent; + border: none; + padding: 0; + box-shadow: none; + } + .cam-gallery-bar { + background-color: #111523; + border-bottom: 1px solid rgba(255, 255, 255, 0.10); + padding: 8px 12px; + } + .cam-gallery-foot { + background-color: #111523; + border-top: 1px solid rgba(255, 255, 255, 0.10); + padding: 8px 14px; + } + .cam-title { + font-size: 14px; + font-weight: 700; + color: #f4f6fc; + } + .cam-sub { + font-size: 12px; + color: #9ba6c2; + } + """ + provider = Gtk.CssProvider() + provider.load_from_data(css) + Gtk.StyleContext.add_provider_for_screen( + Gdk.Screen.get_default(), provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION + ) + + class CameraWindow(Gtk.Window): + def __init__(self): + super().__init__(title=APP_TITLE) + self.set_wmclass(APP_ID, APP_TITLE) + self.set_default_size(520, 960) + self.set_size_request(340, 480) + self.get_style_context().add_class("cam-root") + + self.mode = "photo" # "photo" | "video" + self.high_res = False + self.show_grid = False + self.torch_on = False + self.timer_sec = 0 # 0, 3, 10 + self.countdown_left = 0 + self._countdown_src = None + self._flash_alpha = 0.0 + self._toast_text = "" + self._toast_until = 0.0 + self._draw_pending = False + self._thumb_bgr = None + self._gallery_files = [] + self._gallery_idx = 0 + self._gallery_bgr = None + self._has_flash_led = os.path.exists(FLASH_LED_PATH) + + self.engine = CameraEngine( + cameras, + initial_index=initial_index, + on_frame=self._on_worker_frame, + on_error=self._on_worker_error, + on_camera_changed=lambda: GLib.idle_add(lambda: (self._sync_ui_labels(), False)[1]), + ) + + self.stack = Gtk.Stack() + self.stack.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT) + self.stack.set_transition_duration(180) + self.add(self.stack) + + self._build_viewfinder_page() + self._build_gallery_page() + + self.connect("delete-event", self._on_close) + self.connect("key-press-event", self._on_key_press) + + self._refresh_thumbnail() + self._sync_ui_labels() + + if open_gallery: + self._open_gallery() + else: + self.stack.set_visible_child_name("viewfinder") + + if cameras: + self.engine.start() + else: + self._show_toast("No camera found", 6.0) + + GLib.timeout_add(250, self._tick_ui) + + def _build_viewfinder_page(self): + overlay = Gtk.Overlay() + + self.view_area = Gtk.DrawingArea() + self.view_area.set_hexpand(True) + self.view_area.set_vexpand(True) + self.view_area.connect("draw", self._draw_viewfinder) + overlay.add(self.view_area) + + # Top overlay controls. + top_bar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8) + top_bar.set_halign(Gtk.Align.FILL) + top_bar.set_valign(Gtk.Align.START) + top_bar.set_margin_top(12) + top_bar.set_margin_start(12) + top_bar.set_margin_end(12) + + self.cam_badge_btn = Gtk.Button(label="Camera") + self.cam_badge_btn.get_style_context().add_class("cam-pill") + self.cam_badge_btn.set_can_focus(False) + self.cam_badge_btn.connect("clicked", lambda *_: self._switch_camera()) + top_bar.pack_start(self.cam_badge_btn, False, False, 0) + + spacer = Gtk.Box() + top_bar.pack_start(spacer, True, True, 0) + + self.flash_btn = Gtk.Button(label="Flash") + self.flash_btn.get_style_context().add_class("cam-pill") + self.flash_btn.set_can_focus(False) + self.flash_btn.connect("clicked", lambda *_: self._toggle_flash()) + top_bar.pack_start(self.flash_btn, False, False, 0) + + self.grid_btn = Gtk.Button(label="Grid") + self.grid_btn.get_style_context().add_class("cam-pill") + self.grid_btn.set_can_focus(False) + self.grid_btn.connect("clicked", lambda *_: self._toggle_grid()) + top_bar.pack_start(self.grid_btn, False, False, 0) + + self.timer_btn = Gtk.Button(label="Timer") + self.timer_btn.get_style_context().add_class("cam-pill") + self.timer_btn.set_can_focus(False) + self.timer_btn.connect("clicked", lambda *_: self._cycle_timer()) + top_bar.pack_start(self.timer_btn, False, False, 0) + + self.res_btn = Gtk.Button(label="HD") + self.res_btn.get_style_context().add_class("cam-pill") + self.res_btn.set_can_focus(False) + self.res_btn.connect("clicked", lambda *_: self._toggle_res()) + top_bar.pack_start(self.res_btn, False, False, 0) + + overlay.add_overlay(top_bar) + + # Bottom dock (mode switcher + gallery/shutter/flip row). + dock = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10) + dock.get_style_context().add_class("cam-dock") + dock.set_halign(Gtk.Align.FILL) + dock.set_valign(Gtk.Align.END) + + mode_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8) + mode_row.set_halign(Gtk.Align.CENTER) + + mode_pill = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=2) + mode_pill.get_style_context().add_class("cam-mode-bar") + self.photo_mode_btn = Gtk.Button(label="Photo") + self.photo_mode_btn.get_style_context().add_class("cam-mode-btn") + self.photo_mode_btn.set_can_focus(False) + self.photo_mode_btn.connect("clicked", lambda *_: self._set_mode("photo")) + self.video_mode_btn = Gtk.Button(label="Video") + self.video_mode_btn.get_style_context().add_class("cam-mode-btn") + self.video_mode_btn.set_can_focus(False) + self.video_mode_btn.connect("clicked", lambda *_: self._set_mode("video")) + mode_pill.pack_start(self.photo_mode_btn, False, False, 0) + mode_pill.pack_start(self.video_mode_btn, False, False, 0) + mode_row.pack_start(mode_pill, False, False, 0) + + self.rec_label = Gtk.Label(label="● 00:00") + self.rec_label.get_style_context().add_class("cam-rec-badge") + self.rec_label.set_no_show_all(True) + self.rec_label.hide() + mode_row.pack_start(self.rec_label, False, False, 0) + dock.pack_start(mode_row, False, False, 0) + + action_row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0) + action_row.set_homogeneous(True) + + # Gallery button (left) + self.gallery_btn = Gtk.Button() + self.gallery_btn.get_style_context().add_class("cam-icon-btn") + self.gallery_btn.set_halign(Gtk.Align.CENTER) + self.gallery_btn.set_valign(Gtk.Align.CENTER) + self.gallery_btn.set_size_request(56, 56) + self.gallery_btn.set_can_focus(False) + self.gallery_btn.set_tooltip_text("Open Camera Gallery") + self.thumb_area = Gtk.DrawingArea() + self.thumb_area.set_size_request(52, 52) + self.thumb_area.connect("draw", self._draw_thumb_button) + self.gallery_btn.add(self.thumb_area) + self.gallery_btn.connect("clicked", lambda *_: self._open_gallery()) + action_row.pack_start(self.gallery_btn, True, True, 0) + + # Shutter button (center) + self.shutter_btn = Gtk.Button() + self.shutter_btn.get_style_context().add_class("cam-icon-btn") + self.shutter_btn.set_halign(Gtk.Align.CENTER) + self.shutter_btn.set_valign(Gtk.Align.CENTER) + self.shutter_btn.set_size_request(76, 76) + self.shutter_btn.set_can_focus(False) + self.shutter_btn.set_tooltip_text("Take Photo / Record Video (Space)") + self.shutter_area = Gtk.DrawingArea() + self.shutter_area.set_size_request(76, 76) + self.shutter_area.connect("draw", self._draw_shutter_button) + self.shutter_btn.add(self.shutter_area) + self.shutter_btn.connect("clicked", lambda *_: self._on_shutter()) + action_row.pack_start(self.shutter_btn, True, True, 0) + + # Switch camera button (right) + self.switch_btn = Gtk.Button() + self.switch_btn.get_style_context().add_class("cam-icon-btn") + self.switch_btn.set_halign(Gtk.Align.CENTER) + self.switch_btn.set_valign(Gtk.Align.CENTER) + self.switch_btn.set_size_request(56, 56) + self.switch_btn.set_can_focus(False) + self.switch_btn.set_tooltip_text("Switch Camera (S)") + self.switch_area = Gtk.DrawingArea() + self.switch_area.set_size_request(52, 52) + self.switch_area.connect("draw", self._draw_switch_button) + self.switch_btn.add(self.switch_area) + self.switch_btn.connect("clicked", lambda *_: self._switch_camera()) + action_row.pack_start(self.switch_btn, True, True, 0) + + dock.pack_start(action_row, False, False, 0) + overlay.add_overlay(dock) + self.stack.add_named(overlay, "viewfinder") + + def _build_gallery_page(self): + box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0) + + bar = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8) + bar.get_style_context().add_class("cam-gallery-bar") + + back_btn = Gtk.Button(label="← Camera") + back_btn.get_style_context().add_class("cam-pill") + back_btn.set_can_focus(False) + back_btn.connect("clicked", lambda *_: self._close_gallery()) + bar.pack_start(back_btn, False, False, 0) + + self.gallery_title = Gtk.Label(label="Gallery") + self.gallery_title.get_style_context().add_class("cam-title") + self.gallery_title.set_ellipsize(3) # PANGO_ELLIPSIZE_END + bar.pack_start(self.gallery_title, True, True, 4) + + folder_btn = Gtk.Button(label="Folder") + folder_btn.get_style_context().add_class("cam-pill") + folder_btn.set_can_focus(False) + folder_btn.connect("clicked", lambda *_: self._open_in_thunar()) + bar.pack_start(folder_btn, False, False, 0) + + self.delete_btn = Gtk.Button(label="Delete") + self.delete_btn.get_style_context().add_class("cam-pill") + self.delete_btn.get_style_context().add_class("cam-pill-danger") + self.delete_btn.set_can_focus(False) + self.delete_btn.connect("clicked", lambda *_: self._delete_current_photo()) + bar.pack_start(self.delete_btn, False, False, 0) + box.pack_start(bar, False, False, 0) + + self.gallery_area = Gtk.DrawingArea() + self.gallery_area.set_hexpand(True) + self.gallery_area.set_vexpand(True) + self.gallery_area.connect("draw", self._draw_gallery) + box.pack_start(self.gallery_area, True, True, 0) + + foot = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10) + foot.get_style_context().add_class("cam-gallery-foot") + + self.prev_btn = Gtk.Button(label="‹ Prev") + self.prev_btn.get_style_context().add_class("cam-pill") + self.prev_btn.set_can_focus(False) + self.prev_btn.connect("clicked", lambda *_: self._step_gallery(-1)) + foot.pack_start(self.prev_btn, False, False, 0) + + self.gallery_meta = Gtk.Label(label="") + self.gallery_meta.get_style_context().add_class("cam-sub") + foot.pack_start(self.gallery_meta, True, True, 4) + + self.next_btn = Gtk.Button(label="Next ›") + self.next_btn.get_style_context().add_class("cam-pill") + self.next_btn.set_can_focus(False) + self.next_btn.connect("clicked", lambda *_: self._step_gallery(1)) + foot.pack_start(self.next_btn, False, False, 0) + box.pack_start(foot, False, False, 0) + + self.stack.add_named(box, "gallery") + + def _on_worker_frame(self): + if self._draw_pending: + return + self._draw_pending = True + GLib.idle_add(self._redraw_from_idle) + + def _redraw_from_idle(self): + self._draw_pending = False + if self.stack.get_visible_child_name() == "viewfinder": + self.view_area.queue_draw() + return False + + def _on_worker_error(self, msg): + GLib.idle_add(lambda: (self._show_toast(msg, 4.0), False)[1]) + + def _show_toast(self, text, duration=2.2): + self._toast_text = text + self._toast_until = time.monotonic() + duration + self.view_area.queue_draw() + + def _tick_ui(self): + now = time.monotonic() + dirty = False + if self._flash_alpha > 0.01: + self._flash_alpha = max(0.0, self._flash_alpha - 0.18) + dirty = True + if self._toast_text and now > self._toast_until: + self._toast_text = "" + dirty = True + if self.engine.is_recording(): + secs = int(self.engine.recording_elapsed()) + self.rec_label.set_text("● %02d:%02d" % (secs // 60, secs % 60)) + self.rec_label.show() + else: + if self.rec_label.get_visible(): + self.rec_label.hide() + self.shutter_area.queue_draw() + if dirty and self.stack.get_visible_child_name() == "viewfinder": + self.view_area.queue_draw() + return True + + def _draw_image_contained(self, cr, width, height, bgr, top_pad=0, bottom_pad=0): + cr.set_source_rgb(0.043, 0.051, 0.078) + cr.paint() + if bgr is None: + return None + ih, iw = bgr.shape[:2] + if iw <= 0 or ih <= 0: + return None + avail_h = max(60, height - top_pad - bottom_pad) + scale = min(width / float(iw), avail_h / float(ih)) + dw = max(1, int(round(iw * scale))) + dh = max(1, int(round(ih * scale))) + x = (width - dw) / 2.0 + y = top_pad + (avail_h - dh) / 2.0 + + argb = bgr_to_cairo_argb32(bgr) + surf = cairo.ImageSurface.create_for_data(argb, cairo.FORMAT_RGB24, iw, ih, iw * 4) + cr.save() + cr.translate(x, y) + cr.scale(dw / float(iw), dh / float(ih)) + cr.set_source_surface(surf, 0, 0) + cr.get_source().set_filter(cairo.FILTER_BILINEAR) + cr.paint() + cr.restore() + return (x, y, dw, dh) + + def _draw_viewfinder(self, widget, cr): + w = widget.get_allocated_width() + h = widget.get_allocated_height() + frame, _ = self.engine.latest_frame() + info = self.engine.active_camera + if frame is not None: + disp = cv2.flip(frame, 1) if (info and info.is_front) else frame + rect = self._draw_image_contained(cr, w, h, disp, top_pad=56, bottom_pad=138) + else: + cr.set_source_rgb(0.043, 0.051, 0.078) + cr.paint() + rect = (20, 80, max(100, w - 40), max(120, h - 220)) + cr.set_source_rgba(0.75, 0.80, 0.92, 0.75) + cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) + cr.set_font_size(16) + msg = "Starting camera..." if info else "No camera connected" + ext = cr.text_extents(msg) + cr.move_to((w - ext.width) / 2.0, h / 2.0 - 30) + cr.show_text(msg) + + if self.show_grid and rect is not None: + gx, gy, gw, gh = rect + cr.set_source_rgba(1.0, 1.0, 1.0, 0.28) + cr.set_line_width(1.0) + for frac in (1.0 / 3.0, 2.0 / 3.0): + cr.move_to(gx + gw * frac, gy) + cr.line_to(gx + gw * frac, gy + gh) + cr.move_to(gx, gy + gh * frac) + cr.line_to(gx + gw, gy + gh * frac) + cr.stroke() + + if self.countdown_left > 0: + cr.set_source_rgba(1.0, 1.0, 1.0, 0.92) + cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) + cr.set_font_size(84) + txt = str(self.countdown_left) + ext = cr.text_extents(txt) + cr.move_to((w - ext.width) / 2.0, (h - 80 + ext.height) / 2.0) + cr.show_text(txt) + + if self._flash_alpha > 0.01: + cr.set_source_rgba(1.0, 1.0, 1.0, self._flash_alpha) + cr.paint() + + if self._toast_text and time.monotonic() <= self._toast_until: + cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) + cr.set_font_size(13) + ext = cr.text_extents(self._toast_text) + pw = ext.width + 28 + ph = 32 + px = (w - pw) / 2.0 + py = max(72.0, h - 186.0) + r = 16.0 + cr.new_sub_path() + cr.arc(px + pw - r, py + r, r, -1.5708, 0) + cr.arc(px + pw - r, py + ph - r, r, 0, 1.5708) + cr.arc(px + r, py + ph - r, r, 1.5708, 3.1416) + cr.arc(px + r, py + r, r, 3.1416, 4.7124) + cr.close_path() + cr.set_source_rgba(0.06, 0.08, 0.14, 0.85) + cr.fill_preserve() + cr.set_source_rgba(1.0, 1.0, 1.0, 0.20) + cr.set_line_width(1.0) + cr.stroke() + cr.set_source_rgb(0.96, 0.97, 1.0) + cr.move_to((w - ext.width) / 2.0, py + (ph + ext.height) / 2.0 - 1.0) + cr.show_text(self._toast_text) + + def _draw_thumb_button(self, widget, cr): + w = widget.get_allocated_width() + h = widget.get_allocated_height() + r = 14.0 + cr.new_sub_path() + cr.arc(w - r, r, r, -1.5708, 0) + cr.arc(w - r, h - r, r, 0, 1.5708) + cr.arc(r, h - r, r, 1.5708, 3.1416) + cr.arc(r, r, r, 3.1416, 4.7124) + cr.close_path() + cr.clip_preserve() + + if self._thumb_bgr is not None: + th, tw = self._thumb_bgr.shape[:2] + argb = bgr_to_cairo_argb32(self._thumb_bgr) + surf = cairo.ImageSurface.create_for_data(argb, cairo.FORMAT_RGB24, tw, th, tw * 4) + cr.save() + cr.scale(w / float(tw), h / float(th)) + cr.set_source_surface(surf, 0, 0) + cr.paint() + cr.restore() + else: + cr.set_source_rgba(0.16, 0.19, 0.28, 0.95) + cr.fill_preserve() + cr.set_source_rgba(0.82, 0.86, 0.96, 0.85) + cr.set_line_width(1.8) + cr.rectangle(13, 15, w - 26, h - 30) + cr.stroke() + cr.arc(20, 22, 2.5, 0, 6.2832) + cr.fill() + cr.move_to(15, h - 18) + cr.line_to(24, h - 27) + cr.line_to(30, h - 22) + cr.line_to(35, h - 25) + cr.line_to(w - 15, h - 18) + cr.stroke() + + cr.reset_clip() + cr.new_sub_path() + cr.arc(w - r, r, r, -1.5708, 0) + cr.arc(w - r, h - r, r, 0, 1.5708) + cr.arc(r, h - r, r, 1.5708, 3.1416) + cr.arc(r, r, r, 3.1416, 4.7124) + cr.close_path() + cr.set_source_rgba(1.0, 1.0, 1.0, 0.35) + cr.set_line_width(1.5) + cr.stroke() + + def _draw_shutter_button(self, widget, cr): + w = widget.get_allocated_width() + h = widget.get_allocated_height() + cx, cy = w / 2.0, h / 2.0 + outer_r = min(w, h) / 2.0 - 3.0 + + cr.arc(cx, cy, outer_r, 0, 6.2832) + cr.set_source_rgb(0.95, 0.97, 1.0) + cr.set_line_width(3.5) + cr.stroke() + + if self.mode == "video": + if self.engine.is_recording(): + sz = 26.0 + rx, ry = cx - sz / 2.0, cy - sz / 2.0 + rad = 6.0 + cr.new_sub_path() + cr.arc(rx + sz - rad, ry + rad, rad, -1.5708, 0) + cr.arc(rx + sz - rad, ry + sz - rad, rad, 0, 1.5708) + cr.arc(rx + rad, ry + sz - rad, rad, 1.5708, 3.1416) + cr.arc(rx + rad, ry + rad, rad, 3.1416, 4.7124) + cr.close_path() + cr.set_source_rgb(0.94, 0.27, 0.27) + cr.fill() + else: + cr.arc(cx, cy, outer_r - 7.5, 0, 6.2832) + cr.set_source_rgb(0.94, 0.27, 0.27) + cr.fill() + else: + cr.arc(cx, cy, outer_r - 7.5, 0, 6.2832) + if self.countdown_left > 0: + cr.set_source_rgb(0.43, 0.55, 1.0) + else: + cr.set_source_rgb(0.96, 0.97, 1.0) + cr.fill() + + def _draw_switch_button(self, widget, cr): + w = widget.get_allocated_width() + h = widget.get_allocated_height() + cx, cy = w / 2.0, h / 2.0 + cr.arc(cx, cy, min(w, h) / 2.0 - 1.5, 0, 6.2832) + cr.set_source_rgba(0.16, 0.19, 0.28, 0.92) + cr.fill_preserve() + cr.set_source_rgba(1.0, 1.0, 1.0, 0.22) + cr.set_line_width(1.5) + cr.stroke() + + cr.set_source_rgb(0.94, 0.96, 1.0) + cr.set_line_width(2.2) + cr.set_line_cap(cairo.LINE_CAP_ROUND) + r = 12.0 + cr.arc(cx, cy, r, -2.5, -0.35) + cr.stroke() + cr.arc(cx, cy, r, 0.65, 2.8) + cr.stroke() + # Small arrowheads on both arcs. + ax1, ay1 = cx + r * 0.94, cy - r * 0.34 + cr.move_to(ax1 - 5, ay1 - 2) + cr.line_to(ax1, ay1) + cr.line_to(ax1 - 1, ay1 - 5) + ax2, ay2 = cx - r * 0.94, cy + r * 0.34 + cr.move_to(ax2 + 5, ay2 + 2) + cr.line_to(ax2, ay2) + cr.line_to(ax2 + 1, ay2 + 5) + cr.stroke() + + def _draw_gallery(self, widget, cr): + w = widget.get_allocated_width() + h = widget.get_allocated_height() + if self._gallery_bgr is not None: + self._draw_image_contained(cr, w, h, self._gallery_bgr, top_pad=8, bottom_pad=8) + return + cr.set_source_rgb(0.043, 0.051, 0.078) + cr.paint() + cr.set_source_rgba(0.75, 0.80, 0.92, 0.80) + cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) + cr.set_font_size(16) + msg = "No photos yet" + ext = cr.text_extents(msg) + cr.move_to((w - ext.width) / 2.0, h / 2.0) + cr.show_text(msg) + + def _sync_ui_labels(self): + info = self.engine.active_camera + self.cam_badge_btn.set_label(info.label if info else "No camera") + if self._has_flash_led and info and info.is_back: + self.flash_btn.show() + else: + self.flash_btn.hide() + if self.torch_on: + self.torch_on = False + set_flash_led(False) + + if self.mode == "photo": + self.res_btn.show() + self.timer_btn.show() + else: + self.res_btn.hide() + self.timer_btn.hide() + + self.switch_btn.set_visible(len(self.cameras) > 1 if hasattr(self, "cameras") else len(cameras) > 1) + + def set_active(btn, active): + ctx = btn.get_style_context() + if active: + ctx.add_class("cam-pill-active") + else: + ctx.remove_class("cam-pill-active") + + set_active(self.flash_btn, self.torch_on) + self.flash_btn.set_label("Flash On" if self.torch_on else "Flash") + set_active(self.grid_btn, self.show_grid) + set_active(self.timer_btn, self.timer_sec > 0) + self.timer_btn.set_label("Timer %ds" % self.timer_sec if self.timer_sec > 0 else "Timer") + set_active(self.res_btn, self.high_res) + self.res_btn.set_label("Full" if self.high_res else "HD") + + p_ctx = self.photo_mode_btn.get_style_context() + v_ctx = self.video_mode_btn.get_style_context() + if self.mode == "photo": + p_ctx.add_class("cam-mode-selected") + v_ctx.remove_class("cam-mode-selected-video") + else: + p_ctx.remove_class("cam-mode-selected") + v_ctx.add_class("cam-mode-selected-video") + + self.shutter_area.queue_draw() + + def _switch_camera(self): + if self.countdown_left > 0 or len(cameras) <= 1: + return + self.torch_on = False + set_flash_led(False) + self.engine.cycle_camera() + self._sync_ui_labels() + + def _toggle_flash(self): + self.torch_on = not self.torch_on + if not set_flash_led(self.torch_on): + self.torch_on = False + self._show_toast("Flash control unavailable") + self._sync_ui_labels() + + def _toggle_grid(self): + self.show_grid = not self.show_grid + self._sync_ui_labels() + self.view_area.queue_draw() + + def _cycle_timer(self): + self.timer_sec = {0: 3, 3: 10, 10: 0}.get(self.timer_sec, 0) + self._sync_ui_labels() + + def _toggle_res(self): + self.high_res = not self.high_res + self._sync_ui_labels() + + def _set_mode(self, mode): + if self.engine.is_recording(): + return + self.mode = mode + self._sync_ui_labels() + + def _on_shutter(self): + if self.mode == "video": + if self.engine.is_recording(): + path, frames = self.engine.stop_video() + self._sync_ui_labels() + if path: + self._show_toast("Saved %s (%d frames)" % (os.path.basename(path), frames)) + else: + try: + self.engine.start_video() + self._sync_ui_labels() + except Exception as exc: + self._show_toast(str(exc), 3.0) + return + + if self.countdown_left > 0: + if self._countdown_src is not None: + GLib.source_remove(self._countdown_src) + self._countdown_src = None + self.countdown_left = 0 + self._sync_ui_labels() + self.view_area.queue_draw() + return + + if self.timer_sec > 0: + self.countdown_left = self.timer_sec + self._sync_ui_labels() + self.view_area.queue_draw() + self._countdown_src = GLib.timeout_add(1000, self._countdown_step) + return + + self._take_photo_async() + + def _countdown_step(self): + self.countdown_left -= 1 + if self.countdown_left > 0: + self.view_area.queue_draw() + return True + self._countdown_src = None + self._sync_ui_labels() + self._take_photo_async() + return False + + def _take_photo_async(self): + self._flash_alpha = 0.72 + self.view_area.queue_draw() + high_res = self.high_res + + def job(): + try: + path = self.engine.capture_photo(high_res=high_res) + GLib.idle_add(lambda: (self._after_photo_saved(path), False)[1]) + except Exception as exc: + msg = str(exc) + GLib.idle_add(lambda: (self._show_toast(msg, 3.0), False)[1]) + + threading.Thread(target=job, daemon=True).start() + + def _after_photo_saved(self, path): + self._refresh_thumbnail() + self._show_toast("Saved " + os.path.basename(path)) + + def _refresh_thumbnail(self): + files = list_gallery_photos() + self._thumb_bgr = None + if files: + img = cv2.imread(files[0]) + if img is not None: + h, w = img.shape[:2] + side = min(w, h) + x0 = (w - side) // 2 + y0 = (h - side) // 2 + crop = img[y0:y0 + side, x0:x0 + side] + self._thumb_bgr = cv2.resize(crop, (96, 96), interpolation=cv2.INTER_AREA) + self.thumb_area.queue_draw() + + def _open_gallery(self): + self._gallery_files = list_gallery_photos() + self._gallery_idx = 0 + self._load_gallery_image() + self.stack.set_visible_child_name("gallery") + + def _close_gallery(self): + self.stack.set_visible_child_name("viewfinder") + self._refresh_thumbnail() + self.view_area.queue_draw() + + def _load_gallery_image(self): + self._gallery_bgr = None + n = len(self._gallery_files) + if n == 0: + self.gallery_title.set_text("Gallery (empty)") + self.gallery_meta.set_text("") + self.delete_btn.set_sensitive(False) + self.prev_btn.set_sensitive(False) + self.next_btn.set_sensitive(False) + self.gallery_area.queue_draw() + return + self._gallery_idx = max(0, min(self._gallery_idx, n - 1)) + path = self._gallery_files[self._gallery_idx] + img = cv2.imread(path) + self._gallery_bgr = img + self.gallery_title.set_text("%s · %d/%d" % (os.path.basename(path), self._gallery_idx + 1, n)) + if img is not None: + h, w = img.shape[:2] + kb = max(1, os.path.getsize(path) // 1024) + self.gallery_meta.set_text("%dx%d · %d KB" % (w, h, kb)) + else: + self.gallery_meta.set_text("Unreadable image") + self.delete_btn.set_sensitive(True) + self.prev_btn.set_sensitive(self._gallery_idx > 0) + self.next_btn.set_sensitive(self._gallery_idx + 1 < n) + self.gallery_area.queue_draw() + + def _step_gallery(self, delta): + if not self._gallery_files: + return + self._gallery_idx = max(0, min(len(self._gallery_files) - 1, self._gallery_idx + delta)) + self._load_gallery_image() + + def _delete_current_photo(self): + if not self._gallery_files: + return + path = self._gallery_files[self._gallery_idx] + try: + os.remove(path) + except OSError: + return + self._gallery_files = list_gallery_photos() + if self._gallery_idx >= len(self._gallery_files): + self._gallery_idx = max(0, len(self._gallery_files) - 1) + self._load_gallery_image() + self._refresh_thumbnail() + + def _open_in_thunar(self): + os.makedirs(PICTURE_DIR, exist_ok=True) + try: + subprocess.Popen(["thunar", PICTURE_DIR]) + except Exception: + self._show_toast("Could not launch file manager") + + def _on_key_press(self, _win, ev): + kv = ev.keyval + page = self.stack.get_visible_child_name() + if page == "gallery": + if kv in (Gdk.KEY_Left, Gdk.KEY_Up): + self._step_gallery(-1) + return True + if kv in (Gdk.KEY_Right, Gdk.KEY_Down): + self._step_gallery(1) + return True + if kv == Gdk.KEY_Escape: + self._close_gallery() + return True + return False + + if kv in ( + Gdk.KEY_space, + Gdk.KEY_Return, + Gdk.KEY_KP_Enter, + Gdk.KEY_XF86AudioRaiseVolume, + Gdk.KEY_XF86AudioLowerVolume, + ): + self._on_shutter() + return True + if kv in (Gdk.KEY_s, Gdk.KEY_S, Gdk.KEY_Tab): + self._switch_camera() + return True + if kv in (Gdk.KEY_v, Gdk.KEY_V): + self._set_mode("video" if self.mode == "photo" else "photo") + return True + if kv in (Gdk.KEY_g, Gdk.KEY_G): + self._toggle_grid() + return True + if kv == Gdk.KEY_Escape: + if self.engine.is_recording(): + self._on_shutter() + else: + self._on_close() + return True + return False + + def _on_close(self, *_args): + if self._countdown_src is not None: + GLib.source_remove(self._countdown_src) + self._countdown_src = None + self.engine.stop() + Gtk.main_quit() + return False + + win = CameraWindow() + win.show_all() + + def _handle_sig(*_): + GLib.idle_add(lambda: (win._on_close(), False)[1]) + return True + + GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, _handle_sig) + GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, _handle_sig) + Gtk.main() + return 0 + + +def run_self_test(cameras): + """Verify multi-camera discovery, switching, JPEG capture, MP4 recording, and clean release.""" + if not cameras: + print("FAIL: no cameras discovered", file=sys.stderr) + return 1 + print("Discovered %d camera(s):" % len(cameras)) + for i, c in enumerate(cameras): + print(" [%d] %s (%s, cid=%s, rot=%d, max_px=%d)" % (i, c.label, c.backend, c.cid, c.rotation, c.max_pixels)) + + front_idx = select_initial_camera(cameras, "front") + engine = CameraEngine(cameras, initial_index=0) + engine.start() + try: + # 1. Wait for first camera frames. + t0 = time.monotonic() + while time.monotonic() - t0 < 5.0: + f, seq = engine.latest_frame() + if f is not None and seq >= 3: + break + time.sleep(0.05) + f0, seq0 = engine.latest_frame() + if f0 is None: + raise RuntimeError("no frames from initial camera %s" % cameras[0].label) + print("Initial camera %s frame: shape=%s seq=%d" % (cameras[0].label, f0.shape, seq0)) + + # 2. Switch to front camera if different and capture JPEG photo + 2s H.264 video. + if front_idx != engine.active_index: + engine.switch_camera(front_idx) + t0 = time.monotonic() + while time.monotonic() - t0 < 5.0: + if engine.active_index == front_idx: + f, seq = engine.latest_frame() + if f is not None and seq > seq0 + 3: + break + time.sleep(0.05) + + f1, _ = engine.latest_frame() + if f1 is None or int(f1.max()) == 0: + raise RuntimeError("active camera %s produced empty/black frame" % engine.active_camera.label) + print("Active photo camera %s frame: shape=%s mean=%.1f max=%d" % ( + engine.active_camera.label, f1.shape, float(f1.mean()), int(f1.max()) + )) + + photo_path = engine.capture_photo(high_res=False) + import cv2 + saved_img = cv2.imread(photo_path) + if saved_img is None or os.path.getsize(photo_path) <= 0: + raise RuntimeError("invalid captured photo at %s" % photo_path) + print("Saved JPEG: %s (%d bytes, shape=%s)" % (photo_path, os.path.getsize(photo_path), saved_img.shape)) + + video_path = engine.start_video() + time.sleep(2.0) + final_video, nframes = engine.stop_video() + if not final_video or not os.path.exists(final_video) or os.path.getsize(final_video) <= 0 or nframes < 5: + raise RuntimeError("invalid captured video at %s (frames=%d)" % (final_video, nframes)) + print("Saved MP4: %s (%d bytes, frames=%d)" % (final_video, os.path.getsize(final_video), nframes)) + + # 3. Switch back to camera 0 to prove bidirectional switch cleanly releases qcom-camss. + if len(cameras) > 1: + back_target = 0 if engine.active_index != 0 else 1 + _, seq_before_back = engine.latest_frame() + engine.switch_camera(back_target) + t0 = time.monotonic() + ok_back = False + while time.monotonic() - t0 < 5.0: + if engine.active_index == back_target: + fb, seqb = engine.latest_frame() + if fb is not None and seqb > seq_before_back + 1: + ok_back = True + print("Switched back to %s: shape=%s seq=%d" % (cameras[back_target].label, fb.shape, seqb)) + break + time.sleep(0.05) + if not ok_back: + raise RuntimeError("timed out switching back to camera %s" % cameras[back_target].label) + finally: + engine.stop() + + print("SELF_TEST_OK photo=%s video=%s" % (photo_path, final_video)) + return 0 + + +def parse_args(argv): + p = argparse.ArgumentParser(prog=APP_ID, description="Chandra Wayland Camera App") + p.add_argument("--camera", default="", help="Initial camera ('back', 'front', index, or model/id)") + p.add_argument("--open-gallery", action="store_true", help="Open directly in the in-app gallery") + p.add_argument("--self-test", action="store_true", help="Run non-interactive capture & switch self-test") + p.add_argument("--list-cameras", action="store_true", help="List detected cameras and exit") + return p.parse_args(argv) + + +def main(argv=None): + args = parse_args(sys.argv[1:] if argv is None else argv) + cameras = discover_cameras() + if args.list_cameras: + for i, c in enumerate(cameras): + print("%d\t%s\t%s\t%s\trot=%d" % (i, c.label, c.backend, c.cid, c.rotation)) + return 0 + if args.self_test: + return run_self_test(cameras) + initial = select_initial_camera(cameras, args.camera) + return run_gui(cameras, initial_index=initial, open_gallery=args.open_gallery) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/camera/chandra-camera-ui.c b/camera/chandra-camera-ui.c new file mode 100644 index 0000000..e2852dd --- /dev/null +++ b/camera/chandra-camera-ui.c @@ -0,0 +1,1401 @@ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +typedef struct { + GtkWidget *window; + GtkWidget *stack; + + /* Viewfinder widgets */ + GtkWidget *view_area; + GtkWidget *cam_badge_btn; + GtkWidget *flash_btn; + GtkWidget *grid_btn; + GtkWidget *timer_btn; + GtkWidget *res_btn; + GtkWidget *photo_mode_btn; + GtkWidget *video_mode_btn; + GtkWidget *rec_label; + GtkWidget *thumb_area; + GtkWidget *shutter_area; + GtkWidget *switch_btn; + GtkWidget *switch_area; + + /* Gallery widgets */ + GtkWidget *gallery_title; + GtkWidget *gallery_meta; + GtkWidget *gallery_area; + GtkWidget *delete_btn; + GtkWidget *prev_btn; + GtkWidget *next_btn; + + /* Worker process & pipes */ + gchar *worker_exe; + gchar *initial_camera; + gboolean open_gallery_start; + pid_t worker_pid; + FILE *to_worker; + FILE *from_worker; + GThread *reader_thread; + gboolean shutting_down; + + /* Shared latest frame from worker (CAIRO_FORMAT_RGB24 BGRA32) */ + GMutex frame_mutex; + uint8_t *frame_buf; + int frame_w; + int frame_h; + size_t frame_len; + uint64_t frame_seq; + gboolean draw_pending; + + /* Paint copy owned exclusively by GTK main thread */ + uint8_t *paint_buf; + int paint_w; + int paint_h; + size_t paint_len; + uint64_t paint_seq; + + /* Camera & UI state */ + int cam_count; + gboolean has_flash; + int active_idx; + gboolean active_is_front; + gboolean active_is_back; + gchar *active_label; + + gboolean mode_video; + gboolean high_res; + gboolean show_grid; + gboolean torch_on; + gboolean is_recording; + int64_t rec_start_us; + + int timer_sec; + int countdown_left; + guint countdown_src; + double flash_alpha; + + gchar *toast_text; + int64_t toast_until_us; + + /* Gallery & thumbnail */ + gchar **gallery_files; + int gallery_count; + int gallery_idx; + GdkPixbuf *thumb_pb; + GdkPixbuf *gallery_pb; +} CameraApp; + +typedef struct { + CameraApp *app; + gchar *line; +} WorkerMsg; + +static void sync_ui_labels(CameraApp *app); +static void refresh_thumbnail(CameraApp *app); +static void open_gallery_view(CameraApp *app); +static void close_gallery_view(CameraApp *app); +static void shutdown_app(CameraApp *app); + +static gchar *pictures_camera_dir(void) { + const gchar *home = g_get_home_dir(); + return g_build_filename(home, "Pictures", "Camera", NULL); +} + +static void send_worker(CameraApp *app, const char *cmd) { + if (!app->to_worker || app->shutting_down) return; + fprintf(app->to_worker, "%s\n", cmd); + fflush(app->to_worker); +} + +static void show_toast(CameraApp *app, const char *msg, double seconds) { + g_free(app->toast_text); + app->toast_text = g_strdup(msg ? msg : ""); + app->toast_until_us = g_get_monotonic_time() + (int64_t)(seconds * 1000000.0); + gtk_widget_queue_draw(app->view_area); +} + +static gboolean is_image_filename(const char *name) { + if (!name) return FALSE; + const char *dot = strrchr(name, '.'); + if (!dot) return FALSE; + return g_ascii_strcasecmp(dot, ".jpg") == 0 || + g_ascii_strcasecmp(dot, ".jpeg") == 0 || + g_ascii_strcasecmp(dot, ".png") == 0 || + g_ascii_strcasecmp(dot, ".webp") == 0; +} + +typedef struct { + gchar *path; + time_t mtime; +} GalleryEntry; + +static int cmp_gallery_desc(const void *a, const void *b) { + const GalleryEntry *ea = (const GalleryEntry *)a; + const GalleryEntry *eb = (const GalleryEntry *)b; + if (eb->mtime != ea->mtime) { + return (eb->mtime > ea->mtime) ? 1 : -1; + } + return strcmp(eb->path, ea->path); +} + +static void free_gallery_files(CameraApp *app) { + if (app->gallery_files) { + for (int i = 0; i < app->gallery_count; i++) { + g_free(app->gallery_files[i]); + } + g_free(app->gallery_files); + app->gallery_files = NULL; + } + app->gallery_count = 0; +} + +static void scan_gallery_files(CameraApp *app) { + free_gallery_files(app); + gchar *dir_path = pictures_camera_dir(); + DIR *d = opendir(dir_path); + if (!d) { + g_free(dir_path); + return; + } + GArray *arr = g_array_new(FALSE, FALSE, sizeof(GalleryEntry)); + struct dirent *ent; + while ((ent = readdir(d)) != NULL) { + if (ent->d_name[0] == '.') continue; + if (!is_image_filename(ent->d_name)) continue; + gchar *full = g_build_filename(dir_path, ent->d_name, NULL); + struct stat st; + if (stat(full, &st) == 0 && S_ISREG(st.st_mode)) { + GalleryEntry ge = {full, st.st_mtime}; + g_array_append_val(arr, ge); + } else { + g_free(full); + } + } + closedir(d); + g_free(dir_path); + + if (arr->len > 0) { + qsort(arr->data, arr->len, sizeof(GalleryEntry), cmp_gallery_desc); + app->gallery_count = (int)arr->len; + app->gallery_files = g_new0(gchar *, arr->len + 1); + for (guint i = 0; i < arr->len; i++) { + GalleryEntry *ge = &g_array_index(arr, GalleryEntry, i); + app->gallery_files[i] = ge->path; + } + } + g_array_free(arr, TRUE); +} + +static void refresh_thumbnail(CameraApp *app) { + if (app->thumb_pb) { + g_object_unref(app->thumb_pb); + app->thumb_pb = NULL; + } + scan_gallery_files(app); + if (app->gallery_count > 0) { + GdkPixbuf *raw = gdk_pixbuf_new_from_file_at_scale(app->gallery_files[0], 128, 128, TRUE, NULL); + if (raw) { + app->thumb_pb = gdk_pixbuf_apply_embedded_orientation(raw); + g_object_unref(raw); + } + } + gtk_widget_queue_draw(app->thumb_area); +} + +static void load_gallery_image(CameraApp *app) { + if (app->gallery_pb) { + g_object_unref(app->gallery_pb); + app->gallery_pb = NULL; + } + if (app->gallery_count == 0) { + gtk_label_set_text(GTK_LABEL(app->gallery_title), "Gallery (empty)"); + gtk_label_set_text(GTK_LABEL(app->gallery_meta), ""); + gtk_widget_set_sensitive(app->delete_btn, FALSE); + gtk_widget_set_sensitive(app->prev_btn, FALSE); + gtk_widget_set_sensitive(app->next_btn, FALSE); + gtk_widget_queue_draw(app->gallery_area); + return; + } + if (app->gallery_idx < 0) app->gallery_idx = 0; + if (app->gallery_idx >= app->gallery_count) app->gallery_idx = app->gallery_count - 1; + + const char *path = app->gallery_files[app->gallery_idx]; + gchar *base = g_path_get_basename(path); + gchar *title = g_strdup_printf("%s · %d/%d", base, app->gallery_idx + 1, app->gallery_count); + gtk_label_set_text(GTK_LABEL(app->gallery_title), title); + g_free(base); + g_free(title); + + GdkPixbuf *raw = gdk_pixbuf_new_from_file(path, NULL); + if (raw) { + app->gallery_pb = gdk_pixbuf_apply_embedded_orientation(raw); + g_object_unref(raw); + } + struct stat st; + long kb = (stat(path, &st) == 0) ? (long)(st.st_size / 1024) : 0; + if (kb < 1 && st.st_size > 0) kb = 1; + if (app->gallery_pb) { + gchar *meta = g_strdup_printf("%dx%d · %ld KB", + gdk_pixbuf_get_width(app->gallery_pb), + gdk_pixbuf_get_height(app->gallery_pb), + kb); + gtk_label_set_text(GTK_LABEL(app->gallery_meta), meta); + g_free(meta); + } else { + gtk_label_set_text(GTK_LABEL(app->gallery_meta), "Unreadable image"); + } + + gtk_widget_set_sensitive(app->delete_btn, TRUE); + gtk_widget_set_sensitive(app->prev_btn, app->gallery_idx > 0); + gtk_widget_set_sensitive(app->next_btn, app->gallery_idx + 1 < app->gallery_count); + gtk_widget_queue_draw(app->gallery_area); +} + +static void open_gallery_view(CameraApp *app) { + scan_gallery_files(app); + app->gallery_idx = 0; + load_gallery_image(app); + gtk_stack_set_visible_child_name(GTK_STACK(app->stack), "gallery"); +} + +static void close_gallery_view(CameraApp *app) { + gtk_stack_set_visible_child_name(GTK_STACK(app->stack), "viewfinder"); + refresh_thumbnail(app); + gtk_widget_queue_draw(app->view_area); +} + +static void set_pill_active(GtkWidget *btn, gboolean active) { + GtkStyleContext *ctx = gtk_widget_get_style_context(btn); + if (active) { + gtk_style_context_add_class(ctx, "cam-pill-active"); + } else { + gtk_style_context_remove_class(ctx, "cam-pill-active"); + } +} + +static void sync_ui_labels(CameraApp *app) { + gtk_button_set_label(GTK_BUTTON(app->cam_badge_btn), + app->active_label ? app->active_label : "Camera"); + + if (app->has_flash && app->active_is_back) { + gtk_widget_show(app->flash_btn); + } else { + gtk_widget_hide(app->flash_btn); + app->torch_on = FALSE; + } + + if (!app->mode_video) { + gtk_widget_show(app->res_btn); + gtk_widget_show(app->timer_btn); + } else { + gtk_widget_hide(app->res_btn); + gtk_widget_hide(app->timer_btn); + } + + gtk_widget_set_visible(app->switch_btn, app->cam_count > 1); + + set_pill_active(app->flash_btn, app->torch_on); + gtk_button_set_label(GTK_BUTTON(app->flash_btn), app->torch_on ? "Flash On" : "Flash"); + set_pill_active(app->grid_btn, app->show_grid); + set_pill_active(app->timer_btn, app->timer_sec > 0); + if (app->timer_sec > 0) { + gchar *tlbl = g_strdup_printf("Timer %ds", app->timer_sec); + gtk_button_set_label(GTK_BUTTON(app->timer_btn), tlbl); + g_free(tlbl); + } else { + gtk_button_set_label(GTK_BUTTON(app->timer_btn), "Timer"); + } + set_pill_active(app->res_btn, app->high_res); + gtk_button_set_label(GTK_BUTTON(app->res_btn), app->high_res ? "Full" : "HD"); + + GtkStyleContext *p_ctx = gtk_widget_get_style_context(app->photo_mode_btn); + GtkStyleContext *v_ctx = gtk_widget_get_style_context(app->video_mode_btn); + if (!app->mode_video) { + gtk_style_context_add_class(p_ctx, "cam-mode-selected"); + gtk_style_context_remove_class(v_ctx, "cam-mode-selected-video"); + } else { + gtk_style_context_remove_class(p_ctx, "cam-mode-selected"); + gtk_style_context_add_class(v_ctx, "cam-mode-selected-video"); + } + + if (app->is_recording) { + gtk_widget_show(app->rec_label); + } else { + gtk_widget_hide(app->rec_label); + } + gtk_widget_queue_draw(app->shutter_area); +} + +static void rounded_rect_path(cairo_t *cr, double x, double y, double w, double h, double r) { + cairo_new_sub_path(cr); + cairo_arc(cr, x + w - r, y + r, r, -M_PI / 2.0, 0.0); + cairo_arc(cr, x + w - r, y + h - r, r, 0.0, M_PI / 2.0); + cairo_arc(cr, x + r, y + h - r, r, M_PI / 2.0, M_PI); + cairo_arc(cr, x + r, y + r, r, M_PI, 3.0 * M_PI / 2.0); + cairo_close_path(cr); +} + +static gboolean draw_viewfinder(GtkWidget *widget, cairo_t *cr, gpointer data) { + CameraApp *app = (CameraApp *)data; + int w = gtk_widget_get_allocated_width(widget); + int h = gtk_widget_get_allocated_height(widget); + + cairo_set_source_rgb(cr, 0.043, 0.051, 0.078); + cairo_paint(cr); + + /* Copy latest frame buffer without holding frame_mutex during Cairo paint. */ + g_mutex_lock(&app->frame_mutex); + if (app->frame_buf && app->frame_seq != app->paint_seq) { + uint8_t *nb = (uint8_t *)realloc(app->paint_buf, app->frame_len); + if (nb) { + app->paint_buf = nb; + memcpy(app->paint_buf, app->frame_buf, app->frame_len); + app->paint_w = app->frame_w; + app->paint_h = app->frame_h; + app->paint_len = app->frame_len; + app->paint_seq = app->frame_seq; + } + } + g_mutex_unlock(&app->frame_mutex); + + double rx = 20.0, ry = 80.0; + double rw = fmax(100.0, w - 40.0), rh = fmax(120.0, h - 220.0); + + if (app->paint_buf && app->paint_w > 0 && app->paint_h > 0) { + int iw = app->paint_w; + int ih = app->paint_h; + double top_pad = 56.0; + double bottom_pad = 138.0; + double avail_h = fmax(60.0, h - top_pad - bottom_pad); + double scale = fmin(w / (double)iw, avail_h / (double)ih); + double dw = fmax(1.0, round(iw * scale)); + double dh = fmax(1.0, round(ih * scale)); + double x = (w - dw) / 2.0; + double y = top_pad + (avail_h - dh) / 2.0; + rx = x; + ry = y; + rw = dw; + rh = dh; + + cairo_surface_t *surf = cairo_image_surface_create_for_data( + app->paint_buf, CAIRO_FORMAT_RGB24, iw, ih, iw * 4); + if (cairo_surface_status(surf) == CAIRO_STATUS_SUCCESS) { + cairo_save(cr); + if (app->active_is_front) { + cairo_translate(cr, x + dw, y); + cairo_scale(cr, -dw / (double)iw, dh / (double)ih); + } else { + cairo_translate(cr, x, y); + cairo_scale(cr, dw / (double)iw, dh / (double)ih); + } + cairo_set_source_surface(cr, surf, 0.0, 0.0); + cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_BILINEAR); + cairo_paint(cr); + cairo_restore(cr); + } + cairo_surface_destroy(surf); + } else { + const char *msg = app->cam_count > 0 ? "Starting camera..." : "No camera connected"; + cairo_set_source_rgba(cr, 0.75, 0.80, 0.92, 0.78); + cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); + cairo_set_font_size(cr, 16.0); + cairo_text_extents_t ext; + cairo_text_extents(cr, msg, &ext); + cairo_move_to((w - ext.width) / 2.0, h / 2.0 - 30.0); + cairo_show_text(cr, msg); + } + + if (app->show_grid) { + cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 0.30); + cairo_set_line_width(cr, 1.0); + for (int i = 1; i <= 2; i++) { + double f = i / 3.0; + cairo_move_to(cr, rx + rw * f, ry); + cairo_line_to(cr, rx + rw * f, ry + rh); + cairo_move_to(cr, rx, ry + rh * f); + cairo_line_to(cr, rx + rw, ry + rh * f); + } + cairo_stroke(cr); + } + + if (app->countdown_left > 0) { + char buf[16]; + snprintf(buf, sizeof(buf), "%d", app->countdown_left); + cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 0.92); + cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); + cairo_set_font_size(cr, 84.0); + cairo_text_extents_t ext; + cairo_text_extents(cr, buf, &ext); + cairo_move_to(cr, (w - ext.width) / 2.0, (h - 80.0 + ext.height) / 2.0); + cairo_show_text(cr, buf); + } + + if (app->flash_alpha > 0.01) { + cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, app->flash_alpha); + cairo_paint(cr); + } + + if (app->toast_text && app->toast_text[0] && g_get_monotonic_time() <= app->toast_until_us) { + cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); + cairo_set_font_size(cr, 13.0); + cairo_text_extents_t ext; + cairo_text_extents(cr, app->toast_text, &ext); + double pw = ext.width + 28.0; + double ph = 32.0; + double px = (w - pw) / 2.0; + double py = fmax(72.0, h - 186.0); + rounded_rect_path(cr, px, py, pw, ph, 16.0); + cairo_set_source_rgba(cr, 0.06, 0.08, 0.14, 0.85); + cairo_fill_preserve(cr); + cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 0.22); + cairo_set_line_width(cr, 1.0); + cairo_stroke(cr); + cairo_set_source_rgb(cr, 0.96, 0.97, 1.0); + cairo_move_to(cr, (w - ext.width) / 2.0, py + (ph + ext.height) / 2.0 - 1.0); + cairo_show_text(cr, app->toast_text); + } + + return FALSE; +} + +static gboolean draw_thumb_button(GtkWidget *widget, cairo_t *cr, gpointer data) { + CameraApp *app = (CameraApp *)data; + int w = gtk_widget_get_allocated_width(widget); + int h = gtk_widget_get_allocated_height(widget); + + cairo_save(cr); + rounded_rect_path(cr, 0, 0, w, h, 14.0); + cairo_clip(cr); + + if (app->thumb_pb) { + int pw = gdk_pixbuf_get_width(app->thumb_pb); + int ph = gdk_pixbuf_get_height(app->thumb_pb); + double scale = fmax(w / (double)pw, h / (double)ph); + double dw = pw * scale; + double dh = ph * scale; + cairo_translate(cr, (w - dw) / 2.0, (h - dh) / 2.0); + cairo_scale(cr, scale, scale); + gdk_cairo_set_source_pixbuf(cr, app->thumb_pb, 0.0, 0.0); + cairo_paint(cr); + } else { + cairo_set_source_rgba(cr, 0.16, 0.19, 0.28, 0.95); + cairo_paint(cr); + cairo_set_source_rgba(cr, 0.82, 0.86, 0.96, 0.85); + cairo_set_line_width(cr, 1.8); + cairo_rectangle(cr, 13.0, 15.0, w - 26.0, h - 30.0); + cairo_stroke(cr); + cairo_arc(cr, 20.0, 22.0, 2.5, 0.0, 2.0 * M_PI); + cairo_fill(cr); + cairo_move_to(cr, 15.0, h - 18.0); + cairo_line_to(cr, 24.0, h - 27.0); + cairo_line_to(cr, 30.0, h - 22.0); + cairo_line_to(cr, 35.0, h - 25.0); + cairo_line_to(cr, w - 15.0, h - 18.0); + cairo_stroke(cr); + } + cairo_restore(cr); + + rounded_rect_path(cr, 0.75, 0.75, w - 1.5, h - 1.5, 13.5); + cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 0.35); + cairo_set_line_width(cr, 1.5); + cairo_stroke(cr); + return FALSE; +} + +static gboolean draw_shutter_button(GtkWidget *widget, cairo_t *cr, gpointer data) { + CameraApp *app = (CameraApp *)data; + int w = gtk_widget_get_allocated_width(widget); + int h = gtk_widget_get_allocated_height(widget); + double cx = w / 2.0, cy = h / 2.0; + double outer_r = fmin(w, h) / 2.0 - 3.0; + + cairo_arc(cr, cx, cy, outer_r, 0.0, 2.0 * M_PI); + cairo_set_source_rgb(cr, 0.95, 0.97, 1.0); + cairo_set_line_width(cr, 3.5); + cairo_stroke(cr); + + if (app->mode_video) { + if (app->is_recording) { + double sz = 26.0; + rounded_rect_path(cr, cx - sz / 2.0, cy - sz / 2.0, sz, sz, 6.0); + cairo_set_source_rgb(cr, 0.94, 0.27, 0.27); + cairo_fill(cr); + } else { + cairo_arc(cr, cx, cy, outer_r - 7.5, 0.0, 2.0 * M_PI); + cairo_set_source_rgb(cr, 0.94, 0.27, 0.27); + cairo_fill(cr); + } + } else { + cairo_arc(cr, cx, cy, outer_r - 7.5, 0.0, 2.0 * M_PI); + if (app->countdown_left > 0) { + cairo_set_source_rgb(cr, 0.43, 0.55, 1.0); + } else { + cairo_set_source_rgb(cr, 0.96, 0.97, 1.0); + } + cairo_fill(cr); + } + return FALSE; +} + +static gboolean draw_switch_button(GtkWidget *widget, cairo_t *cr, gpointer data) { + (void)data; + int w = gtk_widget_get_allocated_width(widget); + int h = gtk_widget_get_allocated_height(widget); + double cx = w / 2.0, cy = h / 2.0; + + cairo_arc(cr, cx, cy, fmin(w, h) / 2.0 - 1.5, 0.0, 2.0 * M_PI); + cairo_set_source_rgba(cr, 0.16, 0.19, 0.28, 0.92); + cairo_fill_preserve(cr); + cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 0.22); + cairo_set_line_width(cr, 1.5); + cairo_stroke(cr); + + cairo_set_source_rgb(cr, 0.94, 0.96, 1.0); + cairo_set_line_width(cr, 2.2); + cairo_set_line_cap(cr, CAIRO_LINE_CAP_ROUND); + double r = 12.0; + cairo_arc(cr, cx, cy, r, -2.5, -0.35); + cairo_stroke(cr); + cairo_arc(cr, cx, cy, r, 0.65, 2.8); + cairo_stroke(cr); + + double ax1 = cx + r * 0.94, ay1 = cy - r * 0.34; + cairo_move_to(cr, ax1 - 5.0, ay1 - 2.0); + cairo_line_to(cr, ax1, ay1); + cairo_line_to(cr, ax1 - 1.0, ay1 - 5.0); + + double ax2 = cx - r * 0.94, ay2 = cy + r * 0.34; + cairo_move_to(cr, ax2 + 5.0, ay2 + 2.0); + cairo_line_to(cr, ax2, ay2); + cairo_line_to(cr, ax2 + 1.0, ay2 + 5.0); + cairo_stroke(cr); + return FALSE; +} + +static gboolean draw_gallery(GtkWidget *widget, cairo_t *cr, gpointer data) { + CameraApp *app = (CameraApp *)data; + int w = gtk_widget_get_allocated_width(widget); + int h = gtk_widget_get_allocated_height(widget); + + cairo_set_source_rgb(cr, 0.043, 0.051, 0.078); + cairo_paint(cr); + + if (app->gallery_pb) { + int iw = gdk_pixbuf_get_width(app->gallery_pb); + int ih = gdk_pixbuf_get_height(app->gallery_pb); + double avail_w = fmax(40.0, w - 16.0); + double avail_h = fmax(40.0, h - 16.0); + double scale = fmin(avail_w / (double)iw, avail_h / (double)ih); + double dw = iw * scale; + double dh = ih * scale; + cairo_translate(cr, (w - dw) / 2.0, (h - dh) / 2.0); + cairo_scale(cr, scale, scale); + gdk_cairo_set_source_pixbuf(cr, app->gallery_pb, 0.0, 0.0); + cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_BILINEAR); + cairo_paint(cr); + } else { + cairo_set_source_rgba(cr, 0.75, 0.80, 0.92, 0.80); + cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); + cairo_set_font_size(cr, 16.0); + const char *msg = "No photos yet"; + cairo_text_extents_t ext; + cairo_text_extents(cr, msg, &ext); + cairo_move_to(cr, (w - ext.width) / 2.0, h / 2.0); + cairo_show_text(cr, msg); + } + return FALSE; +} + +static gboolean redraw_from_idle(gpointer data) { + CameraApp *app = (CameraApp *)data; + g_mutex_lock(&app->frame_mutex); + app->draw_pending = FALSE; + g_mutex_unlock(&app->frame_mutex); + if (!app->shutting_down && + g_strcmp0(gtk_stack_get_visible_child_name(GTK_STACK(app->stack)), "viewfinder") == 0) { + gtk_widget_queue_draw(app->view_area); + } + return G_SOURCE_REMOVE; +} + +static gboolean handle_worker_line_idle(gpointer data) { + WorkerMsg *m = (WorkerMsg *)data; + CameraApp *app = m->app; + if (!app->shutting_down) { + char *line = m->line; + size_t n = strlen(line); + while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) { + line[--n] = '\0'; + } + if (strncmp(line, "info ", 5) == 0) { + int cnt = 0, hf = 0; + if (sscanf(line + 5, "%d %d", &cnt, &hf) == 2) { + app->cam_count = cnt; + app->has_flash = (hf != 0); + sync_ui_labels(app); + } + } else if (strncmp(line, "active ", 7) == 0) { + int idx = 0, is_f = 0, is_b = 0; + const char *p = line + 7; + if (sscanf(p, "%d %d %d", &idx, &is_f, &is_b) == 3) { + const char *lbl = p; + for (int k = 0; k < 3; k++) { + lbl = strchr(lbl, ' '); + if (!lbl) break; + lbl++; + } + app->active_idx = idx; + app->active_is_front = (is_f != 0); + app->active_is_back = (is_b != 0); + g_free(app->active_label); + app->active_label = g_strdup(lbl ? lbl : "Camera"); + sync_ui_labels(app); + } + } else if (strncmp(line, "flash ", 6) == 0) { + app->torch_on = (atoi(line + 6) != 0); + sync_ui_labels(app); + } else if (strncmp(line, "rec_state ", 10) == 0) { + gboolean rec = (atoi(line + 10) != 0); + app->is_recording = rec; + if (rec) { + app->rec_start_us = g_get_monotonic_time(); + gtk_label_set_text(GTK_LABEL(app->rec_label), "● 00:00"); + } + sync_ui_labels(app); + } else if (strncmp(line, "saved_photo ", 12) == 0) { + gchar *base = g_path_get_basename(line + 12); + gchar *msg = g_strdup_printf("Saved %s", base); + show_toast(app, msg, 2.4); + g_free(base); + g_free(msg); + refresh_thumbnail(app); + } else if (strncmp(line, "saved_video ", 12) == 0) { + int frames = 0; + const char *p = line + 12; + const char *sp = strchr(p, ' '); + if (sp) { + frames = atoi(p); + gchar *base = g_path_get_basename(sp + 1); + gchar *msg = g_strdup_printf("Saved %s (%d frames)", base, frames); + show_toast(app, msg, 2.8); + g_free(base); + g_free(msg); + } + } else if (strncmp(line, "toast ", 6) == 0) { + show_toast(app, line + 6, 3.0); + } + } + g_free(m->line); + g_free(m); + return G_SOURCE_REMOVE; +} + +static gpointer worker_reader_func(gpointer data) { + CameraApp *app = (CameraApp *)data; + char line[1024]; + while (fgets(line, sizeof(line), app->from_worker) != NULL) { + if (strncmp(line, "frame ", 6) == 0) { + int w = 0, h = 0; + unsigned long len = 0; + if (sscanf(line + 6, "%d %d %lu", &w, &h, &len) == 3 && + w > 0 && h > 0 && len == (unsigned long)w * (unsigned long)h * 4UL && + len <= 16UL * 1024UL * 1024UL) { + uint8_t *buf = (uint8_t *)malloc((size_t)len); + if (!buf) break; + size_t got = 0; + while (got < (size_t)len) { + size_t n = fread(buf + got, 1, (size_t)len - got, app->from_worker); + if (n == 0) break; + got += n; + } + if (got != (size_t)len) { + free(buf); + break; + } + g_mutex_lock(&app->frame_mutex); + free(app->frame_buf); + app->frame_buf = buf; + app->frame_w = w; + app->frame_h = h; + app->frame_len = (size_t)len; + app->frame_seq++; + gboolean need_schedule = !app->draw_pending; + if (need_schedule) app->draw_pending = TRUE; + g_mutex_unlock(&app->frame_mutex); + if (need_schedule && !app->shutting_down) { + g_idle_add(redraw_from_idle, app); + } + } + continue; + } + WorkerMsg *msg = g_new(WorkerMsg, 1); + msg->app = app; + msg->line = g_strdup(line); + g_idle_add(handle_worker_line_idle, msg); + } + return NULL; +} + +static gboolean tick_ui(gpointer data) { + CameraApp *app = (CameraApp *)data; + if (app->shutting_down) return G_SOURCE_REMOVE; + + int64_t now = g_get_monotonic_time(); + gboolean dirty = FALSE; + if (app->flash_alpha > 0.01) { + app->flash_alpha = fmax(0.0, app->flash_alpha - 0.18); + dirty = TRUE; + } + if (app->toast_text && app->toast_text[0] && now > app->toast_until_us) { + g_free(app->toast_text); + app->toast_text = NULL; + dirty = TRUE; + } + if (app->is_recording) { + int secs = (int)((now - app->rec_start_us) / 1000000LL); + if (secs < 0) secs = 0; + char buf[32]; + snprintf(buf, sizeof(buf), "● %02d:%02d", secs / 60, secs % 60); + gtk_label_set_text(GTK_LABEL(app->rec_label), buf); + } + if (dirty && g_strcmp0(gtk_stack_get_visible_child_name(GTK_STACK(app->stack)), "viewfinder") == 0) { + gtk_widget_queue_draw(app->view_area); + } + return G_SOURCE_CONTINUE; +} + +static void trigger_photo_now(CameraApp *app) { + app->flash_alpha = 0.72; + gtk_widget_queue_draw(app->view_area); + send_worker(app, app->high_res ? "snap_full" : "snap"); +} + +static gboolean countdown_step(gpointer data) { + CameraApp *app = (CameraApp *)data; + app->countdown_left--; + if (app->countdown_left > 0) { + gtk_widget_queue_draw(app->view_area); + return G_SOURCE_CONTINUE; + } + app->countdown_src = 0; + sync_ui_labels(app); + trigger_photo_now(app); + return G_SOURCE_REMOVE; +} + +static void on_shutter(CameraApp *app) { + if (app->mode_video) { + send_worker(app, app->is_recording ? "rec_stop" : "rec_start"); + return; + } + if (app->countdown_left > 0) { + if (app->countdown_src > 0) { + g_source_remove(app->countdown_src); + app->countdown_src = 0; + } + app->countdown_left = 0; + sync_ui_labels(app); + gtk_widget_queue_draw(app->view_area); + return; + } + if (app->timer_sec > 0) { + app->countdown_left = app->timer_sec; + sync_ui_labels(app); + gtk_widget_queue_draw(app->view_area); + app->countdown_src = g_timeout_add(1000, countdown_step, app); + return; + } + trigger_photo_now(app); +} + +static void on_switch_clicked(GtkWidget *w, gpointer data) { + (void)w; + CameraApp *app = (CameraApp *)data; + if (app->countdown_left > 0 || app->cam_count <= 1) return; + if (app->is_recording) { + send_worker(app, "rec_stop"); + } + app->torch_on = FALSE; + send_worker(app, "switch"); + sync_ui_labels(app); +} + +static void on_flash_clicked(GtkWidget *w, gpointer data) { + (void)w; + CameraApp *app = (CameraApp *)data; + app->torch_on = !app->torch_on; + send_worker(app, app->torch_on ? "flash 1" : "flash 0"); + sync_ui_labels(app); +} + +static void on_grid_clicked(GtkWidget *w, gpointer data) { + (void)w; + CameraApp *app = (CameraApp *)data; + app->show_grid = !app->show_grid; + sync_ui_labels(app); + gtk_widget_queue_draw(app->view_area); +} + +static void on_timer_clicked(GtkWidget *w, gpointer data) { + (void)w; + CameraApp *app = (CameraApp *)data; + if (app->timer_sec == 0) app->timer_sec = 3; + else if (app->timer_sec == 3) app->timer_sec = 10; + else app->timer_sec = 0; + sync_ui_labels(app); +} + +static void on_res_clicked(GtkWidget *w, gpointer data) { + (void)w; + CameraApp *app = (CameraApp *)data; + app->high_res = !app->high_res; + sync_ui_labels(app); +} + +static void set_mode_video(CameraApp *app, gboolean video) { + if (app->is_recording) return; + app->mode_video = video; + sync_ui_labels(app); +} + +static void on_photo_mode_clicked(GtkWidget *w, gpointer data) { + (void)w; + set_mode_video((CameraApp *)data, FALSE); +} + +static void on_video_mode_clicked(GtkWidget *w, gpointer data) { + (void)w; + set_mode_video((CameraApp *)data, TRUE); +} + +static void on_gallery_btn_clicked(GtkWidget *w, gpointer data) { + (void)w; + open_gallery_view((CameraApp *)data); +} + +static void on_shutter_btn_clicked(GtkWidget *w, gpointer data) { + (void)w; + on_shutter((CameraApp *)data); +} + +static void on_gallery_back_clicked(GtkWidget *w, gpointer data) { + (void)w; + close_gallery_view((CameraApp *)data); +} + +static void on_gallery_prev_clicked(GtkWidget *w, gpointer data) { + (void)w; + CameraApp *app = (CameraApp *)data; + if (app->gallery_idx > 0) { + app->gallery_idx--; + load_gallery_image(app); + } +} + +static void on_gallery_next_clicked(GtkWidget *w, gpointer data) { + (void)w; + CameraApp *app = (CameraApp *)data; + if (app->gallery_idx + 1 < app->gallery_count) { + app->gallery_idx++; + load_gallery_image(app); + } +} + +static void on_gallery_delete_clicked(GtkWidget *w, gpointer data) { + (void)w; + CameraApp *app = (CameraApp *)data; + if (app->gallery_count == 0) return; + if (unlink(app->gallery_files[app->gallery_idx]) != 0) return; + scan_gallery_files(app); + if (app->gallery_idx >= app->gallery_count) { + app->gallery_idx = app->gallery_count - 1; + } + load_gallery_image(app); + refresh_thumbnail(app); +} + +static void on_gallery_folder_clicked(GtkWidget *w, gpointer data) { + (void)w; + CameraApp *app = (CameraApp *)data; + gchar *dir = pictures_camera_dir(); + g_mkdir_with_parents(dir, 0755); + gchar *argv[] = {"thunar", dir, NULL}; + if (!g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL)) { + show_toast(app, "Could not launch file manager", 2.5); + } + g_free(dir); +} + +static gboolean on_key_press(GtkWidget *w, GdkEventKey *ev, gpointer data) { + (void)w; + CameraApp *app = (CameraApp *)data; + guint kv = ev->keyval; + const char *page = gtk_stack_get_visible_child_name(GTK_STACK(app->stack)); + + if (g_strcmp0(page, "gallery") == 0) { + if (kv == GDK_KEY_Left || kv == GDK_KEY_Up) { + on_gallery_prev_clicked(NULL, app); + return TRUE; + } + if (kv == GDK_KEY_Right || kv == GDK_KEY_Down) { + on_gallery_next_clicked(NULL, app); + return TRUE; + } + if (kv == GDK_KEY_Escape) { + close_gallery_view(app); + return TRUE; + } + return FALSE; + } + + if (kv == GDK_KEY_space || kv == GDK_KEY_Return || kv == GDK_KEY_KP_Enter +#ifdef GDK_KEY_AudioRaiseVolume + || kv == GDK_KEY_AudioRaiseVolume +#endif +#ifdef GDK_KEY_AudioLowerVolume + || kv == GDK_KEY_AudioLowerVolume +#endif + ) { + on_shutter(app); + return TRUE; + } + if (kv == GDK_KEY_s || kv == GDK_KEY_S || kv == GDK_KEY_Tab) { + on_switch_clicked(NULL, app); + return TRUE; + } + if (kv == GDK_KEY_v || kv == GDK_KEY_V) { + set_mode_video(app, !app->mode_video); + return TRUE; + } + if (kv == GDK_KEY_g || kv == GDK_KEY_G) { + on_grid_clicked(NULL, app); + return TRUE; + } + if (kv == GDK_KEY_Escape) { + if (app->is_recording) { + on_shutter(app); + } else { + shutdown_app(app); + } + return TRUE; + } + return FALSE; +} + +static void shutdown_app(CameraApp *app) { + if (app->shutting_down) return; + app->shutting_down = TRUE; + + if (app->countdown_src > 0) { + g_source_remove(app->countdown_src); + app->countdown_src = 0; + } + if (app->to_worker) { + fprintf(app->to_worker, "quit\n"); + fflush(app->to_worker); + fclose(app->to_worker); + app->to_worker = NULL; + } + if (app->worker_pid > 0) { + int status = 0; + gboolean reaped = FALSE; + for (int i = 0; i < 40; i++) { + pid_t r = waitpid(app->worker_pid, &status, WNOHANG); + if (r == app->worker_pid) { + reaped = TRUE; + break; + } + usleep(50000); + } + if (!reaped) { + kill(app->worker_pid, SIGTERM); + waitpid(app->worker_pid, &status, 0); + } + app->worker_pid = -1; + } + if (app->reader_thread) { + g_thread_join(app->reader_thread); + app->reader_thread = NULL; + } + if (app->from_worker) { + fclose(app->from_worker); + app->from_worker = NULL; + } + gtk_main_quit(); +} + +static gboolean on_delete_event(GtkWidget *w, GdkEvent *ev, gpointer data) { + (void)w; + (void)ev; + shutdown_app((CameraApp *)data); + return FALSE; +} + +static gboolean on_unix_sig(gpointer data) { + shutdown_app((CameraApp *)data); + return G_SOURCE_REMOVE; +} + +static gboolean start_worker_process(CameraApp *app) { + int in_pipe[2] = {-1, -1}; + int out_pipe[2] = {-1, -1}; + if (pipe(in_pipe) != 0 || pipe(out_pipe) != 0) { + return FALSE; + } + + pid_t pid = fork(); + if (pid < 0) { + close(in_pipe[0]); + close(in_pipe[1]); + close(out_pipe[0]); + close(out_pipe[1]); + return FALSE; + } + if (pid == 0) { + dup2(in_pipe[0], STDIN_FILENO); + dup2(out_pipe[1], STDOUT_FILENO); + close(in_pipe[0]); + close(in_pipe[1]); + close(out_pipe[0]); + close(out_pipe[1]); + + if (app->initial_camera && app->initial_camera[0]) { + char *argv[] = {app->worker_exe, "--worker", "--camera", app->initial_camera, NULL}; + execvp(app->worker_exe, argv); + } else { + char *argv[] = {app->worker_exe, "--worker", NULL}; + execvp(app->worker_exe, argv); + } + _exit(127); + } + + close(in_pipe[0]); + close(out_pipe[1]); + app->worker_pid = pid; + app->to_worker = fdopen(in_pipe[1], "w"); + app->from_worker = fdopen(out_pipe[0], "r"); + if (!app->to_worker || !app->from_worker) { + return FALSE; + } + app->reader_thread = g_thread_new("cam-reader", worker_reader_func, app); + return TRUE; +} + +static void build_ui(CameraApp *app) { + const char *css = + "window, .cam-root { background-color: #0b0d14; color: #f4f6fc; }\n" + ".cam-pill { background-color: rgba(14, 18, 30, 0.74); color: #f4f6fc;\n" + " border: 1px solid rgba(255, 255, 255, 0.16); border-radius: 18px;\n" + " padding: 5px 12px; font-size: 13px; font-weight: 600; min-height: 24px; }\n" + ".cam-pill:hover { background-color: rgba(30, 38, 60, 0.88); }\n" + ".cam-pill-active { background-color: rgba(110, 140, 255, 0.88);\n" + " color: #090d16; border-color: rgba(180, 200, 255, 0.90); }\n" + ".cam-pill-danger { background-color: rgba(239, 68, 68, 0.88);\n" + " color: #ffffff; border-color: rgba(255, 180, 180, 0.80); }\n" + ".cam-dock { background-color: rgba(10, 12, 20, 0.86);\n" + " border-top: 1px solid rgba(255, 255, 255, 0.10); padding: 10px 16px 14px 16px; }\n" + ".cam-mode-bar { background-color: rgba(255, 255, 255, 0.08);\n" + " border-radius: 18px; padding: 3px; }\n" + ".cam-mode-btn { background-color: transparent; color: #c2cadc; border: none;\n" + " border-radius: 15px; padding: 4px 18px; font-size: 13px; font-weight: 600; min-height: 22px; }\n" + ".cam-mode-selected { background-color: #6e8cff; color: #0b0d14; }\n" + ".cam-mode-selected-video { background-color: #ef4444; color: #ffffff; }\n" + ".cam-rec-badge { background-color: rgba(239, 68, 68, 0.90); color: #ffffff;\n" + " border-radius: 12px; padding: 2px 10px; font-size: 12px; font-weight: 700; }\n" + ".cam-icon-btn { background-color: transparent; border: none; padding: 0; box-shadow: none; }\n" + ".cam-gallery-bar { background-color: #111523;\n" + " border-bottom: 1px solid rgba(255, 255, 255, 0.10); padding: 8px 12px; }\n" + ".cam-gallery-foot { background-color: #111523;\n" + " border-top: 1px solid rgba(255, 255, 255, 0.10); padding: 8px 14px; }\n" + ".cam-title { font-size: 14px; font-weight: 700; color: #f4f6fc; }\n" + ".cam-sub { font-size: 12px; color: #9ba6c2; }\n"; + + GtkCssProvider *prov = gtk_css_provider_new(); + gtk_css_provider_load_from_data(prov, css, -1, NULL); + gtk_style_context_add_provider_for_screen( + gdk_screen_get_default(), GTK_STYLE_PROVIDER(prov), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); + g_object_unref(prov); + + app->window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW(app->window), "Camera"); + gtk_window_set_default_size(GTK_WINDOW(app->window), 520, 960); + gtk_widget_set_size_request(app->window, 340, 480); + gtk_style_context_add_class(gtk_widget_get_style_context(app->window), "cam-root"); + + app->stack = gtk_stack_new(); + gtk_stack_set_transition_type(GTK_STACK(app->stack), GTK_STACK_TRANSITION_TYPE_SLIDE_LEFT_RIGHT); + gtk_stack_set_transition_duration(GTK_STACK(app->stack), 180); + gtk_container_add(GTK_CONTAINER(app->window), app->stack); + + /* Viewfinder page */ + GtkWidget *overlay = gtk_overlay_new(); + app->view_area = gtk_drawing_area_new(); + gtk_widget_set_hexpand(app->view_area, TRUE); + gtk_widget_set_vexpand(app->view_area, TRUE); + g_signal_connect(app->view_area, "draw", G_CALLBACK(draw_viewfinder), app); + gtk_container_add(GTK_CONTAINER(overlay), app->view_area); + + GtkWidget *top_bar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8); + gtk_widget_set_halign(top_bar, GTK_ALIGN_FILL); + gtk_widget_set_valign(top_bar, GTK_ALIGN_START); + gtk_widget_set_margin_top(top_bar, 12); + gtk_widget_set_margin_start(top_bar, 12); + gtk_widget_set_margin_end(top_bar, 12); + + app->cam_badge_btn = gtk_button_new_with_label("Camera"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->cam_badge_btn), "cam-pill"); + gtk_widget_set_can_focus(app->cam_badge_btn, FALSE); + g_signal_connect(app->cam_badge_btn, "clicked", G_CALLBACK(on_switch_clicked), app); + gtk_box_pack_start(GTK_BOX(top_bar), app->cam_badge_btn, FALSE, FALSE, 0); + + gtk_box_pack_start(GTK_BOX(top_bar), gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0), TRUE, TRUE, 0); + + app->flash_btn = gtk_button_new_with_label("Flash"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->flash_btn), "cam-pill"); + gtk_widget_set_can_focus(app->flash_btn, FALSE); + g_signal_connect(app->flash_btn, "clicked", G_CALLBACK(on_flash_clicked), app); + gtk_box_pack_start(GTK_BOX(top_bar), app->flash_btn, FALSE, FALSE, 0); + + app->grid_btn = gtk_button_new_with_label("Grid"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->grid_btn), "cam-pill"); + gtk_widget_set_can_focus(app->grid_btn, FALSE); + g_signal_connect(app->grid_btn, "clicked", G_CALLBACK(on_grid_clicked), app); + gtk_box_pack_start(GTK_BOX(top_bar), app->grid_btn, FALSE, FALSE, 0); + + app->timer_btn = gtk_button_new_with_label("Timer"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->timer_btn), "cam-pill"); + gtk_widget_set_can_focus(app->timer_btn, FALSE); + g_signal_connect(app->timer_btn, "clicked", G_CALLBACK(on_timer_clicked), app); + gtk_box_pack_start(GTK_BOX(top_bar), app->timer_btn, FALSE, FALSE, 0); + + app->res_btn = gtk_button_new_with_label("HD"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->res_btn), "cam-pill"); + gtk_widget_set_can_focus(app->res_btn, FALSE); + g_signal_connect(app->res_btn, "clicked", G_CALLBACK(on_res_clicked), app); + gtk_box_pack_start(GTK_BOX(top_bar), app->res_btn, FALSE, FALSE, 0); + + gtk_overlay_add_overlay(GTK_OVERLAY(overlay), top_bar); + + GtkWidget *dock = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); + gtk_style_context_add_class(gtk_widget_get_style_context(dock), "cam-dock"); + gtk_widget_set_halign(dock, GTK_ALIGN_FILL); + gtk_widget_set_valign(dock, GTK_ALIGN_END); + + GtkWidget *mode_row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8); + gtk_widget_set_halign(mode_row, GTK_ALIGN_CENTER); + + GtkWidget *mode_pill = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2); + gtk_style_context_add_class(gtk_widget_get_style_context(mode_pill), "cam-mode-bar"); + app->photo_mode_btn = gtk_button_new_with_label("Photo"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->photo_mode_btn), "cam-mode-btn"); + gtk_widget_set_can_focus(app->photo_mode_btn, FALSE); + g_signal_connect(app->photo_mode_btn, "clicked", G_CALLBACK(on_photo_mode_clicked), app); + + app->video_mode_btn = gtk_button_new_with_label("Video"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->video_mode_btn), "cam-mode-btn"); + gtk_widget_set_can_focus(app->video_mode_btn, FALSE); + g_signal_connect(app->video_mode_btn, "clicked", G_CALLBACK(on_video_mode_clicked), app); + + gtk_box_pack_start(GTK_BOX(mode_pill), app->photo_mode_btn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(mode_pill), app->video_mode_btn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(mode_row), mode_pill, FALSE, FALSE, 0); + + app->rec_label = gtk_label_new("● 00:00"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->rec_label), "cam-rec-badge"); + gtk_widget_set_no_show_all(app->rec_label, TRUE); + gtk_box_pack_start(GTK_BOX(mode_row), app->rec_label, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(dock), mode_row, FALSE, FALSE, 0); + + GtkWidget *action_row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + gtk_box_set_homogeneous(GTK_BOX(action_row), TRUE); + + GtkWidget *gallery_btn = gtk_button_new(); + gtk_style_context_add_class(gtk_widget_get_style_context(gallery_btn), "cam-icon-btn"); + gtk_widget_set_halign(gallery_btn, GTK_ALIGN_CENTER); + gtk_widget_set_valign(gallery_btn, GTK_ALIGN_CENTER); + gtk_widget_set_size_request(gallery_btn, 56, 56); + gtk_widget_set_can_focus(gallery_btn, FALSE); + gtk_widget_set_tooltip_text(gallery_btn, "Open Camera Gallery"); + app->thumb_area = gtk_drawing_area_new(); + gtk_widget_set_size_request(app->thumb_area, 52, 52); + g_signal_connect(app->thumb_area, "draw", G_CALLBACK(draw_thumb_button), app); + gtk_container_add(GTK_CONTAINER(gallery_btn), app->thumb_area); + g_signal_connect(gallery_btn, "clicked", G_CALLBACK(on_gallery_btn_clicked), app); + gtk_box_pack_start(GTK_BOX(action_row), gallery_btn, TRUE, TRUE, 0); + + GtkWidget *shutter_btn = gtk_button_new(); + gtk_style_context_add_class(gtk_widget_get_style_context(shutter_btn), "cam-icon-btn"); + gtk_widget_set_halign(shutter_btn, GTK_ALIGN_CENTER); + gtk_widget_set_valign(shutter_btn, GTK_ALIGN_CENTER); + gtk_widget_set_size_request(shutter_btn, 76, 76); + gtk_widget_set_can_focus(shutter_btn, FALSE); + gtk_widget_set_tooltip_text(shutter_btn, "Take Photo / Record Video (Space)"); + app->shutter_area = gtk_drawing_area_new(); + gtk_widget_set_size_request(app->shutter_area, 76, 76); + g_signal_connect(app->shutter_area, "draw", G_CALLBACK(draw_shutter_button), app); + gtk_container_add(GTK_CONTAINER(shutter_btn), app->shutter_area); + g_signal_connect(shutter_btn, "clicked", G_CALLBACK(on_shutter_btn_clicked), app); + gtk_box_pack_start(GTK_BOX(action_row), shutter_btn, TRUE, TRUE, 0); + + app->switch_btn = gtk_button_new(); + gtk_style_context_add_class(gtk_widget_get_style_context(app->switch_btn), "cam-icon-btn"); + gtk_widget_set_halign(app->switch_btn, GTK_ALIGN_CENTER); + gtk_widget_set_valign(app->switch_btn, GTK_ALIGN_CENTER); + gtk_widget_set_size_request(app->switch_btn, 56, 56); + gtk_widget_set_can_focus(app->switch_btn, FALSE); + gtk_widget_set_tooltip_text(app->switch_btn, "Switch Camera (S)"); + app->switch_area = gtk_drawing_area_new(); + gtk_widget_set_size_request(app->switch_area, 52, 52); + g_signal_connect(app->switch_area, "draw", G_CALLBACK(draw_switch_button), app); + gtk_container_add(GTK_CONTAINER(app->switch_btn), app->switch_area); + g_signal_connect(app->switch_btn, "clicked", G_CALLBACK(on_switch_clicked), app); + gtk_box_pack_start(GTK_BOX(action_row), app->switch_btn, TRUE, TRUE, 0); + + gtk_box_pack_start(GTK_BOX(dock), action_row, FALSE, FALSE, 0); + gtk_overlay_add_overlay(GTK_OVERLAY(overlay), dock); + gtk_stack_add_named(GTK_STACK(app->stack), overlay, "viewfinder"); + + /* Gallery page */ + GtkWidget *gbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + GtkWidget *gbar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8); + gtk_style_context_add_class(gtk_widget_get_style_context(gbar), "cam-gallery-bar"); + + GtkWidget *back_btn = gtk_button_new_with_label("← Camera"); + gtk_style_context_add_class(gtk_widget_get_style_context(back_btn), "cam-pill"); + gtk_widget_set_can_focus(back_btn, FALSE); + g_signal_connect(back_btn, "clicked", G_CALLBACK(on_gallery_back_clicked), app); + gtk_box_pack_start(GTK_BOX(gbar), back_btn, FALSE, FALSE, 0); + + app->gallery_title = gtk_label_new("Gallery"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->gallery_title), "cam-title"); + gtk_label_set_ellipsize(GTK_LABEL(app->gallery_title), PANGO_ELLIPSIZE_END); + gtk_box_pack_start(GTK_BOX(gbar), app->gallery_title, TRUE, TRUE, 4); + + GtkWidget *folder_btn = gtk_button_new_with_label("Folder"); + gtk_style_context_add_class(gtk_widget_get_style_context(folder_btn), "cam-pill"); + gtk_widget_set_can_focus(folder_btn, FALSE); + g_signal_connect(folder_btn, "clicked", G_CALLBACK(on_gallery_folder_clicked), app); + gtk_box_pack_start(GTK_BOX(gbar), folder_btn, FALSE, FALSE, 0); + + app->delete_btn = gtk_button_new_with_label("Delete"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->delete_btn), "cam-pill"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->delete_btn), "cam-pill-danger"); + gtk_widget_set_can_focus(app->delete_btn, FALSE); + g_signal_connect(app->delete_btn, "clicked", G_CALLBACK(on_gallery_delete_clicked), app); + gtk_box_pack_start(GTK_BOX(gbar), app->delete_btn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(gbox), gbar, FALSE, FALSE, 0); + + app->gallery_area = gtk_drawing_area_new(); + gtk_widget_set_hexpand(app->gallery_area, TRUE); + gtk_widget_set_vexpand(app->gallery_area, TRUE); + g_signal_connect(app->gallery_area, "draw", G_CALLBACK(draw_gallery), app); + gtk_box_pack_start(GTK_BOX(gbox), app->gallery_area, TRUE, TRUE, 0); + + GtkWidget *gfoot = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10); + gtk_style_context_add_class(gtk_widget_get_style_context(gfoot), "cam-gallery-foot"); + + app->prev_btn = gtk_button_new_with_label("‹ Prev"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->prev_btn), "cam-pill"); + gtk_widget_set_can_focus(app->prev_btn, FALSE); + g_signal_connect(app->prev_btn, "clicked", G_CALLBACK(on_gallery_prev_clicked), app); + gtk_box_pack_start(GTK_BOX(gfoot), app->prev_btn, FALSE, FALSE, 0); + + app->gallery_meta = gtk_label_new(""); + gtk_style_context_add_class(gtk_widget_get_style_context(app->gallery_meta), "cam-sub"); + gtk_box_pack_start(GTK_BOX(gfoot), app->gallery_meta, TRUE, TRUE, 4); + + app->next_btn = gtk_button_new_with_label("Next ›"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->next_btn), "cam-pill"); + gtk_widget_set_can_focus(app->next_btn, FALSE); + g_signal_connect(app->next_btn, "clicked", G_CALLBACK(on_gallery_next_clicked), app); + gtk_box_pack_start(GTK_BOX(gfoot), app->next_btn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(gbox), gfoot, FALSE, FALSE, 0); + + gtk_stack_add_named(GTK_STACK(app->stack), gbox, "gallery"); + + g_signal_connect(app->window, "delete-event", G_CALLBACK(on_delete_event), app); + g_signal_connect(app->window, "key-press-event", G_CALLBACK(on_key_press), app); +} + +int main(int argc, char **argv) { + signal(SIGPIPE, SIG_IGN); + setenv("GDK_BACKEND", "wayland", 0); + + CameraApp app; + memset(&app, 0, sizeof(app)); + app.worker_pid = -1; + app.active_label = g_strdup("Camera"); + g_mutex_init(&app.frame_mutex); + + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "--worker-exe") == 0 && i + 1 < argc) { + app.worker_exe = g_strdup(argv[++i]); + } else if (strcmp(argv[i], "--camera") == 0 && i + 1 < argc) { + app.initial_camera = g_strdup(argv[++i]); + } else if (strcmp(argv[i], "--open-gallery") == 0) { + app.open_gallery_start = TRUE; + } + } + if (!app.worker_exe) { + app.worker_exe = g_strdup("/usr/local/bin/chandra-camera"); + } + + g_set_prgname("chandra-camera"); + g_set_application_name("Camera"); + gtk_init(&argc, &argv); + + build_ui(&app); + refresh_thumbnail(&app); + sync_ui_labels(&app); + + gtk_widget_show_all(app.window); + if (app.open_gallery_start) { + open_gallery_view(&app); + } else { + gtk_stack_set_visible_child_name(GTK_STACK(app.stack), "viewfinder"); + } + + if (!start_worker_process(&app)) { + show_toast(&app, "Failed to start camera worker", 5.0); + } + + g_timeout_add(120, tick_ui, &app); + g_unix_signal_add(SIGINT, on_unix_sig, &app); + g_unix_signal_add(SIGTERM, on_unix_sig, &app); + + gtk_main(); + + free(app.frame_buf); + free(app.paint_buf); + g_free(app.worker_exe); + g_free(app.initial_camera); + g_free(app.active_label); + g_free(app.toast_text); + free_gallery_files(&app); + if (app.thumb_pb) g_object_unref(app.thumb_pb); + if (app.gallery_pb) g_object_unref(app.gallery_pb); + g_mutex_clear(&app.frame_mutex); + return 0; +} diff --git a/camera/chandra-camera.desktop b/camera/chandra-camera.desktop new file mode 100644 index 0000000..8418524 --- /dev/null +++ b/camera/chandra-camera.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Type=Application +Name=Camera +GenericName=Camera +Comment=Take photos and record videos +Exec=/usr/local/bin/chandra-camera +Icon=chandra-camera +Terminal=false +Categories=AudioVideo;Video;Photography;Utility; +StartupNotify=true +StartupWMClass=chandra-camera diff --git a/camera/chandra-camera.svg b/camera/chandra-camera.svg new file mode 100644 index 0000000..757ba69 --- /dev/null +++ b/camera/chandra-camera.svg @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/camera/test_camera.py b/camera/test_camera.py new file mode 100644 index 0000000..6a24dc5 --- /dev/null +++ b/camera/test_camera.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""Host-side unit tests for chandra-camera frame/camera helpers (no hardware required).""" + +import importlib.machinery +import importlib.util +import os +import sys +import unittest + +try: + import cv2 + import numpy as np + HAS_CV2_NUMPY = True +except ImportError: + cv2 = None + np = None + HAS_CV2_NUMPY = False + +CAM_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "chandra-camera") +_loader = importlib.machinery.SourceFileLoader("chandra_camera_mod", CAM_PATH) +_spec = importlib.util.spec_from_loader("chandra_camera_mod", _loader) +cam_mod = importlib.util.module_from_spec(_spec) +sys.modules["chandra_camera_mod"] = cam_mod +_loader.exec_module(cam_mod) + + +class TestCameraHelpers(unittest.TestCase): + def test_sort_and_label_cameras(self): + raw = [ + ("/base/front", "libcamera", "imx371", 0, 90, 4656 * 3496), + ("/base/back2", "libcamera", "imx376", 1, 270, 2592 * 1944), + ("/base/back1", "libcamera", "imx519", 1, 270, 4656 * 3496), + ] + cams = cam_mod.sort_and_label_cameras(raw) + self.assertEqual([c.model for c in cams], ["imx519", "imx371", "imx376"]) + self.assertEqual([c.label for c in cams], ["Back · imx519", "Front · imx371", "Back 2 · imx376"]) + self.assertEqual(cam_mod.select_initial_camera(cams, ""), 0) + self.assertEqual(cam_mod.select_initial_camera(cams, "front"), 1) + self.assertEqual(cam_mod.select_initial_camera(cams, "back"), 0) + self.assertEqual(cam_mod.select_initial_camera(cams, "imx376"), 2) + + @unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy") + def test_convert_abgr8888_with_stride_and_rotations(self): + # 2x3 image with stride padding (row = 2*4 + 4 padding bytes = 12) + h, w, stride = 3, 2, 12 + buf = bytearray(h * stride) + # Pixel (x=0, y=0): ABGR8888 in LE memory is [R, G, B, A] = [10, 20, 200, 255] -> BGR [200, 20, 10] + buf[0:4] = bytes([10, 20, 200, 255]) + # Pixel (x=1, y=0): R=40, G=50, B=60 -> BGR [60, 50, 40] + buf[4:8] = bytes([40, 50, 60, 255]) + + bgr0 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=0, cv2_mod=cv2, np_mod=np) + self.assertEqual(bgr0.shape, (3, 2, 3)) + self.assertEqual(tuple(bgr0[0, 0]), (200, 20, 10)) + self.assertEqual(tuple(bgr0[0, 1]), (60, 50, 40)) + + bgr90 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=90, cv2_mod=cv2, np_mod=np) + self.assertEqual(bgr90.shape, (2, 3, 3)) + # Clockwise 90 deg puts original (row=0, col=0) at (row=0, col=h-1=2) + self.assertEqual(tuple(bgr90[0, 2]), (200, 20, 10)) + + bgr270 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=270, cv2_mod=cv2, np_mod=np) + self.assertEqual(bgr270.shape, (2, 3, 3)) + # Counter-clockwise 90 deg puts original (row=0, col=0) at (row=w-1=1, col=0) + self.assertEqual(tuple(bgr270[1, 0]), (200, 20, 10)) + + @unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy") + def test_convert_argb_rgb_and_cairo_bgra(self): + # ARGB8888 in LE memory is [B, G, R, A] + buf = bytes([210, 110, 30, 255, 10, 20, 30, 255]) + bgr = cam_mod.convert_frame(buf, 2, 1, 8, "ARGB8888", rot=0, cv2_mod=cv2, np_mod=np) + self.assertEqual(tuple(bgr[0, 0]), (210, 110, 30)) + + rgb_buf = bytes([11, 22, 33, 44, 55, 66]) + bgr2 = cam_mod.convert_frame(rgb_buf, 2, 1, 6, "RGB888", rot=180, cv2_mod=cv2, np_mod=np) + # Inverted horizontally+vertically and channel-flipped -> [66, 55, 44] then [33, 22, 11] + self.assertEqual(tuple(bgr2[0, 0]), (66, 55, 44)) + self.assertEqual(tuple(bgr2[0, 1]), (33, 22, 11)) + + argb32 = cam_mod.bgr_to_cairo_argb32(bgr, np_mod=np) + self.assertEqual(argb32.shape, (1, 2, 4)) + self.assertEqual(tuple(argb32[0, 0]), (210, 110, 30, 255)) + + @unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy") + def test_ensure_even_frame(self): + odd = np.zeros((101, 203, 3), dtype=np.uint8) + even = cam_mod.ensure_even_frame(odd) + self.assertEqual(even.shape, (100, 202, 3)) + + +if __name__ == "__main__": + unittest.main() diff --git a/compositor/host/control.mbt b/compositor/host/control.mbt index d982890..9254e01 100644 --- a/compositor/host/control.mbt +++ b/compositor/host/control.mbt @@ -216,6 +216,7 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin "rotate [cw|ccw|flip|0|90|180|270|status] rotate or flip the display", "screen [on|off|toggle|status] blank or wake the display", "brightness [PCT|status] read or set display backlight percent (5..100)", + "settings [TAB] open Settings popup (session, desktop, panel, power, shortcuts, apps)", "auth-demo [MODE] show the password dialog with a pretend check (password \"demo\"); MODE: " + @polkit.demo_modes.join(", "), "auth-status the password dialog's agent: running, registered, or why not", @@ -458,6 +459,32 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin } } } + "settings" => { + let arg = if words.length() >= 2 { words[1] } else { "session" } + if words.length() > 2 { + return (["error usage: settings [session|desktop|panel|power|shortcuts|apps]"], false) + } + let tab : @shell.SettingsTab? = match arg { + "session" => Some(Session) + "desktop" => Some(Desktop) + "panel" => Some(Panel) + "power" => Some(Power) + "shortcuts" => Some(Shortcuts) + "apps" => Some(Apps) + _ => None + } + match tab { + None => (["error usage: settings [session|desktop|panel|power|shortcuts|apps]"], false) + Some(t) => + if self.shell.open_settings(t) { + self.frame_changed = true + self.damage.mark_full() + (["ok " + arg], true) + } else { + (["error settings module not loaded"], false) + } + } + } other => (["error unknown command '" + other + "' (try: help)"], false) } } diff --git a/docs/handset.md b/docs/handset.md index b3d649d..a3c8d0b 100644 --- a/docs/handset.md +++ b/docs/handset.md @@ -45,3 +45,8 @@ Chandra includes KMS/libinput/compositor adaptations tailored for mainline Linux ## Face Unlock (`libcamera`) - On phones whose MIPI sensors (`imx371`, `imx519`, `imx376`) require `libcamera` SoftISP rather than raw V4L2 nodes, [`face/chandra-face`](../face/chandra-face) supports `libcamera:` entries via `python-libcamera` and applies `libcamera.properties.Rotation`. [`face/install.py`](../face/install.py) supports `--system-python` to run with system `python-opencv` + `python-numpy` on `aarch64`, and [`face/polkit-agent-helper.conf`](../face/polkit-agent-helper.conf) grants `char-video4linux`, `char-media`, and `char-dma_heap` access to polkit's helper sandbox. + +## Camera App (`chandra-camera`) + +- [`camera/chandra-camera`](../camera/chandra-camera) provides a native GTK3/Cairo Wayland camera app installed via [`session/install.py`](../session/install.py) with its desktop launcher and icon (`Camera`). +- Supports multi-sensor `libcamera` discovery and live switching (`Back · imx519`, `Front · imx371`, `Back 2 · imx376` on OnePlus 6T, with automatic V4L2 fallback on desktops), sensor orientation transform + front-camera mirror preview, Photo mode (`HD` instant / `Full` high-resolution `StillCapture`, `0`/`3s`/`10s` self-timer, 3×3 rule-of-thirds grid) saving JPEGs to `~/Pictures/Camera`, Video mode recording H.264 MP4s via `ffmpeg` to `~/Videos/Camera`, an in-app photo gallery viewer, rear flash/torch LED control (`/sys/class/leds/white:flash`) through `org.freedesktop.login1.Session.SetBrightness`, and hardware volume-button or `Space`/`Return` shutter control. diff --git a/face/chandra-face b/face/chandra-face index bbaecf3..2443edd 100755 --- a/face/chandra-face +++ b/face/chandra-face @@ -439,10 +439,16 @@ def query_camera(path): os.close(fd) +def _import_libcamera(): + os.environ.setdefault("LIBCAMERA_LOG_LEVELS", "*:ERROR") + import libcamera + return libcamera + + def list_libcameras(): """[(libcamera:id, label, '')] for cameras exposed through libcamera.""" try: - import libcamera + libcamera = _import_libcamera() except ImportError: return [] out = [] @@ -484,7 +490,7 @@ def camera_problem(device): if device.startswith("libcamera:"): cid = device[len("libcamera:"):] try: - import libcamera + libcamera = _import_libcamera() except ImportError: return "python-libcamera is not installed (cannot open %s)" % device cm = libcamera.CameraManager.singleton() @@ -511,11 +517,13 @@ class LibcameraCamera: if problem: raise Fail(problem, 2) import cv2 - import libcamera import mmap import numpy as np + libcamera = _import_libcamera() self.cv2, self.libcamera, self.mmap, self.np = cv2, libcamera, mmap, np + reuse_enum = getattr(libcamera.Request, "Reuse", None) or getattr(libcamera.Request, "ReuseFlag", None) + self._reuse_arg = getattr(reuse_enum, "ReuseBuffers", None) if reuse_enum is not None else None cid = device[len("libcamera:"):] self.cm = libcamera.CameraManager.singleton() self.cam = self.cm.get(cid) @@ -573,6 +581,17 @@ class LibcameraCamera: return self.cv2.rotate(bgr, self.cv2.ROTATE_90_COUNTERCLOCKWISE) return bgr + def _requeue(self, req): + if self._reuse_arg is not None: + try: + req.reuse(self._reuse_arg) + except TypeError: + self._reuse_arg = None + req.reuse() + else: + req.reuse() + self.cam.queue_request(req) + def read(self): timeout = 3.0 if self._first else 1.5 self._first = False @@ -581,16 +600,14 @@ class LibcameraCamera: 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) + self._requeue(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) + self._requeue(req) if frame is not None: return frame time.sleep(0.01) diff --git a/session/chandra-ctl b/session/chandra-ctl index 8adeb26..bee1315 100755 --- a/session/chandra-ctl +++ b/session/chandra-ctl @@ -13,6 +13,7 @@ chandra-ctl rotate [ARG] rotate/flip display (cw, ccw, flip, 0, 90, 180, 270, status) chandra-ctl screen [ARG] turn display off/on (on, off, toggle, status) chandra-ctl brightness [ARG] get/set backlight brightness percent (5..100, status) + chandra-ctl settings [TAB] open Settings popup tab (session, desktop, panel, power, shortcuts, apps) chandra-ctl auth-demo [MODE] show the password dialog with a pretend check (password "demo"); MODE: password, face, face-ok, die, slow, users (docs/auth-dialog.md) chandra-ctl auth-status the password dialog's agent: registered with polkit, or why not @@ -28,7 +29,7 @@ import os import socket import sys -USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | launch ID | windows | screenshot [PATH] | rotate [ARG] | screen [ARG] | brightness [ARG] | auth-demo [MODE] | auth-status | help}" +USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | launch ID | windows | screenshot [PATH] | rotate [ARG] | screen [ARG] | brightness [ARG] | settings [TAB] | auth-demo [MODE] | auth-status | help}" def runtime_dir(): diff --git a/session/install.py b/session/install.py index 1880fd1..6bd3fce 100755 --- a/session/install.py +++ b/session/install.py @@ -31,6 +31,9 @@ Installs: /usr/local/bin/chandra-auto-rotate DRM session accelerometer watcher (iio-sensor-proxy) /usr/local/bin/chandra-kde-colors Dark mode for KDE/Qt apps: copies a color scheme into kdeglobals (docs/dark-mode.md) + /usr/local/bin/chandra-camera Wayland Camera app (libcamera / V4L2) + /usr/share/applications/chandra-camera.desktop Camera app desktop entry + /usr/share/icons/hicolor/scalable/apps/chandra-camera.svg Camera app icon /usr/local/share/color-schemes/Chandra{Dark,Light}.colors KDE color schemes, used when Breeze's aren't installed /usr/local/share/chandra/{config,wit,assets}/ files the compositor reads at runtime @@ -67,6 +70,9 @@ targets = [ "/usr/local/bin/chandra-ctl", "/usr/local/bin/chandra-auto-rotate", "/usr/local/bin/chandra-kde-colors", + "/usr/local/bin/chandra-camera", + "/usr/share/applications/chandra-camera.desktop", + "/usr/share/icons/hicolor/scalable/apps/chandra-camera.svg", "/usr/local/share/color-schemes/ChandraDark.colors", "/usr/local/share/color-schemes/ChandraLight.colors", "/usr/share/wayland-sessions/chandra.desktop", @@ -177,6 +183,11 @@ else: install(os.path.join(root, "session/chandra-ctl"), "/usr/local/bin/chandra-ctl") install(os.path.join(root, "session/chandra-auto-rotate"), "/usr/local/bin/chandra-auto-rotate") install(os.path.join(root, "session/chandra-kde-colors"), "/usr/local/bin/chandra-kde-colors") +install(os.path.join(root, "camera/chandra-camera"), "/usr/local/bin/chandra-camera") +put(os.path.join(root, "camera/chandra-camera.desktop"), "/usr/share/applications/chandra-camera.desktop", 0o644) +put(os.path.join(root, "camera/chandra-camera.svg"), "/usr/share/icons/hicolor/scalable/apps/chandra-camera.svg", 0o644) +if shutil.which("gtk-update-icon-cache"): + subprocess.run(["gtk-update-icon-cache", "-q", "-f", "/usr/share/icons/hicolor"], check=False) for f in ("ChandraDark.colors", "ChandraLight.colors"): put(os.path.join(root, "session/color-schemes", f), "/usr/local/share/color-schemes/" + f, 0o644) # The display-manager entry stays a real file: some managers don't follow symlinks there.