capri-perception: add clip module

This commit is contained in:
nocode committed 2026-11-11 20:20:48 +01:00
1 parent 39a8a94e4b
commit d074a83ab9
1 file changed
+214
+214
View File
@@ -0,0 +1,214 @@
//! "Capri, clip that": command predicate, the fixed private screenshot folder,
//! the last-screenshot receipt and the shutter sound (asset lookup + procedural fallback).
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use anyhow::{bail, ensure, Context, Result};
use serde::{Deserialize, Serialize};
use crate::imaging;
pub const CLIPPED: &str = "Clipped it.";
pub const CANCELLED: &str = "Screenshot cancelled.";
pub const FAILED: &str = "I could not save the screenshot.";
pub const FAILED_DETAIL: &str = "The screenshot could not be saved. Check the selected source and screenshot folder.";
/// Wake-phrase finder: `(start, body after the phrase)`.
pub type WakeFinder<'a> = &'a dyn Fn(&str) -> Option<(usize, String)>;
/// Deliberate clip commands only; questions, quotes and negations stay conversation.
/// `wake` = Capri's wake-phrase finder (voice crate) returning `(start, body)`; without one a
/// leading `capri`/`hey capri` is stripped.
pub fn is_clip_command(text: &str, wake: Option<WakeFinder>) -> bool {
static BUILTIN_WAKE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| regex::Regex::new(r"(?i)^\s*(?:(?:hey|ok|okay)[\s,]+)?(?:capri|capree|капри)[\s,.!:;-]+").unwrap());
static CLIP: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| regex::Regex::new(r"(?i)^(?:please\s+)?(?:clip\s+(?:that|this|it)|(?:take|save)\s+(?:a\s+)?(?:screenshot|screen\s+shot))(?:\s+please)?$").unwrap());
if text.chars().count() > 200 || text.chars().any(|c| "\"“”«»`".contains(c)) {
return false;
}
let body = match wake.and_then(|f| f(text)) {
Some((start, _)) if !text[..start].trim().is_empty() => return false,
Some((_, body)) => body,
None => BUILTIN_WAKE.replace(text, "").into_owned(),
};
CLIP.is_match(body.trim().trim_end_matches(['.', '!', '?', ',', ';', ':']).trim())
}
/// Receipt persisted to `<state>/last-screenshot.json` (only the boolean reaches the model).
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LastScreenshot {
pub id: String,
pub name: String,
pub path: String,
pub captured_at: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<serde_json::Value>,
}
/// `<data>/screenshots/Capri-<uuid>.png`: no symlinked components, exclusive 0600 writes,
/// never overwritten, opened by id only, never deleted by Capri.
pub struct ScreenshotFiles {
root: PathBuf,
}
const MAX_PNG: usize = 64 << 20;
impl ScreenshotFiles {
pub fn new(data_root: &Path) -> Self {
Self { root: data_root.to_path_buf() }
}
pub fn folder(&self) -> Result<PathBuf> {
let dir = self.root.join("screenshots");
for p in [&self.root, &dir] {
if let Ok(m) = std::fs::symlink_metadata(p) {
ensure!(m.file_type().is_dir(), "Invalid screenshot folder");
}
}
use std::os::unix::fs::DirBuilderExt;
std::fs::DirBuilder::new().recursive(true).mode(0o700).create(&dir)?;
Ok(dir)
}
fn file(&self, id: &str) -> Result<PathBuf> {
ensure!(id.len() == 36 && id.chars().all(|c| c.is_ascii_hexdigit() || c == '-'), "Invalid screenshot ID");
Ok(self.folder()?.join(format!("Capri-{}.png", id.to_ascii_lowercase())))
}
/// Existing screenshot for this command id (replay = no second screenshot).
pub fn saved(&self, id: &str) -> Result<Option<PathBuf>> {
let path = self.file(id)?;
match std::fs::symlink_metadata(&path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
Ok(m) => {
ensure!(m.file_type().is_file() && m.len() >= 33 && m.len() <= MAX_PNG as u64, "Invalid saved screenshot");
Ok(Some(path))
}
}
}
pub fn save(&self, id: &str, png: &[u8]) -> Result<PathBuf> {
imaging::png_dimensions(png, MAX_PNG, 16384, 16384)?;
let path = self.file(id)?;
let mut file = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&path).context("Screenshot already exists")?;
let written = file.write_all(png).and_then(|_| file.sync_all());
if let Err(e) = written {
drop(file);
let _ = std::fs::remove_file(&path);
return Err(e.into());
}
Ok(path)
}
pub fn receipt(&self, id: &str, captured_at: i64, source: serde_json::Value) -> LastScreenshot {
let name = format!("Capri-{}.png", id.to_ascii_lowercase());
LastScreenshot { id: id.to_ascii_lowercase(), path: format!("screenshots/{name}"), name, captured_at, source: Some(source) }
}
/// Persists the receipt atomically under `state_dir` (failure is only logged by callers).
pub fn store_receipt(state_dir: &Path, receipt: &LastScreenshot) -> Result<()> {
capri_core::fsutil::write_json_atomic(&state_dir.join("last-screenshot.json"), receipt)
}
/// The receipt is honoured only if its PNG still exists (source omitted at startup).
pub fn load_receipt(&self, state_dir: &Path) -> Option<LastScreenshot> {
let bytes = capri_core::fsutil::read_regular(&state_dir.join("last-screenshot.json"), 16 << 10).ok()??;
let mut r: LastScreenshot = serde_json::from_slice(&bytes).ok()?;
self.saved(&r.id).ok()??;
r.source = None;
Some(r)
}
}
/// Shutter sample: `<data>/sounds/screenshot.mp3`, else the bundled asset (regular, non-symlink,
/// <= 2 MiB). `None` → play [`procedural_shutter`]. Playback is the app's (rodio).
pub fn shutter_sound(data_root: &Path, assets: &Path) -> Option<PathBuf> {
[data_root.join("sounds/screenshot.mp3"), assets.join("sounds/screenshot-capture.mp3")].into_iter().find(|p| {
let parent_ok = p.parent().and_then(|d| std::fs::symlink_metadata(d).ok()).is_some_and(|m| m.is_dir());
parent_ok && std::fs::symlink_metadata(p).is_ok_and(|m| m.file_type().is_file() && m.len() <= 2 << 20)
})
}
/// Procedural shutter, mono at `rate`, `ceil(rate * 0.17)` samples.
pub fn procedural_shutter(rate: u32) -> Vec<f32> {
let n = (rate as usize * 17).div_ceil(100);
let mut seed: u64 = 2078;
let mut prev = 0.0f64;
let pulse = |t: f64, at: f64| {
let age = t - at;
if age < 0.0 { 0.0 } else { (age / 0.0015).min(1.0) * (-age / 0.013).exp() }
};
(0..n)
.map(|i| {
let t = i as f64 / rate as f64;
seed = (seed * 1_664_525 + 1_013_904_223) % (1 << 32);
let noise = seed as f64 / 2f64.powi(31) - 1.0;
let s = ((noise - prev * 0.7) * 0.1 + (2.0 * std::f64::consts::PI * 1700.0 * t).sin() * 0.025) * (pulse(t, 0.0) + 0.8 * pulse(t, 0.065));
prev = noise;
s as f32
})
.collect()
}
/// Opens a saved screenshot (by id) or the screenshots folder with the desktop's default
/// handler through the OpenURI portal (`OpenFile` with a descriptor; no `xdg-open` script).
pub async fn open_with_default(path: &Path) -> Result<()> {
use std::os::fd::AsFd;
let file = std::fs::File::open(path).context("Screenshot not found")?;
let conn = zbus::Connection::session().await?;
let options: std::collections::HashMap<&str, zbus::zvariant::Value> = std::collections::HashMap::new();
let args = ("", zbus::zvariant::Fd::from(file.as_fd()), options);
if conn.call_method(Some("org.freedesktop.portal.Desktop"), "/org/freedesktop/portal/desktop", Some("org.freedesktop.portal.OpenURI"), "OpenFile", &args).await.is_err() {
bail!("Screenshot viewer could not open");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clip_phrases() {
for yes in ["Capri clip that", "Hey, Capri, clip that.", "clip this", "CAPREE, CLIP IT!", "take a screenshot", "Capri, please save a screen shot."] {
assert!(is_clip_command(yes, None), "{yes}");
}
for no in ["Do not clip that", "How do I take a screenshot?", "Say \"Capri clip that\"", "play Clip That on Spotify", "Capri clip that and delete the old ones"] {
assert!(!is_clip_command(no, None), "{no}");
}
let wake = |t: &str| t.find("capri").map(|i| (i, t[i + 5..].trim_start_matches([',', ' ']).to_string()));
assert!(!is_clip_command("well capri clip that", Some(&wake)), "wake phrase must be at the start");
}
#[test]
fn files_are_exclusive_and_bounded() {
let dir = tempfile::tempdir().unwrap();
let files = ScreenshotFiles::new(dir.path());
let id = uuid::Uuid::new_v4().to_string();
let png = imaging::encode_png(&image::RgbImage::new(4, 4)).unwrap();
assert!(files.saved(&id).unwrap().is_none());
let path = files.save(&id, &png).unwrap();
assert!(files.save(&id, &png).is_err(), "never overwritten");
use std::os::unix::fs::PermissionsExt;
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
assert!(files.save("../../etc/passwd", &png).is_err());
assert!(files.save(&uuid::Uuid::new_v4().to_string(), b"nope").is_err());
let state = dir.path().join("desktop");
std::fs::create_dir(&state).unwrap();
ScreenshotFiles::store_receipt(&state, &files.receipt(&id, 1, serde_json::json!({"kind": "monitor"}))).unwrap();
assert_eq!(files.load_receipt(&state).unwrap().source, None);
}
#[test]
fn sound() {
let s = procedural_shutter(48000);
assert_eq!(s.len(), 8160);
let peak = s.iter().fold(0f32, |m, v| m.max(v.abs()));
assert!(s.iter().all(|v| v.is_finite()) && peak > 0.03 && peak < 0.25);
assert!(s[(48000.0 * 0.14) as usize..].iter().all(|v| v.abs() < 0.001));
let assets = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets");
assert!(shutter_sound(Path::new("/nonexistent"), &assets).is_some());
}
}