AnyBot/src/app/library_ui.rs

320 lines
17 KiB
Rust
Raw Normal View History

所有檔案(計畫 C6,照 OpenBot 檔案庫的排版):每個 Bot 交給你的、你傳給 Bot 的檔案,跨 Bot、跨對話放在一個視窗。從聊天(含較早的對話)已經記下的附件來,不掃硬碟;同一個檔案只列一次,新的在前,開著每 5 秒重讀。側邊欄最上面多一個資料夾按鈕(任務左邊),左下角選單多「所有檔案…」。左欄:搜尋檔名、所有檔案、最近 7 天、每個有檔案的 Bot(顏色點、數量);上面種類分頁帶數量(全部、圖片、文件、程式碼、表格、影音、其他,沒有的不列);右上格子/清單:格子是縮圖或副檔名、檔名、「Bot · 日期」,一排撐滿寬度;清單是「Bot · 日期 · 大小」。視窗高度固定,切種類、看法不跳。檔案被刪掉或搬走的:灰字、紅字「不見了」,點不開;其他點一下用 AnyBot 原本的檢視器打開。 功能地圖新的一區 library.md;settings.md 的左下角選單補上「所有檔案…」「個人資料與用量…」(截圖幀數 14 → 60:14 幀時選單還在淡入,看起來像被後面那列蓋住)。 已驗證: cargo test 834 過(featuremap::、layout_audit:: 含新的「所有檔案」一景);clippy 維持 12(都是沒動到的檔);scratch 照 library.md 三步重跑一次:手機附上七個檔(兩張貓、md、csv、py、txt、zip)送出、刪掉 AnyBot 裡舊的.txt 那份 → 桌面點側邊欄資料夾按鈕:左欄 所有檔案 7/最近 7 天 7/驗證小幫手 7,分頁 全部 7、圖片 2、文件 2、程式碼 1、表格 1、其他 1,貓是縮圖,舊的.txt 紅字「不見了(檔案已經刪掉或搬走)」;按「清單」每列 Bot · 今天 14:17 · 大小,舊的.txt「不見了」;按 release-notes-v4.md 在檢視器打開「發布計畫/11/22 上線」;左下角選單(示範資料)分隔線下 所有檔案…/個人資料與用量…/設定…。 未驗證: 螢幕電腦上的「所有檔案」(看的是從大腦抓的副本;scratch 沒有第二台);搜尋框、點某個 Bot、圖片以外種類的實際篩選結果只看了數量(截圖工具不能打字);幾百個以上檔案時的速度(每 5 秒在畫面執行緒查一次檔案在不在)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm
2026-11-21 06:19:29 +00:00
// 所有檔案 (plan C6, laid out like OpenBot's library): every file the bots handed over or were
// given, across bots and conversations, from the attachments the chats already keep — nothing on
// disk is scanned. By kind (圖片、文件、程式碼、表格、影音、其他, each with its count), by bot, the
// last 7 days, a search; as cards or a list; each still there or gone; opened in AnyBot's own
// viewer (files_ui). Gathered when the window opens and again every few seconds while it shows.
use super::*;
#[derive(Default)]
pub(super) struct LibraryUi {
pub open: bool,
files: Vec<Item>,
pub at: Option<Instant>,
kind: &'static str,
place: Place,
query: String,
list: bool,
}
#[derive(Default, Clone, Copy, PartialEq)]
enum Place {
#[default]
All,
Recent,
Bot(u64),
}
#[derive(Clone)]
struct Item {
name: String,
path: String,
bot: u64,
at: i64,
bytes: u64,
kind: &'static str,
there: bool,
image: bool,
}
const KINDS: [(&str, &str); 7] = [("all", "全部"), ("image", "圖片"), ("doc", "文件"), ("code", "程式碼"), ("sheet", "表格"), ("media", "影音"), ("other", "其他")];
const EVERY_SECS: u64 = 5;
const CARD_W: f32 = 168.0;
const CARD_H: f32 = 156.0;
const CODE_EXT: &[&str] = &[
"rs", "py", "pyi", "js", "jsx", "mjs", "cjs", "ts", "tsx", "go", "java", "kt", "swift", "c", "h", "cc", "cpp", "hpp", "m", "mm", "rb", "php", "sh", "bash", "zsh", "fish", "ps1", "lua", "sql", "css", "scss", "vue", "svelte", "json", "jsonl",
"yaml", "yml", "toml", "xml",
];
/// A file's kind in the library: 圖片、文件、程式碼、表格、影音、其他.
pub(super) fn library_kind(name: &str) -> &'static str {
let ext = name.rsplit_once('.').map(|(_, e)| e.to_lowercase()).unwrap_or_default();
match crate::preview::kind_of(name) {
"image" => "image",
"video" | "audio" => "media",
"sheet" => "sheet",
_ if CODE_EXT.contains(&ext.as_str()) => "code",
"markdown" | "docx" | "doc" | "pdf" | "html" | "text" => "doc",
_ => "other",
}
}
impl App {
/// 所有檔案 for the phone: the same files, newest first (at most 500).
pub(super) fn library_json(&self) -> serde_json::Value {
let mut seen = std::collections::HashSet::new();
let mut files = vec![];
for b in &self.state.bots {
for m in b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())) {
for a in &m.attachments {
if a.path.is_empty() || !seen.insert(a.path.clone()) {
continue;
}
files.push((m.at, serde_json::json!({"name": a.name, "path": a.path, "bot": b.id, "at": m.at, "bytes": a.bytes, "kind": library_kind(&a.name), "there": std::path::Path::new(&a.path).exists(), "image": a.image})));
}
}
}
files.sort_by_key(|f| std::cmp::Reverse(f.0));
serde_json::json!({"ok": true, "files": files.into_iter().take(500).map(|f| f.1).collect::<Vec<_>>()})
}
所有檔案(計畫 C6,照 OpenBot 檔案庫的排版):每個 Bot 交給你的、你傳給 Bot 的檔案,跨 Bot、跨對話放在一個視窗。從聊天(含較早的對話)已經記下的附件來,不掃硬碟;同一個檔案只列一次,新的在前,開著每 5 秒重讀。側邊欄最上面多一個資料夾按鈕(任務左邊),左下角選單多「所有檔案…」。左欄:搜尋檔名、所有檔案、最近 7 天、每個有檔案的 Bot(顏色點、數量);上面種類分頁帶數量(全部、圖片、文件、程式碼、表格、影音、其他,沒有的不列);右上格子/清單:格子是縮圖或副檔名、檔名、「Bot · 日期」,一排撐滿寬度;清單是「Bot · 日期 · 大小」。視窗高度固定,切種類、看法不跳。檔案被刪掉或搬走的:灰字、紅字「不見了」,點不開;其他點一下用 AnyBot 原本的檢視器打開。 功能地圖新的一區 library.md;settings.md 的左下角選單補上「所有檔案…」「個人資料與用量…」(截圖幀數 14 → 60:14 幀時選單還在淡入,看起來像被後面那列蓋住)。 已驗證: cargo test 834 過(featuremap::、layout_audit:: 含新的「所有檔案」一景);clippy 維持 12(都是沒動到的檔);scratch 照 library.md 三步重跑一次:手機附上七個檔(兩張貓、md、csv、py、txt、zip)送出、刪掉 AnyBot 裡舊的.txt 那份 → 桌面點側邊欄資料夾按鈕:左欄 所有檔案 7/最近 7 天 7/驗證小幫手 7,分頁 全部 7、圖片 2、文件 2、程式碼 1、表格 1、其他 1,貓是縮圖,舊的.txt 紅字「不見了(檔案已經刪掉或搬走)」;按「清單」每列 Bot · 今天 14:17 · 大小,舊的.txt「不見了」;按 release-notes-v4.md 在檢視器打開「發布計畫/11/22 上線」;左下角選單(示範資料)分隔線下 所有檔案…/個人資料與用量…/設定…。 未驗證: 螢幕電腦上的「所有檔案」(看的是從大腦抓的副本;scratch 沒有第二台);搜尋框、點某個 Bot、圖片以外種類的實際篩選結果只看了數量(截圖工具不能打字);幾百個以上檔案時的速度(每 5 秒在畫面執行緒查一次檔案在不在)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha2uBHmbnuWBhNzjbJm
2026-11-21 06:19:29 +00:00
fn library_gather(&mut self) {
let mut seen = std::collections::HashSet::new();
let mut files = vec![];
for b in &self.state.bots {
let all = b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter()));
for m in all {
for a in &m.attachments {
if a.path.is_empty() || !seen.insert(a.path.clone()) {
continue;
}
files.push(Item { name: a.name.clone(), path: a.path.clone(), bot: b.id, at: m.at, bytes: a.bytes, kind: library_kind(&a.name), there: std::path::Path::new(&a.path).exists(), image: a.image });
}
}
}
files.sort_by_key(|f| std::cmp::Reverse(f.at));
self.lib.files = files;
self.lib.at = Some(Instant::now());
}
/// The window.
pub(super) fn library_window(&mut self, ctx: &egui::Context) {
if !self.lib.open {
return;
}
if self.lib.at.is_none_or(|t| t.elapsed().as_secs() >= EVERY_SECS) {
self.library_gather();
}
if self.lib.kind.is_empty() {
self.lib.kind = "all";
}
let p = self.pal;
let body_h = dialog_max_height(ctx) - 48.0;
let names: HashMap<u64, (String, Color32)> = self.state.bots.iter().map(|b| (b.id, (b.name.clone(), self.bot_color(b)))).collect();
let week = crate::model::now_ms() - 7 * 86_400_000;
let q = self.lib.query.trim().to_lowercase();
let in_place = |f: &Item, place: Place| match place {
Place::All => true,
Place::Recent => f.at >= week,
Place::Bot(id) => f.bot == id,
};
let mut open: Option<(String, String)> = None;
let closed = dialog(ctx, "library", "所有檔案", 960.0, true, p, |ui| {
// (The left column keeps off the dialog's edge; the right one's files get their margin
// from dialog_body, and the kinds above them take the same.)
Frame::new().inner_margin(Margin { left: 16, right: 0, top: 10, bottom: 0 }).show(ui, |ui| {
ui.horizontal_top(|ui| {
// Left: the search, where, each bot.
ui.vertical(|ui| {
ui.set_width(200.0);
ui.add(egui::TextEdit::singleline(&mut self.lib.query).hint_text(t("搜尋檔案名稱")).desired_width(196.0));
ui.add_space(8.0);
let count = |place: Place| self.lib.files.iter().filter(|f| in_place(f, place)).count();
let mut pick: Option<Place> = None;
let mut row = |ui: &mut egui::Ui, place: Place, label: &str, dot: Option<Color32>, n: usize, cur: Place| {
let (rect, r) = ui.allocate_exact_size(vec2(196.0, 30.0), egui::Sense::click());
if cur == place || r.hovered() {
ui.painter().rect_filled(rect, R_M, if cur == place { p.active } else { p.hover });
}
let mut x = rect.left() + 10.0;
if let Some(c) = dot {
ui.painter().circle_filled(egui::pos2(x + 5.0, rect.center().y), 5.0, c);
x += 16.0;
}
let label = super::sidebar_ui::shorten_width(ui, label, 196.0 - (x - rect.left()) - 40.0, FONT_SM);
ui.painter().text(egui::pos2(x, rect.center().y), egui::Align2::LEFT_CENTER, label, egui::FontId::proportional(FONT_SM), p.text);
ui.painter().text(rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, n.to_string(), egui::FontId::proportional(FONT_XS), p.text3);
if r.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
pick = Some(place);
}
};
let cur = self.lib.place;
row(ui, Place::All, &t("所有檔案"), None, count(Place::All), cur);
row(ui, Place::Recent, &t("最近 7 天"), None, count(Place::Recent), cur);
ui.add_space(10.0);
ui.label(RichText::new(t("Bot")).size(FONT_XS).color(p.text3));
let mut bots: Vec<(u64, String, Color32, usize)> = names.iter().map(|(id, (n, c))| (*id, n.clone(), *c, count(Place::Bot(*id)))).filter(|b| b.3 > 0).collect();
bots.sort_by_key(|b| (std::cmp::Reverse(b.3), b.1.clone()));
for (id, n, c, k) in bots {
row(ui, Place::Bot(id), &n, Some(c), k, cur);
}
if let Some(pl) = pick {
self.lib.place = pl;
}
});
ui.add_space(12.0);
// Right: the kinds, the view, the files. (Given its height: a column in a row only
// gets the row's, and the files would scroll in a strip.)
ui.allocate_ui_with_layout(vec2(ui.available_width(), body_h - 20.0), Layout::top_down(Align::Min), |ui| {
// One height whatever is shown: switching kinds or views doesn't make the
// window jump.
ui.set_min_height(body_h - 20.0);
let here: Vec<&Item> = self.lib.files.iter().filter(|f| in_place(f, self.lib.place) && (q.is_empty() || f.name.to_lowercase().contains(&q))).collect();
Frame::new().inner_margin(Margin { left: 20, right: 20, top: 0, bottom: 0 }).show(ui, |ui| {
ui.horizontal_wrapped(|ui| {
for (k, label) in KINDS {
let n = here.iter().filter(|f| k == "all" || f.kind == k).count();
if n == 0 && k != "all" {
continue;
}
let on = self.lib.kind == k;
let text = RichText::new(format!("{} {n}", t(label))).size(FONT_SM).color(if on { p.text } else { p.text2 });
if ui.add(egui::Button::new(if on { text.strong() } else { text }).fill(if on { p.active } else { Color32::TRANSPARENT }).corner_radius(R_M)).clicked() {
self.lib.kind = k;
}
}
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if let Some(v) = segmented(ui, p, self.lib.list, &[(false, "格子"), (true, "清單")]) {
self.lib.list = v;
}
});
});
});
ui.add_space(8.0);
let shown: Vec<Item> = here.into_iter().filter(|f| self.lib.kind == "all" || f.kind == self.lib.kind).cloned().collect();
dialog_body(ui, "library-body", body_h - 60.0, |ui| {
if shown.is_empty() {
hint(ui, if self.lib.files.is_empty() { "還沒有檔案。Bot 交給你的、你傳給 Bot 的檔案都會出現在這裡。" } else { "沒有符合的檔案" }, p);
return;
}
if self.lib.list {
for f in &shown {
if self.library_row(ui, f, &names) {
open = Some((f.name.clone(), f.path.clone()));
}
}
} else {
// As many as fit, widened to fill the row.
let avail = ui.available_width();
let cols = ((avail + 10.0) / (CARD_W + 10.0)).floor().max(1.0) as usize;
let w = ((avail - 10.0 * (cols - 1) as f32) / cols as f32).floor();
for chunk in shown.chunks(cols) {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 10.0;
for f in chunk {
if self.library_card(ui, f, w, &names) {
open = Some((f.name.clone(), f.path.clone()));
}
}
});
ui.add_space(10.0);
}
}
});
});
});
});
});
if let Some((name, path)) = open {
self.open_file(&name, &path);
}
if closed {
self.lib.open = false;
}
}
/// One file as a card: the picture (or its kind), the name, whose and when; a gone one says so.
fn library_card(&mut self, ui: &mut egui::Ui, f: &Item, w: f32, names: &HashMap<u64, (String, Color32)>) -> bool {
let p = self.pal;
let (rect, r) = ui.allocate_exact_size(vec2(w, CARD_H), if f.there { egui::Sense::click() } else { egui::Sense::hover() });
ui.painter().rect_filled(rect, R_L, if r.hovered() && f.there { p.hover } else { p.elevated });
ui.painter().rect_stroke(rect, R_L, Stroke::new(1.0, p.border), egui::StrokeKind::Inside);
let top = egui::Rect::from_min_size(rect.min + vec2(8.0, 8.0), vec2(w - 16.0, 96.0));
let ctx = ui.ctx().clone();
let thumb = if f.image && f.there { self.thumb(&ctx, &f.path) } else { None };
match thumb {
Some(tex) => {
let s = tex.size_vec2();
let k = (top.width() / s.x).max(top.height() / s.y);
let shown = s * k;
let uv = egui::Rect::from_center_size(egui::pos2(0.5, 0.5), vec2(top.width() / shown.x, top.height() / shown.y));
egui::Image::new((tex.id(), top.size())).uv(uv).corner_radius(R_M).paint_at(ui, top);
}
None => {
ui.painter().rect_filled(top, R_M, p.hover);
let ext = f.name.rsplit_once('.').map(|(_, e)| e.to_uppercase()).unwrap_or_else(|| "FILE".into());
ui.painter().text(top.center(), egui::Align2::CENTER_CENTER, ext.chars().take(5).collect::<String>(), egui::FontId::new(FONT_H3, crate::bold()), p.text2);
}
}
let name = super::sidebar_ui::shorten_width(ui, &f.name, w - 16.0, FONT_SM);
ui.painter().text(egui::pos2(rect.left() + 8.0, top.bottom() + 10.0), egui::Align2::LEFT_TOP, name, egui::FontId::proportional(FONT_SM), if f.there { p.text } else { p.text3 });
let sub = if f.there { format!("{} · {}", names.get(&f.bot).map(|x| x.0.as_str()).unwrap_or("?"), when_words(f.at)) } else { t("不見了(檔案已經刪掉或搬走)") };
let sub = super::sidebar_ui::shorten_width(ui, &sub, w - 16.0, FONT_XS);
ui.painter().text(egui::pos2(rect.left() + 8.0, top.bottom() + 30.0), egui::Align2::LEFT_TOP, sub, egui::FontId::proportional(FONT_XS), if f.there { p.text3 } else { p.danger });
let tip = format!("{}\n{}{}", f.name, f.path, if f.bytes > 0 { format!("\n{}", size_words(f.bytes)) } else { String::new() });
r.on_hover_text(tip).clicked()
}
/// One file as a row (the list view).
fn library_row(&mut self, ui: &mut egui::Ui, f: &Item, names: &HashMap<u64, (String, Color32)>) -> bool {
let p = self.pal;
let (rect, r) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), if f.there { egui::Sense::click() } else { egui::Sense::hover() });
if r.hovered() && f.there {
ui.painter().rect_filled(rect, R_M, p.hover);
}
super::panel_ui::file_glyph(ui.painter(), egui::Rect::from_center_size(rect.left_center() + vec2(16.0, 0.0), vec2(16.0, 18.0)), &f.name, p);
let right = if f.there { format!("{} · {} · {}", names.get(&f.bot).map(|x| x.0.as_str()).unwrap_or("?"), when_words(f.at), size_words(f.bytes)) } else { t("不見了") };
let rw = super::panel_ui::text_width(ui, &right, FONT_XS) + 12.0;
let name = super::sidebar_ui::shorten_width(ui, &f.name, rect.width() - 40.0 - rw, FONT_SM);
ui.painter().text(rect.left_center() + vec2(32.0, 0.0), egui::Align2::LEFT_CENTER, name, egui::FontId::proportional(FONT_SM), if f.there { p.text } else { p.text3 });
ui.painter().text(rect.right_center() - vec2(8.0, 0.0), egui::Align2::RIGHT_CENTER, right, egui::FontId::proportional(FONT_XS), if f.there { p.text3 } else { p.danger });
r.on_hover_text(&f.path).clicked()
}
}
/// 11/20, 今天 14:05.
fn when_words(ms: i64) -> String {
use chrono::TimeZone;
let Some(d) = chrono::Local.timestamp_millis_opt(ms).single() else { return String::new() };
if d.date_naive() == chrono::Local::now().date_naive() {
format!("今天 {}", d.format("%H:%M"))
} else {
d.format("%-m/%-d").to_string()
}
}
/// 812 B, 4.2 KB, 1.3 MB.
fn size_words(b: u64) -> String {
match b {
0 => String::new(),
1..=1023 => format!("{b} B"),
1024..=1_048_575 => format!("{:.1} KB", b as f64 / 1024.0),
_ => format!("{:.1} MB", b as f64 / 1_048_576.0),
}
}
#[cfg(test)]
mod tests {
use super::library_kind as k;
#[test]
fn files_are_sorted_into_kinds() {
assert_eq!((k("a.PNG"), k("b.heic"), k("c.mp4"), k("d.m4a")), ("image", "image", "media", "media"));
assert_eq!((k("e.xlsx"), k("f.csv")), ("sheet", "sheet"));
assert_eq!((k("g.md"), k("h.pdf"), k("i.docx"), k("j.txt"), k("k.html")), ("doc", "doc", "doc", "doc", "doc"));
assert_eq!((k("l.rs"), k("m.py"), k("n.json"), k("o.yaml")), ("code", "code", "code", "code"));
assert_eq!((k("p.zip"), k("noext")), ("other", "other"));
assert_eq!((super::size_words(0), super::size_words(812), super::size_words(4_300), super::size_words(1_363_149)), ("".into(), "812 B".into(), "4.2 KB".into(), "1.3 MB".into()));
}
}