capri-ui: add detach module

This commit is contained in:
nocode committed 2026-11-11 20:20:48 +01:00
1 parent 7ccd26b624
commit e3c94f0017
1 file changed
+845
+845
View File
@@ -0,0 +1,845 @@
//! "Take Capri out of her frame": the detached desktop avatar on a
//! transparent override-redirect overlay covering the work area, the teleport choreography,
//! drag tether, docking on windows and display edges, the floating HUD and the mini composer.
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use capri_core::avatar::Catalog;
use eframe::egui::{self, Align2, Color32, FontId, Pos2, Rect, RichText, Sense, Stroke, Vec2, ViewportBuilder, ViewportId};
use tokio::task::JoinHandle;
use crate::avatar::{self, Loader, CANVAS};
use crate::desktop::Snapshot;
use crate::dock::{self, Dock};
use crate::teleport::{self, Motion, PainterInk, Profile, Spot};
use crate::{body, geom, i18n::t, theme, x11, App};
const OVERLAY: &str = "Capri Avatar";
const COMPOSER: &str = "Capri Composer";
const STANDING_ANCHOR: (f32, f32) = (627.0, 1166.0);
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Phase {
Attached,
Leaving,
Detached,
Teleporting,
Returning,
}
/// A reviewed desktop pose: anchor and visible bounds on the 1254 canvas.
struct Pose {
anchor: (f32, f32),
bounds: Rect,
}
/// Loads `poses-v2/runtime-poses.json` next to the sprite folder; any checksum failure rejects the pack.
fn load_poses(catalog: &Catalog) -> HashMap<String, (Pose, PathBuf)> {
#[derive(serde::Deserialize)]
struct P {
x: f32,
y: f32,
}
#[derive(serde::Deserialize)]
struct B {
x: f32,
y: f32,
width: f32,
height: f32,
}
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct S {
id: String,
file: String,
anchor: P,
visible_bounds: B,
sha256: String,
}
#[derive(serde::Deserialize)]
struct M {
sprites: Vec<S>,
}
let load = || -> Option<HashMap<String, (Pose, PathBuf)>> {
let dir = catalog.dir.parent()?.join("poses-v2");
let manifest: M = serde_json::from_slice(&capri_core::fsutil::read_regular(&dir.join("runtime-poses.json"), 16 * 1024).ok()??).ok()?;
manifest
.sprites
.into_iter()
.map(|s| {
let ok_name = s.file.starts_with("capri-") && s.file.ends_with(".png") && !s.file.contains('/');
let path = dir.join("PNG").join(&s.file);
let bytes = capri_core::fsutil::read_regular(&path, 20 << 20).ok()??;
(ok_name && avatar::sha256(&bytes) == s.sha256).then(|| {
let b = s.visible_bounds;
(s.id, (Pose { anchor: (s.anchor.x, s.anchor.y), bounds: Rect::from_min_size(Pos2::new(b.x, b.y), egui::vec2(b.width, b.height)) }, path))
})
})
.collect()
};
if catalog.dir.as_os_str().is_empty() {
return HashMap::new();
}
load().unwrap_or_else(|| {
tracing::warn!("Capri desktop poses are missing or damaged; docking is off");
HashMap::new()
})
}
/// Where the avatar stands: contact point (desktop logical px), sprite square size and pose.
#[derive(Clone, Debug)]
struct Place {
at: Pos2,
scale: f32,
/// Reviewed pose id when docked, else the standing frame follows the portrait director.
pose: Option<String>,
/// Window id being perched on (None for display docks).
window: Option<String>,
dock: Option<Dock>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Kind {
Leave,
Hop,
Return,
}
struct Flight {
motion: Motion,
from: Spot,
to: Spot,
from_frame: String,
to_frame: String,
kind: Kind,
start: Instant,
target: Place,
}
enum Pending {
/// Leave the frame or hop: to a point (grab offset kept) or a random landing.
Move { point: Option<Pos2>, grab: Vec2 },
Perch { title: String },
Follow,
}
struct Press {
start: Pos2,
at: Instant,
grab: Vec2,
seed: u32,
}
pub struct Detach {
phase: Phase,
sprites: Loader,
poses: HashMap<String, Pose>,
standing_top: HashMap<String, f32>,
place: Option<Place>,
/// Portrait anchor relative to the companion window and its sprite scale, for the return flight.
home: Option<(Vec2, f32)>,
flight: Option<Flight>,
press: Option<Press>,
tether: Option<(Pos2, Pos2, u32)>,
snapshot: Option<Snapshot>,
pending: Option<(JoinHandle<anyhow::Result<Snapshot>>, Pending)>,
want_return: bool,
last_follow: Instant,
area: Rect,
overlay: Option<u32>,
composer: Option<u32>,
overlay_shape: Option<Vec<x11::Px>>,
composer_shape: Option<Vec<x11::Px>>,
last_raise: Instant,
opened: Option<Instant>,
draft: String,
reply_for_perch: bool,
composer_pos: Option<Pos2>,
}
fn standing_spot(at: Pos2, scale: f32) -> Spot {
let k = scale / CANVAS;
Spot { at, scale, focus: None, rect: Rect::from_min_size(at - egui::vec2(STANDING_ANCHOR.0, STANDING_ANCHOR.1) * k, egui::vec2(scale, scale)) }
}
impl Detach {
pub fn new(catalog: &Arc<Catalog>, ctx: egui::Context) -> Self {
let poses = load_poses(catalog);
let mut paths: HashMap<String, PathBuf> = catalog.frames.iter().map(|f| (f.id.clone(), catalog.frame_path(f))).collect();
paths.extend(poses.iter().map(|(id, (_, p))| (id.clone(), p.clone())));
Self {
phase: Phase::Attached,
sprites: Loader::new(ctx, paths, None, 512, true),
poses: poses.into_iter().map(|(id, (pose, _))| (id, pose)).collect(),
standing_top: catalog.frames.iter().filter_map(|f| Some((f.id.clone(), f.visible_bounds?.y))).collect(),
place: None,
home: None,
flight: None,
press: None,
tether: None,
snapshot: None,
pending: None,
want_return: false,
last_follow: Instant::now(),
area: Rect::NOTHING,
overlay: None,
composer: None,
overlay_shape: None,
composer_shape: None,
last_raise: Instant::now(),
opened: None,
draft: String::new(),
reply_for_perch: false,
composer_pos: None,
}
}
pub fn attached(&self) -> bool {
self.phase == Phase::Attached
}
/// No flight or query in progress.
pub fn idle(&self) -> bool {
self.flight.is_none() && self.pending.is_none()
}
pub fn animating(&self) -> bool {
self.flight.is_some() || self.tether.is_some() || self.pending.is_some()
}
/// Displays from the last desktop snapshot, in logical px.
pub fn displays(&self, ppp: f32) -> Vec<dock::Display> {
let r = |p: x11::Px| Rect::from_min_size(Pos2::new(p[0] as f32, p[1] as f32) / ppp, egui::vec2(p[2] as f32, p[3] as f32) / ppp);
self.snapshot.iter().flat_map(|s| s.displays.iter().map(|d| dock::Display { bounds: r(d.bounds), work: r(d.work) })).collect()
}
/// "Return to frame" (button, tray, command). False when Capri is already home.
pub fn request_return(&mut self) -> bool {
if self.phase == Phase::Detached {
self.want_return = true;
return true;
}
self.phase == Phase::Returning
}
fn pose_of(&self, id: &str) -> Option<&Pose> {
self.poses.get(id)
}
fn spot(&self, place: &Place) -> Spot {
let k = place.scale / CANVAS;
match place.pose.as_deref().and_then(|p| self.pose_of(p)) {
Some(pose) => {
let min = place.at - egui::vec2(pose.anchor.0, pose.anchor.1) * k;
Spot { at: place.at, scale: place.scale, focus: Some(min + pose.bounds.center().to_vec2() * k), rect: Rect::from_min_size(min, egui::vec2(place.scale, place.scale)) }
}
None => standing_spot(place.at, place.scale),
}
}
/// Visible body rectangle in desktop px.
fn body(&self, place: &Place) -> Rect {
let spot = self.spot(place);
let k = place.scale / CANVAS;
let bounds = place.pose.as_deref().and_then(|p| self.pose_of(p)).map_or(Rect::from_min_max(Pos2::new(202.0, 113.0), Pos2::new(1083.0, 1168.0)), |p| p.bounds);
Rect::from_min_size(spot.rect.min + bounds.min.to_vec2() * k, bounds.size() * k)
}
}
impl App {
fn can_detach(&self) -> bool {
self.avatar.animated() && self.desktop.is_some()
}
/// Leave the frame (attached) or hop to a random landing (detached).
pub(crate) fn teleport(&mut self) {
if self.can_detach() && self.detach.idle() && matches!(self.detach.phase, Phase::Attached | Phase::Detached) {
self.query(Pending::Move { point: None, grab: Vec2::ZERO });
}
}
pub(crate) fn request_perch(&mut self, title: String) -> bool {
if !self.can_detach() || !self.detach.idle() || self.detach.poses.is_empty() {
return false;
}
self.detach.reply_for_perch = true;
self.query(Pending::Perch { title });
true
}
fn query(&mut self, pending: Pending) {
let Some(desktop) = self.desktop.clone() else { return };
if self.detach.pending.is_none() {
self.detach.pending = Some((self.rt.spawn(desktop.snapshot()), pending));
}
}
fn sprite_scale(&self, work: Rect) -> f32 {
240f32.min(0.42 * work.width()).min(0.48 * work.height())
}
fn display_at(&self, ctx: &egui::Context, p: Pos2) -> dock::Display {
let displays = self.detach.displays(ctx.pixels_per_point());
displays.iter().copied().find(|d| d.bounds.contains(p)).or(displays.first().copied()).unwrap_or_else(|| {
let work = self.work_area(ctx);
dock::Display { bounds: work, work }
})
}
/// Dock near `point`: reserved strips and display edges first,
/// then the nearest qualifying window edge, then the display again.
fn try_dock(&self, ctx: &egui::Context, point: Pos2) -> Option<(Dock, Option<String>)> {
if self.detach.poses.is_empty() {
return None;
}
let ppp = ctx.pixels_per_point();
let display = self.display_at(ctx, point);
let radius = self.cfg.avatar_snap_radius as f32;
let screen = dock::nearest_display(point, &display, radius);
if dock::in_reserved(point, &display) || screen.is_some_and(|d| d.distance <= radius.min(12.0)) {
return screen.map(|d| (d, None));
}
let mut best: Option<(Dock, String)> = None;
for w in self.detach.snapshot.iter().flat_map(|s| s.candidates()) {
let rect = Rect::from_min_size(Pos2::new(w.rect[0] as f32, w.rect[1] as f32) / ppp, egui::vec2(w.rect[2] as f32, w.rect[3] as f32) / ppp);
if let Some(d) = dock::nearest(point, rect, radius, false)
&& dock::visible(&d, dock::dock_point(&d), display.work)
&& best.as_ref().is_none_or(|(b, _)| d.distance < b.distance)
{
best = Some((d, w.id.clone()));
}
}
best.map(|(d, id)| (d, Some(id))).or(screen.map(|d| (d, None)))
}
/// Placement for a dock: contact point, pose, visible body kept inside the work area.
fn dock_place(&self, d: Dock, window: Option<String>, scale: f32, work: Rect) -> Option<Place> {
let pose = dock::pose(&d).to_string();
self.detach.pose_of(&pose)?;
let mut place = Place { at: dock::dock_point(&d), scale, pose: Some(pose), window, dock: Some(d) };
let body = self.detach.body(&place);
let shift = egui::vec2((work.min.x - body.min.x).max(0.0) + (work.max.x - body.max.x).min(0.0), (work.min.y - body.min.y).max(0.0) + (work.max.y - body.max.y).min(0.0));
place.at += shift;
Some(place)
}
/// Free landing: the whole sprite square stays in the work area.
fn free_place(&self, at: Pos2, scale: f32, work: Rect) -> Place {
let spot = standing_spot(at, scale);
let shift = egui::vec2((work.min.x - spot.rect.min.x).max(0.0) + (work.max.x - spot.rect.max.x).min(0.0), (work.min.y - spot.rect.min.y).max(0.0) + (work.max.y - spot.rect.max.y).min(0.0));
Place { at: at + shift, scale, pose: None, window: None, dock: None }
}
fn standing_frame(&mut self) -> String {
let sleeping = self.ui.0.state.lock().sleeping;
let id = self.avatar.current(Instant::now(), sleeping).0;
if self.avatar.catalog().frame(&id).is_some() { id } else { self.avatar.catalog().default_id.clone() }
}
fn frame_of(&mut self, place: &Place) -> String {
place.pose.clone().unwrap_or_else(|| self.standing_frame())
}
fn start_flight(&mut self, ctx: &egui::Context, kind: Kind, from: Spot, from_frame: String, target: Place) {
let to = self.detach.spot(&target);
let to_frame = self.frame_of(&target);
tracing::debug!("teleport {kind:?}: {:?} -> {:?} pose {:?} window {:?}", from.at, to.at, target.pose, target.window);
let work = self.display_at(ctx, to.at).work;
self.detach.area = work;
let profile = Profile {
intensity: self.cfg.teleport_intensity as f32 / 100.0,
jaggedness: self.cfg.teleport_jaggedness as f32 / 100.0,
branches: self.cfg.teleport_branches as f32 / 100.0,
reduced_flash: self.cfg.teleport_reduced_flash,
seed: (self.now_ms() as u64 as u32).wrapping_mul(2654435761),
};
let local = |s: Spot| Spot { at: s.at - work.min.to_vec2(), focus: s.focus.map(|f| f - work.min.to_vec2()), rect: s.rect.translate(-work.min.to_vec2()), ..s };
let (from, to) = (local(from), local(to));
let motion = Motion::new(&from, &to, profile, Some((work.width(), work.height())));
self.detach.phase = match kind {
Kind::Leave => Phase::Leaving,
Kind::Hop => Phase::Teleporting,
Kind::Return => Phase::Returning,
};
let dialogue = self.cfg.detached_style == "dialogue";
if !dialogue {
self.sounds.play(&self.cfg.teleport_sound);
}
self.detach.sprites.want(&from_frame);
self.detach.sprites.want(&to_frame);
self.detach.flight = Some(Flight { motion, from, to, from_frame, to_frame, kind, start: Instant::now(), target });
if self.reduced() || dialogue {
self.finish_flight();
}
self.avatar.skip_intro();
}
fn finish_flight(&mut self) {
let Some(flight) = self.detach.flight.take() else { return };
if flight.kind == Kind::Return {
self.detach.phase = Phase::Attached;
self.detach.place = None;
} else {
self.detach.phase = Phase::Detached;
self.detach.place = Some(flight.target);
self.detach.last_follow = Instant::now();
}
}
/// Spot of the portrait sprite in desktop px (departure and return).
fn portrait_spot(&self, ctx: &egui::Context) -> Option<Spot> {
let view = self.avatar.view.as_ref()?;
let origin = self.companion_rect(ctx).min.to_vec2();
let scale = view.draw.width() * CANVAS / view.crop.width();
let at = view.to_screen(STANDING_ANCHOR.0, STANDING_ANCHOR.1) + origin;
Some(standing_spot(at, scale))
}
/// Resolves a finished desktop query.
fn resolve(&mut self, ctx: &egui::Context, snapshot: anyhow::Result<Snapshot>, pending: Pending) {
match snapshot {
Ok(s) => {
tracing::debug!("desktop snapshot: {} windows, displays {:?}", s.windows.len(), s.displays);
self.detach.snapshot = Some(s);
}
Err(e) => tracing::warn!("desktop query failed: {e:#}"),
}
let companion = self.companion_rect(ctx);
let current = self.detach.place.clone();
let (from, from_frame, kind) = match &current {
Some(place) => {
let frame = self.frame_of(place);
(Some(self.detach.spot(place)), frame, Kind::Hop)
}
None => (self.portrait_spot(ctx), self.standing_frame(), Kind::Leave),
};
let Some(from) = from else { return };
if kind == Kind::Leave {
self.detach.home = Some((from.at - companion.min, from.scale));
}
match pending {
Pending::Follow => self.follow_perch(ctx),
Pending::Move { point, grab } => {
let target = match point {
// Dropped on the visible companion: back into the frame.
Some(p) if kind == Kind::Hop && companion.contains(p) && !self.hidden => {
self.detach.want_return = true;
return;
}
Some(p) => {
let display = self.display_at(ctx, p);
let scale = self.sprite_scale(display.work);
self.try_dock(ctx, p).and_then(|(d, w)| self.dock_place(d, w, scale, display.work)).unwrap_or_else(|| self.free_place(p + grab * scale, scale, display.work))
}
None => {
let display = self.display_at(ctx, from.at);
let scale = self.sprite_scale(display.work);
let mut seed = self.now_ms() as u64 as u32 | 1;
let top_left = dock::random_landing(display.work, scale, companion, from.rect.center(), || teleport::Lcg::new({ seed = seed.wrapping_mul(747796405).wrapping_add(1); seed }).next());
self.free_place(top_left + egui::vec2(STANDING_ANCHOR.0, STANDING_ANCHOR.1) * (scale / CANVAS), scale, display.work)
}
};
self.start_flight(ctx, kind, from, from_frame, target);
}
Pending::Perch { title } => {
let ppp = ctx.pixels_per_point();
let wanted = title.to_lowercase();
let window = self.detach.snapshot.as_ref().and_then(|s| s.candidates().find(|w| wanted.is_empty() || w.title.to_lowercase().contains(&wanted)).cloned());
let place = window.and_then(|w| {
let rect = Rect::from_min_size(Pos2::new(w.rect[0] as f32, w.rect[1] as f32) / ppp, egui::vec2(w.rect[2] as f32, w.rect[3] as f32) / ppp);
let display = self.display_at(ctx, rect.center());
let d = Dock { kind: dock::Kind::Seat, edge: dock::Edge::Top, fraction: 0.66, distance: 0.0, bounds: rect, display: false };
let scale = self.sprite_scale(display.work);
self.dock_place(d, Some(w.id), scale, display.work)
});
if self.detach.reply_for_perch {
self.detach.reply_for_perch = false;
let russian = self.store.get().language.conversation == "ru";
self.reply = dock::command_reply(&dock::AvatarCommand::Perch { title: String::new() }, place.is_some(), russian).to_string();
}
if let Some(target) = place {
self.start_flight(ctx, kind, from, from_frame, target);
}
}
}
}
/// Follows the perched window (1800 ms poll, as Capri's Linux bridge): moved, closed, hidden.
fn follow_perch(&mut self, ctx: &egui::Context) {
let ppp = ctx.pixels_per_point();
let Some(place) = self.detach.place.clone() else { return };
let (Some(id), Some(d)) = (place.window.clone(), place.dock) else { return };
let found = self.detach.snapshot.as_ref().and_then(|s| s.windows.iter().find(|w| w.id == id).cloned());
match found {
Some(w) => {
let rect = Rect::from_min_size(Pos2::new(w.rect[0] as f32, w.rect[1] as f32) / ppp, egui::vec2(w.rect[2] as f32, w.rect[3] as f32) / ppp);
if rect != d.bounds && self.detach.press.is_none() {
let work = self.display_at(ctx, rect.center()).work;
if let Some(next) = self.dock_place(Dock { bounds: rect, ..d }, Some(id), place.scale, work) {
self.detach.place = Some(next);
}
}
}
// Window closed or minimized: stay on the desktop, standing.
None => self.detach.place = Some(Place { pose: None, window: None, dock: None, ..place }),
}
}
/// Attached drag-out from the portrait: tether past the dead zone, leave on release
/// more than 24 px outside the window.
pub(crate) fn drag_out(&mut self, ctx: &egui::Context, response: &egui::Response, view: &avatar::View) {
let origin = self.companion_rect(ctx).min.to_vec2();
let cursor = || -> Option<Pos2> {
let ppp = ctx.pixels_per_point();
self.desktop.as_ref().and_then(|d| d.cursor()).map(|(x, y)| Pos2::new(x as f32, y as f32) / ppp).or_else(|| ctx.input(|i| i.pointer.latest_pos()).map(|p| p + origin))
};
if response.drag_started()
&& let Some(p) = response.interact_pointer_pos()
{
let scale = view.draw.width() * CANVAS / view.crop.width();
let anchor = view.to_screen(STANDING_ANCHOR.0, STANDING_ANCHOR.1);
self.detach.press = Some(Press { start: p + origin, at: Instant::now(), grab: (anchor - p) / scale, seed: self.now_ms() as u64 as u32 });
let area = self.work_area(ctx);
self.detach.area = area;
}
let Some(press) = &self.detach.press else { return };
let Some(now) = cursor() else { return };
let dead = self.cfg.avatar_drag_tether_dead_zone as f32;
let beyond = (now - press.start).length() > dead.max(5.0);
self.detach.tether = (beyond && self.cfg.avatar_drag_tether && self.cfg.detached_style == "character").then_some((press.start, now, press.seed));
if response.drag_stopped() || !ctx.input(|i| i.pointer.primary_down()) {
let press = self.detach.press.take().unwrap();
self.detach.tether = None;
let outside = !self.companion_rect(ctx).expand(24.0).contains(now);
if beyond && outside && press.at.elapsed() < Duration::from_secs(30) && self.can_detach() {
self.query(Pending::Move { point: Some(now), grab: press.grab });
}
}
}
/// Overlay, mini composer and the detach state machine; called every frame.
pub(crate) fn detached_ui(&mut self, ctx: &egui::Context) {
if let Some((handle, _)) = &self.detach.pending
&& handle.is_finished()
{
let (handle, pending) = self.detach.pending.take().unwrap();
let result = self.rt.block_on(handle).unwrap_or_else(|e| Err(e.into()));
self.resolve(ctx, result, pending);
}
if self.detach.want_return && self.detach.idle() && self.detach.phase == Phase::Detached {
self.detach.want_return = false;
let place = self.detach.place.clone().unwrap();
let from = self.detach.spot(&place);
let from_frame = self.frame_of(&place);
let companion = self.companion_rect(ctx);
let (offset, scale) = self.detach.home.unwrap_or((egui::vec2(240.0, 560.0), 400.0));
let target = Place { at: companion.min + offset, scale, pose: None, window: None, dock: None };
self.hidden = false;
self.start_flight(ctx, Kind::Return, from, from_frame, target);
self.detach.area = self.detach.area.union(companion);
}
if self.detach.phase == Phase::Detached && self.detach.place.as_ref().is_some_and(|p| p.window.is_some()) && self.detach.idle() && self.detach.last_follow.elapsed() > Duration::from_millis(1800) {
self.detach.last_follow = Instant::now();
self.query(Pending::Follow);
}
let visible = self.detach.phase != Phase::Attached || self.detach.flight.is_some() || self.detach.tether.is_some();
if !visible || self.focus {
self.detach.overlay = None;
self.detach.composer = None;
self.detach.overlay_shape = None;
self.detach.composer_shape = None;
self.detach.opened = None;
return;
}
let opened = *self.detach.opened.get_or_insert_with(|| {
tracing::debug!("desktop avatar overlay opened ({:?})", self.detach.phase);
Instant::now()
});
let area = self.detach.area;
let builder = ViewportBuilder::default()
.with_title(OVERLAY)
.with_position(area.min)
.with_inner_size(area.size())
.with_transparent(true)
.with_decorations(false)
.with_resizable(false)
.with_taskbar(false)
.with_active(false)
.with_override_redirect(true)
.with_window_level(egui::WindowLevel::AlwaysOnTop);
let hits = ctx.show_viewport_immediate(ViewportId::from_hash_of(OVERLAY), builder, |ui, _| self.overlay_ui(ui, area));
// Immediate viewports expose no window handle: find ours by title once mapped.
if let Some(x) = self.x11.clone() {
if self.detach.overlay.is_none() && opened.elapsed() > Duration::from_millis(150) {
self.detach.overlay = x.find_own(OVERLAY);
}
if let Some(w) = self.detach.overlay {
let ppp = ctx.pixels_per_point();
let rects: Vec<x11::Px> = hits.iter().map(|r| px(*r, ppp)).collect();
if self.detach.overlay_shape.as_ref() != Some(&rects) && !ctx.input_for(ViewportId::from_hash_of(OVERLAY), |i| i.pointer.any_down()) {
let _ = x.set_input(w, &rects);
self.detach.overlay_shape = Some(rects);
}
if self.detach.last_raise.elapsed() > Duration::from_millis(750) {
self.detach.last_raise = Instant::now();
x.raise(w);
}
}
}
if self.detach.phase == Phase::Detached && self.detach.flight.is_none() {
self.composer_ui(ctx);
} else {
self.detach.composer = None;
self.detach.composer_shape = None;
self.detach.composer_pos = None;
}
}
/// Paints the overlay; returns its interactive rectangles (overlay-local logical px).
fn overlay_ui(&mut self, ui: &mut egui::Ui, area: Rect) -> Vec<Rect> {
let ctx = ui.ctx().clone();
self.detach.sprites.poll(&ctx);
let origin = area.min;
let painter = ui.painter().clone();
let now = self.now_ms();
let reduced = self.reduced();
let mut hits = Vec::new();
if let Some((from, to, seed)) = self.detach.tether {
let (intensity, chaos) = (self.cfg.avatar_drag_tether_intensity as f32, self.cfg.avatar_drag_tether_chaos as f32);
teleport::draw_tether(&painter, from - origin.to_vec2(), to - origin.to_vec2(), (intensity, chaos), seed, now, reduced);
}
if let Some(flight) = self.detach.flight.take() {
let frame = flight.start.elapsed().as_secs_f32() * teleport::FPS;
let (from_rect, to_rect) = (flight.from.rect, flight.to.rect);
let textures: Vec<_> = [&flight.from_frame, &flight.to_frame].iter().map(|id| self.detach.sprites.get(id).map(|t| (t.texture.id(), t.silhouette.as_ref().map(|s| s.id())))).collect();
let unit = Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0));
let red = Color32::from_rgb(0xff, 0x00, 0x3d);
let mut ink = PainterInk {
painter: &painter,
capri: |p: &egui::Painter, arriving: bool, tint: f32, clip: Option<&[Vec<Pos2>]>| {
let (rect, tex) = if arriving { (to_rect, textures[1]) } else { (from_rect, textures[0]) };
let Some((tex, silhouette)) = tex else { return };
let tinted = silhouette.filter(|_| tint > 0.0);
match clip {
None => {
p.image(tex, rect, unit, Color32::WHITE);
if let Some(s) = tinted {
p.image(s, rect, unit, red.gamma_multiply(tint));
}
}
Some(polys) => {
for poly in polys {
geom::image_clipped(p, tex, rect, poly, Color32::WHITE);
if let Some(s) = tinted {
geom::image_clipped(p, s, rect, poly, red.gamma_multiply(tint));
}
}
}
}
},
};
let running = flight.motion.draw(&mut ink, frame, &flight.to);
self.detach.flight = Some(flight);
if !running {
self.finish_flight();
}
ctx.request_repaint();
return hits;
}
let Some(place) = self.detach.place.clone() else { return hits };
let spot = self.detach.spot(&place);
let local = |r: Rect| r.translate(-origin.to_vec2());
let rect = local(spot.rect);
let body = local(self.detach.body(&place));
let dialogue = self.cfg.detached_style == "dialogue";
let frame = self.frame_of(&place);
let (mouth, sleeping) = {
let s = self.ui.0.state.lock();
(s.mouth, s.sleeping)
};
if !dialogue {
if let Some(tex) = self.detach.sprites.get(&frame) {
painter.image(tex.texture.id(), rect, Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0)), Color32::WHITE);
}
let k = place.scale / CANVAS;
let to_screen = |x: f32, y: f32| rect.min + egui::vec2(x, y) * k;
match body::landmarks(&frame) {
Some(l) if !sleeping => avatar::pose_mouth(&painter, to_screen, l.mouth, mouth),
None if !sleeping && mouth > 0 => {
if let Some((mx, my)) = body::portrait_mouth(&frame) {
let level = mouth.min(3) as usize;
let o = [0.0, 7.0, 17.0, 24.0][level];
let pts = |list: &[(f32, f32)]| -> Vec<Pos2> { list.iter().map(|&(x, y)| to_screen(mx + x, my + y)).collect() };
geom::fill(&painter, &pts(&[(-36., -12.), (36., -24.), (30., 17.), (4., 29.), (-33., 18.)]), Color32::from_rgb(0x07, 0x08, 0x12));
geom::fill(&painter, &pts(&[(-21., 1.), (22., -12.), (12., o), (-5., o - 2.)]), Color32::from_rgb(0xf9, 0xfa, 0xff));
}
}
_ => {}
}
if sleeping {
let caption = crate::fx::sleep_caption(if reduced { 1500.0 } else { now });
painter.text(body.right_top() + egui::vec2(-20.0, 10.0), Align2::LEFT_TOP, caption, FontId::proportional(20.0), theme::VIOLET);
}
}
// HUD: status badge above the crown and the floating reply.
let crown = match body::landmarks(&frame) {
Some(l) => rect.min.y + l.crown * place.scale / CANVAS,
None => rect.min.y + self.detach.standing_top.get(&frame).copied().unwrap_or(113.0) * place.scale / CANVAS,
};
let face_x = spot.focus.map_or(spot.at.x, |f| f.x) - origin.x;
let signal = self.signal();
let badge_text = self.status_text();
let galley = painter.layout_no_wrap(badge_text, FontId::proportional(10.0), signal.color());
let badge = Rect::from_center_size(Pos2::new(face_x, crown - 16.0 - galley.size().y / 2.0 - 4.0), galley.size() + egui::vec2(14.0, 8.0));
let badge = badge.translate(egui::vec2((8.0 - badge.min.x).max(0.0) + (area.width() - 8.0 - badge.max.x).min(0.0), (8.0 - badge.min.y).max(0.0)));
painter.rect_filled(badge, 2.0, theme::alpha(0x08, 0x14, 0x1b, 0xe8));
painter.rect_stroke(badge, 2.0, Stroke::new(1.0, signal.color()), egui::StrokeKind::Inside);
painter.galley(badge.center() - galley.size() / 2.0, galley, signal.color());
let reply: String = self.reply.chars().rev().take(512).collect::<Vec<_>>().into_iter().rev().collect();
if (!reply.is_empty() && !self.reply_hidden()) || dialogue {
let (fill, line) = if dialogue { (Color32::from_rgba_unmultiplied(0x09, 0x23, 0x16, 0xf5), Color32::from_rgb(0x59, 0xed, 0x91)) } else { (theme::alpha(0x0c, 0x12, 0x1a, 0xee), theme::cyan()) };
let text = if reply.is_empty() { t("Hey. I'm here.") } else { reply };
let galley = painter.layout(text, FontId::proportional(14.0), theme::TEXT, 320.0);
let size = galley.size().min(egui::vec2(320.0, 150.0)) + egui::vec2(20.0, 16.0);
let above = badge.min.y - 8.0 - size.y >= 8.0 && !body::landmarks(&frame).is_some_and(|l| l.inverted);
let min = if above { Pos2::new(face_x - size.x / 2.0, badge.min.y - 8.0 - size.y) } else { Pos2::new(face_x - size.x / 2.0, body.max.y + 8.0) };
let bubble = Rect::from_min_size(min, size);
let bubble = bubble.translate(egui::vec2((8.0 - bubble.min.x).max(0.0) + (area.width() - 8.0 - bubble.max.x).min(0.0), (area.height() - 8.0 - bubble.max.y).min(0.0)));
painter.rect_filled(bubble, 4.0, fill);
painter.rect_stroke(bubble, 4.0, Stroke::new(1.0, line), egui::StrokeKind::Inside);
painter.with_clip_rect(bubble.shrink(6.0)).galley(bubble.min + egui::vec2(10.0, 8.0), galley, theme::TEXT);
self.reply_hover = ui.rect_contains_pointer(bubble);
hits.push(bubble);
}
// Pointer: grab, drag (tether), drop (teleport/dock/return) or tap.
let grab = if dialogue { badge } else { body.expand(12.0) };
hits.push(grab);
hits.push(badge);
let response = ui.interact(grab, ui.scope_id().with("desktop-avatar"), Sense::click_and_drag());
let pointer = response.interact_pointer_pos().map(|p| p + origin.to_vec2());
if response.drag_started()
&& let Some(p) = pointer
{
let at = spot.at;
self.detach.press = Some(Press { start: p, at: Instant::now(), grab: (at - p) / place.scale, seed: now as u64 as u32 });
}
if let (Some(press), Some(p)) = (&self.detach.press, pointer) {
let dead = self.cfg.avatar_drag_tether_dead_zone as f32;
let beyond = (p - press.start).length() > dead.max(5.0);
self.detach.tether = (beyond && self.cfg.avatar_drag_tether && !dialogue).then_some((press.start, p, press.seed));
if response.drag_stopped() {
let press = self.detach.press.take().unwrap();
self.detach.tether = None;
if beyond && press.at.elapsed() < Duration::from_secs(30) {
self.query(Pending::Move { point: Some(p), grab: press.grab });
}
}
}
if response.clicked()
&& let Some(p) = pointer
&& !dialogue
{
let local_p = p - origin.to_vec2();
let (u, v) = ((local_p.x - rect.min.x) / rect.width(), (local_p.y - rect.min.y) / rect.height());
let opaque = |u: f32, v: f32| self.detach.sprites.textures.get(&frame).is_some_and(|t| t.alpha.opaque(u, v));
if let Some(part) = body::part_at(u, v, opaque, &frame) {
self.tap(part, p, false);
}
}
self.tap_effects(&painter, origin);
let _ = ctx.input(|i| i.pointer.hover_pos()).map(|_| ctx.request_repaint_after(Duration::from_millis(100)));
hits
}
/// Mini composer under the desktop avatar: shown near the pointer, with a draft or focus.
fn composer_ui(&mut self, ctx: &egui::Context) {
let Some(place) = self.detach.place.clone() else { return };
let body = self.detach.body(&place);
let work = self.detach.area;
let size = egui::vec2(344.0, 44.0);
let mut min = Pos2::new(body.center().x - size.x / 2.0, body.max.y + 8.0);
if min.y + size.y > work.max.y {
min.y = body.min.y - 8.0 - size.y - 40.0;
}
min.x = min.x.clamp(work.min.x, work.max.x - size.x);
min.y = min.y.clamp(work.min.y, work.max.y - size.y);
let rect = Rect::from_min_size(min, size);
let ppp = ctx.pixels_per_point();
let cursor = self.desktop.as_ref().and_then(|d| d.cursor()).map(|(x, y)| Pos2::new(x as f32, y as f32) / ppp);
let near = cursor.is_some_and(|c| rect.expand(90.0).contains(c));
let builder = ViewportBuilder::default()
.with_title(COMPOSER)
.with_position(min)
.with_inner_size(size)
.with_transparent(true)
.with_decorations(false)
.with_resizable(false)
.with_taskbar(false)
.with_active(false)
.with_window_level(egui::WindowLevel::AlwaysOnTop)
.with_window_type(egui::X11WindowType::Utility);
let mut send = None;
let mut toggle_panel = false;
let busy = self.engine.busy();
let show = near || !self.detach.draft.is_empty() || ctx.input_for(ViewportId::from_hash_of(COMPOSER), |i| i.focused);
let draft = &mut self.detach.draft;
let moved = self.detach.composer_pos != Some(min);
self.detach.composer_pos = Some(min);
ctx.show_viewport_immediate(ViewportId::from_hash_of(COMPOSER), builder, |ui, _| {
if moved {
ui.ctx().send_viewport_cmd(egui::ViewportCommand::OuterPosition(min));
}
if !show {
return;
}
theme::composer_frame().show(ui, |ui| {
ui.horizontal(|ui| {
let edit = ui.add(egui::TextEdit::singleline(draft).hint_text(t("Talk to Capri…")).desired_width(250.0).char_limit(capri_agent::engine::MAX_INPUT));
if edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
send = Some(std::mem::take(draft));
edit.request_focus();
}
if ui.add_enabled(!busy, egui::Button::new(RichText::new("↗").color(theme::cyan()))).on_hover_text(t("Send (Enter)")).clicked() {
send = Some(std::mem::take(draft));
}
if ui.button("≡").on_hover_text(t("Show Capri")).clicked() {
toggle_panel = true;
}
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
draft.clear();
}
});
});
});
if let Some(text) = send {
self.send_text(ctx, text);
}
if toggle_panel {
if self.hidden { self.hidden = false } else { self.hide() }
}
if let Some(x) = self.x11.clone() {
if self.detach.composer.is_none() {
self.detach.composer = x.find_own(COMPOSER);
if let Some(w) = self.detach.composer {
let _ = x.pin(w, true);
}
}
if let Some(w) = self.detach.composer {
let rects = if show { vec![[0, 0, (size.x * ppp).ceil() as i32, (size.y * ppp).ceil() as i32]] } else { vec![] };
if self.detach.composer_shape.as_ref() != Some(&rects) {
let _ = x.set_input(w, &rects);
self.detach.composer_shape = Some(rects);
}
}
}
if !show {
ctx.request_repaint_after(Duration::from_millis(100));
}
}
}
fn px(r: Rect, ppp: f32) -> x11::Px {
[(r.min.x * ppp).floor() as i32, (r.min.y * ppp).floor() as i32, (r.width() * ppp).ceil() as i32, (r.height() * ppp).ceil() as i32]
}