#!/usr/bin/python3 """Lock the GNOME screen when its owner walks away, for howdy-settings. Runs in the user's session. The infrared camera stays off while the keyboard or mouse is in use. After some idle time it looks for the owner's face every few seconds at first and less often while the face stays (the camera light is wired to the camera, so every look shows it); when the face is gone twice in a row a notification warns, and the screen locks ten seconds later unless the owner comes back or moves the mouse. Someone else's face counts as nobody. Frames are never stored. """ import errno import fcntl import gettext import importlib.machinery import importlib.util import json import os import pathlib import pwd import struct ENROLL = "/usr/libexec/howdy-settings/enroll" DESKTOP_ID = "io.github.m_wilkowski.HowdySettings" # Looser than the unlock limit: looking aside scores about 3, other people over 6 PRESENT_SCORE = 4.5 MISSES_TO_WARN = 2 WARNING_SECONDS = 10 FRAMES = 8 # Seconds: first look after the last input, wait after the first sighting (doubles # with each one after it), after a miss, longest wait while the face is there PACE_AC = (20, 40, 5, 120) PACE_BATTERY = (30, 60, 5, 240) VIDIOC_G_CTRL = 0xC008561B V4L2_CID_PRIVACY = 0x009A0910 _ = gettext.translation("howdy-settings", fallback=True).gettext def pace(on_battery, power_saver): chosen = PACE_BATTERY if on_battery else PACE_AC return tuple(seconds * 2 for seconds in chosen) if power_saver else chosen class Tracker: """Turns each look at the camera into a decision.""" def __init__(self): self.misses = 0 self.seen = 0 self.warning = False def look(self, present): """present is True, False, or None when the camera could not tell (busy, covered). Returns "warn", "cancel" or None.""" if present is False: self.misses += 1 self.seen = 0 if self.misses >= MISSES_TO_WARN and not self.warning: self.warning = True return "warn" return None self.misses = 0 self.seen = self.seen + 1 if present else 0 if self.warning: self.warning = False return "cancel" return None def delay(self, chosen_pace): _first, between, after_miss, longest = chosen_pace if self.misses: return after_miss return min(between * 2 ** max(self.seen - 1, 0), longest) class Camera: def __init__(self, user): loader = importlib.machinery.SourceFileLoader("enroll", ENROLL) self.enroll = importlib.util.module_from_spec(importlib.util.spec_from_loader("enroll", loader)) loader.exec_module(self.enroll) config, paths_factory = self.enroll.load_config() import dlib # noqa: E402 dlib before OpenCV, as Howdy does import cv2 self.cv2 = cv2 self.device = config.get("video", "device_path") self.dark = config.getfloat("video", "dark_threshold", fallback=60) self.detector = dlib.get_frontal_face_detector() self.pose = dlib.shape_predictor(paths_factory.shape_predictor_5_face_landmarks_path()) self.encoder = dlib.face_recognition_model_v1( paths_factory.dlib_face_recognition_resnet_model_v1_path()) self.clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)) self.model_file = pathlib.Path(paths_factory.user_model_path(user)) self.known, self.loaded = None, None def models(self): """The owner's face views, reread when the Face Login window changes them.""" if not self.model_file.exists(): return None mtime = self.model_file.stat().st_mtime if mtime != self.loaded: self.known = [v for m in json.loads(self.model_file.read_text()) for v in m["data"]] self.loaded = mtime return self.known or None def shutter_closed(self): """The privacy shutter, read from the driver without starting the camera.""" control = bytearray(struct.pack("Ii", V4L2_CID_PRIVACY, 0)) with open(self.device, "rb") as device: try: fcntl.ioctl(device, VIDIOC_G_CTRL, control) except OSError as error: if error.errno == errno.EINVAL: # the camera has no shutter control return False raise return struct.unpack("Ii", control)[1] == 1 def look(self): """(present, best score); present is None when no frame was usable.""" known = self.models() if known is None or self.shutter_closed(): return None, None capture = self.cv2.VideoCapture(self.device, self.cv2.CAP_V4L2) usable, best = 0, None for _frame in range(FRAMES): ok, frame = capture.read() if not ok: break gray = self.clahe.apply(self.cv2.cvtColor(frame, self.cv2.COLOR_BGR2GRAY)) hist = self.cv2.calcHist([gray], [0], None, [8], [0, 256]) # The emitter lights every other frame; the dark ones say nothing if hist[0][0] / hist.sum() * 100 > self.dark: continue usable += 1 for face in self.detector(gray, 1): score = self.enroll.score_of(known, self.encoder.compute_face_descriptor( frame, self.pose(frame, face))) best = score if best is None else min(best, score) if best is not None and best < PRESENT_SCORE: break capture.release() if not usable: return None, None return best is not None and best < PRESENT_SCORE, best class Daemon: def __init__(self, camera): from gi.repository import Gio, GLib self.Gio, self.GLib = Gio, GLib self.camera = camera self.session = Gio.bus_get_sync(Gio.BusType.SESSION) self.system = Gio.bus_get_sync(Gio.BusType.SYSTEM) self.tracker = Tracker() self.look_timer = self.lock_timer = 0 self.active_watch = self.notification = 0 self.idle_watch = self.call("org.gnome.Mutter.IdleMonitor", "/org/gnome/Mutter/IdleMonitor/Core", "AddIdleWatch", GLib.Variant("(t)", (PACE_AC[0] * 1000,)))[0] self.session.signal_subscribe(None, "org.gnome.Mutter.IdleMonitor", "WatchFired", None, None, Gio.DBusSignalFlags.NONE, self.on_watch) self.session.signal_subscribe(None, "org.gnome.ScreenSaver", "ActiveChanged", None, None, Gio.DBusSignalFlags.NONE, self.on_screensaver) self.session.signal_subscribe(None, "org.freedesktop.Notifications", "ActionInvoked", None, None, Gio.DBusSignalFlags.NONE, self.on_action) def call(self, name, path, method, args=None, bus=None, interface=None): return (bus or self.session).call_sync( name, path, interface or name, method, args, None, self.Gio.DBusCallFlags.NONE, -1, None).unpack() def prop(self, name, path, prop): args = self.GLib.Variant("(ss)", (name, prop)) return self.call(name, path, "Get", args, self.system, "org.freedesktop.DBus.Properties")[0] def pace(self): on_battery = self.prop("org.freedesktop.UPower", "/org/freedesktop/UPower", "OnBattery") profile = self.prop("org.freedesktop.UPower.PowerProfiles", "/org/freedesktop/UPower/PowerProfiles", "ActiveProfile") return pace(on_battery, profile == "power-saver") def on_screensaver(self, _bus, _sender, _path, _iface, _signal, args): if args.unpack()[0]: self.stop("locked") def on_watch(self, _bus, _sender, _path, _iface, _signal, args): watch = args.unpack()[0] if watch == self.idle_watch: if self.call("org.gnome.ScreenSaver", "/org/gnome/ScreenSaver", "GetActive")[0]: return self.active_watch = self.call("org.gnome.Mutter.IdleMonitor", "/org/gnome/Mutter/IdleMonitor/Core", "AddUserActiveWatch")[0] self.schedule(self.pace()[0] - PACE_AC[0]) elif watch == self.active_watch: self.active_watch = 0 self.stop("activity") def on_action(self, _bus, _sender, _path, _iface, _signal, args): if args.unpack()[0] == self.notification: self.stop("kept unlocked") def schedule(self, seconds): self.look_timer = self.GLib.timeout_add_seconds(max(seconds, 1), self.look) def look(self): present, score = self.camera.look() state = {True: "present", False: "away", None: "unknown"}[present] print(f"look: {state}" + (f" {score:.2f}" if score is not None else ""), flush=True) action = self.tracker.look(present) if action == "warn": self.warn() elif action == "cancel": self.cancel_warning() self.schedule(self.tracker.delay(self.pace())) return False def warn(self): print("warn", flush=True) hints = {"desktop-entry": self.GLib.Variant("s", DESKTOP_ID), "urgency": self.GLib.Variant("y", 2)} args = self.GLib.Variant("(susssasa{sv}i)", ( _("Face Login"), 0, "", _("Locking the Screen"), _("The camera no longer sees your face"), ["default", _("Keep Unlocked"), "keep", _("Keep Unlocked")], hints, -1)) self.notification = self.call("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "Notify", args)[0] self.lock_timer = self.GLib.timeout_add_seconds(WARNING_SECONDS, self.lock) def cancel_warning(self): print("cancel: face back", flush=True) self.clear_warning() def clear_warning(self): if self.lock_timer: self.GLib.source_remove(self.lock_timer) self.lock_timer = 0 if self.notification: self.call("org.freedesktop.Notifications", "/org/freedesktop/Notifications", "CloseNotification", self.GLib.Variant("(u)", (self.notification,))) self.notification = 0 def lock(self): self.lock_timer = 0 print("lock", flush=True) self.call("org.gnome.ScreenSaver", "/org/gnome/ScreenSaver", "Lock") self.stop("locked") return False def stop(self, reason): if self.look_timer or self.lock_timer: print(f"stop: {reason}", flush=True) if self.look_timer: self.GLib.source_remove(self.look_timer) self.look_timer = 0 self.clear_warning() if self.active_watch: self.call("org.gnome.Mutter.IdleMonitor", "/org/gnome/Mutter/IdleMonitor/Core", "RemoveWatch", self.GLib.Variant("(u)", (self.active_watch,))) self.active_watch = 0 self.tracker = Tracker() def main(): from gi.repository import GLib camera = Camera(pwd.getpwuid(os.getuid()).pw_name) Daemon(camera) print("watching", flush=True) GLib.MainLoop().run() if __name__ == "__main__": main()