AnyBot/src/app/panel_ui.rs

608 lines
31 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.

// 對話詳細資訊 (the right panel), laid out like the original (captured from the reference assistant itself):
// a round ✕ at the top right, the bot's big face and name, two small tabs 動態|資料庫, then
// rounded cards — 建議 (新增至 Slack / 建立例行工作 / 加入會議), 電腦 (Bot 的電腦 with its
// state), 語音聊天 (語音 / 速度 / 語言). 資料庫 lists the chat's files under 本週 and 更早.
// Measured: panel 280 px; cards radius 12, 1 px border at 6 %, 4 px inside; text 13 px, section
// titles 13 px at 66 %, secondary 12 px at 54 %; buttons are 36 px pills.
use super::*;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PanelTab {
/// 動態
Activity,
/// 資料庫
Library,
}
pub const PANEL_WIDTH: f32 = 280.0;
/// Narrowest the side panel gets before it floats over the chat instead.
pub const PANEL_MIN_WIDTH: f32 = 260.0;
const ROW_H: f32 = 36.0;
/// Files shown per group before 「展開」.
const LIBRARY_FOLD: usize = 5;
impl App {
pub(super) fn bot_panel(&mut self, root: &mut egui::Ui, bot: &Bot) {
let Some(tab) = self.panel else { return };
let p = self.pal;
let ctx = root.ctx().clone();
// Next to the chat when the chat keeps its minimum width; otherwise it floats over the
// chat, so a narrow window never squeezes the chat.
let avail = root.available_width();
if avail - PANEL_MIN_WIDTH >= CHAT_MIN_WIDTH {
let w = (avail - CHAT_MIN_WIDTH).min(PANEL_WIDTH);
egui::Panel::right("bot-panel").exact_size(w).resizable(false).frame(Frame::new().fill(p.pane).inner_margin(Margin { left: 16, right: 16, top: 10, bottom: 12 })).show(root, |ui| keep_width(ui, |ui| self.panel_contents(ui, &ctx, bot, tab)));
} else {
let screen = ctx.content_rect();
let w = PANEL_WIDTH.min(avail - 16.0).max(220.0);
egui::Area::new(egui::Id::unique("bot-panel-overlay")).order(egui::Order::Foreground).anchor(egui::Align2::RIGHT_TOP, vec2(-8.0, 8.0)).show(&ctx, |ui| {
Frame::new().fill(p.pane).stroke(Stroke::new(1.0, p.border)).corner_radius(16).inner_margin(Margin::symmetric(16, 10)).shadow(egui::epaint::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(60) }).show(ui, |ui| {
ui.set_width(w);
ui.set_max_height(screen.height() - 16.0);
self.panel_contents(ui, &ctx, bot, tab);
});
});
}
}
fn panel_contents(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot, tab: PanelTab) {
let p = self.pal;
// ✕ at the top right (36 px round, like the original).
ui.horizontal(|ui| {
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if round_button(ui, p, 36.0).on_hover_text(t("關閉")).clicked() {
self.panel = None;
}
});
});
egui::ScrollArea::vertical().id_salt(("panel", bot.id, tab as u8)).auto_shrink([false, false]).show(ui, |ui| {
ui.spacing_mut().item_spacing.y = 0.0;
// The bot: big face (編輯 Bot 頭像) and its name.
ui.vertical_centered(|ui| {
let (face, r) = ui.allocate_exact_size(vec2(96.0, 96.0), egui::Sense::click());
self.live_face(ui, bot.id, face, true);
if r.on_hover_text(t("編輯 Bot 頭像")).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
self.edit_bot = Some((bot.clone(), false));
}
ui.add_space(14.0);
ui.add(egui::Label::new(RichText::new(&bot.name).size(19.0).strong().family(crate::bold()).color(p.text)).truncate());
if !bot.description.is_empty() {
ui.add_space(3.0);
ui.add(egui::Label::new(RichText::new(&bot.description).size(12.0).color(p.text3)).truncate());
}
ui.add_space(16.0);
// 動態|資料庫
ui.horizontal(|ui| {
let tabs = [(PanelTab::Activity, "動態"), (PanelTab::Library, "資料庫")];
let w: f32 = tabs.iter().map(|(_, n)| text_width(ui, &t(n), 13.0) + 24.0).sum::<f32>() + 4.0;
ui.add_space(((ui.available_width() - w) / 2.0).max(0.0));
ui.spacing_mut().item_spacing.x = 4.0;
for (tb, name) in tabs {
let on = tb == tab;
let b = egui::Button::new(RichText::new(t(name)).size(13.0).color(if on { p.text } else { p.text2 })).fill(if on { p.active } else { Color32::TRANSPARENT }).corner_radius(14).min_size(vec2(0.0, 26.0));
if ui.add(b).clicked() {
self.panel = Some(tb);
}
}
});
});
ui.add_space(22.0);
match tab {
PanelTab::Activity => self.panel_activity(ui, ctx, bot),
PanelTab::Library => self.panel_library(ui, bot),
}
ui.add_space(16.0);
});
}
fn panel_activity(&mut self, ui: &mut egui::Ui, ctx: &egui::Context, bot: &Bot) {
let p = self.pal;
// What it is doing now (only while there is something).
if self.approvals.contains_key(&bot.id) || self.streams.contains_key(&bot.id) {
panel_title(ui, "進行中", p);
let waiting = self.approvals.contains_key(&bot.id);
let status = self.streams.get(&bot.id).and_then(|l| l.status.clone()).unwrap_or_else(|| t("工作中…"));
let mut clicked = false;
panel_card(ui, p, |ui| {
let label = match self.approvals.get(&bot.id).map(|a| a.kind) {
Some(crate::providers::ApprovalKind::Handoff) => t("等你處理"),
Some(crate::providers::ApprovalKind::Question) => t("等你回答"),
_ => t("需要你允許"),
};
clicked = if waiting { panel_row(ui, p, Some(crate::icons::Icon::Shield), &label, "", true).clicked() } else { panel_row(ui, p, Some(crate::icons::Icon::Stop), &status, &t("停止"), false).clicked() };
});
if clicked {
if waiting {
self.popup_hidden.remove(&bot.id);
} else {
self.stop(bot.id);
}
}
}
// 建議
panel_title(ui, "建議", p);
let mut open_channels = false;
let mut new_routine = false;
let mut meeting = false;
let meeting_label = if self.meeting_on() { t("結束會議錄音") } else { t("加入會議") };
panel_card(ui, p, |ui| {
open_channels = panel_row(ui, p, Some(crate::icons::Icon::Chat), &t("新增至 Slack"), "", true).clicked();
new_routine = panel_row(ui, p, Some(crate::icons::Icon::Clock), &t("建立例行工作"), "", true).clicked();
if self.can_listen() || self.meeting_on() {
meeting = panel_row(ui, p, Some(crate::icons::Icon::Calendar), &meeting_label, "", true).clicked();
}
});
if open_channels {
self.show_settings = true;
self.settings_tab = SettingsTab::Channels;
}
if new_routine {
self.drafts.insert(bot.id, t("幫我建立一個例行任務:"));
}
if meeting {
// (It used to start plain voice input: the meeting ended up in the message box.)
if self.meeting_on() {
self.voice_toggle(ctx, bot.id);
} else {
self.start_meeting(ctx, bot.id);
}
}
// 例行任務 (when it has some)
if !bot.routines.is_empty() {
panel_title(ui, "例行任務", p);
let mut open = false;
panel_card(ui, p, |ui| {
for r in bot.routines.iter().take(6) {
let when = match (&r.trigger, r.paused) {
(_, true) => t("已暫停"),
(Some(tr), _) => tr.describe(),
(None, _) => crate::routines::describe(&r.schedule),
};
if panel_row_sub(ui, p, &r.title, &when).clicked() {
open = true;
}
}
});
if open {
self.show_routines = Some(bot.id);
}
}
// 電腦: the bot's own computer with a live picture of its screen (like the original).
panel_title(ui, "電腦", p);
let mut view = false;
// On a screen of a brain, the bot's computer is on the brain: its state and picture come
// from there (this computer's own box is a different machine).
let brain = self.mir.on;
let available = if brain { self.mir.box_state["available"].as_bool().unwrap_or(true) } else { crate::cloudbox::available() };
let thumb = if available { self.box_thumbnail(ctx) } else { None };
let own_name = crate::model::own_computer_name(&bot.name);
let brain_name = self.state.remote.brain_name.clone();
// 做事的電腦: which computer this bot works on (its own unless the person picks another).
let (choices, current) = if bot.members.is_empty() { self.computer_choices(bot) } else { (vec![], String::new()) };
let mut pick: Option<String> = None;
panel_card(ui, p, |ui| {
let run = crate::cloudbox::run_state();
let running = if brain { self.mir.box_state["running"].as_bool().unwrap_or(false) } else { run.is_running() };
let state = if brain {
self.mir.box_state["label"].as_str().map(t).unwrap_or_else(|| t("連線中…"))
} else if available {
t(&run.label())
} else {
t("沒有 Docker")
};
// Where it is, on its own line (it ran into the picture when it shared the state's).
let place = brain.then(|| t("在大腦「{name}」上").replace("{name}", &brain_name));
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), if place.is_some() { 72.0 } else { 64.0 }), egui::Sense::click());
if r.hovered() {
ui.painter().rect_filled(rect, 9, p.hover);
}
// Every line stops before the picture (long names end in …).
let text_w = (rect.width() - 86.0 - 10.0 - 8.0).max(40.0);
let top = if place.is_some() { 9.0 } else { 15.0 };
ui.painter().text(rect.left_top() + vec2(10.0, top), egui::Align2::LEFT_TOP, super::sidebar_ui::shorten_width(ui, &own_name, text_w, 13.0), egui::FontId::proportional(13.0), p.text);
ui.painter().text(rect.left_top() + vec2(10.0, top + 18.0), egui::Align2::LEFT_TOP, super::sidebar_ui::shorten_width(ui, &state, text_w, 12.0), egui::FontId::proportional(12.0), p.text3);
if let Some(place) = &place {
ui.painter().text(rect.left_top() + vec2(10.0, top + 35.0), egui::Align2::LEFT_TOP, super::sidebar_ui::shorten_width(ui, place, text_w, 12.0), egui::FontId::proportional(12.0), p.text3);
}
// The screen: 16:10, rounded, the real desktop when there is a picture.
let box_r = egui::Rect::from_min_size(egui::pos2(rect.right() - 86.0, rect.center().y - 24.0), vec2(78.0, 48.0));
match thumb {
Some((tex, size)) => {
let mut img = egui::Image::new((tex, size)).fit_to_exact_size(box_r.size()).corner_radius(7);
if !running {
img = img.tint(Color32::from_gray(110));
}
img.paint_at(ui, box_r);
}
None => {
ui.painter().rect_filled(box_r, 7, p.active);
let c = box_r.center();
for dx in [-5.0, 5.0] {
ui.painter().rect_filled(egui::Rect::from_center_size(c + vec2(dx, 0.0), vec2(4.0, 8.0)), 2, p.text3);
}
}
}
ui.painter().rect_stroke(box_r, 7, Stroke::new(1.0, p.border), egui::StrokeKind::Inside);
if running {
ui.painter().circle_filled(box_r.right_top() + vec2(-6.0, 6.0), 3.5, Color32::from_rgb(0x14, 0xc3, 0x70));
}
let tip = if running { t("看「{name}」的螢幕,也可以取得控制權自己操作") } else { t("叫醒「{name}」並看它的螢幕") }.replace("{name}", &own_name);
view = r.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tip).clicked();
if !choices.is_empty() {
let shown = super::sidebar_ui::shorten_width(ui, &current, (ui.available_width() - 120.0).max(60.0), 13.0);
panel_select(ui, p, "做事的電腦", ("computer", bot.id), &shown, |ui| {
for (name, kind) in &choices {
let what = t(match kind.as_str() {
"own" => "它自己的電腦",
"person" => "你正在用的這台",
"this" => "這台電腦",
"server" => "大腦所在的伺服器",
"device" => "帳號裡的電腦",
_ => "SSH 電腦",
});
if ui.selectable_label(*name == current, format!("{name} · {what}")).clicked() {
pick = Some(name.clone());
}
}
});
}
});
if let Some(n) = pick {
self.set_computer(bot.id, &n);
}
if view {
if available {
self.open_viewer();
} else {
self.show_settings = true;
self.settings_tab = SettingsTab::Computers;
}
}
// 成員 (group chats)
if !bot.members.is_empty() {
panel_title(ui, "成員", p);
let mut edit = false;
let members: Vec<Bot> = bot.members.iter().filter_map(|m| self.state.bot(*m).cloned()).collect();
let colors: Vec<Color32> = members.iter().map(|b| self.bot_color(b)).collect();
panel_card(ui, p, |ui| {
for (b, col) in members.iter().zip(colors) {
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), egui::Sense::click());
if r.hovered() {
ui.painter().rect_filled(rect, 9, p.hover);
}
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(vec2(10.0, 0.0))).layout(Layout::left_to_right(Align::Center)));
avatar::avatar(&mut child, 20.0, &b.shape, col);
child.label(RichText::new(&b.name).size(13.0).color(p.text));
edit |= r.clicked();
}
});
if edit {
self.edit_bot = Some((bot.clone(), false));
}
}
// 語音聊天: 聲音、速度、語言 (only with 設定 › 語音 set up: no voice, no section).
let (listen, speak) = (self.can_listen(), self.can_speak());
if !listen && !speak {
return;
}
panel_title(ui, "語音聊天", p);
let mut b2 = bot.clone();
let mut changed = false;
panel_card(ui, p, |ui| {
if speak {
let before = b2.voice.clone();
ui.add_space(4.0);
Frame::new().inner_margin(Margin::symmetric(10, 0)).show(ui, |ui| self.voice_picker(ui, &mut b2.voice, &format!("bot-voice-{}", bot.id)));
changed |= b2.voice != before;
let rate = if b2.voice_rate > 0.0 { b2.voice_rate } else { 1.0 };
panel_select(ui, p, "速度", ("rate", bot.id), &format!("{}x", trim_rate(rate)), |ui| {
for s in crate::voice::SPEEDS {
if ui.selectable_label((rate - s).abs() < 0.01, format!("{}x", trim_rate(s))).clicked() {
b2.voice_rate = s;
changed = true;
}
}
});
}
let lang_name = crate::voice::SPOKEN.iter().find(|l| l.0 == b2.voice_lang).map(|l| t(l.1)).unwrap_or_else(|| b2.voice_lang.clone());
panel_select(ui, p, "語言", ("lang", bot.id), &lang_name, |ui| {
for (code, name) in crate::voice::SPOKEN {
if ui.selectable_label(b2.voice_lang == code, t(name)).clicked() {
b2.voice_lang = code.to_string();
changed = true;
}
}
});
if !speak {
return;
}
// 朗讀回答 (AnyBot: read every answer aloud, not only in a call).
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), egui::Sense::click());
ui.painter().text(rect.left_center() + vec2(10.0, 0.0), egui::Align2::LEFT_CENTER, t("朗讀每個回答"), egui::FontId::proportional(13.0), p.text);
let sw = egui::Rect::from_center_size(rect.right_center() - vec2(28.0, 0.0), vec2(34.0, 20.0));
ui.painter().rect_filled(sw, 10, if b2.speak_replies { p.primary } else { p.active });
let knob = if b2.speak_replies { sw.right_center() - vec2(10.0, 0.0) } else { sw.left_center() + vec2(10.0, 0.0) };
ui.painter().circle_filled(knob, 8.0, if b2.speak_replies { p.on_primary } else { p.pane });
if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
b2.speak_replies = !b2.speak_replies;
if !b2.speak_replies {
crate::voice::stop_speaking();
}
changed = true;
}
});
if changed {
if let Some(b) = self.state.bot_mut(bot.id) {
b.voice = b2.voice;
b.voice_rate = b2.voice_rate;
b.voice_lang = b2.voice_lang;
b.speak_replies = b2.speak_replies;
}
self.mark();
}
}
/// 資料庫: the chat's files, newest first, under 本週 and 更早 (5 each, then 展開).
fn panel_library(&mut self, ui: &mut egui::Ui, bot: &Bot) {
let p = self.pal;
let mut files: Vec<(String, String, i64)> = vec![];
let mut seen = std::collections::HashSet::new();
let modified = |path: &str| std::fs::metadata(path).and_then(|m| m.modified()).ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs() as i64).unwrap_or(0);
for m in bot.messages.iter().rev() {
for a in &m.attachments {
if seen.insert(a.path.clone()) {
files.push((a.name.clone(), a.path.clone(), modified(&a.path)));
}
}
// Pages and files the bot opened for the person (on this Mac).
for c in m.tool_calls.iter().filter(|c| c.name == "open_for_person") {
let path = tools::args_of(&c.args)["path"].as_str().unwrap_or("").to_string();
if path.starts_with('/') && std::path::Path::new(&path).exists() && seen.insert(path.clone()) {
let name = std::path::Path::new(&path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let when = modified(&path);
files.push((name, path, when));
}
}
}
files.sort_by_key(|f| std::cmp::Reverse(f.2));
// 頁面 the bot made come first.
let has_pages = self.pages_library(ui, bot);
if files.is_empty() && has_pages {
return;
}
if files.is_empty() {
ui.vertical_centered(|ui| {
ui.add_space(20.0);
ui.label(RichText::new(t("這個對話裡的檔案會出現在這裡")).size(12.0).color(p.text3));
});
return;
}
let week_ago = chrono::Utc::now().timestamp() - 7 * 86_400;
let (recent, older): (Vec<_>, Vec<_>) = files.into_iter().partition(|f| f.2 >= week_ago);
for (title, list, key) in [("本週", recent, "lib-week"), ("更早", older, "lib-older")] {
if list.is_empty() {
continue;
}
panel_title(ui, title, p);
let id = egui::Id::unique((key, bot.id));
let expanded: bool = ui.data(|d| d.get_temp(id)).unwrap_or(false);
let more = list.len() > LIBRARY_FOLD;
let mut toggle = false;
panel_card(ui, p, |ui| {
for (name, path, _) in list.iter().take(if expanded { list.len() } else { LIBRARY_FOLD }) {
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), egui::Sense::click());
if r.hovered() {
ui.painter().rect_filled(rect, 9, p.hover);
}
file_glyph(ui.painter(), egui::Rect::from_center_size(rect.left_center() + vec2(20.0, 0.0), vec2(16.0, 18.0)), name, p);
let text = shorten(ui, name, rect.width() - 46.0);
ui.painter().text(rect.left_center() + vec2(36.0, 0.0), egui::Align2::LEFT_CENTER, text, egui::FontId::proportional(13.0), p.text);
if r.on_hover_text(name).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
crate::preview::open_with_system(&path.to_string());
}
}
if more {
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), egui::Sense::click());
ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, t(if expanded { "收合" } else { "展開" }), egui::FontId::proportional(12.5), p.text2);
toggle = r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
}
});
if toggle {
ui.data_mut(|d| d.insert_temp(id, !expanded));
}
}
}
}
/// A 36 px round button with ✕ (the original's close).
/// Lays out a side panel's contents so they can't widen it. Contents wider than a right panel make
/// egui move the panel's left edge in by the overflow (it trims the panel from its far end), and
/// the chat then covers that much of it, as the voice row once did; this way too-wide contents are
/// cut off at the right edge instead.
fn keep_width<R>(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R {
let rect = ui.max_rect();
let mut inner = ui.new_child(egui::UiBuilder::new().id_salt("keep-width").max_rect(rect).layout(Layout::top_down(Align::Min)));
add(&mut inner)
}
fn round_button(ui: &mut egui::Ui, p: Palette, size: f32) -> egui::Response {
let (rect, r) = ui.allocate_exact_size(vec2(size, size), egui::Sense::click());
ui.painter().circle_filled(rect.center(), size / 2.0, if r.hovered() { p.hover } else { p.elevated });
ui.painter().circle_stroke(rect.center(), size / 2.0 - 0.5, Stroke::new(1.0, p.border));
let c = rect.center();
let st = Stroke::new(1.5, p.text2);
ui.painter().line_segment([c + vec2(-5.0, -5.0), c + vec2(5.0, 5.0)], st);
ui.painter().line_segment([c + vec2(-5.0, 5.0), c + vec2(5.0, -5.0)], st);
r.on_hover_cursor(egui::CursorIcon::PointingHand)
}
pub(super) fn panel_title(ui: &mut egui::Ui, title: &str, p: Palette) {
ui.horizontal(|ui| {
ui.add_space(12.0);
ui.label(RichText::new(t(title)).size(13.0).color(p.text.gamma_multiply(0.66)));
});
ui.add_space(8.0);
}
/// The original's card: radius 12, a hairline border, 4 px inside.
pub(super) fn panel_card(ui: &mut egui::Ui, p: Palette, body: impl FnOnce(&mut egui::Ui)) {
Frame::new().fill(p.elevated).stroke(Stroke::new(1.0, p.border)).corner_radius(12).inner_margin(Margin::same(4)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.spacing_mut().item_spacing.y = 0.0;
body(ui);
});
ui.add_space(22.0);
}
/// One row: icon, label, then a value or a chevron.
fn panel_row(ui: &mut egui::Ui, p: Palette, icon: Option<crate::icons::Icon>, label: &str, value: &str, chevron: bool) -> egui::Response {
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), egui::Sense::click());
if r.hovered() {
ui.painter().rect_filled(rect, 9, p.hover);
}
let mut x = rect.left() + 10.0;
if let Some(ic) = icon {
crate::icons::paint(ui.painter(), egui::Rect::from_center_size(egui::pos2(x + 8.0, rect.center().y), vec2(15.0, 15.0)), ic, p.text2);
x += 26.0;
}
ui.painter().text(egui::pos2(x, rect.center().y), egui::Align2::LEFT_CENTER, label, egui::FontId::proportional(13.0), p.text);
let right = rect.right() - 12.0;
if chevron {
let c = egui::pos2(right - 3.0, rect.center().y);
let st = Stroke::new(1.4, p.text3);
ui.painter().line_segment([c + vec2(-3.0, -4.5), c + vec2(1.5, 0.0)], st);
ui.painter().line_segment([c + vec2(-3.0, 4.5), c + vec2(1.5, 0.0)], st);
} else if !value.is_empty() {
ui.painter().text(egui::pos2(right, rect.center().y), egui::Align2::RIGHT_CENTER, value, egui::FontId::proportional(13.0), p.text2);
}
r.on_hover_cursor(egui::CursorIcon::PointingHand)
}
/// A two-line row (title and a smaller grey line).
fn panel_row_sub(ui: &mut egui::Ui, p: Palette, title: &str, sub: &str) -> egui::Response {
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), 46.0), egui::Sense::click());
if r.hovered() {
ui.painter().rect_filled(rect, 9, p.hover);
}
let w = rect.width() - 20.0;
let title = shorten(ui, title, w);
let sub = shorten_size(ui, sub, w, 12.0);
ui.painter().text(rect.left_top() + vec2(10.0, 8.0), egui::Align2::LEFT_TOP, title, egui::FontId::proportional(13.0), p.text);
ui.painter().text(rect.left_top() + vec2(10.0, 26.0), egui::Align2::LEFT_TOP, sub, egui::FontId::proportional(12.0), p.text3);
r.on_hover_cursor(egui::CursorIcon::PointingHand)
}
/// A label with a small drop-down on the right (語音 Helix ⌄).
fn panel_select(ui: &mut egui::Ui, p: Palette, label: &str, id: impl std::hash::Hash + std::fmt::Debug, shown: &str, menu: impl FnOnce(&mut egui::Ui)) {
ui.horizontal(|ui| {
ui.set_height(ROW_H);
ui.add_space(10.0);
ui.label(RichText::new(t(label)).size(13.0).color(p.text));
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.add_space(4.0);
// Plain text and a small chevron, no box (like the original's "Helix ⌄").
let w = &mut ui.style_mut().visuals.widgets;
for st in [&mut w.inactive, &mut w.hovered, &mut w.active, &mut w.open] {
st.weak_bg_fill = Color32::TRANSPARENT;
st.bg_fill = Color32::TRANSPARENT;
st.bg_stroke = Stroke::NONE;
}
w.hovered.weak_bg_fill = p.hover;
w.open.weak_bg_fill = p.hover;
egui::ComboBox::from_id_salt(id).selected_text(RichText::new(shown).size(13.0).color(p.text2)).icon(chevron_down).width(0.0).height(320.0).show_ui(ui, menu);
});
});
}
/// The small ⌄ after a value.
fn chevron_down(ui: &egui::Ui, rect: egui::Rect, visuals: &egui::style::WidgetVisuals, _open: bool) {
let c = rect.center();
let st = Stroke::new(1.3, visuals.fg_stroke.color.gamma_multiply(0.7));
ui.painter().line_segment([c + vec2(-3.5, -1.5), c + vec2(0.0, 2.0)], st);
ui.painter().line_segment([c + vec2(3.5, -1.5), c + vec2(0.0, 2.0)], st);
}
fn trim_rate(r: f32) -> String {
let s = format!("{r:.2}");
s.trim_end_matches('0').trim_end_matches('.').to_string()
}
fn text_width(ui: &egui::Ui, s: &str, size: f32) -> f32 {
ui.painter().layout_no_wrap(s.to_string(), egui::FontId::proportional(size), Color32::WHITE).size().x
}
fn shorten(ui: &egui::Ui, s: &str, max_w: f32) -> String {
shorten_size(ui, s, max_w, 13.0)
}
/// Cut text to fit, keeping the end of a file name ("orders_….xlsx" like the original).
pub(super) fn shorten_size(ui: &egui::Ui, s: &str, max_w: f32, size: f32) -> String {
if text_width(ui, s, size) <= max_w {
return s.to_string();
}
let chars: Vec<char> = s.chars().collect();
let tail: String = s.rsplit_once('.').filter(|(_, e)| e.chars().count() <= 5).map(|(_, e)| format!(".{e}")).unwrap_or_default();
let tail_n = tail.chars().count();
let mut n = chars.len().saturating_sub(tail_n);
while n > 1 {
let cand: String = chars[..n].iter().collect::<String>() + "…" + &tail;
if text_width(ui, &cand, size) <= max_w {
return cand;
}
n -= 1;
}
"…".into()
}
/// A small mark for the file's kind (the same Lucide icons as the cards).
fn file_glyph(painter: &egui::Painter, r: egui::Rect, name: &str, p: Palette) {
let col = match crate::preview::kind_of(name) {
"sheet" => Color32::from_rgb(0x1f, 0xb3, 0x5d),
"markdown" => Color32::from_rgb(0x8b, 0x5c, 0xf6),
"html" => Color32::from_rgb(0xf9, 0x73, 0x16),
"pdf" => Color32::from_rgb(0xe5, 0x48, 0x4d),
_ => p.text2,
};
crate::icons::paint(painter, egui::Rect::from_center_size(r.center(), vec2(16.0, 16.0)), crate::icons::for_file(name), col);
}
#[cfg(test)]
mod tests {
use super::*;
/// Where the chat ends (= the side panel's left edge) in a 1000 px window with a 280 px panel
/// whose contents want 400 px.
fn chat_right_edge(guarded: bool) -> f32 {
let ctx = egui::Context::default();
let mut edge = 0.0;
for _ in 0..2 {
let input = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1000.0, 600.0))), ..Default::default() };
let mut out = ctx.run_ui(input, |root| {
let wide = |ui: &mut egui::Ui| {
ui.horizontal(|ui| {
ui.allocate_exact_size(vec2(400.0, 20.0), egui::Sense::hover());
});
};
egui::Panel::right("p").exact_size(PANEL_WIDTH).resizable(false).frame(Frame::NONE).show(root, |ui| {
if guarded {
keep_width(ui, wide);
} else {
wide(ui);
}
});
edge = root.available_rect_before_wrap().right();
});
out.textures_delta.clear(); // (no renderer here to hand the font atlas to)
}
edge
}
#[test]
fn too_wide_contents_keep_the_panel_in_place() {
// What egui does on its own: the panel's left edge moves in by the overflow, under the chat.
assert!(chat_right_edge(false) > 1000.0 - PANEL_WIDTH + 50.0, "{}", chat_right_edge(false));
assert_eq!(chat_right_edge(true), 1000.0 - PANEL_WIDTH);
}
}