diff --git a/crates/capri-ui/src/settings_window.rs b/crates/capri-ui/src/settings_window.rs new file mode 100644 index 0000000..109bd6c --- /dev/null +++ b/crates/capri-ui/src/settings_window.rs @@ -0,0 +1,723 @@ +//! Settings window: header, grouped navigation, search, inline help, +//! Capri's shell sections, and pages registered by feature crates. Changes apply live. +use std::collections::HashSet; +use std::time::{Duration, Instant}; + +use eframe::egui::{self, Align, Color32, Layout, Pos2, RichText, ScrollArea, Stroke, ViewportBuilder, ViewportCommand, ViewportId}; + +use crate::i18n::{self, t}; +use crate::settings::UiSettings; +use crate::{theme, App}; + +const TITLE: &str = "Capri Settings"; + +/// Navigation groups and sections (`settings-registry.mjs`). Sections owned by other crates +/// appear only when a page is registered for them, except the model page (placeholder). +const GROUPS: &[(&str, &[(&str, &str)])] = &[ + ("Capri", &[("general", "General"), ("languages", "Languages"), ("appearance", "Appearance and animations"), ("window", "Window")]), + ("Conversation", &[("dialogue", "Conversation and personality"), ("knowledge", "Brain and private memory"), ("microphone", "Microphone settings"), ("voice", "Voice effects"), ("calls", "Voice calls"), ("music", "Music listening")]), + ("Language model", &[("models", "Language model"), ("api", "API connections")]), + ("Capabilities", &[("computer", "Computer control"), ("workflows", "Task training"), ("user-tools", "User tools"), ("screen", "Screen snapshot"), ("applications", "Application access"), ("files", "File access"), ("time", "Timers and reminders")]), + ("Community", &[("updates", "Updates"), ("support", "Support the author"), ("credits", "Credits")]), + ("Developer", &[("developer", "For developers")]), +]; +const BUILT_IN: [&str; 9] = ["general", "languages", "appearance", "window", "dialogue", "models", "support", "credits", "developer"]; + +/// Controls per section, for search (English keys; matched in English and translated). +const INDEX: &[(&str, &str)] = &[ + ("general", "Always on top"), + ("general", "Hide to tray"), + ("general", "Reset to bottom-right corner"), + ("general", "Focus mode"), + ("general", "Show a restore chip when minimized"), + ("general", "Restore Capri from the tray on voice activation"), + ("general", "Start hidden in the tray"), + ("general", "Play the startup intro"), + ("general", "Launch Capri when I log in"), + ("general", "Quit and unload models"), + ("general", "Reset settings to defaults"), + ("languages", "Interface language"), + ("languages", "Conversation language"), + ("languages", "Language name"), + ("appearance", "Color palette"), + ("appearance", "Accent colour"), + ("appearance", "Background colour"), + ("appearance", "Out-of-frame appearance"), + ("appearance", "Auto-hide completed replies"), + ("appearance", "Delay after speech (seconds)"), + ("appearance", "Enable visual glitches"), + ("appearance", "Glitch intensity"), + ("appearance", "Ambient glitch interval"), + ("appearance", "Glitch on speech and pose changes"), + ("appearance", "Preview glitch"), + ("appearance", "CRT screen effect"), + ("appearance", "Teleport intensity"), + ("appearance", "Lightning jaggedness"), + ("appearance", "Lightning branches"), + ("appearance", "Reduce teleport flashes"), + ("appearance", "Teleport sound"), + ("appearance", "Show drag lightning on the desktop"), + ("appearance", "Dead zone"), + ("appearance", "Attachment distance"), + ("appearance", "Maximum time between taps (seconds)"), + ("window", "Enable floating motion"), + ("window", "Motion amplitude"), + ("window", "Motion cycle"), + ("window", "Reduce motion"), + ("window", "Dim the area behind Capri"), + ("window", "Strength"), + ("window", "Soft edges"), + ("dialogue", "Communication style"), + ("dialogue", "Personality"), + ("dialogue", "Show Personality file"), + ("dialogue", "Restore original character"), + ("dialogue", "Clear conversation"), + ("developer", "Open logs folder"), + ("support", "Help Capri grow"), + ("credits", "The team"), +]; + +fn fold(s: &str) -> String { + s.to_lowercase().replace('ё', "е").split_whitespace().collect::>().join(" ") +} + +/// Search ranking: 0 exact name, 1 name contains, 2 every word in a name; sections +/// rank +3 and disappear when one of their controls matches. +pub fn search(query: &str, sections: &[(String, String)], controls: &[(String, String)]) -> Vec<(String, String)> { + let q = fold(query); + if q.is_empty() { + return vec![]; + } + let rank = |label: &str| -> Option { + let names = [fold(label), fold(&t(label))]; + if names.contains(&q) { + Some(0) + } else if names.iter().any(|n| n.contains(&q)) { + Some(1) + } else { + q.split(' ').all(|w| names.iter().any(|n| n.contains(w))).then_some(2) + } + }; + let mut hits: Vec<(u8, String, String)> = controls.iter().filter_map(|(s, l)| rank(l).map(|r| (r, s.clone(), l.clone()))).collect(); + let matched: HashSet = hits.iter().map(|h| h.1.clone()).collect(); + hits.extend(sections.iter().filter(|(s, _)| !matched.contains(s)).filter_map(|(s, l)| rank(l).map(|r| (r + 3, s.clone(), l.clone())))); + hits.sort_by_key(|h| h.0); + hits.into_iter().map(|(_, s, l)| (s, l)).collect() +} + +#[derive(Default)] +pub struct SettingsUi { + pub open: bool, + section: String, + query: String, + help: HashSet<&'static str>, + personality: Option, + style: Option, + confirm: Option<(&'static str, Instant)>, + status: Option<(String, Instant)>, + custom_language: Option, + pinned: Option, + mapped: bool, + highlight: Option<(String, Instant)>, +} + +impl SettingsUi { + pub fn open(&mut self, section: Option) { + self.open = true; + if let Some(s) = section { + self.section = s; + } + } + pub fn toggle(&mut self) { + self.open = !self.open; + } +} + +/// Writes or removes the XDG autostart entry. +pub fn set_autostart(on: bool) -> anyhow::Result<()> { + let home = std::env::var_os("HOME").ok_or_else(|| anyhow::anyhow!("No home directory"))?; + let dir = std::path::PathBuf::from(home).join(".config/autostart"); + let file = dir.join("capri.desktop"); + if on { + std::fs::create_dir_all(&dir)?; + let exe = std::env::current_exe()?; + let entry = format!("[Desktop Entry]\nType=Application\nName=Capri\nComment=Capri desktop companion\nExec=\"{}\"\nX-GNOME-Autostart-enabled=true\n", exe.display()); + capri_core::fsutil::write_atomic(&file, entry.as_bytes()) + } else { + match std::fs::remove_file(&file) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e.into()), + _ => Ok(()), + } + } +} + +/// Opens a fixed URL or a folder with the desktop's handler. +// TODO: use the OpenURI portal; xdg-open is fine on KDE and i3 with xdg-utils. +pub fn open(target: &str) { + if let Err(e) = std::process::Command::new("xdg-open").arg(target).stdin(std::process::Stdio::null()).spawn() { + tracing::warn!("xdg-open failed: {e}"); + } +} + +fn row(ui: &mut egui::Ui, help: &mut HashSet<&'static str>, label: &'static str, text: Option<&'static str>, widget: impl FnOnce(&mut egui::Ui)) { + ui.horizontal(|ui| { + ui.label(RichText::new(t(label)).color(Color32::from_rgb(0xd7, 0xee, 0xed))); + if text.is_some() { + let open = help.contains(label); + if ui.selectable_label(open, RichText::new("i").italics().size(11.0)).on_hover_text(t("More information")).clicked() { + if open { help.remove(label) } else { help.insert(label) }; + } + } + ui.with_layout(Layout::right_to_left(Align::Center), widget); + }); + if let Some(text) = text + && help.contains(label) + { + ui.label(RichText::new(t(text)).size(11.0).color(theme::MUTED)); + } +} + +fn heading(ui: &mut egui::Ui, text: &str) { + ui.add_space(10.0); + ui.label(RichText::new(t(text)).size(14.0).color(Color32::from_rgb(0xa0, 0xf5, 0xe9))); + ui.separator(); +} + +fn percent(ui: &mut egui::Ui, value: &mut u32, max: u32, unit: &str) { + ui.add(egui::Slider::new(value, 0..=max).suffix(unit)); +} + +fn combo(ui: &mut egui::Ui, id: &str, value: &mut String, options: &[(&str, String)]) { + let selected = options.iter().find(|(v, _)| v == value).map(|(_, l)| l.clone()).unwrap_or_else(|| value.clone()); + egui::ComboBox::from_id_salt(id).selected_text(selected).width(220.0).show_ui(ui, |ui| { + for (v, label) in options { + ui.selectable_value(value, v.to_string(), label); + } + }); +} + +impl App { + pub(crate) fn settings_window(&mut self, ctx: &egui::Context) { + if !self.settings_ui.open || self.focus { + self.settings_ui.pinned = None; + self.settings_ui.mapped = false; + return; + } + if self.settings_ui.section.is_empty() { + self.settings_ui.section = "general".into(); + } + let owner = self.companion_rect(ctx); + let work = self.work_area(ctx); + let width = 680f32.min(work.width() - 24.0); + let height = 400f32.max(owner.height()).min(work.height() - 24.0); + let mut x = owner.min.x - width - 12.0; + if x < work.min.x + 12.0 { + x = owner.max.x + 12.0; + } + let pos = Pos2::new(x.clamp(work.min.x + 12.0, (work.max.x - width - 12.0).max(work.min.x)), owner.min.y.clamp(work.min.y + 12.0, (work.max.y - height - 12.0).max(work.min.y))); + let builder = ViewportBuilder::default() + .with_title(TITLE) + .with_app_id("capri") + .with_position(pos) + .with_inner_size([width, height]) + .with_min_inner_size([400.0, 400.0]) + .with_decorations(false) + .with_taskbar(false) + .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()) { + ui.ctx().send_viewport_cmd(ViewportCommand::CancelClose); + self.settings_ui.open = false; + } + egui::CentralPanel::default().frame(egui::Frame::new().fill(theme::SETTINGS_BG)).show(ui, |ui| self.settings_contents(ui)); + }); + // States are applied once the window is mapped (see `x11::X11::pin`). + let opened = *self.settings_ui.pinned.get_or_insert_with(|| { + tracing::debug!("settings window opened"); + Instant::now() + }); + if !self.settings_ui.mapped && opened.elapsed() < Duration::from_secs(3) { + if opened.elapsed() > Duration::from_millis(300) + && let Some(x11) = &self.x11 + && let Some(w) = x11.find_own(TITLE) + { + let _ = x11.pin(w, self.cfg.always_on_top); + self.settings_ui.mapped = true; + } + ctx.request_repaint_after(Duration::from_millis(100)); + } + } + + fn page_index(&self, section: &str) -> Option { + self.pages.iter().position(|p| p.section == section) + } + + fn settings_contents(&mut self, ui: &mut egui::Ui) { + // Header: title, notice, close; dragging moves the window. + let header = egui::Panel::top("settings-header").frame(egui::Frame::new().fill(Color32::from_rgb(0x0b, 0x20, 0x2b)).stroke(Stroke::new(2.0, Color32::from_rgb(0x5a, 0xdc, 0xd1))).inner_margin(egui::Margin::symmetric(14, 12))); + header.show(ui, |ui| { + // click_and_drag: dragging starts only after the pointer moves, so a press on × stays a click. + let drag = ui.interact(ui.max_rect(), ui.scope_id().with("settings-drag"), egui::Sense::click_and_drag()); + if drag.drag_started() { + ui.ctx().send_viewport_cmd(ViewportCommand::StartDrag); + } + ui.horizontal(|ui| { + ui.label(RichText::new("CAPRI //").color(theme::ACID).strong()); + ui.label(RichText::new(t("Settings")).color(theme::cyan()).size(16.0)); + if let Some((text, at)) = &self.settings_ui.status + && at.elapsed() < Duration::from_secs(10) + { + ui.label(RichText::new(text).color(Color32::from_rgb(0xff, 0xf1, 0xb5)).size(11.0)); + } + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if ui.button("×").on_hover_text(t("Close")).clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) { + self.settings_ui.open = false; + } + }); + }); + }); + let nav = egui::Panel::left("settings-nav").exact_size(if ui.available_width() < 540.0 { 136.0 } else { 176.0 }).frame(egui::Frame::new().fill(Color32::from_rgb(0x08, 0x17, 0x20)).stroke(Stroke::new(1.0, Color32::from_rgb(0x29, 0x63, 0x73))).inner_margin(8)); + nav.show(ui, |ui| self.navigation(ui)); + egui::CentralPanel::default().frame(egui::Frame::new().inner_margin(egui::Margin::symmetric(16, 10))).show(ui, |ui| { + let section = self.settings_ui.section.clone(); + ScrollArea::vertical().id_salt(("settings", section.clone())).show(ui, |ui| { + ui.set_width(ui.available_width()); + let rtl = i18n::rtl(); + let layout = if rtl { Layout::top_down(Align::Max) } else { Layout::top_down(Align::Min) }; + ui.with_layout(layout, |ui| self.section_ui(ui, §ion)); + }); + }); + } + + fn navigation(&mut self, ui: &mut egui::Ui) { + ui.add(egui::TextEdit::singleline(&mut self.settings_ui.query).hint_text(t("Search settings")).desired_width(f32::INFINITY)); + if ui.input(|i| i.key_pressed(egui::Key::Escape)) && !self.settings_ui.query.is_empty() { + self.settings_ui.query.clear(); + } + let pages: HashSet = self.pages.iter().map(|p| p.section.clone()).collect(); + let visible = |id: &str| BUILT_IN.contains(&id) || pages.contains(id); + let mut sections: Vec<(String, String)> = GROUPS.iter().flat_map(|(_, s)| s.iter()).filter(|(id, _)| visible(id)).map(|(id, l)| (id.to_string(), l.to_string())).collect(); + let known: HashSet<&str> = GROUPS.iter().flat_map(|(_, s)| s.iter().map(|(id, _)| *id)).collect(); + let extra: Vec<(String, String)> = self.pages.iter().filter(|p| !known.contains(p.section.as_str())).map(|p| (p.section.clone(), p.title.clone())).collect(); + sections.extend(extra.iter().cloned()); + ScrollArea::vertical().show(ui, |ui| { + if !self.settings_ui.query.is_empty() { + let mut controls: Vec<(String, String)> = INDEX.iter().map(|(s, l)| (s.to_string(), l.to_string())).collect(); + controls.extend(self.pages.iter().map(|p| (p.section.clone(), p.title.clone()))); + let results = search(&self.settings_ui.query, §ions, &controls); + if results.is_empty() { + ui.label(RichText::new(t("No matching settings")).color(theme::MUTED)); + } + let enter = ui.input(|i| i.key_pressed(egui::Key::Enter)); + for (i, (section, label)) in results.iter().enumerate() { + let section_label = sections.iter().find(|(s, _)| s == section).map(|(_, l)| t(l)).unwrap_or_default(); + if ui.button(format!("{}\n{}", t(label), section_label)).clicked() || (enter && i == 0) { + self.settings_ui.section = section.clone(); + self.settings_ui.highlight = Some((label.clone(), Instant::now())); + self.settings_ui.query.clear(); + } + } + return; + } + for (group, items) in GROUPS { + let items: Vec<_> = items.iter().filter(|(id, _)| visible(id)).collect(); + if items.is_empty() { + continue; + } + ui.add_space(8.0); + ui.label(RichText::new(t(group).to_uppercase()).size(9.0).color(theme::MUTED)); + for (id, label) in items { + let title = self.page_index(id).filter(|_| !BUILT_IN.contains(id)).map(|i| self.pages[i].title.clone()).unwrap_or_else(|| t(label)); + self.nav_item(ui, id, title); + } + } + if !extra.is_empty() { + ui.add_space(8.0); + ui.label(RichText::new(t("Capabilities").to_uppercase()).size(9.0).color(theme::MUTED)); + for (id, title) in extra { + self.nav_item(ui, &id, title); + } + } + }); + } + + fn nav_item(&mut self, ui: &mut egui::Ui, id: &str, title: String) { + let current = self.settings_ui.section == id; + let text = RichText::new(title).size(12.0).color(if current { Color32::from_rgb(0xf3, 0xf2, 0xa4) } else { Color32::from_rgb(0x9b, 0xc6, 0xcd) }); + let response = ui.add(egui::Button::new(text).fill(if current { Color32::from_rgb(0x19, 0x36, 0x3b) } else { Color32::TRANSPARENT }).stroke(Stroke::NONE).min_size(egui::vec2(ui.available_width(), 24.0))); + if current { + let r = response.rect; + ui.painter().line_segment([r.left_top(), r.left_bottom()], Stroke::new(3.0, Color32::from_rgb(0xed, 0xeb, 0x73))); + } + if response.clicked() { + self.settings_ui.section = id.to_string(); + self.settings_ui.personality = None; + } + } + + fn section_ui(&mut self, ui: &mut egui::Ui, section: &str) { + let title = GROUPS.iter().flat_map(|(_, s)| s.iter()).find(|(id, _)| *id == section).map(|(_, l)| t(l)); + if let Some((label, at)) = &self.settings_ui.highlight + && at.elapsed() < Duration::from_millis(1200) + { + ui.label(RichText::new(format!("→ {}", t(label))).color(theme::cyan()).background_color(Color32::from_rgba_unmultiplied(0x8e, 0xf5, 0xed, 0x33))); + } + if let Some(i) = self.page_index(section) { + ui.heading(RichText::new(self.pages[i].title.clone()).color(theme::cyan())); + (self.pages[i].draw)(ui); + return; + } + if let Some(title) = title { + ui.heading(RichText::new(title).color(theme::cyan())); + } + let mut c = self.cfg.clone(); + match section { + "general" => self.general(ui, &mut c), + "languages" => self.languages(ui), + "appearance" => self.appearance(ui, &mut c), + "window" => self.window_section(ui, &mut c), + "dialogue" => self.dialogue(ui), + "models" => { + ui.label(RichText::new(t("The language model page is provided by the inference module.")).color(theme::MUTED)); + ui.label(format!("{}: {}", t("Current model"), self.engine.model())); + } + "support" | "credits" => self.credits(ui), + "developer" => self.developer(ui), + _ => drop(ui.label(t("This section is not available."))), + } + if c != self.cfg { + self.set_cfg(|x| *x = c); + } + } + + fn general(&mut self, ui: &mut egui::Ui, c: &mut UiSettings) { + let help = &mut self.settings_ui.help; + heading(ui, "Window controls"); + row(ui, help, "Always on top", Some("Keep the companion window above other windows."), |ui| drop(ui.checkbox(&mut c.always_on_top, ""))); + row(ui, help, "Focus mode", Some("Hide both windows until you bring Capri back from the system tray."), |ui| { + let mut focus = self.focus; + if ui.checkbox(&mut focus, "").changed() { + self.focus = focus; + self.hidden = focus; + } + }); + row(ui, help, "Show a restore chip when minimized", None, |ui| drop(ui.checkbox(&mut c.minimized_chip, ""))); + row(ui, help, "Restore Capri from the tray on voice activation", None, |ui| drop(ui.checkbox(&mut c.restore_from_tray_on_wake, ""))); + let mut actions = (false, false); + ui.horizontal_wrapped(|ui| { + actions.0 = ui.button(t("Hide to tray")).on_hover_text(t("Hide the companion window. Bring it back from the system tray.")).clicked(); + actions.1 = ui.button(t("Reset to bottom-right corner")).on_hover_text(t("Move the companion window to the bottom-right of the primary display.")).clicked(); + }); + if actions.0 { + self.hide(); + } + if actions.1 { + self.ui.command(crate::Command::ResetPosition); + } + heading(ui, "Startup"); + let help = &mut self.settings_ui.help; + row(ui, help, "Launch Capri when I log in", Some("Adds Capri to the desktop's autostart applications (KDE Plasma, and i3 with an XDG autostart runner such as dex)."), |ui| drop(ui.checkbox(&mut c.launch_at_login, ""))); + row(ui, help, "Start hidden in the tray", None, |ui| drop(ui.checkbox(&mut c.start_hidden, ""))); + row(ui, help, "Play the startup intro", None, |ui| drop(ui.checkbox(&mut c.startup_intro, ""))); + heading(ui, "Connection, sleep and quit"); + if ui.add(egui::Button::new(RichText::new(t("Quit and unload models")).color(Color32::from_rgb(0xff, 0xb4, 0xc4))).fill(Color32::from_rgb(0x34, 0x14, 0x21))).clicked() { + self.ui.command(crate::Command::Quit); + } + heading(ui, "Settings reset"); + let armed = self.settings_ui.confirm.filter(|(k, _)| *k == "reset"); + match armed { + None => { + if ui.button(t("Reset settings to defaults")).clicked() { + self.settings_ui.confirm = Some(("reset", Instant::now())); + } + } + Some((_, at)) => { + ui.label(RichText::new(t("Reset settings to defaults?")).strong()); + ui.label(RichText::new(t("This restores the default window and appearance settings, monitoring, voice effects, speech pause, initiative, screen observation and computer control effects. Unsaved changes to these settings will be discarded.")).size(11.0).color(theme::MUTED)); + ui.horizontal(|ui| { + let left = 3u64.saturating_sub(at.elapsed().as_secs()); + let label = if left > 0 { format!("{} ({left} s)", t("Reset settings")) } else { t("Reset settings") }; + if ui.add_enabled(left == 0, egui::Button::new(label)).clicked() { + *c = UiSettings { launch_at_login: c.launch_at_login, ..UiSettings::default() }; + self.settings_ui.confirm = None; + self.settings_ui.status = Some((t("Default settings restored."), Instant::now())); + } + if ui.button(t("Cancel")).clicked() { + self.settings_ui.confirm = None; + } + }); + ui.ctx().request_repaint_after(Duration::from_millis(200)); + } + } + } + + fn languages(&mut self, ui: &mut egui::Ui) { + let mut language = self.store.get().language; + let before = language.clone(); + let help = &mut self.settings_ui.help; + let locales: Vec<(&str, String)> = i18n::LOCALES.iter().map(|id| (*id, i18n::native_name(id))).collect(); + row(ui, help, "Interface language", Some("Changes Capri's menus and labels only. Conversation, recognition and voice keep their own languages."), |ui| combo(ui, "interface", &mut language.interface, &locales)); + if i18n::rtl() { + ui.label(RichText::new(t("Right-to-left layout is partial: text is right-aligned but not reshaped.")).size(10.0).color(theme::MUTED)); + } + let mut conversations: Vec<(&str, String)> = capri_core::persona::languages().iter().map(|l| (l.id.as_str(), i18n::language_name(&l.id))).collect(); + conversations.push(("custom", t("Other language / text only"))); + row(ui, help, "Conversation language", Some("Capri replies in this language."), |ui| combo(ui, "conversation", &mut language.conversation, &conversations)); + if language.conversation == "custom" { + let draft = self.settings_ui.custom_language.get_or_insert_with(|| language.custom_conversation.clone()); + row(ui, help, "Language name", None, |ui| drop(ui.add(egui::TextEdit::singleline(draft).char_limit(60)))); + let name = draft.trim().to_string(); + let valid = !name.is_empty() && name.chars().all(|ch| ch.is_alphabetic() || " ()'-".contains(ch) || unicode_mark(ch)); + if valid { + language.custom_conversation = name; + } else { + ui.label(RichText::new(t("Enter a language name, without instructions or formatting.")).color(theme::RED).size(11.0)); + } + } + if language != before + && let Err(e) = self.store.update(|s| s.language = language) + { + self.settings_ui.status = Some((e.to_string(), Instant::now())); + } + } + + fn appearance(&mut self, ui: &mut egui::Ui, c: &mut UiSettings) { + let help = &mut self.settings_ui.help; + heading(ui, "Interface theme"); + let presets = [("capri", "Capri".to_string()), ("blackwall", "Blackwall".into()), ("amethyst", "Amethyst".into()), ("overdrive", "Overdrive".into()), ("custom", t("Custom"))]; + row(ui, help, "Color palette", Some("Choose a palette or set the accent and background colors separately."), |ui| combo(ui, "palette", &mut c.interface_theme.preset, &presets)); + let p = c.interface_theme.palette(); + ui.horizontal(|ui| { + for color in [p.cyan, p.pink, p.panel, p.background, p.text] { + let (r, _) = ui.allocate_exact_size(egui::vec2(22.0, 14.0), egui::Sense::hover()); + ui.painter().rect_filled(r, 2.0, color); + } + }); + if c.interface_theme.preset == "custom" { + let th = &mut c.interface_theme; + row(ui, help, "Accent colour", None, |ui| { + ui.add(egui::Slider::new(&mut th.saturation, 35..=100).suffix("%")); + ui.add(egui::Slider::new(&mut th.hue, 0..=359).suffix("°")); + }); + row(ui, help, "Background colour", None, |ui| { + ui.add(egui::Slider::new(&mut th.background_saturation, 0..=100).suffix("%")); + ui.add(egui::Slider::new(&mut th.background_hue, 0..=359).suffix("°")); + }); + } + heading(ui, "Desktop presentation"); + let styles = [("character", t("Character")), ("dialogue", t("Dialogue only"))]; + row(ui, help, "Out-of-frame appearance", None, |ui| combo(ui, "style", &mut c.detached_style, &styles)); + row(ui, help, "Auto-hide completed replies", None, |ui| drop(ui.checkbox(&mut c.reply_auto_hide, ""))); + row(ui, help, "Delay after speech (seconds)", None, |ui| drop(ui.add_enabled(c.reply_auto_hide, egui::Slider::new(&mut c.reply_auto_hide_seconds, 2..=60)))); + heading(ui, "Visual glitch"); + row(ui, help, "Enable visual glitches", None, |ui| drop(ui.checkbox(&mut c.glitch_enabled, ""))); + let on = c.glitch_enabled; + row(ui, help, "Glitch intensity", None, |ui| drop(ui.add_enabled(on, egui::Slider::new(&mut c.glitch_strength, 0..=100).suffix("%")))); + row(ui, help, "Ambient glitch interval", None, |ui| drop(ui.add_enabled(on, egui::Slider::new(&mut c.glitch_interval_seconds, 10..=120).suffix(" s")))); + row(ui, help, "Glitch on speech and pose changes", None, |ui| drop(ui.add_enabled(on, egui::Checkbox::new(&mut c.glitch_events, "")))); + row(ui, help, "CRT screen effect", Some("Curved scanline screen over the portrait."), |ui| drop(ui.checkbox(&mut c.crt, ""))); + if ui.add_enabled(on, egui::Button::new(t("Preview glitch"))).clicked() { + self.burst_preview(); + } + let help = &mut self.settings_ui.help; + heading(ui, "Teleport effects"); + row(ui, help, "Teleport intensity", None, |ui| percent(ui, &mut c.teleport_intensity, 100, "%")); + row(ui, help, "Lightning jaggedness", None, |ui| percent(ui, &mut c.teleport_jaggedness, 100, "%")); + row(ui, help, "Lightning branches", None, |ui| percent(ui, &mut c.teleport_branches, 100, "%")); + row(ui, help, "Reduce teleport flashes", None, |ui| drop(ui.checkbox(&mut c.teleport_reduced_flash, ""))); + let sounds = [("spark", t("Spark")), ("thunder", t("Thunder")), ("pulse", t("Pulse")), ("off", t("Off"))]; + let mut preview = false; + row(ui, help, "Teleport sound", None, |ui| { + preview = ui.button("▶").on_hover_text(t("Preview")).clicked(); + combo(ui, "teleport-sound", &mut c.teleport_sound, &sounds); + }); + if preview { + self.sounds.play(&c.teleport_sound); + } + let help = &mut self.settings_ui.help; + heading(ui, "Drag lightning"); + row(ui, help, "Show drag lightning on the desktop", None, |ui| drop(ui.checkbox(&mut c.avatar_drag_tether, ""))); + let on = c.avatar_drag_tether; + row(ui, help, "Intensity", None, |ui| drop(ui.add_enabled(on, egui::Slider::new(&mut c.avatar_drag_tether_intensity, 0..=100).suffix("%")))); + row(ui, help, "Chaos", None, |ui| drop(ui.add_enabled(on, egui::Slider::new(&mut c.avatar_drag_tether_chaos, 0..=100).suffix("%")))); + row(ui, help, "Dead zone", Some("Releasing Capri closer than this to where you grabbed her does not teleport her."), |ui| drop(ui.add(egui::Slider::new(&mut c.avatar_drag_tether_dead_zone, 0..=120).suffix(" px")))); + heading(ui, "Avatar attachment zones"); + row(ui, help, "Attachment distance", Some("How close to a window or screen edge Capri must be dropped to perch on it."), |ui| drop(ui.add(egui::Slider::new(&mut c.avatar_snap_radius, 12..=100).suffix(" px")))); + heading(ui, "Avatar click reactions"); + row(ui, help, "Maximum time between taps (seconds)", None, |ui| drop(ui.add(egui::Slider::new(&mut c.avatar_tap_gap_seconds, 1..=15)))); + } + + fn burst_preview(&mut self) { + self.burst_at = self.now_ms(); + } + + fn window_section(&mut self, ui: &mut egui::Ui, c: &mut UiSettings) { + let help = &mut self.settings_ui.help; + heading(ui, "Window motion"); + row(ui, help, "Enable floating motion", None, |ui| drop(ui.checkbox(&mut c.float_enabled, ""))); + row(ui, help, "Motion amplitude", None, |ui| drop(ui.add_enabled(c.float_enabled, egui::Slider::new(&mut c.float_amplitude, 0..=24).suffix(" px")))); + row(ui, help, "Motion cycle", None, |ui| drop(ui.add_enabled(c.float_enabled, egui::Slider::new(&mut c.float_period_seconds, 4..=30).suffix(" s")))); + let modes = [("system", t("Follow the desktop")), ("on", t("On")), ("off", t("Off"))]; + row(ui, help, "Reduce motion", Some("Turns off glitches, floating, teleport animation and the intro. \"Follow the desktop\" uses KDE's animation speed setting."), |ui| combo(ui, "reduced", &mut c.reduced_motion, &modes)); + heading(ui, "Window dimming"); + row(ui, help, "Dim the area behind Capri", None, |ui| drop(ui.checkbox(&mut c.dimming_enabled, ""))); + let on = c.dimming_enabled; + row(ui, help, "Strength", None, |ui| drop(ui.add_enabled(on, egui::Slider::new(&mut c.dimming_level, 0..=85).suffix("%")))); + row(ui, help, "Soft edges", None, |ui| drop(ui.add_enabled(on, egui::Slider::new(&mut c.dimming_softness, 0..=320).step_by(5.0).suffix(" px")))); + } + + fn dialogue(&mut self, ui: &mut egui::Ui) { + let workspace = self.store.paths().workspace(); + heading(ui, "Conversation"); + let style = self.settings_ui.style.get_or_insert_with(|| capri_core::persona::read_style(&workspace)).clone(); + let mut next = style.clone(); + let styles: Vec<(&str, String)> = capri_core::persona::communication_styles().map(|s| (s, t(&format!("{}{}", s[..1].to_uppercase(), &s[1..])))).collect(); + row(ui, &mut self.settings_ui.help, "Communication style", None, |ui| combo(ui, "style", &mut next, &styles)); + if next != style { + match capri_core::persona::save_style(&workspace, &next) { + Ok(()) => self.settings_ui.style = Some(next), + Err(e) => self.settings_ui.status = Some((e.to_string(), Instant::now())), + } + } + heading(ui, "Personality"); + if self.settings_ui.personality.is_none() { + match capri_core::persona::read_personality(&workspace) { + Ok(text) => self.settings_ui.personality = Some(text), + Err(e) => self.settings_ui.status = Some((e.to_string(), Instant::now())), + } + } + let text = self.settings_ui.personality.get_or_insert_with(String::new); + ui.add(egui::TextEdit::multiline(text).code_editor().desired_rows(14).desired_width(f32::INFINITY).char_limit(24_000)); + let busy = self.engine.busy(); + let mut save = false; + ui.horizontal_wrapped(|ui| { + save = ui.add_enabled(!busy, egui::Button::new(t("Save changes"))).on_disabled_hover_text(t("Wait for the current reply to finish.")).clicked(); + if ui.button(t("Show Personality file")).clicked() { + if !workspace.join("PERSONALITY.md").is_file() { + save = true; + } + open(&workspace.to_string_lossy()); + } + if ui.button(t("Restore original character")).clicked() { + self.settings_ui.confirm = Some(("personality", Instant::now())); + } + }); + if self.settings_ui.confirm.is_some_and(|(k, _)| k == "personality") { + ui.label(RichText::new(t("Restore original character?")).strong()); + ui.label(RichText::new(t("Your custom personality will be replaced by the original character.")).size(11.0).color(theme::MUTED)); + ui.horizontal(|ui| { + if ui.add_enabled(!busy, egui::Button::new(RichText::new(t("Restore original character")).color(Color32::from_rgb(0xff, 0xb4, 0xc4)))).clicked() { + self.settings_ui.personality = Some(String::new()); + save = true; + self.settings_ui.confirm = None; + } + if ui.button(t("Cancel")).clicked() { + self.settings_ui.confirm = None; + } + }); + } + if save { + let text = self.settings_ui.personality.clone().unwrap_or_default(); + match capri_core::persona::save_personality(&workspace, &text) { + Ok(()) => { + self.settings_ui.personality = None; + self.settings_ui.status = Some((t("Saved."), Instant::now())); + } + Err(e) => self.settings_ui.status = Some((e.to_string(), Instant::now())), + } + } + heading(ui, "Memory"); + if ui.add_enabled(!busy, egui::Button::new(t("Clear conversation"))).on_hover_text(t("Current context and the visible history will be cleared. Long-term memory is retained.")).clicked() { + match self.engine.reset_conversation() { + Ok(()) => { + self.reply.clear(); + self.settings_ui.status = Some((t("Conversation cleared."), Instant::now())); + } + Err(e) => self.settings_ui.status = Some((e.to_string(), Instant::now())), + } + } + } + + fn credits(&mut self, ui: &mut egui::Ui) { + heading(ui, "Help Capri grow"); + ui.label(t("Developed by Overyx")); + ui.horizontal_wrapped(|ui| { + // Fixed community URLs: the UI never takes URLs from elsewhere. + for (label, url) in [ + ("Boosty", "https://boosty.to/overyx/donate"), + ("Discord", "https://discord.gg/capricore"), + ("TikTok", "https://www.tiktok.com/@overyx2"), + ("GitHub", "https://github.com/CapriChooms/CapriCore"), + ("capri-core.com", "https://capri-core.com/"), + ] { + if ui.button(label).clicked() { + open(url); + } + } + }); + if ui.button(t("Open GitHub issues")).clicked() { + open("https://github.com/CapriChooms/CapriCore/issues/new/choose"); + } + heading(ui, "The team"); + for (name, role) in [("Overyx", "Developer"), ("v1rch", "Discord developer"), ("Leberrr", "Discord moderator")] { + ui.horizontal(|ui| { + ui.label(RichText::new(name).strong().color(theme::cyan())); + ui.label(RichText::new(t(role)).color(theme::MUTED)); + }); + } + ui.add_space(8.0); + ui.label(RichText::new("Capri for Linux is a Rust port of CapriCore, GPL-3.0-only. Character artwork is read from your Capri installation and is not covered by the code license. UI font: Exo 2 (SIL Open Font License).").size(11.0).color(theme::MUTED)); + } + + fn developer(&mut self, ui: &mut egui::Ui) { + let paths = self.store.paths().clone(); + heading(ui, "For developers"); + egui::Grid::new("dev").num_columns(2).striped(true).show(ui, |ui| { + let mut line = |k: &str, v: String| { + ui.label(RichText::new(t(k)).color(theme::MUTED)); + ui.label(RichText::new(v).monospace()); + ui.end_row(); + }; + line("Version", env!("CARGO_PKG_VERSION").into()); + line("Model", self.engine.model().into()); + 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))); + line("Cursor", self.desktop.as_ref().and_then(|d| d.cursor()).map_or("unknown".into(), |(x, y)| format!("{x}, {y}"))); + line("Reduced motion", self.reduced().to_string()); + line("Avatar artwork", if self.avatar.animated() { self.avatar.catalog().dir.display().to_string() } else { "fallback symbol".into() }); + line("Detached avatar", format!("{:?}", !self.detach.attached())); + }); + if ui.button(t("Open logs folder")).clicked() { + let _ = std::fs::create_dir_all(paths.logs()); + open(&paths.logs().to_string_lossy()); + } + ui.ctx().request_repaint_after(Duration::from_millis(500)); + } +} + +/// Combining marks are allowed in language names (`\p{M}`). +fn unicode_mark(ch: char) -> bool { + matches!(ch as u32, 0x0300..=0x036F | 0x0483..=0x0489 | 0x0591..=0x05BD | 0x0610..=0x061A | 0x064B..=0x065F | 0x0900..=0x0903 | 0x093A..=0x094F | 0x0E31 | 0x0E34..=0x0E3A | 0x3099..=0x309A) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn search_ranking() { + let sections = vec![("appearance".to_string(), "Appearance and animations".to_string()), ("window".to_string(), "Window".to_string())]; + let controls: Vec<(String, String)> = INDEX.iter().map(|(s, l)| (s.to_string(), l.to_string())).collect(); + let r = search("glitch", §ions, &controls); + assert!(r.iter().all(|(s, _)| s == "appearance") && r.len() >= 4); + let r = search(" WINDOW ", §ions, &controls); + assert_eq!(r[0], ("window".to_string(), "Window".to_string()), "exact section name, no control is named exactly so"); + let r = search("teleport sound", §ions, &controls); + assert_eq!(r[0].1, "Teleport sound"); + let r = search("drag desktop", §ions, &controls); + assert_eq!(r[0].1, "Show drag lightning on the desktop", "all words"); + assert!(search("zzzz", §ions, &controls).is_empty()); + assert!(search("", §ions, &controls).is_empty()); + } +}