Files
capri-core-rust/crates/capri-ui/src/lib.rs
T
2026-11-11 20:20:48 +01:00

1142 lines
50 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Capri's desktop shell (egui): companion window, settings window, detached desktop avatar,
//! minimized chip and tray. See README.md "Integration" for the public API.
mod avatar;
mod body;
mod desktop;
mod detach;
mod dock;
mod fx;
mod geom;
mod hooks;
mod overlay;
mod pages;
pub mod i18n;
mod settings;
mod settings_window;
mod sound;
mod teleport;
mod theme;
mod tray;
mod x11;
use std::path::PathBuf;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::Result;
use capri_agent::{Engine, JournalMessage, TurnEvent};
use capri_core::{fsutil, Settings, SettingsStore};
use eframe::egui::{self, Align, Color32, Key, Layout, Pos2, Rect, RichText, Stroke, ViewportBuilder, ViewportCommand, ViewportId};
use tokio::sync::watch;
pub use dock::{parse_command as avatar_command, AvatarCommand};
pub use hooks::{Attachments, Command, ControlOverlay, Stopwatch, UiHandle, Wake};
pub use settings::{Theme, UiSettings};
use avatar::Avatar;
use fx::Signal;
use i18n::{t, tf};
/// A settings page contributed by a feature crate (voice, memory, tools, models...).
/// `section` is a Capri section id (`models`, `microphone`, `voice`, `knowledge`, `files`...):
/// a known id replaces Capri's placeholder there, any other id gets its own entry.
pub struct SettingsPage {
pub section: String,
pub title: String,
pub draw: Box<dyn FnMut(&mut egui::Ui) + Send>,
}
const WINDOW_SIZE: [f32; 2] = [480.0, 660.0];
#[derive(serde::Serialize, serde::Deserialize)]
struct WindowState {
x: f32,
y: f32,
}
/// Tap sequence: same part (or asleep) within the gap continues the count.
struct Taps {
part: String,
count: u32,
at: Instant,
}
pub(crate) struct App {
rt: tokio::runtime::Handle,
engine: Arc<Engine>,
store: Arc<SettingsStore>,
settings_rx: watch::Receiver<Settings>,
pub(crate) cfg: settings::UiSettings,
interface: String,
pub(crate) ui: UiHandle,
events: Receiver<TurnEvent>,
sender: Sender<TurnEvent>,
pub(crate) input: String,
pub(crate) reply: String,
reply_done: Option<Instant>,
reply_hover: bool,
/// Subtitle page shown, when it appeared, and whether the owner stepped manually.
reply_page: usize,
page_shown: Instant,
page_paused: bool,
/// The owner hid this reply ("Hide reply"); cleared by the next turn.
reply_collapsed: bool,
notice: Option<String>,
thinking: bool,
tool: Option<String>,
show_history: bool,
history: Vec<JournalMessage>,
pub(crate) avatar: Avatar,
window_file: PathBuf,
saved_pos: Option<Pos2>,
started: Instant,
pub(crate) epoch: Instant,
pinned_on_top: Option<bool>,
pub(crate) x11: Option<Arc<x11::X11>>,
pub(crate) desktop: Option<Arc<desktop::Desktop>>,
own_window: Option<u32>,
shape: Option<Vec<x11::Px>>,
hits: Vec<Rect>,
pub(crate) hidden: bool,
pub(crate) focus: bool,
burst_at: f64,
last_signal: Signal,
taps: Option<Taps>,
spark: Option<(Pos2, Instant, &'static str, u32)>,
headpat: Option<(Pos2, Instant)>,
dimming: Option<(egui::TextureHandle, [u32; 4])>,
pub(crate) detach: detach::Detach,
pub(crate) settings_ui: settings_window::SettingsUi,
chip: chip::Chip,
tray: tray::TrayHandle,
tray_state: (bool, bool, bool),
pub(crate) sounds: sound::Sounds,
reduced_system: bool,
pub(crate) pages: Vec<SettingsPage>,
}
mod chip;
/// KDE's "animation speed: instant" (`AnimationDurationFactor=0`) means reduced motion.
// TODO: kdeglobals is read once; use the settings portal `reduced-motion` key with change signals.
fn system_reduced_motion() -> bool {
let Some(home) = std::env::var_os("HOME") else { return false };
std::fs::read_to_string(PathBuf::from(home).join(".config/kdeglobals")).is_ok_and(|s| s.lines().any(|l| l.replace(' ', "") == "AnimationDurationFactor=0"))
}
fn saved_position(file: &std::path::Path) -> Option<Pos2> {
let bytes = fsutil::read_regular(file, 4096).ok()??;
let state: WindowState = serde_json::from_slice(&bytes).ok()?;
Some(Pos2::new(state.x, state.y))
}
impl App {
fn new(cc: &eframe::CreationContext, rt: tokio::runtime::Handle, engine: Arc<Engine>, store: Arc<SettingsStore>, pages: Vec<SettingsPage>, ui: UiHandle) -> Self {
let ctx = cc.egui_ctx.clone();
let _ = ui.0.ctx.set(ctx.clone());
let settings = store.get();
let cfg = settings.section::<settings::UiSettings>().sanitized();
i18n::set_locale(&settings.language.interface);
theme::install_fonts(&ctx, &settings.language.interface);
theme::apply(&ctx, &cfg.interface_theme);
let reduced_system = system_reduced_motion();
let (sender, events) = channel();
let history = engine.history();
let reply = history.iter().rev().find(|m| m.role == "assistant" && m.status == "complete").map(|m| m.text.clone()).unwrap_or_default();
let intro = cfg.startup_intro && !cfg.start_hidden && !cfg.reduced(reduced_system);
let mut avatar = Avatar::new(engine.catalog().clone(), ctx.clone(), intro);
if let Some(id) = history.iter().rev().find_map(|m| m.avatar.as_ref().map(|a| a.id.clone())) {
avatar.set_expression(&id);
}
// Load the model in the background so the first reply is fast.
let warm = engine.clone();
rt.spawn(async move {
if let Err(e) = warm.warm_up().await {
tracing::warn!("warm-up failed: {e:#}");
}
});
let x11 = match x11::X11::connect() {
Ok(x) => Some(Arc::new(x)),
Err(e) => {
tracing::warn!("no X11 connection, click-through and docking are off: {e:#}");
None
}
};
let desktop = x11.clone().map(|x| rt.block_on(desktop::Desktop::new(x)));
if let Some(d) = &desktop {
tracing::info!("desktop backend: {:?}", d.backend);
}
let icon = avatar::install_root(engine.catalog()).and_then(|r| std::fs::read(r.join("assets/default/icon-source.png")).ok()).unwrap_or_else(|| capri_core::avatar::DEFAULT_AVATAR_PNG.to_vec());
let tray = tray::spawn(&rt, ui.clone(), &icon);
let window_file = store.paths().state().join("companion-window.json");
let detach = detach::Detach::new(engine.catalog(), ctx.clone());
Self {
notice: engine.history_warning(),
settings_rx: store.subscribe(),
interface: settings.language.interface.clone(),
rt,
engine,
store,
hidden: cfg.start_hidden,
cfg,
ui,
events,
sender,
input: String::new(),
reply,
reply_done: Some(Instant::now()),
reply_hover: false,
reply_page: 0,
page_shown: Instant::now(),
page_paused: false,
reply_collapsed: false,
thinking: false,
tool: None,
show_history: false,
history,
avatar,
saved_pos: saved_position(&window_file),
window_file,
started: Instant::now(),
epoch: Instant::now(),
pinned_on_top: None,
x11,
desktop,
own_window: None,
shape: None,
hits: Vec::new(),
focus: false,
burst_at: -1e9,
last_signal: Signal::Online,
taps: None,
spark: None,
headpat: None,
dimming: None,
detach,
settings_ui: Default::default(),
chip: Default::default(),
tray,
tray_state: (false, false, true),
sounds: sound::Sounds::new(),
reduced_system,
pages,
}
}
pub(crate) fn now_ms(&self) -> f64 {
self.epoch.elapsed().as_secs_f64() * 1000.0
}
pub(crate) fn reduced(&self) -> bool {
self.cfg.reduced(self.reduced_system)
}
pub(crate) fn set_cfg(&mut self, change: impl FnOnce(&mut settings::UiSettings)) {
let mut next = self.cfg.clone();
change(&mut next);
let next = next.sanitized();
if let Err(e) = self.store.set_section(&next) {
self.notice = Some(format!("{}: {e}", t("Settings could not be saved.")));
}
}
/// Applies settings changed by the Settings window or another process.
fn sync_settings(&mut self, ctx: &egui::Context) {
if !self.settings_rx.has_changed().unwrap_or(false) {
return;
}
let settings = self.settings_rx.borrow_and_update().clone();
let cfg = settings.section::<settings::UiSettings>().sanitized();
if cfg.interface_theme != self.cfg.interface_theme {
theme::apply(ctx, &cfg.interface_theme);
}
if cfg.launch_at_login != self.cfg.launch_at_login
&& let Err(e) = settings_window::set_autostart(cfg.launch_at_login)
{
self.notice = Some(e.to_string());
}
if settings.language.interface != self.interface {
self.interface = settings.language.interface.clone();
i18n::set_locale(&self.interface);
theme::install_fonts(ctx, &self.interface);
}
self.cfg = cfg;
}
pub(crate) fn send_text(&mut self, ctx: &egui::Context, text: String) {
let text = text.trim().to_string();
if text.is_empty() || self.engine.busy() {
return;
}
self.notice = None;
self.avatar.skip_intro();
// Movement commands run before inference.
if let Some(command) = dock::parse_command(&text) {
self.run_avatar_command(command);
return;
}
self.reply.clear();
self.reply_done = None;
self.reply_page = 0;
self.page_shown = Instant::now();
self.page_paused = false;
self.reply_collapsed = false;
self.thinking = true;
self.tool = None;
let engine = self.engine.clone();
let sender = self.sender.clone();
let ctx = ctx.clone();
self.rt.spawn(async move {
let notify = |event| {
let _ = sender.send(event);
ctx.request_repaint();
};
if let Err(message) = engine.submit(&text, notify).await {
let _ = sender.send(TurnEvent::Failed { turn_id: String::new(), message, code: "CAPRI_INPUT".into() });
ctx.request_repaint();
}
});
}
fn send(&mut self, ctx: &egui::Context) {
if self.engine.busy() {
return;
}
let text = std::mem::take(&mut self.input);
self.send_text(ctx, text);
}
pub(crate) fn run_avatar_command(&mut self, command: AvatarCommand) {
let russian = self.store.get().language.conversation == "ru";
let ok = match &command {
AvatarCommand::Return => self.detach.request_return(),
AvatarCommand::Perch { title } => self.request_perch(title.clone()),
};
// TODO: the fixed reply is not stored in the transcript; needs an Engine API to append messages.
self.reply = dock::command_reply(&command, ok, russian).to_string();
self.reply_done = Some(Instant::now());
}
fn handle_events(&mut self) {
while let Ok(event) = self.events.try_recv() {
match event {
TurnEvent::Started { .. } => {}
TurnEvent::Tool { name, ok, .. } => self.tool = ok.is_none().then_some(name),
TurnEvent::Delta { text, .. } => {
self.thinking = false;
self.tool = None;
self.reply.push_str(&text);
self.avatar.speaking(true);
}
TurnEvent::Avatar { id, .. } => {
self.avatar.set_expression(&id);
self.request_burst();
}
TurnEvent::Completed { text, .. } => {
self.reply = text;
self.finish();
}
TurnEvent::Failed { message, .. } => {
self.notice = Some(message);
self.finish();
}
TurnEvent::Cancelled { .. } => {
self.notice = Some(t("Reply stopped."));
self.finish();
}
}
}
}
fn finish(&mut self) {
self.thinking = false;
self.tool = None;
self.reply_done = Some(Instant::now());
self.avatar.speaking(false);
self.history = self.engine.history();
}
fn request_burst(&mut self) {
if self.cfg.glitch_events {
let now = self.now_ms();
fx::request_burst(&mut self.burst_at, now);
}
}
pub(crate) fn signal(&self) -> Signal {
let s = self.ui.0.state.lock();
if s.sleeping {
Signal::Sleeping
} else if s.speaking {
Signal::Speaking
} else if self.engine.busy() {
if self.thinking { Signal::Thinking } else { Signal::Receiving }
} else if s.wake == Wake::Listening {
Signal::Listening
} else if !self.input.is_empty() {
Signal::Input
} else {
Signal::Online
}
}
pub(crate) fn status_text(&self) -> String {
match &self.tool {
Some(tool) => tf("Using {tool}…", &[("tool", tool)]),
None => t(self.signal().label()),
}
}
/// Commands from the tray and other crates.
fn handle_commands(&mut self, ctx: &egui::Context) {
for command in self.ui.take_commands() {
match command {
Command::Show => {
self.hidden = false;
self.focus = false;
}
Command::Hide => self.hide(),
Command::ToggleFocus => {
self.focus = !self.focus;
self.hidden = self.focus;
}
Command::Settings(section) => {
self.hidden = false;
self.settings_ui.open(section);
self.avatar.skip_intro();
}
Command::Teleport => {
self.hidden = false;
self.teleport();
}
Command::Return => {
self.detach.request_return();
}
Command::ResetPosition => self.reset_position(ctx),
Command::AlwaysOnTop(on) => self.set_cfg(|c| c.always_on_top = on),
Command::Avatar(command) => self.run_avatar_command(command),
Command::Notice(text) => self.notice = Some(text),
Command::Submit(text) => self.send_text(ctx, text),
Command::Quit => ctx.send_viewport_cmd(ViewportCommand::Close),
}
}
// Approvals need the owner: an arriving card reveals the companion.
if !self.ui.0.state.lock().cards.is_empty() && self.hidden && !self.focus {
self.hidden = false;
}
}
/// Hide to tray; when detached, the desktop avatar stays (avatar-only mode).
pub(crate) fn hide(&mut self) {
self.hidden = true;
self.show_history = false;
}
fn reset_position(&mut self, ctx: &egui::Context) {
let work = self.work_area(ctx);
let pos = Pos2::new(work.max.x - WINDOW_SIZE[0] - 16.0, work.max.y - WINDOW_SIZE[1] - 16.0);
ctx.send_viewport_cmd(ViewportCommand::OuterPosition(pos));
}
/// Work area of the companion's display in logical px (cached desktop snapshot, else the monitor).
pub(crate) fn work_area(&self, ctx: &egui::Context) -> Rect {
let center = self.companion_rect(ctx).center();
if let Some(d) = self.detach.displays(ctx.pixels_per_point()).into_iter().find(|d| d.bounds.contains(center)) {
return d.work;
}
let size = ctx.input(|i| i.viewport().monitor_size).unwrap_or(egui::vec2(1920.0, 1080.0));
Rect::from_min_size(Pos2::ZERO, size)
}
/// Companion window rectangle in desktop logical px.
pub(crate) fn companion_rect(&self, ctx: &egui::Context) -> Rect {
ctx.input_for(ViewportId::ROOT, |i| i.viewport().outer_rect).unwrap_or(Rect::from_min_size(Pos2::ZERO, WINDOW_SIZE.into()))
}
/// Applies window states once mapped, and again when "Always on top" changes.
fn pin(&mut self, frame: &eframe::Frame) {
if self.started.elapsed() < Duration::from_millis(300) || self.pinned_on_top == Some(self.cfg.always_on_top) {
return;
}
self.pinned_on_top = Some(self.cfg.always_on_top);
self.own_window = x11::window_id(frame);
if let (Some(x), Some(w)) = (&self.x11, self.own_window)
&& let Err(e) = x.pin(w, self.cfg.always_on_top)
{
tracing::warn!("cannot keep the companion above other windows: {e:#}");
}
}
/// Click-through outside the visible frame, controls and sprite.
fn apply_shape(&mut self, ctx: &egui::Context) {
let (Some(x), Some(window)) = (&self.x11, self.own_window) else { return };
// Never reshape a window that holds the pointer grab of a press.
if ctx.input(|i| i.pointer.any_down()) {
return;
}
let ppp = ctx.pixels_per_point();
let rects: Vec<x11::Px> = if self.hidden {
vec![]
} else {
self.hits.iter().map(|r| [(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]).collect()
};
if self.shape.as_ref() != Some(&rects) {
if let Err(e) = x.set_input(window, &rects) {
tracing::warn!("input shape: {e:#}");
}
self.shape = Some(rects);
}
}
fn header(&mut self, ui: &mut egui::Ui) {
let response = ui.interact(ui.max_rect(), ui.scope_id().with("drag"), egui::Sense::click_and_drag());
if response.drag_started() {
ui.ctx().send_viewport_cmd(ViewportCommand::StartDrag);
}
ui.horizontal(|ui| {
ui.label(RichText::new("CAPRI").color(theme::cyan()).strong().size(16.0));
let signal = self.signal();
let (rect, _) = ui.allocate_exact_size(egui::vec2(8.0, 8.0), egui::Sense::hover());
ui.painter().circle_filled(rect.center(), 3.5, signal.color());
ui.label(RichText::new(self.status_text()).color(theme::MUTED).size(11.0));
let stopwatch = self.ui.0.state.lock().stopwatch.clone();
if let Some((w, at)) = stopwatch {
let elapsed = w.elapsed + if w.running { at.elapsed() } else { Duration::ZERO };
let s = elapsed.as_secs();
let title = if w.title.is_empty() { t("Stopwatch") } else { w.title.clone() };
ui.label(RichText::new(format!("{:02}:{:02}:{:02}", s / 3600, s / 60 % 60, s % 60)).monospace().color(theme::ACID))
.on_hover_text(format!("{title} · {}", t(if w.running { "Running" } else { "Paused" })));
}
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if ui.button("✕").on_hover_text(t("Quit and unload models")).clicked() {
ui.ctx().send_viewport_cmd(ViewportCommand::Close);
}
if ui.button("–").on_hover_text(t(if self.detach.attached() { "Hide to tray" } else { "Hide interface" })).clicked() {
self.hide();
}
if ui.button("⚙").on_hover_text(t("Settings")).clicked() {
self.settings_ui.toggle();
self.avatar.skip_intro();
}
if ui.selectable_label(self.show_history, "☰").on_hover_text(t("Open conversation history")).clicked() {
self.show_history = !self.show_history;
}
self.audio_buttons(ui);
if self.avatar.animated() {
let (label, tip) = if self.detach.attached() { ("⇱", "Leave frame") } else { ("⇲", "Return to frame") };
if ui.add_enabled(self.detach.idle(), egui::Button::new(label)).on_hover_text(t(tip)).clicked() {
if self.detach.attached() { self.teleport() } else { self.detach.request_return(); }
}
}
if self.reply_hidden() && !self.reply.is_empty() && ui.button("»").on_hover_text(t("Show reply")).clicked() {
self.reply_done = Some(Instant::now());
}
});
});
}
fn composer(&mut self, ui: &mut egui::Ui) {
let wake = {
let s = self.ui.0.state.lock();
match s.wake {
Wake::Listening => Some("I'M LISTENING"),
Wake::Heard if s.wake_at.is_some_and(|a| a.elapsed() < Duration::from_millis(900)) => Some("HEARD YOU"),
_ => None,
}
};
if let Some(text) = wake {
ui.label(RichText::new(t(text)).color(theme::cyan()).size(10.0).strong());
}
let hook = self.ui.0.state.lock().attachments.clone();
if let Some(hook) = &hook {
let names = hook.names();
if !names.is_empty() {
ui.horizontal_wrapped(|ui| {
for name in names {
if ui.small_button(format!("{name} ×")).on_hover_text(tf("Remove {filename}", &[("filename", &name)])).clicked() {
hook.remove(&name);
}
}
});
}
}
ui.horizontal(|ui| {
let busy = self.engine.busy();
let button_width = 64.0;
let edit = egui::TextEdit::multiline(&mut self.input)
.hint_text(t("Talk to Capri…"))
.desired_rows(2)
.char_limit(capri_agent::engine::MAX_INPUT)
.desired_width(ui.available_width() - button_width - 8.0)
.return_key(None);
let response = ui.add(edit);
if response.changed() {
self.avatar.skip_intro();
}
// Enter sends; Shift+Enter inserts a new line.
if response.has_focus() && ui.input(|i| i.key_pressed(Key::Enter) && !i.modifiers.shift) {
self.input = self.input.trim_end_matches('\n').to_string();
self.send(ui.ctx());
response.request_focus();
}
if busy {
if ui.add_sized([button_width, 36.0], egui::Button::new(t("Stop"))).on_hover_text(t("Stop reply (Esc)")).clicked() {
self.engine.cancel();
}
} else if ui.add_sized([button_width, 36.0], egui::Button::new(RichText::new(t("Send")).color(theme::cyan()))).on_hover_text(t("Send (Enter)")).clicked() {
self.send(ui.ctx());
}
});
if self.engine.busy() && ui.input(|i| i.key_pressed(Key::Escape)) {
self.engine.cancel();
}
}
/// Completed replies hide after the configured delay unless hovered.
pub(crate) fn reply_hidden(&self) -> bool {
let delay = Duration::from_secs(self.cfg.reply_auto_hide_seconds as u64).max(Duration::from_millis(30 * self.reply.chars().count() as u64).min(Duration::from_secs(30)));
self.cfg.reply_auto_hide && !self.reply_hover && self.reply_done.is_some_and(|d| d.elapsed() > delay)
}
/// Microphone and spoken-reply switches (Capri: both off at every launch).
fn audio_buttons(&mut self, ui: &mut egui::Ui) {
let Some(audio) = self.ui.0.state.lock().audio.clone() else { return };
if icon_button(ui, audio.voice_on, Icon::Speaker).on_hover_text(t(if audio.voice_on { "Mute spoken replies" } else { "Speak replies" })).clicked() {
match (audio.voice)(!audio.voice_on) {
Ok(()) => self.ui.with_audio(|a| a.voice_on = !audio.voice_on),
Err(e) => self.notice = Some(e),
}
}
if icon_button(ui, audio.microphone_on, Icon::Microphone).on_hover_text(t(if audio.microphone_on { "Turn microphone off" } else { "Turn microphone on" })).clicked() {
match (audio.microphone)(!audio.microphone_on) {
Ok(()) => self.ui.with_audio(|a| a.microphone_on = !audio.microphone_on),
Err(e) => self.notice = Some(e),
}
}
}
fn bubble(&mut self, ui: &mut egui::Ui) {
if self.reply_collapsed && !self.reply.is_empty() {
let r = ui.with_layout(Layout::right_to_left(Align::Max), |ui| ui.small_button(t("Show reply")).clicked());
if r.inner {
self.reply_collapsed = false;
self.reply_done = Some(Instant::now());
}
self.hits.push(r.response.rect);
return;
}
let thinking = self.reply.is_empty() && self.thinking;
if (self.reply.is_empty() || self.reply_hidden()) && !thinking {
return;
}
// Capri shows the reply as short subtitle pages so the bubble never covers her.
let all = if thinking { vec!["…".to_string()] } else { pages::pages(&self.reply, pages::page_limit(ui.available_width() - 40.0)) };
let last = all.len().saturating_sub(1);
let streaming = self.reply_done.is_none();
if streaming && !self.page_paused {
self.reply_page = last; // follow the newest text while it streams
} else if !self.page_paused && self.reply_page < last && self.page_shown.elapsed() > Duration::from_millis(pages::reading_ms(&all[self.reply_page])) {
self.reply_page += 1;
self.page_shown = Instant::now();
}
self.reply_page = self.reply_page.min(last);
if self.reply_page < last {
// Auto-hide counts from the last page.
self.reply_done = self.reply_done.map(|_| Instant::now());
ui.ctx().request_repaint_after(Duration::from_millis(250));
}
let page = all[self.reply_page].clone();
let response = theme::reply_frame().show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
if ui.small_button("–").on_hover_text(t("Hide reply")).clicked() {
self.reply_collapsed = true;
}
ui.add(egui::Label::new(RichText::new(&page).color(theme::TEXT).size(17.0)).wrap());
});
});
if all.len() >= 2 {
ui.horizontal(|ui| {
if ui.add_enabled(self.reply_page > 0, egui::Button::new("‹").small()).on_hover_text(t("Previous part of this reply")).clicked() {
self.reply_page -= 1;
self.page_paused = true;
}
ui.label(RichText::new(format!("{} / {}", self.reply_page + 1, all.len())).size(11.0).color(theme::MUTED));
if ui.add_enabled(self.reply_page < last, egui::Button::new("›").small()).on_hover_text(t("Next part of this reply")).clicked() {
self.reply_page += 1;
self.page_paused = true;
}
});
}
});
self.reply_hover = response.response.contains_pointer();
if self.reply_hover {
self.reply_done = self.reply_done.map(|_| Instant::now());
}
self.hits.push(response.response.rect);
}
fn notices(&mut self, ui: &mut egui::Ui) {
let cards: Vec<(u64, String, String, Duration, bool, Duration)> = self.ui.0.state.lock().cards.iter().map(|c| (c.id, c.request.title.clone(), c.request.detail.clone(), c.expires.saturating_duration_since(Instant::now()), c.request.kind == hooks::DANGER_KIND, hooks::DANGER_DELAY.saturating_sub(c.created.elapsed()))).collect();
if let Some(overlay) = self.ui.0.state.lock().overlay.clone() {
let r = theme::notice_frame(true).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.label(RichText::new(t(&overlay.caption)).strong().color(theme::RED));
if ui.button(t("Stop computer control")).clicked()
&& let Some(stop) = self.ui.0.state.lock().stop_hook.clone()
{
stop();
}
});
});
self.hits.push(r.response.rect);
}
for (id, title, detail, left, danger, wait) in cards {
let r = theme::approval_frame().show(ui, |ui| {
ui.set_width(ui.available_width());
ui.label(RichText::new(t(&title)).strong().color(if danger { theme::RED } else { Color32::from_rgb(0xf5, 0xe9, 0x55) }));
egui::ScrollArea::vertical().max_height(170.0).id_salt(("approval", id)).show(ui, |ui| ui.label(RichText::new(&detail).monospace()));
let help = if left.as_secs() > 85 { t("Only approve actions you requested. This request expires in 90 seconds.") } else { tf("{seconds} s", &[("seconds", &left.as_secs().to_string())]) };
ui.label(RichText::new(help).size(10.0).color(theme::MUTED));
ui.horizontal(|ui| {
let label = if !danger {
t("Confirm")
} else if wait.is_zero() {
t("Give full computer access")
} else {
format!("{} ({})", t("Give full computer access"), wait.as_secs() + 1)
};
let button = egui::Button::new(if danger { RichText::new(label).color(theme::RED) } else { RichText::new(label) });
if ui.add_enabled(!danger || wait.is_zero(), button).clicked() {
self.ui.answer(id, true);
}
if ui.button(t("Cancel")).clicked() {
self.ui.answer(id, false);
}
});
});
self.hits.push(r.response.rect);
}
if let Some(notice) = self.notice.clone() {
let r = theme::notice_frame(false).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.horizontal(|ui| {
ui.label(RichText::new(t(&notice)).color(theme::NOTICE).size(11.0));
if ui.small_button("×").on_hover_text(t("Dismiss")).clicked() {
self.notice = None;
}
});
});
self.hits.push(r.response.rect);
}
}
fn history_view(&mut self, ui: &mut egui::Ui) {
let r = theme::panel_frame().show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new(t("Conversation history")).color(theme::cyan()).size(11.0));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if ui.small_button("×").on_hover_text(t("Close conversation history")).clicked() || ui.input(|i| i.key_pressed(Key::Escape)) {
self.show_history = false;
}
if ui.small_button("⟲").on_hover_text(t("Clear conversation")).clicked() {
match self.engine.reset_conversation() {
Ok(()) => {
self.reply.clear();
self.history.clear();
}
Err(e) => self.notice = Some(e.to_string()),
}
}
});
});
egui::ScrollArea::vertical().stick_to_bottom(true).show(ui, |ui| {
ui.set_width(ui.available_width());
if self.history.is_empty() {
ui.label(RichText::new(t("No messages yet.")).color(theme::MUTED));
}
for m in &self.history {
let (who, color) = if m.role == "user" { (t("You"), theme::cyan()) } else { ("Capri".to_string(), theme::pink()) };
ui.label(RichText::new(who).color(color).size(10.0));
let text = if m.text.is_empty() && m.status == "streaming" { t("Thinking…") } else { m.text.clone() };
ui.label(RichText::new(text).color(if m.role == "user" { Color32::from_rgb(0xbf, 0xcf, 0xd3) } else { theme::TEXT }));
match m.status.as_str() {
"interrupted" => drop(ui.label(RichText::new(t("Stopped")).size(9.0).color(theme::MUTED))),
"error" => drop(ui.label(RichText::new(t("Response incomplete")).size(9.0).color(theme::RED))),
_ => {}
}
ui.add_space(6.0);
}
});
});
self.hits.push(r.response.rect);
}
/// Taps on the portrait or the desktop avatar: count, spark, reaction frame.
/// `at` is in desktop logical px.
pub(crate) fn tap(&mut self, part: &'static str, at: Pos2, attached: bool) {
let sleeping = self.ui.0.state.lock().sleeping;
let gap = Duration::from_secs(self.cfg.avatar_tap_gap_seconds as u64);
let count = match &self.taps {
Some(s) if (sleeping || s.part == part) && s.at.elapsed() <= gap => (s.count + 1).min(11),
_ => 1,
};
self.taps = Some(Taps { part: part.into(), count, at: Instant::now() });
if sleeping {
return; // silent while asleep
}
let tone = body::tone(part);
if part == "head" && self.avatar.animated() {
if self.headpat.is_none_or(|(_, t)| t.elapsed() >= Duration::from_millis(220)) {
self.headpat = Some((at, Instant::now()));
}
} else {
self.spark = Some((at, Instant::now(), tone, count));
if attached {
self.avatar.react(tone);
}
}
if let Some(hook) = self.ui.0.state.lock().tap_hook.clone() {
hook(part, tone, count);
}
tracing::debug!("tap {part} ({tone}) x{count}");
}
/// Spark and hearts (stored in desktop px) over a surface whose top-left is `origin`.
pub(crate) fn tap_effects(&mut self, painter: &egui::Painter, origin: Pos2) {
let reduced = self.reduced();
if let Some((at, when, tone, count)) = self.spark {
let at = at - origin.to_vec2();
let age = when.elapsed().as_secs_f32() / 0.23;
if age >= 1.0 {
self.spark = None;
} else {
let color = match tone {
"curious" => Color32::from_rgb(0x8f, 0xf5, 0xff),
"neutral" => Color32::from_rgb(0xd9, 0xff, 0x96),
"affectionate" => Color32::from_rgb(0xff, 0x8f, 0xae),
_ => Color32::from_rgb(0xff, 0x00, 0x3d),
};
let size = (24.0 + count as f32 * 4.0).min(56.0) / 2.0;
let stepped = (age * 4.0).ceil() / 4.0;
let scale = if reduced { 1.0 } else if stepped < 0.62 { 0.45 + (1.04 - 0.45) * stepped / 0.62 } else { 1.04 + (1.3 - 1.04) * (stepped - 0.62) / 0.38 };
let r = size * scale;
let star: Vec<Pos2> = (0..8).map(|i| {
let a = i as f32 * std::f32::consts::FRAC_PI_4;
let k = if i % 2 == 0 { r } else { r * 0.32 };
at + egui::vec2(a.cos() * k, a.sin() * k)
}).collect();
geom::fill(painter, &star, color.gamma_multiply(1.0 - age * 0.7));
}
}
if let Some((at, when)) = self.headpat {
let at = at - origin.to_vec2();
let age = when.elapsed().as_secs_f32();
if age > 1.45 {
self.headpat = None;
} else {
const HEARTS: [(f32, f32, f32, f32, u32); 4] = [(24., -10., -46., 0., 0xff3e83), (17., 29., -36., 0.065, 0xffa7dc), (12., -34., -25., 0.135, 0xff1f63), (9., 15., -63., 0.18, 0xffe0f0)];
for (size, dx, dy, delay, rgb) in HEARTS {
let p = ((age - delay) / 1.04).clamp(0.0, 1.0);
if p <= 0.0 || p >= 1.0 {
continue;
}
let rise = if reduced { 0.0 } else { 1.0 - (1.0 - p).powi(3) };
let c = at + egui::vec2(dx * rise, dy * rise);
let color = Color32::from_rgb((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8).gamma_multiply(1.0 - p);
let s = size / 2.0;
painter.circle_filled(c + egui::vec2(-s * 0.5, -s * 0.2), s * 0.55, color);
painter.circle_filled(c + egui::vec2(s * 0.5, -s * 0.2), s * 0.55, color);
geom::fill(painter, &[c + egui::vec2(-s * 1.02, 0.0), c + egui::vec2(s * 1.02, 0.0), c + egui::vec2(0.0, s * 1.1)], color);
}
}
}
}
pub(crate) fn headpat_active(&self) -> bool {
self.headpat.is_some_and(|(_, t)| t.elapsed() < Duration::from_millis(1450))
}
/// Dimming shade behind the panel.
fn dim(&mut self, ui: &egui::Ui, area: Rect) {
if !self.cfg.dimming_enabled || self.cfg.dimming_level == 0 || area.width() < 1.0 {
return;
}
let key = [area.width() as u32, area.height() as u32, self.cfg.dimming_softness, 0];
if self.dimming.as_ref().is_none_or(|(_, k)| *k != key) {
let image = fx::dimming_image(area.width(), area.height(), self.cfg.dimming_softness as f32);
self.dimming = Some((ui.ctx().load_texture("dimming", image, egui::TextureOptions::LINEAR), key));
}
let (tex, _) = self.dimming.as_ref().unwrap();
let painter = ui.ctx().layer_painter(egui::LayerId::background());
painter.image(tex.id(), area, Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0)), Color32::WHITE.gamma_multiply(self.cfg.dimming_level as f32 / 100.0));
}
/// The framed portrait with its effects, taps and drag-out.
fn portrait(&mut self, ui: &mut egui::Ui, area: Rect) {
let now = self.now_ms();
let reduced = self.reduced();
let glitch = if self.cfg.glitch_enabled && !reduced && !self.avatar.intro_playing() {
fx::glitch(now, self.burst_at, self.cfg.glitch_strength as f32 / 100.0, self.cfg.glitch_interval_seconds as f64 * 1000.0, self.cfg.glitch_events)
} else {
fx::Glitch { strength: 0.0, x: 0.0, y: 0.0 }
};
let (mouth, music, sleeping) = {
let s = self.ui.0.state.lock();
(s.mouth, s.music_bpm, s.sleeping)
};
let dance = match music {
Some(bpm) if !reduced && !sleeping && !self.engine.busy() && self.input.is_empty() => fx::dance_angle(now, bpm, 1.0) * 3.0,
_ => 0.0,
};
let float = if self.cfg.float_enabled && !reduced && ui.input(|i| i.pointer.hover_pos()).is_none() { fx::float_offset(now, self.cfg.float_amplitude as f32, self.cfg.float_period_seconds as f32) } else { 0.0 };
let area = area.translate(egui::vec2(0.0, float));
let paint = avatar::Paint { crt: self.cfg.crt, glitch: glitch.strength, time: (now / 1000.0) as f32, reduced, mouth, dance, sleeping, headpat: self.headpat_active() };
self.avatar.paint(ui, area, &paint);
let Some(view) = self.avatar.view.clone() else { return };
let painter = ui.painter_at(area.expand(40.0));
// Frame damage ghosts while a glitch burst runs.
if glitch.strength > 0.04 {
for (color, k) in [(theme::cyan(), 1.0), (theme::pink(), -1.0)] {
painter.rect_stroke(area.shrink(4.0).translate(egui::vec2(glitch.x * k, glitch.y * k)), 0.0, Stroke::new(1.5, color.gamma_multiply(glitch.strength * 0.88)), egui::StrokeKind::Inside);
}
}
if sleeping {
let elapsed = self.epoch.elapsed().as_secs_f64() * 1000.0;
let caption = fx::sleep_caption(if reduced { 1500.0 } else { elapsed });
let p = Pos2::new((view.draw.min.x + view.draw.width() * 0.7).clamp(16.0, area.right() - 95.0), (view.draw.min.y + view.draw.height() * 0.12).max(area.top() + 8.0));
painter.text(p, egui::Align2::LEFT_TOP, caption, egui::FontId::proportional(22.0), crate::theme::VIOLET);
}
let origin = self.companion_rect(ui.ctx()).min;
self.tap_effects(&painter, origin);
if !self.detach.attached() || self.avatar.intro_playing() {
return;
}
let hit = view.draw.expand(12.0).intersect(area);
self.hits.push(hit);
let response = ui.interact(hit, ui.scope_id().with("sprite"), egui::Sense::click_and_drag());
if response.clicked() && let Some(p) = response.interact_pointer_pos() {
let (u, v) = view.to_canvas(p);
let part = if self.avatar.animated() { body::part_at(u, v, |u, v| view.opaque(u, v), &view.frame) } else { view.opaque(u, v).then_some("body") };
if let Some(part) = part {
self.tap(part, self.companion_rect(ui.ctx()).min + p.to_vec2(), true);
}
}
self.drag_out(ui.ctx(), &response, &view);
}
}
impl eframe::App for App {
fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
[0.0; 4]
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
let ctx = ui.ctx().clone();
self.sync_settings(&ctx);
self.handle_commands(&ctx);
self.handle_events();
self.pin(frame);
let signal = self.signal();
if signal != self.last_signal {
if matches!(signal, Signal::Thinking | Signal::Speaking) {
self.request_burst();
}
self.last_signal = signal;
}
let speaking = self.ui.0.state.lock().speaking;
self.avatar.speaking(speaking || matches!(signal, Signal::Receiving));
if ctx.input(|i| i.pointer.any_pressed() || !i.keys_down.is_empty()) {
self.avatar.skip_intro();
}
self.hits.clear();
if !self.hidden {
let full = ctx.content_rect();
let compact = !self.detach.attached();
if !compact {
self.dim(ui, full);
}
let header = egui::Panel::top("header").frame(theme::header_frame()).show(ui, |ui| self.header(ui));
self.hits.push(header.response.rect);
let composer = egui::Panel::bottom("composer").frame(theme::composer_frame()).show(ui, |ui| self.composer(ui));
self.hits.push(composer.response.rect);
egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| {
self.notices(ui);
if self.show_history {
self.history_view(ui);
return;
}
let rect = ui.available_rect_before_wrap();
if !compact {
self.portrait(ui, rect);
}
ui.with_layout(Layout::bottom_up(Align::Min), |ui| self.bubble(ui));
});
if compact {
let union = self.hits.iter().fold(Rect::NOTHING, |a, r| a.union(*r)).expand(12.0);
self.dim(ui, union);
}
// Dropped files go to the attachments feature.
let dropped: Vec<PathBuf> = ctx.input(|i| i.raw.dropped_files.iter().map(|f| f.path().to_path_buf()).filter(|p| !p.as_os_str().is_empty()).collect());
if !dropped.is_empty() && let Some(hook) = self.ui.0.state.lock().attachments.clone() {
hook.add(dropped);
}
}
self.apply_shape(&ctx);
self.remember_position(&ctx);
self.detached_ui(&ctx);
self.control_overlay(&ctx);
self.settings_window(&ctx);
if self.hidden && !self.focus && self.cfg.minimized_chip {
self.chip_ui(&ctx);
} else {
self.chip.close();
}
let state = (!self.detach.attached(), self.focus, self.cfg.always_on_top);
if state != self.tray_state {
self.tray_state = state;
self.ui.0.state.lock().tray = state;
tray::refresh(&self.rt, &self.tray);
}
let sleeping = self.ui.0.state.lock().sleeping;
let mut next = self.avatar.next_change(sleeping);
let animating = self.detach.animating() || self.spark.is_some() || self.headpat.is_some() || {
let s = self.ui.0.state.lock();
s.speaking || s.music_bpm.is_some() || s.wake != Wake::Off || s.stopwatch.as_ref().is_some_and(|(w, _)| w.running) || !s.cards.is_empty() || s.overlay.is_some()
};
if animating || self.thinking {
next = next.min(Duration::from_millis(if self.ui.0.state.lock().stopwatch.is_some() && !self.detach.animating() { 250 } else { 33 }));
}
if self.cfg.glitch_enabled && !self.reduced() {
next = next.min(Duration::from_millis(fx::glitch_wait_ms(self.now_ms(), self.burst_at, self.cfg.glitch_interval_seconds as f64 * 1000.0) as u64));
}
if self.hidden {
next = next.max(Duration::from_millis(250));
}
ctx.request_repaint_after(next);
}
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
if let Some(d) = self.desktop.clone() {
self.rt.block_on(d.stop());
}
}
}
impl App {
/// Saves the window position after the owner moves it.
fn remember_position(&mut self, ctx: &egui::Context) {
let Some(pos) = ctx.input(|i| i.viewport().outer_rect.map(|r| r.min)) else { return };
if self.started.elapsed() < Duration::from_secs(1) || self.saved_pos.is_some_and(|old| (old - pos).length() < 1.0) {
return;
}
self.saved_pos = Some(pos);
if let Err(e) = fsutil::write_json_atomic(&self.window_file, &WindowState { x: pos.x, y: pos.y }) {
tracing::warn!("cannot save window position: {e:#}");
}
}
}
/// Opens Capri's windows and blocks until quit. Wires the settings store to the engine and
/// `ui` as the engine's approval surface.
pub fn run(rt: tokio::runtime::Handle, engine: Arc<Engine>, store: Arc<SettingsStore>, pages: Vec<SettingsPage>, ui: UiHandle) -> Result<()> {
engine.set_approvals(Arc::new(ui.clone()));
let mut changes = store.subscribe();
let live = engine.clone();
rt.spawn(async move {
while changes.changed().await.is_ok() {
let settings = changes.borrow_and_update().clone();
live.update_settings(settings);
}
});
let window_file = store.paths().state().join("companion-window.json");
let mut viewport = ViewportBuilder::default()
.with_title("Capri")
.with_app_id("capri")
.with_inner_size(WINDOW_SIZE)
.with_resizable(false)
.with_transparent(true)
.with_decorations(false)
.with_has_shadow(false)
.with_taskbar(false)
.with_window_level(egui::WindowLevel::AlwaysOnTop)
.with_window_type(egui::X11WindowType::Utility);
if let Some(pos) = saved_position(&window_file) {
viewport = viewport.with_position(pos);
}
let options = eframe::NativeOptions {
viewport,
// X11 lets Capri place its windows and shape their input (XWayland on KDE Plasma Wayland).
event_loop_builder: Some(Box::new(|builder| {
use winit::platform::x11::EventLoopBuilderExtX11;
builder.with_x11();
})),
..Default::default()
};
eframe::run_native("capri", options, Box::new(move |cc| Ok(Box::new(App::new(cc, rt, engine, store, pages, ui)))))
.map_err(|e| anyhow::anyhow!("Cannot open the companion window: {e}"))
}
#[derive(Clone, Copy)]
enum Icon {
Microphone,
Speaker,
}
/// Header toggle with a drawn icon (the bundled fonts do not render these glyphs reliably).
/// Off draws the icon struck through.
fn icon_button(ui: &mut egui::Ui, on: bool, icon: Icon) -> egui::Response {
let size = egui::vec2(ui.spacing().interact_size.y, ui.spacing().interact_size.y);
let response = ui.add(egui::Button::new("").min_size(size).selected(on));
let r = response.rect.shrink(4.0);
let color = if on { theme::cyan() } else { theme::MUTED };
let stroke = egui::Stroke::new(1.5, color);
let p = ui.painter();
let c = r.center();
match icon {
Icon::Microphone => {
let capsule = egui::Rect::from_center_size(c - egui::vec2(0.0, r.height() * 0.12), egui::vec2(r.width() * 0.32, r.height() * 0.55));
p.rect_filled(capsule, r.width() * 0.16, color);
let arc: Vec<egui::Pos2> = (0..=12)
.map(|i| {
let a = std::f32::consts::PI * i as f32 / 12.0;
c + egui::vec2(-a.cos() * r.width() * 0.3, a.sin() * r.height() * 0.22)
})
.collect();
p.add(egui::Shape::line(arc, stroke));
p.line_segment([c + egui::vec2(0.0, r.height() * 0.22), c + egui::vec2(0.0, r.height() * 0.42)], stroke);
p.line_segment([c + egui::vec2(-r.width() * 0.18, r.height() * 0.42), c + egui::vec2(r.width() * 0.18, r.height() * 0.42)], stroke);
}
Icon::Speaker => {
let x = r.left() + r.width() * 0.12;
let body = vec![
egui::pos2(x, c.y - r.height() * 0.14),
egui::pos2(x + r.width() * 0.18, c.y - r.height() * 0.14),
egui::pos2(x + r.width() * 0.42, c.y - r.height() * 0.36),
egui::pos2(x + r.width() * 0.42, c.y + r.height() * 0.36),
egui::pos2(x + r.width() * 0.18, c.y + r.height() * 0.14),
egui::pos2(x, c.y + r.height() * 0.14),
];
p.add(egui::Shape::convex_polygon(body, color, egui::Stroke::NONE));
if on {
for k in [0.22, 0.38] {
let wave: Vec<egui::Pos2> = (0..=10)
.map(|i| {
let a = -0.9 + 1.8 * i as f32 / 10.0;
egui::pos2(x + r.width() * 0.42 + a.cos() * r.width() * k, c.y + a.sin() * r.height() * k)
})
.collect();
p.add(egui::Shape::line(wave, stroke));
}
}
}
}
if !on {
p.line_segment([r.left_top(), r.right_bottom()], egui::Stroke::new(1.5, theme::RED));
}
response
}