diff --git a/camera/chandra-camera b/camera/chandra-camera index 4604868..b654ea8 100755 --- a/camera/chandra-camera +++ b/camera/chandra-camera @@ -866,914 +866,183 @@ def list_gallery_photos(): 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 +def run_worker(cameras, initial_index): + """Stream Cairo BGRA viewfinder frames to stdout and handle UI commands on stdin.""" 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) + write_lock = threading.Lock() + has_flash = 1 if os.path.exists(FLASH_LED_PATH) else 0 + stop_flag = threading.Event() + last_sent = [0.0] - 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 + def emit(line): + data = (line + "\n").encode("utf-8", "replace") + with write_lock: + try: + sys.stdout.buffer.write(data) + sys.stdout.buffer.flush() + except (BrokenPipeError, OSError): + stop_flag.set() + + def emit_active(info, idx): + if info is None: + emit("active -1 0 0 No camera") + else: + emit("active %d %d %d %s" % ( + idx, + 1 if info.is_front else 0, + 1 if info.is_back else 0, + info.label, + )) + + engine_holder = [None] + + def on_frame(): + if stop_flag.is_set(): + return + now = time.monotonic() + if now - last_sent[0] < 0.045: + return + eng = engine_holder[0] + if eng is None: + return + frame, _ = eng.latest_frame() + if frame is None: + return + last_sent[0] = now + h, w = frame.shape[:2] + max_dim = max(w, h) + if max_dim > 640: + scale = 640.0 / float(max_dim) + pw = max(2, int(round(w * scale))) + ph = max(2, int(round(h * scale))) + preview = cv2.resize(frame, (pw, ph), interpolation=cv2.INTER_AREA) + else: + pw, ph = w, h + preview = frame + raw = bgr_to_cairo_argb32(preview, np_mod=eng.np).tobytes() + hdr = ("frame %d %d %d\n" % (pw, ph, len(raw))).encode("ascii") + with write_lock: + try: + sys.stdout.buffer.write(hdr) + sys.stdout.buffer.write(raw) + sys.stdout.buffer.flush() + except (BrokenPipeError, OSError): + stop_flag.set() + + def on_camera_changed(): + eng = engine_holder[0] + if eng is not None: + emit_active(eng.active_camera, eng.active_index) + emit("flash 0") + + engine = CameraEngine( + cameras, + initial_index=initial_index, + on_frame=on_frame, + on_error=lambda msg: emit("toast " + str(msg).replace("\n", " ")), + on_camera_changed=on_camera_changed, ) - - 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: + engine_holder[0] = engine + + def _sig_stop(*_): + stop_flag.set() + + signal.signal(signal.SIGINT, _sig_stop) + signal.signal(signal.SIGTERM, _sig_stop) + + emit("info %d %d" % (len(cameras), has_flash)) + emit_active(engine.active_camera, engine.active_index) + if cameras: + engine.start() + else: + emit("toast No camera connected") + + try: + while not stop_flag.is_set(): + line = sys.stdin.readline() + if not line: + break + cmd = line.strip() + if not cmd: + continue + if cmd == "quit": + break + if cmd == "switch": + set_flash_led(False) + engine.cycle_camera() + elif cmd in ("snap", "snap_full"): + high_res = cmd == "snap_full" + + def snap_job(hr=high_res): try: - self.engine.start_video() - self._sync_ui_labels() + p = engine.capture_photo(high_res=hr) + emit("saved_photo " + p) except Exception as exc: - self._show_toast(str(exc), 3.0) - return + emit("toast " + str(exc).replace("\n", " ")) - 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(): + threading.Thread(target=snap_job, daemon=True).start() + elif cmd == "rec_start": try: - path = self.engine.capture_photo(high_res=high_res) - GLib.idle_add(lambda: (self._after_photo_saved(path), False)[1]) + engine.start_video() + emit("rec_state 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() + emit("toast " + str(exc).replace("\n", " ")) + elif cmd == "rec_stop": + try: + p, frames = engine.stop_video() + emit("rec_state 0") + if p: + emit("saved_video %d %s" % (frames, p)) + except Exception as exc: + emit("rec_state 0") + emit("toast " + str(exc).replace("\n", " ")) + elif cmd.startswith("flash "): + want_on = cmd.split(None, 1)[1].strip() in ("1", "on", "true") + if want_on: + if set_flash_led(True): + emit("flash 1") + else: + emit("flash 0") + emit("toast Flash control unavailable") 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() + set_flash_led(False) + emit("flash 0") + finally: + engine.stop() + set_flash_led(False) return 0 +def launch_ui(args): + """Execute the native GTK3 + Cairo UI binary pointing back to this worker.""" + repo_ui = os.path.join( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "build", + "chandra-camera-ui", + ) + candidates = [ + os.environ.get("CHANDRA_CAMERA_UI", ""), + repo_ui, + "/usr/local/lib/chandra/chandra-camera-ui", + ] + ui_bin = next((p for p in candidates if p and os.access(p, os.X_OK)), "") + if not ui_bin: + print( + "chandra-camera: UI binary not found (checked CHANDRA_CAMERA_UI, %s, /usr/local/lib/chandra/chandra-camera-ui)" + % repo_ui, + file=sys.stderr, + ) + return 1 + + cmd = [ui_bin, "--worker-exe", os.path.abspath(__file__)] + if args.camera: + cmd += ["--camera", args.camera] + if args.open_gallery: + cmd.append("--open-gallery") + os.execv(ui_bin, cmd) + + def run_self_test(cameras): """Verify multi-camera discovery, switching, JPEG capture, MP4 recording, and clean release.""" if not cameras: @@ -1859,6 +1128,7 @@ 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("--worker", action="store_true", help="Run stdio frame/control worker for native UI") 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) @@ -1866,15 +1136,17 @@ def 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 args.list_cameras or args.self_test or args.worker: + 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_worker(cameras, initial_index=initial) + return launch_ui(args) if __name__ == "__main__": diff --git a/camera/chandra-camera-ui.c b/camera/chandra-camera-ui.c index e2852dd..8588cb3 100644 --- a/camera/chandra-camera-ui.c +++ b/camera/chandra-camera-ui.c @@ -254,6 +254,7 @@ static void load_gallery_image(CameraApp *app) { g_object_unref(raw); } struct stat st; + memset(&st, 0, sizeof(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) { @@ -423,7 +424,7 @@ static gboolean draw_viewfinder(GtkWidget *widget, cairo_t *cr, gpointer data) { 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_move_to(cr, (w - ext.width) / 2.0, h / 2.0 - 30.0); cairo_show_text(cr, msg); } @@ -1027,7 +1028,7 @@ static void shutdown_app(CameraApp *app) { reaped = TRUE; break; } - usleep(50000); + g_usleep(50000); } if (!reaped) { kill(app->worker_pid, SIGTERM); diff --git a/docs/handset.md b/docs/handset.md index a3c8d0b..91df1a7 100644 --- a/docs/handset.md +++ b/docs/handset.md @@ -48,5 +48,5 @@ Chandra includes KMS/libinput/compositor adaptations tailored for mainline Linux ## 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`). +- [`camera/chandra-camera`](../camera/chandra-camera) and [`camera/chandra-camera-ui.c`](../camera/chandra-camera-ui.c) provide a native GTK3/Cairo Wayland camera app (no extra Python GI packages required) 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/session/install.py b/session/install.py index 6bd3fce..3b14c65 100755 --- a/session/install.py +++ b/session/install.py @@ -32,6 +32,7 @@ Installs: /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/local/lib/chandra/chandra-camera-ui Native GTK3/Cairo Camera UI binary /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 @@ -71,6 +72,7 @@ targets = [ "/usr/local/bin/chandra-auto-rotate", "/usr/local/bin/chandra-kde-colors", "/usr/local/bin/chandra-camera", + "/usr/local/lib/chandra/chandra-camera-ui", "/usr/share/applications/chandra-camera.desktop", "/usr/share/icons/hicolor/scalable/apps/chandra-camera.svg", "/usr/local/share/color-schemes/ChandraDark.colors", @@ -184,6 +186,17 @@ 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") +cam_ui_src = os.path.join(root, "camera/chandra-camera-ui.c") +cam_ui_dst = "/usr/local/lib/chandra/chandra-camera-ui" +cc = shutil.which("cc") or shutil.which("gcc") +if not cc or not shutil.which("pkg-config"): + sys.exit("install.py: C compiler and pkg-config are needed to build chandra-camera-ui") +gtk_flags = subprocess.check_output(["pkg-config", "--cflags", "--libs", "gtk+-3.0"], text=True).split() +os.makedirs(os.path.dirname(cam_ui_dst), exist_ok=True) +subprocess.check_call([cc, "-O2", "-Wall", "-Wextra", "-o", cam_ui_dst + ".new", cam_ui_src] + gtk_flags + ["-lm"]) +os.chmod(cam_ui_dst + ".new", 0o755) +os.replace(cam_ui_dst + ".new", cam_ui_dst) +print("installed", cam_ui_dst) 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"):