capri-ui: add dock module
This commit is contained in:
1 file changed
+322
@@ -0,0 +1,322 @@
|
||||
//! Docking ("perching") geometry (ported from Capri's `avatar-docking.mjs`), random destinations and
|
||||
//! the avatar movement commands.
|
||||
use eframe::egui::{Pos2, Rect};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
Seat,
|
||||
Ceiling,
|
||||
Left,
|
||||
Right,
|
||||
Floor,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Edge {
|
||||
Top,
|
||||
Bottom,
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Dock {
|
||||
pub kind: Kind,
|
||||
pub edge: Edge,
|
||||
pub fraction: f32,
|
||||
pub distance: f32,
|
||||
/// The window or display rectangle the dock belongs to.
|
||||
pub bounds: Rect,
|
||||
pub display: bool,
|
||||
}
|
||||
|
||||
/// A monitor and its work area (bounds minus panels), in logical px.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Display {
|
||||
pub bounds: Rect,
|
||||
pub work: Rect,
|
||||
}
|
||||
|
||||
fn contains(r: Rect, p: Pos2) -> bool {
|
||||
p.x >= r.min.x && p.x < r.max.x && p.y >= r.min.y && p.y < r.max.y
|
||||
}
|
||||
|
||||
pub fn nearest(point: Pos2, bounds: Rect, radius: f32, display: bool) -> Option<Dock> {
|
||||
if radius <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let fx = (point.x - bounds.min.x) / bounds.width();
|
||||
let fy = (point.y - bounds.min.y) / bounds.height();
|
||||
let dock = |kind, edge, fraction, distance: f32| Dock { kind, edge, fraction, distance, bounds, display };
|
||||
let mut options = Vec::new();
|
||||
if (0.04..=0.96).contains(&fx) {
|
||||
options.push(dock(if display { Kind::Ceiling } else { Kind::Seat }, Edge::Top, fx, (point.y - bounds.min.y).abs()));
|
||||
if !display {
|
||||
options.push(dock(Kind::Ceiling, Edge::Bottom, fx, (point.y - bounds.max.y).abs()));
|
||||
}
|
||||
}
|
||||
if (0.04..=0.96).contains(&fy) {
|
||||
options.push(dock(Kind::Left, Edge::Left, fy, (point.x - bounds.min.x).abs()));
|
||||
options.push(dock(Kind::Right, Edge::Right, fy, (point.x - bounds.max.x).abs()));
|
||||
}
|
||||
// Stable sort: the first of equally near edges wins, as in Capri.
|
||||
options.into_iter().filter(|d| d.distance <= radius).fold(None, |best: Option<Dock>, d| match best {
|
||||
Some(b) if b.distance <= d.distance => Some(b),
|
||||
_ => Some(d),
|
||||
})
|
||||
}
|
||||
|
||||
/// Contact point of a dock on its rectangle.
|
||||
pub fn dock_point(d: &Dock) -> Pos2 {
|
||||
let b = d.bounds;
|
||||
Pos2::new(
|
||||
match d.edge {
|
||||
Edge::Left => b.min.x,
|
||||
Edge::Right => b.max.x,
|
||||
_ => b.min.x + b.width() * d.fraction,
|
||||
}
|
||||
.round(),
|
||||
match d.edge {
|
||||
Edge::Top => b.min.y,
|
||||
Edge::Bottom => b.max.y,
|
||||
_ => b.min.y + b.height() * d.fraction,
|
||||
}
|
||||
.round(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn in_reserved(point: Pos2, display: &Display) -> bool {
|
||||
contains(display.bounds, point) && !contains(display.work, point)
|
||||
}
|
||||
|
||||
/// An underside coincident with a panel or the monitor floor has nowhere to hang.
|
||||
pub fn visible(d: &Dock, contact: Pos2, work: Rect) -> bool {
|
||||
contact.x >= work.min.x - 1.0
|
||||
&& contact.x <= work.max.x + 1.0
|
||||
&& contact.y >= work.min.y - 1.0
|
||||
&& contact.y <= work.max.y + 1.0
|
||||
&& (d.edge != Edge::Bottom || d.kind == Kind::Floor || contact.y < work.max.y - 2.0)
|
||||
}
|
||||
|
||||
pub fn nearest_display(point: Pos2, display: &Display, radius: f32) -> Option<Dock> {
|
||||
if radius <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let reserved = in_reserved(point, display);
|
||||
let (bounds, work) = (display.bounds, display.work);
|
||||
let edge = if reserved { None } else { nearest(point, bounds, radius, true) };
|
||||
let visible_edge = edge.filter(|e| visible(e, dock_point(e), work));
|
||||
let bottom = work.max.y;
|
||||
let fraction = (point.x - work.min.x) / work.width();
|
||||
let distance = if reserved && point.y >= bottom { (point.y - bottom).min((point.y - bounds.max.y).abs()) } else { (point.y - bottom).abs() };
|
||||
if (!reserved || point.y >= bottom)
|
||||
&& (0.04..=0.96).contains(&fraction)
|
||||
&& distance <= radius
|
||||
&& visible_edge.is_none_or(|e| distance < e.distance)
|
||||
{
|
||||
return Some(Dock { kind: Kind::Floor, edge: Edge::Bottom, fraction, distance, bounds: work, display: true });
|
||||
}
|
||||
visible_edge
|
||||
}
|
||||
|
||||
/// Reviewed pose for a dock.
|
||||
pub fn pose(d: &Dock) -> &'static str {
|
||||
let sprite_to_right = (d.edge == Edge::Right) != d.display;
|
||||
match d.kind {
|
||||
Kind::Floor => "pose-sit-floor",
|
||||
Kind::Seat => "pose-sit-edge",
|
||||
Kind::Ceiling if d.display => "pose-ceiling-upside-down",
|
||||
Kind::Ceiling => "pose-ceiling",
|
||||
_ if sprite_to_right => "pose-dock-left",
|
||||
_ => "pose-dock-right",
|
||||
}
|
||||
}
|
||||
|
||||
/// Free landing for "leave the frame": the sprite square top-left inside the work area,
|
||||
/// clear of the companion window and far enough from where she left.
|
||||
pub fn random_landing(work: Rect, size: f32, owner: Rect, origin: Pos2, mut random: impl FnMut() -> f32) -> Pos2 {
|
||||
let inset = 18f32.min(work.width() * 0.04).min(work.height() * 0.04);
|
||||
let (x0, y0) = (work.min.x + inset, work.min.y + inset);
|
||||
let (x1, y1) = ((work.max.x - inset - size).max(x0), (work.max.y - inset - size).max(y0));
|
||||
let gap = 180f32.min(0.29 * work.width().hypot(work.height()));
|
||||
let mut candidates: Vec<Pos2> = (0..24).map(|_| Pos2::new(x0 + (x1 - x0) * random(), y0 + (y1 - y0) * random())).collect();
|
||||
candidates.extend([Pos2::new(x0, y0), Pos2::new(x1, y0), Pos2::new(x0, y1), Pos2::new(x1, y1)]);
|
||||
let score = |p: &Pos2| {
|
||||
let clear = !Rect::from_min_size(*p, [size, size].into()).intersects(owner);
|
||||
let distance = (*p + eframe::egui::vec2(size / 2.0, size / 2.0) - origin).length();
|
||||
(clear, distance)
|
||||
};
|
||||
candidates
|
||||
.iter()
|
||||
.find(|p| matches!(score(p), (true, d) if d >= gap))
|
||||
.copied()
|
||||
.unwrap_or_else(|| *candidates.iter().max_by(|a, b| {
|
||||
let s = |p| { let (c, d) = score(p); d + if c { gap } else { 0.0 } };
|
||||
s(a).total_cmp(&s(b))
|
||||
}).unwrap())
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum AvatarCommand {
|
||||
Return,
|
||||
Perch { title: String },
|
||||
}
|
||||
|
||||
fn strip_prefix_any<'a>(s: &'a str, prefixes: &[&str]) -> Option<&'a str> {
|
||||
prefixes.iter().find_map(|p| s.strip_prefix(p))
|
||||
}
|
||||
|
||||
fn opt<'a>(s: &'a str, prefixes: &[&str]) -> &'a str {
|
||||
strip_prefix_any(s, prefixes).unwrap_or(s)
|
||||
}
|
||||
|
||||
/// Recognizes "return to your frame" / "sit on the <title> window" (English and Russian),
|
||||
/// checked before inference. Questions and longer sentences do not match.
|
||||
// TODO: add NFKC normalization (needs unicode-normalization) if compatibility forms show up.
|
||||
pub fn parse_command(text: &str) -> Option<AvatarCommand> {
|
||||
let mut s = text.trim().trim_end_matches(['.', '!', '?', '…']).to_lowercase();
|
||||
for vocative in ["capri", "капри"] {
|
||||
if let Some(rest) = s.strip_prefix(vocative)
|
||||
&& rest.starts_with([' ', ',', ':', '!'])
|
||||
{
|
||||
s = rest.trim_start_matches([' ', ',', ':', '!']).to_string();
|
||||
}
|
||||
}
|
||||
if let Some(rest) = s.strip_prefix("please ") {
|
||||
s = rest.to_string();
|
||||
} else if let Some(rest) = s.strip_prefix("пожалуйста") && rest.starts_with([',', ' ']) {
|
||||
s = rest.trim_start_matches([',', ' ']).to_string();
|
||||
}
|
||||
for suffix in [", please", " please", ", пожалуйста", " пожалуйста"] {
|
||||
if let Some(rest) = s.strip_suffix(suffix) {
|
||||
s = rest.to_string();
|
||||
break;
|
||||
}
|
||||
}
|
||||
let s = s.trim();
|
||||
if let Some(rest) = strip_prefix_any(s, &["return ", "go back ", "come back ", "teleport back "]) {
|
||||
let target = strip_prefix_any(rest, &["to ", "into "]).and_then(|r| strip_prefix_any(r, &["your ", "the "]));
|
||||
if rest == "home" || target.is_some_and(|t| t == "frame" || t == "window") {
|
||||
return Some(AvatarCommand::Return);
|
||||
}
|
||||
}
|
||||
if let Some(rest) = strip_prefix_any(s, &["вернись", "возвращайся", "телепортируйся обратно"]) {
|
||||
let rest = rest.trim_start();
|
||||
let place = opt(rest, &["обратно "]);
|
||||
let place = match place.strip_prefix("в ") {
|
||||
Some(p) => opt(p, &["свое ", "своё ", "свою "]),
|
||||
None => place,
|
||||
};
|
||||
if rest.is_empty() || ["окно", "окошко", "рамку", "к себе", "домой", "на место"].contains(&place) {
|
||||
return Some(AvatarCommand::Return);
|
||||
}
|
||||
}
|
||||
let perch = |title: &str| Some(AvatarCommand::Perch { title: title.trim_matches(['«', '»', '"', '\'']).chars().take(160).collect() });
|
||||
if let Some(rest) = strip_prefix_any(s, &["sit on ", "perch on "]) {
|
||||
let w = opt(opt(opt(rest, &["top of "]), &["the "]), &["active ", "current "]);
|
||||
if let Some(title) = w.strip_prefix("window") && (title.is_empty() || title.starts_with(' ')) {
|
||||
return perch(title.trim());
|
||||
}
|
||||
let named = opt(opt(rest, &["top of "]), &["the "]);
|
||||
if let Some(title) = named.strip_suffix(" window") && !title.is_empty() {
|
||||
return perch(title);
|
||||
}
|
||||
}
|
||||
if let Some(rest) = strip_prefix_any(s, &["сядь на ", "присядь на ", "посиди на "]) {
|
||||
let w = opt(opt(rest, &["край ", "верх "]), &["активное ", "активном ", "текущее ", "текущем "]);
|
||||
if let Some(title) = strip_prefix_any(w, &["окно", "окне"]) && (title.is_empty() || title.starts_with(' ')) {
|
||||
let title = title.trim();
|
||||
let alias = match title {
|
||||
"хром" | "хрома" | "гугл хром" | "гугл хрома" => "chrome",
|
||||
"блокнот" | "блокнота" => "notepad",
|
||||
"дискорд" | "дискорда" => "discord",
|
||||
"проводник" | "проводника" => "explorer",
|
||||
t => t,
|
||||
};
|
||||
return perch(alias);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Fixed replies, Russian when the conversation language is `ru`.
|
||||
pub fn command_reply(command: &AvatarCommand, ok: bool, russian: bool) -> &'static str {
|
||||
match (command, ok, russian) {
|
||||
(AvatarCommand::Return, true, false) => "I’m back in my frame.",
|
||||
(AvatarCommand::Return, true, true) => "Я снова в рамке.",
|
||||
(AvatarCommand::Return, false, false) => "I couldn’t get back to my frame.",
|
||||
(AvatarCommand::Return, false, true) => "Не получилось вернуться.",
|
||||
(AvatarCommand::Perch { .. }, true, false) => "I’m perched on the window.",
|
||||
(AvatarCommand::Perch { .. }, true, true) => "Я на краю окна.",
|
||||
(AvatarCommand::Perch { .. }, false, false) => "I couldn’t find an open window to perch on.",
|
||||
(AvatarCommand::Perch { .. }, false, true) => "Не нашла подходящего открытого окна.",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn r(x: f32, y: f32, w: f32, h: f32) -> Rect {
|
||||
Rect::from_min_size(Pos2::new(x, y), [w, h].into())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_edges() {
|
||||
let win = r(100.0, 100.0, 400.0, 300.0);
|
||||
let top = nearest(Pos2::new(300.0, 110.0), win, 36.0, false).unwrap();
|
||||
assert_eq!((top.kind, top.edge), (Kind::Seat, Edge::Top));
|
||||
assert_eq!(dock_point(&top), Pos2::new(300.0, 100.0));
|
||||
assert_eq!(pose(&top), "pose-sit-edge");
|
||||
let under = nearest(Pos2::new(300.0, 420.0), win, 36.0, false).unwrap();
|
||||
assert_eq!((under.kind, pose(&under)), (Kind::Ceiling, "pose-ceiling"));
|
||||
let right = nearest(Pos2::new(510.0, 250.0), win, 36.0, false).unwrap();
|
||||
assert_eq!((right.kind, pose(&right)), (Kind::Right, "pose-dock-left"));
|
||||
assert!(nearest(Pos2::new(300.0, 101.0), win, 36.0, false).is_some_and(|d| d.distance == 1.0));
|
||||
assert!(nearest(Pos2::new(300.0, 250.0), win, 36.0, false).is_none(), "middle of the window");
|
||||
assert!(nearest(Pos2::new(103.0, 60.0), win, 50.0, false).is_none(), "corner fraction < 0.04");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_edges_and_floor() {
|
||||
let display = Display { bounds: r(0.0, 0.0, 1920.0, 1200.0), work: r(0.0, 0.0, 1920.0, 1156.0) };
|
||||
let floor = nearest_display(Pos2::new(900.0, 1140.0), &display, 36.0).unwrap();
|
||||
assert_eq!((floor.kind, pose(&floor)), (Kind::Floor, "pose-sit-floor"));
|
||||
// A drop on the bottom panel still lands on the floor above it.
|
||||
let panel = nearest_display(Pos2::new(900.0, 1180.0), &display, 36.0).unwrap();
|
||||
assert_eq!(panel.kind, Kind::Floor);
|
||||
let ceiling = nearest_display(Pos2::new(900.0, 5.0), &display, 36.0).unwrap();
|
||||
assert_eq!(pose(&ceiling), "pose-ceiling-upside-down");
|
||||
let left = nearest_display(Pos2::new(3.0, 600.0), &display, 36.0).unwrap();
|
||||
assert_eq!(pose(&left), "pose-dock-left");
|
||||
assert!(nearest_display(Pos2::new(900.0, 600.0), &display, 36.0).is_none());
|
||||
// A window underside on the panel edge is invisible.
|
||||
let d = Dock { kind: Kind::Ceiling, edge: Edge::Bottom, fraction: 0.5, distance: 0.0, bounds: r(0.0, 0.0, 10.0, 1156.0), display: false };
|
||||
assert!(!visible(&d, Pos2::new(5.0, 1156.0), display.work));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destinations() {
|
||||
let area = r(0.0, 0.0, 1920.0, 1200.0);
|
||||
let owner = r(1400.0, 500.0, 480.0, 660.0);
|
||||
let mut n = 0.0f32;
|
||||
let landing = random_landing(area, 200.0, owner, Pos2::new(1640.0, 800.0), || { n = (n + 0.37) % 1.0; n });
|
||||
assert!(!Rect::from_min_size(landing, [200.0, 200.0].into()).intersects(owner));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn commands() {
|
||||
use AvatarCommand::*;
|
||||
assert_eq!(parse_command("Capri, return to your frame please."), Some(Return));
|
||||
assert_eq!(parse_command("go back home"), Some(Return));
|
||||
assert_eq!(parse_command("Вернись в своё окно!"), Some(Return));
|
||||
assert_eq!(parse_command("вернись"), Some(Return));
|
||||
assert_eq!(parse_command("can you return to your frame?"), None);
|
||||
assert_eq!(parse_command("sit on the active window"), Some(Perch { title: String::new() }));
|
||||
assert_eq!(parse_command("perch on window Firefox"), Some(Perch { title: "firefox".into() }));
|
||||
assert_eq!(parse_command("sit on top of the Dolphin window"), Some(Perch { title: "dolphin".into() }));
|
||||
assert_eq!(parse_command("сядь на окно хрома"), Some(Perch { title: "chrome".into() }));
|
||||
assert_eq!(parse_command("tell me about windows"), None);
|
||||
assert_eq!(command_reply(&Return, true, false), "I’m back in my frame.");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user