AnyBot/src/app/panel_ui.rs

679 lines
36 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(R_L).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(FONT_H3).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(FONT_XS).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(FONT_SM).color(if on { p.text } else { p.text2 })).fill(if on { p.active } else { Color32::TRANSPARENT }).corner_radius(R_L).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);
}
}
}
// 操作紀錄: what it did, turn by turn (activity_ui).
self.panel_record(ui, ctx, bot);
// 建議
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() };
// A computer not made yet has no screen: an old picture left from before (often just
// black) is not shown as if it were its screen.
let absent = if brain { self.mir.box_state["label"].as_str() == Some("尚未建立") } else { crate::cloudbox::run_state() == crate::cloudbox::Run::Absent };
let thumb = if available && !absent { 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) —
// shown here, set in one place: Bot 設定 › 電腦操作 (the name opens it there).
let (choices, current) = if bot.members.is_empty() { self.computer_choices(bot) } else { (vec![], String::new()) };
let mut change = false;
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, R_M, 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(FONT_SM), 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(FONT_XS), 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(FONT_XS), p.text3);
}
// The screen: 16:10, rounded, the real desktop when there is a picture; until there is
// one, a quiet muted tile with a small screen mark (never an empty black box).
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(R_S);
if !running {
img = img.tint(Color32::from_gray(110));
}
img.paint_at(ui, box_r);
ui.painter().rect_stroke(box_r, R_S, Stroke::new(1.0, p.border), egui::StrokeKind::Inside);
}
None => {
ui.painter().rect_filled(box_r, R_S, p.muted);
crate::icons::paint(ui.painter(), egui::Rect::from_center_size(box_r.center(), vec2(18.0, 18.0)), crate::icons::Icon::Monitor, p.text3);
}
}
if running {
ui.painter().circle_filled(box_r.right_top() + vec2(-6.0, 6.0), 3.5, p.up);
}
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 tools = bot.tools_enabled || self.direct_on();
let tip = if tools { t("在 Bot 設定 › 電腦操作 裡改") } else { t("這個 Bot 的電腦操作關著:用電腦前會先問你。在 Bot 設定 › 電腦操作 裡改") };
change = panel_link_row(ui, p, "做事的電腦", &current).on_hover_text(tip).clicked();
}
});
if change {
self.edit_bot_at(ctx, bot, "computer");
}
// 全部螢幕: every bot's own screen at once (when any is open).
let open = if available { self.screen_tiles().len() } else { 0 };
if open > 0 {
let label = t("全部螢幕({n})").replace("{n}", &open.to_string());
ui.horizontal(|ui| {
ui.add_space(10.0);
if ui.add(egui::Label::new(RichText::new(label).size(FONT_XS).color(p.accent)).sense(egui::Sense::click())).on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(t("每個 Bot 自己的螢幕,一次看")).clicked() {
self.cu.screens.open = true;
}
});
}
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();
// 每個 Bot 一個螢幕: a member's own screen, small, when it has one open; a click
// shows it in the 電腦 card (again: back to the member speaking).
let pictures: Vec<_> = members.iter().map(|b| self.screen_tile(b.id)).collect();
let shown = self.screen_key_for(self.shown_bot(bot.id));
let keys: Vec<String> = members.iter().map(|b| self.screen_key_for(b.id)).collect();
let picked = self.cu.screens.pick.get(&bot.id).copied();
let mut pick: Option<Option<u64>> = None;
panel_card(ui, p, |ui| {
for (((b, col), pic), key) in members.iter().zip(colors).zip(&pictures).zip(&keys) {
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), ROW_H), egui::Sense::click());
if r.hovered() {
ui.painter().rect_filled(rect, R_M, p.hover);
}
// (The name stops before the member's screen, and ends in … when it is long.)
let mut words = rect.shrink2(vec2(10.0, 0.0));
if pic.is_some() {
words.max.x -= 48.0;
}
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(words).layout(Layout::left_to_right(Align::Center)));
avatar::avatar(&mut child, 20.0, &b.shape, col);
child.add(egui::Label::new(RichText::new(&b.name).size(FONT_SM).color(p.text)).truncate());
if let Some((tex, size)) = pic {
let at = egui::Rect::from_min_size(egui::pos2(rect.right() - 10.0 - 40.0, rect.center().y - 12.5), vec2(40.0, 25.0));
let on = *key == shown;
let tr = ui.interact(at, egui::Id::unique(("member-screen", b.id)), egui::Sense::click());
egui::Image::new((*tex, *size)).fit_to_exact_size(at.size()).corner_radius(R_S).paint_at(ui, at);
ui.painter().rect_stroke(at, R_S, Stroke::new(if on { 2.0 } else { 1.0 }, if on { p.accent } else { p.border }), egui::StrokeKind::Inside);
let tip = if on { t("右側正在顯示「{name}」的螢幕") } else { t("在右側顯示「{name}」的螢幕") }.replace("{name}", &b.name);
if tr.on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text(tip).clicked() {
pick = Some(if picked == Some(b.id) { None } else { Some(b.id) });
continue;
}
}
edit |= r.clicked();
}
});
match pick {
Some(Some(m)) => {
self.cu.screens.pick.insert(bot.id, m);
}
Some(None) => {
self.cu.screens.pick.remove(&bot.id);
}
None => {}
}
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 {
// 聲音 like 速度 and 語言: one row, its menu offers 預設 and the service's voices.
let before = b2.voice.clone();
let inherit = self.state.voice.speak.voice.clone();
let row = self.voice_row(ui.ctx(), &b2.voice, &inherit);
let at = format!("bot-voice-{}", bot.id);
panel_select_with(ui, p, "聲音", ("voice", bot.id), &row.shown, egui::PopupCloseBehavior::CloseOnClickOutside, |ui| self.voice_menu(ui, &mut b2.voice, &row, &at));
changed |= b2.voice != before;
if let Some(e) = self.voice_note(&at) {
Frame::new().inner_margin(Margin::symmetric(10, 0)).show(ui, |ui| {
ui.add(egui::Label::new(RichText::new(&e).size(FONT_XS).color(p.danger)).truncate()).on_hover_text(e);
});
}
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(FONT_SM), 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, R_M, 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(FONT_XS).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, R_M, 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(FONT_SM), 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(FONT_SM), 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(FONT_SM).color(p.text.gamma_multiply(0.66)));
});
ui.add_space(8.0);
}
/// The original's card: radius 12, a hairline border — with real 天地 inside (a 4 px inset
/// made every row hug the frame; the panel's cards read as a stack of labels, not cards).
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(R_M).inner_margin(Margin::symmetric(12, 10)).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.spacing_mut().item_spacing.y = 6.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, R_M, 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;
}
let right = rect.right() - 12.0;
// The value (or the chevron) keeps its place at the right; the label gets the room that is
// left and ends in … (a long retry message ran over 停止 and out of the card).
let value_w = if chevron { 14.0 } else if value.is_empty() { 0.0 } else { text_width(ui, value, 13.0) + 12.0 };
let shown = super::sidebar_ui::shorten_width(ui, label, (right - value_w - x).max(24.0), 13.0);
let cut = shown != label;
ui.painter().text(egui::pos2(x, rect.center().y), egui::Align2::LEFT_CENTER, shown, egui::FontId::proportional(FONT_SM), p.text);
let r = if cut { r.on_hover_text(label) } else { r };
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(FONT_SM), 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, R_M, 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(FONT_SM), p.text);
ui.painter().text(rect.left_top() + vec2(10.0, 26.0), egui::Align2::LEFT_TOP, sub, egui::FontId::proportional(FONT_XS), 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)) {
panel_select_with(ui, p, label, id, shown, egui::PopupCloseBehavior::CloseOnClick, menu);
}
/// A row that shows a value set elsewhere: the label, and on the right the value with a › (the
/// whole row opens where it is set).
fn panel_link_row(ui: &mut egui::Ui, p: Palette, label: &str, value: &str) -> 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, R_M, p.hover);
}
let label = ui.painter().text(rect.left_center() + vec2(10.0, 0.0), egui::Align2::LEFT_CENTER, t(label), egui::FontId::proportional(FONT_SM), p.text);
// The value takes what is left between the label and the ›.
let shown = super::sidebar_ui::shorten_width(ui, value, (rect.right() - 24.0 - 4.0 - label.right() - 8.0).max(40.0), FONT_SM);
let chev = egui::Rect::from_center_size(rect.right_center() - vec2(12.0, 0.0), vec2(11.0, 11.0));
crate::icons::paint(ui.painter(), chev, crate::icons::Icon::ChevronRight, p.text3);
ui.painter().text(chev.left_center() - vec2(4.0, 0.0), egui::Align2::RIGHT_CENTER, shown, egui::FontId::proportional(FONT_SM), p.text2);
r.on_hover_cursor(egui::CursorIcon::PointingHand)
}
/// The same, choosing how its menu closes (one with a field in it stays open while typing).
fn panel_select_with(ui: &mut egui::Ui, p: Palette, label: &str, id: impl std::hash::Hash + std::fmt::Debug, shown: &str, close: egui::PopupCloseBehavior, 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(FONT_SM).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(FONT_SM).color(p.text2)).icon(chevron_down).width(0.0).height(320.0).close_behavior(close).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()
}
pub(super) 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).
pub(super) 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);
}
}