Linux port: first run, packaging, single instance, privacy and wiring
CI / test (push) Has been cancelled

First run and backend
- The companion opens without Ollama or a model (OFFLINE / SETUP REQUIRED),
  opens Settings > Language model and picks the model up once downloaded.
- Model, provider and GPU changes apply without restarting (Ollama is
  restarted when launch settings change); no silent fallback from API mode.
- Fatal startup errors are shown in a window; the fallback avatar loads
  again; the shipped Capri artwork is used when nothing was imported.

Packaging and tooling
- packaging/arch/PKGBUILD, capri.desktop (KWin ScreenShot2 key), icons,
  artwork under /usr/share/capri/assets, Gitea Actions CI.
- xtask: `icons` and `release-check` (no private data or credentials).

Runtime
- One instance per data folder (flock + control socket): second launch
  shows the window; capri stop / restart / toggle / status (JSON, starts
  nothing) / doctor / setup / diagnostics export / purge.
- A foreign program on the Ollama port is refused; an Ollama left behind
  by Capri is replaced.

Privacy and security
- No raw Ollama log on disk; API keys are never saved in plaintext (old
  ones move to the keyring); refused credential notes are stored as
  [Credentials omitted]; launched apps get an allow-listed environment.

Fixes
- Stop/Escape silence the voice; saved voice effects apply to replies;
  settings_control glitch settings apply; distinct KWin cursor scripts;
  KDE window capture authorized for source builds; Linux wording.
- Voice pack references zipped with Windows separators are found.

Wired features
- Initiatives, request router, resource monitor, "clip that", questions
  about a snapshot, sleep mode, tap reactions, stopwatch, attachments,
  Internet mode button, voice-synced subtitles, wake visuals, dictation
  draft, tray switches, Spotify seek/shuffle/repeat; computer-control
  planner and classifier follow model switches and API mode.
- Approval cards: one shown, 8 queued, deduplicated, cancelled on stop,
  failure, lock or pause; one Application access switch.

Desktop
- Compositor detection (no black overlay on i3 without picom), i3lock
  detection, unsupported desktops reported at startup, screenshot-only
  control without AT-SPI, fontconfig fallbacks, translatable feature
  pages with French translations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
nocodeandClaude Opus 5.5 committed 2026-11-12 20:21:40 +01:00
1 parent a2abf01280
commit 49349d6ecd
73 files changed
+4834 -517

No files matched your search

+5
View File
@@ -315,6 +315,11 @@ impl Avatar {
!self.catalog.dir.as_os_str().is_empty()
}
/// The committed expression id (the tap reaction mood is read from it).
pub fn expression(&self) -> &str {
&self.expression
}
/// Applies a model choice: a persistent expression, or an action clip followed by its rest frame.
pub fn set_expression(&mut self, id: &str) {
let Some(sprite) = self.catalog.model_sprite(id).cloned() else { return };
+7 -1
View File
@@ -249,12 +249,18 @@ impl Detach {
}
impl App {
/// Leaving the frame draws Capri in a transparent window over the desktop: it needs a
/// compositor, else the whole work area would turn black (i3 without picom).
fn can_detach(&self) -> bool {
self.avatar.animated() && self.desktop.is_some()
self.avatar.animated() && self.desktop.is_some() && self.compositing.get()
}
/// Leave the frame (attached) or hop to a random landing (detached).
pub(crate) fn teleport(&mut self) {
if self.avatar.animated() && self.desktop.is_some() && !self.compositing.get() {
self.notice = Some(t("Leaving the frame needs a compositor. On i3, start picom (for example `picom -b`)."));
return;
}
if self.can_detach() && self.detach.idle() && matches!(self.detach.phase, Phase::Attached | Phase::Detached) {
self.query(Pending::Move { point: None, grab: Vec2::ZERO });
}
+7
View File
@@ -132,6 +132,10 @@ pub enum Signal {
Speaking,
Listening,
Sleeping,
/// The local model server does not answer.
Offline,
/// No language model installed yet.
Setup,
}
impl Signal {
@@ -144,12 +148,15 @@ impl Signal {
Signal::Speaking => "SPEAKING",
Signal::Listening => "LISTENING",
Signal::Sleeping => "SLEEPING",
Signal::Offline => "OFFLINE",
Signal::Setup => "SETUP REQUIRED",
}
}
pub fn color(self) -> Color32 {
match self {
Signal::Thinking | Signal::Receiving | Signal::Speaking => crate::theme::ACID,
Signal::Sleeping => crate::theme::VIOLET,
Signal::Offline | Signal::Setup => crate::theme::NOTICE,
_ => crate::theme::cyan(),
}
}
+279 -18
View File
@@ -14,6 +14,18 @@ use tokio::sync::oneshot;
pub use crate::dock::AvatarCommand;
/// What the presence indicator reports about the model backend.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Backend {
/// The model answers.
#[default]
Ready,
/// The local model server does not answer (Ollama missing or stopped).
Offline,
/// The server answers but no language model is installed (first run).
Setup,
}
/// Wake-word feedback.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Wake {
@@ -46,10 +58,47 @@ pub trait Attachments: Send + Sync {
/// the model reaction at count 10 belong to the voice/engine side.
pub type TapHook = Arc<dyn Fn(&str, &str, u32) + Send + Sync>;
/// Sleep (`true`) or wake (`false`): the app unloads or reloads the models (spec 10 ORC-06).
pub type PowerHook = Arc<dyn Fn(bool) + Send + Sync>;
/// `isSleepCommand` (spec 10 ORC-06): the whole message asks Capri to go to sleep.
pub fn is_sleep_command(text: &str) -> bool {
let mut t = text.trim().to_lowercase().replace(['’', '‘'], "'");
t = t.trim_end_matches(['.', '!', '?', '…', ' ']).to_string();
for prefix in ["hey ", "эй "] {
if let Some(rest) = t.strip_prefix(prefix) {
t = rest.trim_start().to_string();
}
}
for name in ["capri", "капри"] {
if let Some(rest) = t.strip_prefix(name) {
t = rest.trim_start_matches([',', ':', '!', ' ']).to_string();
}
}
for polite in ["please ", "пожалуйста, ", "пожалуйста "] {
if let Some(rest) = t.strip_prefix(polite) {
t = rest.to_string();
}
}
for polite in [", please", " please", ", пожалуйста", " пожалуйста"] {
if let Some(rest) = t.strip_suffix(polite) {
t = rest.to_string();
}
}
let t = t.trim();
const PHRASES: [&str; 18] = [
"sleep", "go to sleep", "you can sleep", "you can go to sleep", "time to sleep", "time to go to sleep", "it's time to sleep", "it's time to go to sleep",
"it is time to sleep", "it is time to go to sleep", "take a nap", "get some rest", "иди спать", "иди поспи", "ложись спать", "пора спать", "тебе пора спать", "отдыхай",
];
PHRASES.contains(&t) || ["можешь идти спать", "можешь поспать", "можешь отдохнуть"].contains(&t)
}
#[derive(Debug)]
pub enum Command {
Show,
Hide,
/// Show when hidden, hide when shown (`capri toggle`, bound to a key by the owner).
Toggle,
ToggleFocus,
Settings(Option<String>),
Teleport,
@@ -60,17 +109,38 @@ pub enum Command {
Notice(String),
/// Send this text as an owner message, exactly like the composer (spoken input).
Submit(String),
/// Recognized speech to review before sending (automatic sending off): fills the composer.
Draft(String),
/// Sleep (`true`, unload the models) or wake up (`false`).
Sleep(bool),
/// Tray switches: microphone, spoken replies, internet mode.
ToggleMicrophone,
ToggleVoice,
ToggleInternet,
/// Plays a cue preset (`spark`, `pulse`…) or a sound file (`file:<path>`).
Sound(String),
/// A line Capri says on her own (initiative): shown like a reply, with its expression.
Line { text: String, avatar: Option<String> },
/// The sentence Capri starts speaking: the reply page follows the voice.
Subtitle(String),
Quit,
}
/// One approval card. Only the first card of `State::cards` is shown and can be answered;
/// the others wait their turn (`MAX_QUEUED`), each with a fresh lifetime when shown.
pub(crate) struct Card {
pub id: u64,
pub request: Approval,
/// When the card became the shown one (the danger delay counts from here).
pub created: Instant,
pub expires: Instant,
pub reply: Option<oneshot::Sender<bool>>,
/// Every waiting caller: an identical request joins the existing card.
pub replies: Vec<oneshot::Sender<bool>>,
}
/// Cards waiting behind the shown one (spec 08 TL-05: one pending + 8 queued).
pub const MAX_QUEUED: usize = 8;
#[derive(Default)]
pub(crate) struct State {
pub mouth: u8,
@@ -79,6 +149,7 @@ pub(crate) struct State {
pub sleeping: bool,
pub wake: Wake,
pub wake_at: Option<Instant>,
pub backend: Backend,
pub stopwatch: Option<(Stopwatch, Instant)>,
pub commands: VecDeque<Command>,
pub cards: Vec<Card>,
@@ -87,11 +158,18 @@ pub(crate) struct State {
pub tap_hook: Option<TapHook>,
/// Tray checkboxes: (detached, focus mode, always on top).
pub tray: (bool, bool, bool),
/// Tray switches: (microphone, spoken replies, internet mode); `None` = no voice controls.
pub tray_switches: (Option<(bool, bool)>, bool),
/// Computer-control indicator: one click-through overlay per monitor while `Some`.
pub overlay: Option<ControlOverlay>,
/// Set by the shell once every overlay window was drawn.
pub overlay_drawn: bool,
pub stop_hook: Option<Arc<dyn Fn() + Send + Sync>>,
pub power: Option<PowerHook>,
/// Compact resource line under the header (`RAM 42% · CPU 12% · GPU 3.1/8 GB`).
pub resources: Option<String>,
/// Silences Capri's voice (Stop button, Escape).
pub stop_speech: Option<Arc<dyn Fn() + Send + Sync>>,
/// Microphone and spoken-reply switches (header buttons).
pub audio: Option<AudioControls>,
/// Real pointer (desktop pixels) and its recent positions for the overlay reticle.
@@ -199,10 +277,50 @@ impl UiHandle {
}
/// Sleep visuals: closed eyes, `Zzz` caption, silent taps.
pub fn set_resource_line(&self, line: Option<String>) {
if self.0.state.lock().resources != line {
self.with(|s| s.resources = line);
}
}
/// Capri's voice is playing (read by the initiative gates).
pub fn speaking(&self) -> bool {
self.0.state.lock().speaking
}
pub fn sleeping(&self) -> bool {
self.0.state.lock().sleeping
}
pub fn set_sleeping(&self, sleeping: bool) {
self.with(|s| s.sleeping = sleeping);
}
pub fn on_power(&self, hook: PowerHook) {
self.with(|s| s.power = Some(hook));
}
/// Puts Capri to sleep or wakes her: shown at once, models unloaded/reloaded by the app.
pub fn request_sleep(&self, sleep: bool) {
let hook = {
let mut s = self.0.state.lock();
if s.sleeping == sleep {
return;
}
s.sleeping = sleep;
s.power.clone()
};
if sleep {
self.cancel_approvals();
}
if let Some(hook) = hook {
hook(sleep);
}
if let Some(ctx) = self.0.ctx.get() {
ctx.request_repaint();
}
}
pub fn set_wake(&self, wake: Wake) {
self.with(|s| {
s.wake = wake;
@@ -222,6 +340,11 @@ impl UiHandle {
self.with(|s| s.tap_hook = Some(hook));
}
/// Backend state shown by the presence indicator (`OFFLINE`, `SETUP REQUIRED`).
pub fn set_backend(&self, backend: Backend) {
self.with(|s| s.backend = backend);
}
/// Error notice in the companion.
pub fn notice(&self, text: impl Into<String>) {
self.command(Command::Notice(text.into()));
@@ -275,6 +398,18 @@ impl UiHandle {
}
/// Called by the "Stop computer control" button.
pub fn on_stop_speech(&self, hook: Arc<dyn Fn() + Send + Sync>) {
self.with(|s| s.stop_speech = Some(hook));
}
/// Silences the voice now (no effect when nothing is spoken).
pub(crate) fn stop_speech(&self) {
let hook = self.0.state.lock().stop_speech.clone();
if let Some(stop) = hook {
stop();
}
}
pub fn on_stop_control(&self, hook: Arc<dyn Fn() + Send + Sync>) {
self.with(|s| s.stop_hook = Some(hook));
}
@@ -287,38 +422,115 @@ impl UiHandle {
self.0.state.lock().commands.drain(..).collect()
}
/// Answers a card from the UI.
/// Answers the shown card from the UI.
pub(crate) fn answer(&self, id: u64, accepted: bool) {
self.with(|s| {
if let Some(i) = s.cards.iter().position(|c| c.id == id) {
// The danger delay is enforced here, not only by a disabled button.
if accepted && s.cards[i].request.kind == DANGER_KIND && s.cards[i].created.elapsed() < DANGER_DELAY {
return;
}
let mut card = s.cards.remove(i);
if let Some(reply) = card.reply.take() {
let _ = reply.send(accepted && Instant::now() < card.expires);
let Some(card) = s.cards.first() else { return };
if card.id != id {
return;
}
// The danger delay is enforced here, not only by a disabled button.
if accepted && card.request.kind == DANGER_KIND && card.created.elapsed() < DANGER_DELAY {
return;
}
let card = s.cards.remove(0);
let accepted = accepted && Instant::now() < card.expires;
for reply in card.replies {
let _ = reply.send(accepted);
}
Self::promote(s);
});
}
/// Refuses every shown and queued card: Stop, Escape, a cancelled or failed turn, screen
/// lock, Application access paused, quit (spec 08 TL-05 `cancel()` triggers).
pub fn cancel_approvals(&self) {
self.with(|s| {
for card in s.cards.drain(..) {
for reply in card.replies {
let _ = reply.send(false);
}
}
});
}
/// The next queued card becomes the shown one with its own full lifetime.
fn promote(s: &mut State) {
if let Some(next) = s.cards.first_mut() {
next.created = Instant::now();
next.expires = next.created + next.request.timeout;
}
}
/// Refuses the shown card once its time is over.
fn expire(&self) {
self.with(|s| {
if s.cards.first().is_some_and(|c| Instant::now() >= c.expires) {
for reply in s.cards.remove(0).replies {
let _ = reply.send(false);
}
Self::promote(s);
}
});
}
/// Drops cards whose callers all went away (their turn was cancelled).
fn forget_abandoned(&self) {
self.with(|s| {
let first = s.cards.first().map(|c| c.id);
for card in &mut s.cards {
card.replies.retain(|r| !r.is_closed());
}
s.cards.retain(|c| !c.replies.is_empty());
if s.cards.first().map(|c| c.id) != first {
Self::promote(s);
}
});
}
}
/// Removes the caller's card when `confirm` is dropped before an answer (cancelled turn).
struct Abandon(UiHandle);
impl Drop for Abandon {
fn drop(&mut self) {
self.0.forget_abandoned();
}
}
#[async_trait]
impl Approvals for UiHandle {
/// Shows an exact, temporary card; anything but an explicit accept before expiry is a refusal.
async fn confirm(&self, request: Approval) -> bool {
let (tx, rx) = oneshot::channel();
let timeout = request.timeout;
let mut id = 0;
// Declared first so it drops last, after the receiver: the sender then reads as closed.
let _abandon = Abandon(self.clone());
let (tx, mut rx) = oneshot::channel();
let mut queued = true;
self.with(|s| {
let same = |c: &Card| c.request.kind == request.kind && c.request.title == request.title && c.request.detail == request.detail;
if let Some(card) = s.cards.iter_mut().find(|c| same(c)) {
card.replies.push(tx);
return;
}
if s.cards.len() > MAX_QUEUED {
queued = false; // "Too many pending permission requests."
return;
}
s.next_id += 1;
id = s.next_id;
s.cards.push(Card { id, request, created: Instant::now(), expires: Instant::now() + timeout, reply: Some(tx) });
let now = Instant::now();
// A queued card gets its lifetime when it is shown (see `promote`).
let expires = if s.cards.is_empty() { now + request.timeout } else { now + Duration::from_secs(86_400) };
s.cards.push(Card { id: s.next_id, request, created: now, expires, replies: vec![tx] });
});
let accepted = matches!(tokio::time::timeout(timeout, rx).await, Ok(Ok(true)));
self.with(|s| s.cards.retain(|c| c.id != id));
accepted
if !queued {
return false;
}
loop {
match tokio::time::timeout(Duration::from_millis(200), &mut rx).await {
Ok(answer) => return answer.unwrap_or(false),
Err(_) => self.expire(),
}
}
}
}
@@ -357,4 +569,53 @@ mod tests {
ui.set_mouth_level(9);
assert_eq!(ui.0.state.lock().mouth, 3);
}
#[test]
fn sleep_commands() {
for yes in ["sleep", "Go to sleep.", "Hey Capri, take a nap please", "capri: you can go to sleep!", "It’s time to sleep", "Капри, иди спать", "пожалуйста, отдыхай"] {
assert!(is_sleep_command(yes), "{yes}");
}
for no in ["sleep well tonight", "I want to sleep", "how do I sleep better?", "remind me to sleep at 11"] {
assert!(!is_sleep_command(no), "{no}");
}
}
#[tokio::test]
async fn approval_queue_dedupe_cap_and_cancel() {
let ui = UiHandle::new();
let ask = |a: Approval| { let ui = ui.clone(); tokio::spawn(async move { ui.confirm(a).await }) };
let count = |ui: &UiHandle| ui.0.state.lock().cards.len();
let first = ask(approval(5000));
let same = ask(approval(5000));
while count(&ui) == 0 || ui.0.state.lock().cards[0].replies.len() < 2 {
tokio::task::yield_now().await;
}
assert_eq!(count(&ui), 1, "an identical request joins the shown card");
let queued: Vec<_> = (0..MAX_QUEUED).map(|i| ask(Approval { detail: format!("/tmp/{i}"), ..approval(5000) })).collect();
while count(&ui) < 1 + MAX_QUEUED {
tokio::task::yield_now().await;
}
assert!(!ui.confirm(Approval { detail: "/tmp/one-too-many".into(), ..approval(5000) }).await, "the queue is full");
// Only the shown card can be answered; both callers get the answer.
let second = ui.0.state.lock().cards[1].id;
ui.answer(second, true);
assert_eq!(count(&ui), 1 + MAX_QUEUED);
let shown = ui.0.state.lock().cards[0].id;
ui.answer(shown, true);
assert!(first.await.unwrap() && same.await.unwrap());
// Stop refuses everything left.
ui.cancel_approvals();
for waiter in queued {
assert!(!waiter.await.unwrap());
}
assert_eq!(count(&ui), 0);
// A caller that goes away (cancelled turn) leaves no card behind.
let gone = ask(approval(5000));
while count(&ui) == 0 {
tokio::task::yield_now().await;
}
gone.abort();
let _ = gone.await;
assert_eq!(count(&ui), 0);
}
}
-130
View File
@@ -1,130 +0,0 @@
//! Interface translations: English source strings are the keys of
//! `assets/i18n/interface-locales.json`; a missing locale or key falls back to English.
use std::collections::HashMap;
use std::sync::{Arc, OnceLock};
use parking_lot::RwLock;
use serde::Deserialize;
use serde_json::value::RawValue;
static BUNDLE_JSON: &[u8] = include_bytes!("../../../assets/i18n/interface-locales.json");
/// Bundle order; the JSON object order is lost by the map below.
pub const LOCALES: [&str; 50] = [
"en", "ru", "de", "fr", "es", "it", "pt", "nl", "pl", "uk", "cs", "sk", "bg", "hr", "sr", "sl", "ro", "hu", "el", "da", "no",
"sv", "fi", "et", "lv", "lt", "is", "ca", "ar", "he", "fa", "ur", "hi", "bn", "ta", "te", "mr", "gu", "pa", "zh", "ja", "ko",
"vi", "th", "id", "ms", "tl", "tr", "sw", "af",
];
#[derive(Deserialize)]
struct Bundle {
locales: HashMap<String, Locale>,
#[serde(rename = "languageNames")]
language_names: HashMap<String, Box<RawValue>>,
}
#[derive(Deserialize)]
struct Locale {
#[serde(rename = "nativeName")]
native_name: String,
direction: String,
messages: Box<RawValue>,
}
fn bundle() -> &'static Bundle {
static BUNDLE: OnceLock<Bundle> = OnceLock::new();
BUNDLE.get_or_init(|| serde_json::from_slice(BUNDLE_JSON).expect("bundled interface locales"))
}
struct Active {
id: String,
rtl: bool,
messages: HashMap<String, String>,
names: HashMap<String, String>,
}
static ACTIVE: RwLock<Option<Arc<Active>>> = RwLock::new(None);
fn load(id: &str) -> Active {
let bundle = bundle();
let id = if bundle.locales.contains_key(id) { id } else { "en" };
let locale = &bundle.locales[id];
let names = bundle.language_names.get(id).and_then(|raw| serde_json::from_str(raw.get()).ok()).unwrap_or_default();
Active {
id: id.to_string(),
rtl: locale.direction == "rtl",
messages: serde_json::from_str(locale.messages.get()).unwrap_or_default(),
names,
}
}
fn active() -> Arc<Active> {
if let Some(a) = ACTIVE.read().clone() {
return a;
}
let a = Arc::new(load("en"));
*ACTIVE.write() = Some(a.clone());
a
}
/// Switches the interface language; unknown ids mean English.
pub fn set_locale(id: &str) {
if ACTIVE.read().as_ref().is_some_and(|a| a.id == id) {
return;
}
*ACTIVE.write() = Some(Arc::new(load(id)));
}
pub fn locale() -> String {
active().id.clone()
}
/// Arabic, Hebrew, Persian and Urdu. egui has no bidi shaping: text is right-aligned only.
pub fn rtl() -> bool {
active().rtl
}
/// Translation of an English UI key; unknown keys (owner data) pass through unchanged.
pub fn t(key: &str) -> String {
active().messages.get(key).cloned().unwrap_or_else(|| key.to_string())
}
/// `t` with `{name}` placeholders replaced.
pub fn tf(key: &str, values: &[(&str, &str)]) -> String {
values.iter().fold(t(key), |text, (name, value)| text.replace(&format!("{{{name}}}"), value))
}
/// Native name of an interface locale, for the language picker.
pub fn native_name(id: &str) -> String {
bundle().locales.get(id).map(|l| l.native_name.clone()).unwrap_or_else(|| id.to_string())
}
/// Conversation language name in the interface language.
pub fn language_name(id: &str) -> String {
if let Some(name) = active().names.get(id) {
return name.clone();
}
capri_core::persona::languages().iter().find(|l| l.id == id).map(|l| l.label.clone()).unwrap_or_else(|| id.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lookup_and_fallback() {
// One test: the active locale is process-global.
set_locale("fr");
assert_ne!(t("Settings"), "Settings");
assert_eq!(t("my own note"), "my own note");
assert!(!rtl());
assert_eq!(language_name("de"), "allemand");
set_locale("he");
assert!(rtl());
set_locale("xx");
assert_eq!(locale(), "en");
assert_eq!(t("VOICE PENDING"), "PREPARING VOICE");
assert_eq!(tf("{seconds} s", &[("seconds", "3")]), "3 s");
assert_eq!(native_name("ru"), "Русский");
}
}
+305 -30
View File
@@ -10,7 +10,8 @@ mod geom;
mod hooks;
mod overlay;
mod pages;
pub mod i18n;
/// Interface translations (shared with the feature crates' settings pages).
pub use capri_core::i18n;
mod settings;
mod settings_window;
mod sound;
@@ -31,7 +32,7 @@ use eframe::egui::{self, Align, Color32, Key, Layout, Pos2, Rect, RichText, Stro
use tokio::sync::watch;
pub use dock::{parse_command as avatar_command, AvatarCommand};
pub use hooks::{Attachments, Command, ControlOverlay, Stopwatch, UiHandle, Wake};
pub use hooks::{is_sleep_command, Attachments, Backend, Command, ControlOverlay, PowerHook, Stopwatch, UiHandle, Wake};
pub use settings::{Theme, UiSettings};
use avatar::Avatar;
@@ -62,6 +63,41 @@ struct Taps {
at: Instant,
}
/// Cached "is a compositor running" answer (one X11 round trip at most every 5 s).
pub(crate) struct Compositing {
x11: Option<Arc<x11::X11>>,
cache: std::cell::Cell<(bool, Option<Instant>)>,
}
impl Compositing {
fn new(x11: Option<Arc<x11::X11>>) -> Self {
Self { x11, cache: std::cell::Cell::new((true, None)) }
}
pub(crate) fn get(&self) -> bool {
let (value, at) = self.cache.get();
if at.is_some_and(|t| t.elapsed() < Duration::from_secs(5)) {
return value;
}
let value = self.x11.as_ref().is_none_or(|x| x.compositing());
self.cache.set((value, Some(Instant::now())));
value
}
}
/// Tap reaction cooldowns and the approach sentence that cycles between reactions.
struct Reactions {
next_at: Instant,
by_part: std::collections::HashMap<String, Instant>,
variation: u8,
}
impl Default for Reactions {
fn default() -> Self {
Self { next_at: Instant::now(), by_part: Default::default(), variation: 0 }
}
}
pub(crate) struct App {
rt: tokio::runtime::Handle,
engine: Arc<Engine>,
@@ -78,6 +114,8 @@ pub(crate) struct App {
reply_hover: bool,
/// Subtitle page shown, when it appeared, and whether the owner stepped manually.
reply_page: usize,
/// Sentence being spoken (voice subtitles); the reply page follows it.
spoken: Option<String>,
page_shown: Instant,
page_paused: bool,
/// The owner hid this reply ("Hide reply"); cleared by the next turn.
@@ -110,6 +148,11 @@ pub(crate) struct App {
pub(crate) settings_ui: settings_window::SettingsUi,
chip: chip::Chip,
tray: tray::TrayHandle,
/// Sleeping state last shown in the tray menu (Sleep / Wake Capri).
tray_sleeping: bool,
reactions: Reactions,
/// Compositing manager present (checked every 5 s; picom may start after Capri).
pub(crate) compositing: Compositing,
tray_state: (bool, bool, bool),
pub(crate) sounds: sound::Sounds,
reduced_system: bool,
@@ -164,6 +207,7 @@ impl App {
}
};
let desktop = x11.clone().map(|x| rt.block_on(desktop::Desktop::new(x)));
let compositor_x11 = x11.clone();
if let Some(d) = &desktop {
tracing::info!("desktop backend: {:?}", d.backend);
}
@@ -188,6 +232,7 @@ impl App {
reply_done: Some(Instant::now()),
reply_hover: false,
reply_page: 0,
spoken: None,
page_shown: Instant::now(),
page_paused: false,
reply_collapsed: false,
@@ -217,6 +262,9 @@ impl App {
settings_ui: Default::default(),
chip: Default::default(),
tray,
tray_sleeping: false,
reactions: Reactions::default(),
compositing: Compositing::new(compositor_x11),
tray_state: (false, false, true),
sounds: sound::Sounds::new(),
reduced_system,
@@ -276,14 +324,15 @@ impl App {
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;
// "Go to sleep": handled here, never sent to the model (spec 10 ORC-06 / ORC-24).
if hooks::is_sleep_command(&text) {
self.input.clear();
self.ui.request_sleep(true);
return;
}
// Any other message wakes Capri first; the reply loads the model again.
self.ui.request_sleep(false);
self.begin_reply();
let engine = self.engine.clone();
let sender = self.sender.clone();
let ctx = ctx.clone();
@@ -299,6 +348,68 @@ impl App {
});
}
/// Clears the reply bubble for a new reply (owner message or a line Capri says herself).
fn begin_reply(&mut self) {
self.reply.clear();
self.reply_done = None;
self.reply_page = 0;
self.spoken = None;
self.page_shown = Instant::now();
self.page_paused = false;
self.reply_collapsed = false;
self.thinking = true;
self.tool = None;
}
/// Tap reaction (spec 03 AV-17): on the 10th tap, one short model line, shown and spoken.
/// Global cooldown 8.5 s, per part 10.6 s (not for `body`); never during another reply,
/// speech, an approval card or computer control.
fn react_to_taps(&mut self, part: &str, tone: &str, awakened: bool) {
let now = Instant::now();
let blocked = {
let s = self.ui.0.state.lock();
s.speaking || !s.cards.is_empty() || s.overlay.is_some()
};
if self.engine.busy() || blocked || self.hidden || self.reactions.next_at > now || self.reactions.by_part.get(part).is_some_and(|t| *t > now) {
return;
}
self.reactions.next_at = now + Duration::from_millis(8500);
if part != "body" {
self.reactions.by_part.insert(part.to_string(), now + Duration::from_millis(10_625));
}
let cue = capri_agent::reaction::TapCue {
part: part.to_string(),
tone: tone.to_string(),
headpat: part == "head" && self.avatar.animated(),
awakened,
mood: capri_agent::reaction::Mood::of(self.avatar.expression(), awakened),
variation: self.reactions.variation,
};
self.reactions.variation = (self.reactions.variation + 1) % 3;
let settings = self.store.get();
let style = capri_core::persona::read_style(&self.store.paths().workspace());
let (system, user) = capri_agent::reaction::tap_prompt(&cue, &style, &settings.language);
self.begin_reply();
let (engine, sender) = (self.engine.clone(), self.sender.clone());
let ctx = self.ui.0.ctx.get().cloned();
self.rt.spawn(async move {
let notify = |event| {
let _ = sender.send(event);
if let Some(ctx) = &ctx {
ctx.request_repaint();
}
};
let origin = serde_json::json!({"kind": "avatar-click", "awakened": awakened});
match engine.say(system, user, origin, capri_agent::reaction::clean_line, notify).await {
Ok(Some(_)) => {}
// Nothing usable: the bubble closes again, no error is shown for a gesture.
Ok(None) | Err(_) => {
let _ = sender.send(TurnEvent::Cancelled { turn_id: String::new() });
}
}
});
}
fn send(&mut self, ctx: &egui::Context) {
if self.engine.busy() {
return;
@@ -341,8 +452,11 @@ impl App {
self.notice = Some(message);
self.finish();
}
TurnEvent::Cancelled { .. } => {
self.notice = Some(t("Reply stopped."));
TurnEvent::Cancelled { turn_id } => {
// An empty id closes a line Capri gave up on (tap reaction): no notice.
if !turn_id.is_empty() {
self.notice = Some(t("Reply stopped."));
}
self.finish();
}
}
@@ -372,6 +486,10 @@ impl App {
Signal::Speaking
} else if self.engine.busy() {
if self.thinking { Signal::Thinking } else { Signal::Receiving }
} else if s.backend == hooks::Backend::Offline {
Signal::Offline
} else if s.backend == hooks::Backend::Setup {
Signal::Setup
} else if s.wake == Wake::Listening {
Signal::Listening
} else if !self.input.is_empty() {
@@ -397,6 +515,14 @@ impl App {
self.focus = false;
}
Command::Hide => self.hide(),
Command::Toggle => {
if self.hidden {
self.hidden = false;
self.focus = false;
} else {
self.hide();
}
}
Command::ToggleFocus => {
self.focus = !self.focus;
self.hidden = self.focus;
@@ -416,8 +542,50 @@ impl App {
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::Notice(text) => {
// Startup can report several problems at once (Ollama, provider, model): keep the last three.
let mut lines: Vec<String> = self.notice.take().map(|n| n.lines().map(str::to_string).collect()).unwrap_or_default();
if !lines.contains(&text) {
lines.push(text);
}
let skip = lines.len().saturating_sub(3);
self.notice = Some(lines[skip..].join("\n"));
}
Command::Submit(text) => self.send_text(ctx, text),
Command::Sleep(sleep) => self.ui.request_sleep(sleep),
Command::ToggleInternet => self.engine.set_internet(!self.engine.internet()),
Command::ToggleMicrophone | Command::ToggleVoice => {
let Some(audio) = self.ui.0.state.lock().audio.clone() else { continue };
let microphone = matches!(command, Command::ToggleMicrophone);
let (switch, on) = if microphone { (audio.microphone.clone(), audio.microphone_on) } else { (audio.voice.clone(), audio.voice_on) };
match switch(!on) {
Ok(()) => self.ui.with_audio(|a| if microphone { a.microphone_on = !on } else { a.voice_on = !on }),
Err(e) => self.notice = Some(e),
}
}
Command::Sound(sound) => self.sounds.play(&sound),
Command::Line { text, avatar } => {
if !self.engine.busy() {
self.begin_reply();
self.thinking = false;
if let Some(id) = avatar {
self.avatar.set_expression(&id);
}
self.reply = text;
self.reply_done = Some(Instant::now());
self.history = self.engine.history();
}
}
Command::Draft(text) => {
// Never overwrite something the owner is typing.
if self.input.trim().is_empty() {
self.input = text;
}
}
Command::Subtitle(text) => {
self.spoken = Some(text);
ctx.request_repaint();
}
Command::Quit => ctx.send_viewport_cmd(ViewportCommand::Close),
}
}
@@ -461,10 +629,13 @@ impl App {
}
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:#}");
if let (Some(x), Some(w)) = (&self.x11, self.own_window) {
if let Err(e) = x.set_class(w) {
tracing::warn!("window class not set: {e:#}");
}
if let Err(e) = x.pin(w, self.cfg.always_on_top) {
tracing::warn!("cannot keep the companion above other windows: {e:#}");
}
}
}
@@ -500,6 +671,9 @@ impl App {
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));
if let Some(line) = self.ui.0.state.lock().resources.clone() {
ui.label(RichText::new(line).color(theme::MUTED).size(10.0).monospace()).on_hover_text(t("Resource monitor (Settings › Resources)"));
}
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 };
@@ -580,16 +754,21 @@ impl App {
self.send(ui.ctx());
response.request_focus();
}
if busy {
let speaking = self.ui.0.state.lock().speaking;
if busy || speaking {
if ui.add_sized([button_width, 36.0], egui::Button::new(t("Stop"))).on_hover_text(t("Stop reply (Esc)")).clicked() {
self.engine.cancel();
self.ui.cancel_approvals();
self.ui.stop_speech();
}
} 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)) {
if (self.engine.busy() || self.ui.0.state.lock().speaking) && ui.input(|i| i.key_pressed(Key::Escape)) {
self.engine.cancel();
self.ui.cancel_approvals();
self.ui.stop_speech();
}
}
@@ -599,8 +778,13 @@ impl App {
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).
/// Internet mode, microphone and spoken-reply switches (Capri: all off at every launch).
fn audio_buttons(&mut self, ui: &mut egui::Ui) {
let internet = self.engine.internet();
let hint = if internet { "Internet mode on: replies use web search results. Click to turn it off." } else { "Internet mode: search the web for the next replies" };
if icon_button(ui, internet, Icon::Globe).on_hover_text(t(hint)).clicked() {
self.engine.set_internet(!internet);
}
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) {
@@ -634,7 +818,18 @@ impl App {
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 {
// While Capri speaks, the page holding the spoken sentence is shown (voice-synced subtitles).
let voiced = self.spoken.as_deref().filter(|_| !self.page_paused).and_then(|sentence| {
let words = |t: &str| t.split_whitespace().collect::<Vec<_>>().join(" ");
let probe: String = sentence.split_whitespace().take(6).collect::<Vec<_>>().join(" ");
(!probe.is_empty()).then(|| all.iter().position(|p| words(p).contains(&probe))).flatten()
});
if let Some(page) = voiced {
if page != self.reply_page {
self.reply_page = page;
self.page_shown = Instant::now();
}
} else 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;
@@ -679,7 +874,13 @@ impl App {
}
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();
// Only the first card can be answered; the others wait their turn.
type Shown = (u64, String, String, Duration, bool, Duration);
let (cards, waiting): (Vec<Shown>, usize) = {
let state = self.ui.0.state.lock();
let shown = state.cards.iter().take(1).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();
(shown, state.cards.len().saturating_sub(1))
};
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());
@@ -701,6 +902,9 @@ impl App {
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));
if waiting > 0 {
ui.label(RichText::new(tf("{count} more waiting", &[("count", &waiting.to_string())])).size(10.0).color(theme::MUTED));
}
ui.horizontal(|ui| {
let label = if !danger {
t("Confirm")
@@ -723,8 +927,12 @@ impl App {
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));
ui.horizontal_top(|ui| {
// Long notices (setup steps, errors) wrap instead of being cut at the window edge.
let text = notice.lines().map(t).collect::<Vec<_>>().join("\n");
ui.allocate_ui(egui::vec2((ui.available_width() - 24.0).max(40.0), 0.0), |ui| {
ui.add(egui::Label::new(RichText::new(text).color(theme::NOTICE).size(11.0)).wrap());
});
if ui.small_button("×").on_hover_text(t("Dismiss")).clicked() {
self.notice = None;
}
@@ -786,7 +994,13 @@ impl App {
};
self.taps = Some(Taps { part: part.into(), count, at: Instant::now() });
if sleeping {
return; // silent while asleep
// Silent while asleep; the 10th tap of a sequence wakes Capri (spec 03 AV-17).
if count == 10 {
self.taps = None;
self.ui.request_sleep(false);
self.react_to_taps(part, "boundary", true);
}
return;
}
let tone = body::tone(part);
if part == "head" && self.avatar.animated() {
@@ -802,6 +1016,9 @@ impl App {
if let Some(hook) = self.ui.0.state.lock().tap_hook.clone() {
hook(part, tone, count);
}
if count == 10 {
self.react_to_taps(part, tone, false);
}
tracing::debug!("tap {part} ({tone}) x{count}");
}
@@ -931,7 +1148,12 @@ impl App {
impl eframe::App for App {
fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
[0.0; 4]
// Without a compositor (i3 without picom) transparency is black: use the panel colour.
if self.compositing.get() {
[0.0; 4]
} else {
egui::Rgba::from(theme::SETTINGS_BG).to_array()
}
}
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
@@ -996,12 +1218,17 @@ impl eframe::App for App {
self.chip.close();
}
let state = (!self.detach.attached(), self.focus, self.cfg.always_on_top);
if state != self.tray_state {
let sleeping = self.ui.0.state.lock().sleeping;
let switches = (self.ui.0.state.lock().audio.as_ref().map(|a| (a.microphone_on, a.voice_on)), self.engine.internet());
if state != self.tray_state || sleeping != self.tray_sleeping || switches != self.ui.0.state.lock().tray_switches {
self.tray_state = state;
self.ui.0.state.lock().tray = state;
self.tray_sleeping = sleeping;
let mut shared = self.ui.0.state.lock();
shared.tray = state;
shared.tray_switches = switches;
drop(shared);
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();
@@ -1080,10 +1307,45 @@ pub fn run(rt: tokio::runtime::Handle, engine: Arc<Engine>, store: Arc<SettingsS
.map_err(|e| anyhow::anyhow!("Cannot open the companion window: {e}"))
}
/// Small window that explains why Capri could not start (launched from a menu, stderr is unseen).
pub fn fatal(message: &str) -> Result<()> {
let message = message.to_string();
let viewport = ViewportBuilder::default().with_title("Capri").with_app_id("capri").with_inner_size([460.0, 200.0]).with_resizable(true);
let options = eframe::NativeOptions {
viewport,
event_loop_builder: Some(Box::new(|builder| {
use winit::platform::x11::EventLoopBuilderExtX11;
builder.with_x11();
})),
..Default::default()
};
eframe::run_ui_native("capri-fatal", options, move |ui, _frame| {
egui::CentralPanel::default().show(ui, |ui| {
ui.heading(i18n::t("Capri could not start"));
ui.add_space(6.0);
egui::ScrollArea::vertical().max_height(110.0).show(ui, |ui| {
ui.add(egui::Label::new(message.as_str()).wrap());
});
ui.add_space(6.0);
ui.horizontal(|ui| {
if ui.button(i18n::t("Copy")).clicked() {
ui.ctx().copy_text(message.clone());
}
if ui.button(i18n::t("Close")).clicked() {
ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close);
}
});
});
})
.map_err(|e| anyhow::anyhow!("Cannot open the error window: {e}"))
}
#[derive(Clone, Copy)]
enum Icon {
Microphone,
Speaker,
/// Internet mode (web search for the next replies).
Globe,
}
/// Header toggle with a drawn icon (the bundled fonts do not render these glyphs reliably).
@@ -1110,6 +1372,18 @@ fn icon_button(ui: &mut egui::Ui, on: bool, icon: Icon) -> egui::Response {
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::Globe => {
let radius = r.width().min(r.height()) * 0.42;
p.circle_stroke(c, radius, stroke);
p.line_segment([c - egui::vec2(radius, 0.0), c + egui::vec2(radius, 0.0)], stroke);
let meridian: Vec<egui::Pos2> = (0..=16)
.map(|i| {
let a = std::f32::consts::TAU * i as f32 / 16.0;
c + egui::vec2(a.cos() * radius * 0.45, a.sin() * radius)
})
.collect();
p.add(egui::Shape::line(meridian, stroke));
}
Icon::Speaker => {
let x = r.left() + r.width() * 0.12;
let body = vec![
@@ -1134,7 +1408,8 @@ fn icon_button(ui: &mut egui::Ui, on: bool, icon: Icon) -> egui::Response {
}
}
}
if !on {
// Off is the normal state of Internet mode: dimmed, not struck through.
if !on && !matches!(icon, Icon::Globe) {
p.line_segment([r.left_top(), r.right_bottom()], egui::Stroke::new(1.5, theme::RED));
}
response
+4 -1
View File
@@ -223,6 +223,8 @@ impl App {
.with_min_inner_size([400.0, 400.0])
.with_decorations(false)
.with_taskbar(false)
// A typed window floats on i3 (an untyped one is tiled into the workspace).
.with_window_type(egui::X11WindowType::Dialog)
.with_window_level(if self.cfg.always_on_top { egui::WindowLevel::AlwaysOnTop } else { egui::WindowLevel::Normal });
ctx.show_viewport_immediate(ViewportId::from_hash_of(TITLE), builder, |ui, _| {
if ui.input(|i| i.viewport().close_requested()) {
@@ -241,6 +243,7 @@ impl App {
&& let Some(x11) = &self.x11
&& let Some(w) = x11.find_own(TITLE)
{
let _ = x11.set_class(w);
let _ = x11.pin(w, self.cfg.always_on_top);
self.settings_ui.mapped = true;
}
@@ -679,7 +682,7 @@ impl App {
ui.end_row();
};
line("Version", env!("CARGO_PKG_VERSION").into());
line("Model", self.engine.model().into());
line("Model", self.engine.model());
line("Settings", paths.settings_file().display().to_string());
line("Data", paths.data.display().to_string());
line("Desktop backend", self.desktop.as_ref().map_or("none".into(), |d| format!("{:?}", d.backend)));
+11 -3
View File
@@ -70,8 +70,10 @@ impl Sounds {
.spawn(move || {
let mut sink: Option<rodio::MixerDeviceSink> = None;
for preset in rx {
let samples = synth(&preset);
if samples.is_empty() {
// `file:<path>`: a sound file (shutter sample); anything else is a synthesized cue.
let file = preset.strip_prefix("file:").map(std::path::PathBuf::from);
let samples = if file.is_some() { vec![] } else { synth(&preset) };
if samples.is_empty() && file.is_none() {
continue;
}
if sink.is_none() {
@@ -82,7 +84,13 @@ impl Sounds {
});
}
if let Some(sink) = &sink {
sink.mixer().add(rodio::buffer::SamplesBuffer::new(NonZero::new(1).unwrap(), NonZero::new(RATE).unwrap(), samples));
match file {
Some(path) => match std::fs::File::open(&path).map_err(|e| e.to_string()).and_then(|f| rodio::Decoder::try_from(f).map_err(|e| e.to_string())) {
Ok(decoder) => sink.mixer().add(decoder),
Err(e) => tracing::debug!("sound {}: {e}", path.display()),
},
None => sink.mixer().add(rodio::buffer::SamplesBuffer::new(NonZero::new(1).unwrap(), NonZero::new(RATE).unwrap(), samples)),
}
}
}
})
+31 -5
View File
@@ -55,16 +55,42 @@ fn fallback_files(locale: &str) -> Vec<&'static str> {
["noto/NotoSans-Regular.ttf", script, "TTF/DejaVuSans.ttf", "noto/NotoSansSymbols2-Regular.ttf"].into_iter().filter(|f| !f.is_empty()).collect()
}
/// Font file fontconfig picks for `pattern` (`:lang=ar`, `sans-serif`…), when it exists.
fn fc_match(pattern: &str) -> Option<String> {
let output = std::process::Command::new("fc-match").args(["-f", "%{file}", pattern]).stderr(std::process::Stdio::null()).output().ok()?;
let file = String::from_utf8(output.stdout).ok()?.trim().to_string();
(output.status.success() && std::path::Path::new(&file).is_file()).then_some(file)
}
/// Fallback font files for `locale`: the usual Arch paths first, then whatever fontconfig
/// offers for that language and for general text (other distributions, user fonts).
fn fallback_paths(locale: &str) -> Vec<String> {
let mut out: Vec<String> = fallback_files(locale).into_iter().map(|f| format!("/usr/share/fonts/{f}")).filter(|p| std::path::Path::new(p).is_file()).collect();
let lang = match locale {
"zh" => "zh-cn",
other => other,
};
for pattern in [format!(":lang={lang}"), "sans-serif".to_string()] {
if let Some(file) = fc_match(&pattern)
&& !out.contains(&file)
&& out.len() < 6
{
out.push(file);
}
}
out
}
/// Installs Exo 2 plus the fallbacks the interface language needs.
// TODO: fixed fontconfig paths and no text shaping (Arabic letters stay unjoined); use fontconfig and a shaping renderer.
/// Note: egui does not shape text, so Arabic letters are drawn in their isolated forms.
pub fn install_fonts(ctx: &egui::Context, locale: &str) {
let mut fonts = FontDefinitions::default();
fonts.font_data.insert("exo2".into(), Arc::new(FontData::from_static(EXO2)));
let mut chain = vec!["exo2".to_string()];
for file in fallback_files(locale) {
if let Ok(bytes) = std::fs::read(format!("/usr/share/fonts/{file}")) {
fonts.font_data.insert(file.into(), Arc::new(FontData::from_owned(bytes)));
chain.push(file.into());
for file in fallback_paths(locale) {
if let Ok(bytes) = std::fs::read(&file) {
fonts.font_data.insert(file.clone(), Arc::new(FontData::from_owned(bytes)));
chain.push(file);
}
}
let proportional = fonts.families.get_mut(&FontFamily::Proportional).unwrap();
+18 -2
View File
@@ -40,9 +40,23 @@ impl ksni::Tray for Tray {
}
fn menu(&self) -> Vec<MenuItem<Self>> {
let (detached, focus, on_top) = self.ui.0.state.lock().tray;
vec![
let sleeping = self.ui.0.state.lock().sleeping;
let (audio, internet) = self.ui.0.state.lock().tray_switches;
let mut switches: Vec<MenuItem<Self>> = vec![];
if let Some((microphone, voice)) = audio {
switches.push(check("Microphone", microphone, |_| Command::ToggleMicrophone));
switches.push(check("Speak replies", voice, |_| Command::ToggleVoice));
}
switches.push(check("Internet mode", internet, |_| Command::ToggleInternet));
switches.push(item("Clip the screen", || Command::Submit("Capri, clip that".into())));
switches.push(MenuItem::Separator);
let mut menu = vec![
item("Show Capri", || Command::Show),
item("Settings", || Command::Settings(None)),
MenuItem::Separator,
];
menu.extend(switches);
menu.extend(vec![
item("Teleport Capri", || Command::Teleport),
StandardItem { label: t("Return to frame"), visible: detached, activate: Box::new(|tray: &mut Tray| tray.ui.command(Command::Return)), ..Default::default() }.into(),
check("Focus mode", focus, |_| Command::ToggleFocus),
@@ -50,9 +64,11 @@ impl ksni::Tray for Tray {
check("Always on top", on_top, Command::AlwaysOnTop),
MenuItem::Separator,
item("Hide to tray", || Command::Hide),
if sleeping { item("Wake Capri", || Command::Sleep(false)) } else { item("Sleep (unload models)", || Command::Sleep(true)) },
MenuItem::Separator,
item("Quit and unload models", || Command::Quit),
]
]);
menu
}
}
+19 -2
View File
@@ -6,12 +6,14 @@ use raw_window_handle::{HasWindowHandle, RawWindowHandle};
use x11rb::connection::Connection;
use x11rb::protocol::randr::ConnectionExt as _;
use x11rb::protocol::shape::{ConnectionExt as _, SK, SO};
use x11rb::protocol::xproto::{AtomEnum, ClientMessageEvent, ClipOrdering, ConfigureWindowAux, ConnectionExt, EventMask, Rectangle, StackMode, Window};
use x11rb::protocol::xproto::{AtomEnum, ClientMessageEvent, ClipOrdering, ConfigureWindowAux, ConnectionExt, EventMask, PropMode, Rectangle, StackMode, Window};
use x11rb::rust_connection::RustConnection;
use x11rb::wrapper::ConnectionExt as _;
pub struct X11 {
conn: RustConnection,
root: Window,
screen: usize,
}
/// A rectangle in root pixels.
@@ -37,7 +39,7 @@ impl X11 {
pub fn connect() -> Result<Self> {
let (conn, screen) = x11rb::connect(None).context("X11 connection")?;
let root = conn.setup().roots[screen].root;
Ok(Self { conn, root })
Ok(Self { conn, root, screen })
}
fn atom(&self, name: &str) -> Result<u32> {
@@ -79,6 +81,21 @@ impl X11 {
Ok(())
}
/// A compositing manager runs (KWin, picom…): transparent windows show what is behind them.
/// Without one (plain i3), transparency is drawn black.
pub fn compositing(&self) -> bool {
let Ok(atom) = self.atom(&format!("_NET_WM_CM_S{}", self.screen)) else { return true };
self.conn.get_selection_owner(atom).ok().and_then(|c| c.reply().ok()).is_none_or(|r| r.owner != x11rb::NONE)
}
/// `WM_CLASS` = `capri` / `Capri`: winit leaves the instance empty, while desktop entries
/// (`StartupWMClass=capri`) and i3 rules (`for_window [class="Capri"]`) need both parts.
pub fn set_class(&self, window: Window) -> Result<()> {
self.conn.change_property8(PropMode::REPLACE, window, AtomEnum::WM_CLASS, AtomEnum::STRING, b"capri\0Capri\0")?;
self.conn.flush()?;
Ok(())
}
/// Clicks pass through everything outside `rects` (window-relative pixels).
pub fn set_input(&self, window: Window, rects: &[Px]) -> Result<()> {
let rects: Vec<Rectangle> = rects