// 所有檔案 (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, pub at: Option, 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 { // (The archived head's files too, once its words are read: chatarchive::said.) let said = crate::chatarchive::said(b.id, b.archived).unwrap_or_default(); let archived = said.iter().flat_map(|s| s.files.iter().map(move |a| (s.at, a))); let live = b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())).flat_map(|m| m.attachments.iter().map(move |a| (m.at, a))); for (at, a) in archived.chain(live) { if a.path.is_empty() || !seen.insert(a.path.clone()) { continue; } files.push((at, serde_json::json!({"name": a.name, "path": a.path, "bot": b.id, "at": 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::>()}) } fn library_gather(&mut self) { let mut seen = std::collections::HashSet::new(); let mut files = vec![]; for b in &self.state.bots { // (The archived head's files too, once its words are read: chatarchive::said.) let said = crate::chatarchive::said(b.id, b.archived).unwrap_or_default(); let archived = said.iter().flat_map(|s| s.files.iter().map(move |a| (s.at, a))); let live = b.messages.iter().chain(b.threads.iter().flat_map(|(_, m)| m.iter())).flat_map(|m| m.attachments.iter().map(move |a| (m.at, a))); for (at, a) in archived.chain(live) { 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, 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 = 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 = None; let mut row = |ui: &mut egui::Ui, place: Place, label: &str, dot: Option, 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 = 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) -> 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::(), 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) -> 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())); } }