AnyBot/src/preview.rs

908 lines
45 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.

// 檔案預覽: what a file in the chat looks like when opened (the original's full-screen viewer:
// spreadsheets as a grid with row numbers, documents rendered, pictures shown).
use std::path::Path;
/// Rows and columns read from a spreadsheet (the rest is left to the real app).
pub const MAX_ROWS: usize = 2_000;
pub const MAX_COLS: usize = 60;
/// Characters of a text file shown.
pub const MAX_TEXT: usize = 200_000;
#[derive(Clone, Debug, PartialEq)]
pub enum Preview {
/// Sheets: (name, rows). The first row is shown as the header.
Table(Vec<(String, Vec<Vec<String>>)>),
/// Markdown, and Word documents turned into Markdown (headings, lists, tables, bold).
Markdown(String),
/// A web page as Markdown (its headings, lists, tables and links), plus "open in the browser".
Html(String),
Image,
/// A PDF: its pages are drawn in the viewer (hayro, pure Rust, so the same on every system).
Pdf,
/// Played inside AnyBot (rodio).
Audio,
/// A video: its first frame when ffmpeg is around, and a play button for the system player.
Video,
/// Plain text, code, and JSON (pretty-printed).
Text(String),
/// Something we can't show inside AnyBot.
Other(String),
}
/// What kind of file this is, with the same groups as the original's viewer (image, video,
/// audio, pdf, markdown, html, text, json, table, docx, unknown).
pub fn kind_of(name: &str) -> &'static str {
let lower = name.to_lowercase();
let file = lower.rsplit(['/', '\\']).next().unwrap_or("");
if ["dockerfile", "makefile", "readme", "license", "gemfile", "procfile"].contains(&file) {
return "text";
}
match file.rsplit_once('.').map(|(_, e)| e).unwrap_or("") {
"xlsx" | "xlsm" | "xls" | "xlsb" | "ods" | "csv" | "tsv" => "sheet",
"md" | "markdown" | "mdx" => "markdown",
"html" | "htm" | "xhtml" => "html",
"png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "ico" | "svg" | "avif" | "heic" | "heif" | "tif" | "tiff" => "image",
"pdf" => "pdf",
"mp4" | "mov" | "m4v" | "webm" | "ogv" | "mkv" | "avi" => "video",
"mp3" | "m4a" | "wav" | "aac" | "flac" | "ogg" | "oga" | "opus" | "weba" | "aif" | "aiff" | "caf" => "audio",
"docx" => "docx",
"doc" | "rtf" | "pages" | "odt" => "doc",
"json" => "json",
e if TEXT_EXT.contains(&e) => "text",
_ => "other",
}
}
/// The original's list of files it shows as text.
const TEXT_EXT: &[&str] = &[
"txt", "text", "log", "rst", "adoc", "tex", "jsonc", "json5", "ndjson", "jsonl", "xml", "yaml", "yml", "toml", "ini", "cfg", "conf", "env",
"properties", "plist", "gradle", "css", "scss", "sass", "less", "js", "jsx", "mjs", "cjs", "ts", "tsx", "mts", "cts", "py", "pyi", "rb", "go",
"rs", "java", "kt", "kts", "c", "h", "cc", "cpp", "cxx", "hpp", "hh", "cs", "php", "swift", "scala", "dart", "lua", "pl", "pm", "r", "sql",
"graphql", "gql", "proto", "vue", "svelte", "astro", "sh", "bash", "zsh", "fish", "bat", "ps1", "tf", "tfvars", "dockerfile", "diff", "patch",
"srt", "vtt", "m", "mm", "zig", "nim", "ex", "exs", "erl", "hs", "ml", "clj", "groovy", "cmake", "mk", "lock", "gitignore", "editorconfig",
];
/// The label under a file card ("XLSX", "Markdown"…).
pub fn kind_label(name: &str) -> String {
let ext = name.rsplit('.').next().unwrap_or("").to_uppercase();
match kind_of(name) {
"markdown" => "Markdown".into(),
"html" => "HTML".into(),
_ if ext.len() <= 5 && !ext.is_empty() && name.contains('.') => ext,
_ => "檔案".into(),
}
}
pub fn load(path: &Path, name: &str) -> Preview {
match kind_of(name) {
"sheet" => load_sheet(path, name).unwrap_or_else(Preview::Other),
"markdown" => read_text(path).map(Preview::Markdown).unwrap_or_else(Preview::Other),
"html" => read_text(path).map(|h| Preview::Html(html_markdown(&h))).unwrap_or_else(Preview::Other),
"image" => Preview::Image,
"pdf" => Preview::Pdf,
"audio" => Preview::Audio,
"video" => Preview::Video,
"json" => read_text(path)
.map(|t| serde_json::from_str::<serde_json::Value>(&t).ok().and_then(|v| serde_json::to_string_pretty(&v).ok()).map(clip).unwrap_or(t))
.map(Preview::Text)
.unwrap_or_else(Preview::Other),
"text" => read_text(path).map(Preview::Text).unwrap_or_else(Preview::Other),
"docx" => docx_markdown(path).map(Preview::Markdown).unwrap_or_else(Preview::Other),
"doc" => crate::attach::read_text(&path.display().to_string(), name)
.map(|t| Preview::Text(clip(t)))
.unwrap_or_else(|| Preview::Other("這種文件在 AnyBot 裡看不到內容,可以用其他 App 打開;存成 .docx 或 PDF 就能直接預覽。".into())),
_ => read_text(path).ok().filter(|t| !t.trim().is_empty()).map(Preview::Text).unwrap_or_else(|| Preview::Other("這種檔案在 AnyBot 裡沒辦法預覽,可以用其他 App 打開。".into())),
}
}
/// The command that opens a file (or a web address) with the computer's own app: `open` on
/// macOS, the shell's `start` on Windows, `xdg-open` on Linux.
pub fn system_open(target: impl AsRef<std::ffi::OsStr>) -> std::process::Command {
#[cfg(target_os = "macos")]
let mut c = std::process::Command::new("open");
#[cfg(target_os = "windows")]
let mut c = {
let mut c = std::process::Command::new("cmd");
c.args(["/C", "start", ""]);
c
};
#[cfg(all(unix, not(target_os = "macos")))]
let mut c = std::process::Command::new("xdg-open");
c.arg(target);
c
}
/// Opening this file would run it (or install it) instead of showing it: scripts Terminal
/// starts on a double click, apps, installers, shortcuts that point at something else. A bot
/// may show the person what it made; it may not have their computer run what it made — that
/// is the shell's job, with the shell's questions.
pub fn runs_when_opened(p: &Path) -> bool {
const RUNS: [&str; 15] = ["command", "tool", "app", "terminal", "pkg", "mpkg", "jar", "workflow", "prefpane", "saver", "inetloc", "fileloc", "desktop", "appimage", "run"];
const RUNS_ON_WINDOWS: [&str; 17] = ["exe", "bat", "cmd", "com", "msi", "lnk", "ps1", "vbs", "vbe", "js", "jse", "wsf", "hta", "scr", "pif", "reg", "url"];
// What an executable bit doesn't turn into a program: the system opens these by their kind.
const SHOWN: [&str; 38] = [
"html", "htm", "pdf", "png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "tiff", "heic", "txt", "md", "csv", "tsv", "json", "xml", "yaml", "yml", "log", "rtf", "doc", "docx", "xls", "xlsx",
"ppt", "pptx", "pages", "numbers", "key", "mp3", "m4a", "wav", "mp4", "mov", "webm", "zip",
];
let ext = p.extension().map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();
if RUNS.contains(&ext.as_str()) || (cfg!(target_os = "windows") && RUNS_ON_WINDOWS.contains(&ext.as_str())) {
return true;
}
// A file marked executable that isn't a known kind of document opens in Terminal and runs.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if let Ok(m) = std::fs::metadata(p) {
if m.is_file() && m.permissions().mode() & 0o111 != 0 && !SHOWN.contains(&ext.as_str()) {
return true;
}
}
}
#[cfg(not(unix))]
let _ = SHOWN;
false
}
pub fn open_with_system(target: &str) {
let mut c = system_open(target);
if let Err(e) = crate::computer::spawn_reaped(&mut c) {
eprintln!("anybot: couldn't open {target}: {e}");
}
}
/// Show a file in the file manager (Finder selects it; elsewhere its folder opens).
pub fn reveal(path: &Path) {
#[cfg(target_os = "macos")]
let _ = std::process::Command::new("open").arg("-R").arg(path).spawn();
#[cfg(target_os = "windows")]
let _ = std::process::Command::new("explorer").arg(format!("/select,{}", path.display())).spawn();
#[cfg(all(unix, not(target_os = "macos")))]
let _ = system_open(path.parent().unwrap_or(path)).spawn();
}
fn clip(t: String) -> String {
if t.chars().count() > MAX_TEXT {
t.chars().take(MAX_TEXT).collect::<String>() + "\n…"
} else {
t
}
}
fn read_text(path: &Path) -> Result<String, String> {
use std::io::Read;
// Read only the head of the file: a preview never shows more than clip() keeps (200 K
// chars), and reading a multi-GB log whole on the UI thread froze the whole window.
const HEAD: u64 = 4 << 20;
let mut f = std::fs::File::open(path).map_err(|e| format!("讀不到檔案:{e}"))?;
let mut bytes = Vec::new();
f.by_ref().take(HEAD).read_to_end(&mut bytes).map_err(|e| format!("讀不到檔案:{e}"))?;
if bytes.iter().take(8000).any(|b| *b == 0) {
return Err("這是二進位檔案,沒辦法當文字顯示。".into());
}
Ok(clip(String::from_utf8_lossy(&bytes).to_string()))
}
/// A picture file as RGBA pixels: PNG, JPEG, GIF, WebP, BMP, TIFF and ICO are decoded in
/// AnyBot itself and SVG is drawn with resvg, so this works the same on macOS, Windows and
/// Linux. HEIC and AVIF have no pure-Rust decoder: macOS converts them with `sips`; elsewhere
/// they open in another app.
pub fn decode_image(path: &Path) -> Option<image::RgbaImage> {
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_lowercase();
if ext == "svg" {
let data = std::fs::read(path).ok()?;
let tree = resvg::usvg::Tree::from_data(&data, &resvg::usvg::Options::default()).ok()?;
let size = tree.size();
let scale = (1600.0 / size.width().max(size.height())).clamp(0.1, 8.0);
let (w, h) = ((size.width() * scale).ceil() as u32, (size.height() * scale).ceil() as u32);
let mut pm = resvg::tiny_skia::Pixmap::new(w.max(1), h.max(1))?;
resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(scale, scale), &mut pm.as_mut());
// tiny-skia keeps premultiplied pixels.
let mut px = pm.take();
for c in px.as_chunks_mut::<4>().0 {
let a = c[3] as u32;
if a > 0 && a < 255 {
for v in &mut c[..3] {
*v = ((*v as u32 * 255 + a / 2) / a).min(255) as u8;
}
}
}
return image::RgbaImage::from_raw(w.max(1), h.max(1), px);
}
if let Ok(img) = image::ImageReader::open(path).ok()?.with_guessed_format().ok()?.decode() {
return Some(img.to_rgba8());
}
// HEIC, AVIF and the rest: macOS's sips, else ffmpeg (or ImageMagick) when installed.
let tmp = std::env::temp_dir().join(format!("anybot-view-{}-{}.png", std::process::id(), crate::model::now_ms()));
let tries: Vec<std::process::Command> = {
let mut v = vec![];
if cfg!(target_os = "macos") {
let mut c = std::process::Command::new("sips");
c.args(["-s", "format", "png"]).arg(path).arg("--out").arg(&tmp);
v.push(c);
}
let safe_path = if path.is_relative() { std::path::Path::new(".").join(path) } else { path.to_path_buf() };
let mut f = std::process::Command::new("ffmpeg");
f.env("PATH", crate::cloudbox::tool_path()).args(["-nostdin", "-loglevel", "error", "-y", "-i"]).arg(&safe_path).args(["-frames:v", "1"]).arg(&tmp).stdin(std::process::Stdio::null());
v.push(f);
// Guard ImageMagick `convert` against leading `-` options and coder prefixes (`ephemeral:`, `msl:`, `vid:`).
let s = safe_path.display().to_string();
if !s.starts_with('-') && !s.split('/').next().unwrap_or("").contains(':') {
let mut m = std::process::Command::new("convert");
m.arg("--").arg(format!("{s}[0]")).arg(&tmp);
v.push(m);
}
let mut h = std::process::Command::new("heif-convert");
h.arg(&safe_path).arg(&tmp);
v.push(h);
v
};
for mut c in tries {
if c.output().map(|o| o.status.success()).unwrap_or(false) {
if let Ok(i) = image::open(&tmp) {
let _ = std::fs::remove_file(&tmp);
return Some(i.to_rgba8());
}
}
}
let _ = std::fs::remove_file(&tmp);
None
}
/// Pages drawn from a PDF, one at a time (the viewer calls this from a worker thread).
/// `width` is the pixel width each page is drawn at.
pub fn pdf_pages(path: &Path, width: f32, max_pages: usize, mut each: impl FnMut(usize, usize, image::RgbaImage) -> bool) -> Result<(), String> {
let data = std::fs::read(path).map_err(|e| format!("讀不到檔案:{e}"))?;
let pdf = hayro::hayro_syntax::Pdf::new(data).map_err(|e| format!("這個 PDF 打不開({e:?})"))?;
let pages = pdf.pages();
let total = pages.len();
if total == 0 {
return Err("這個 PDF 沒有頁面".into());
}
let cache = hayro::RenderCache::new();
let interp = hayro::hayro_interpret::InterpreterSettings::default();
let render = hayro::RenderSettings::default();
for (i, page) in pages.iter().enumerate().take(max_pages) {
let (pw, ph) = page.render_dimensions();
let scale = (width / pw.max(1.0)).min(4000.0 / ph.max(1.0)).clamp(0.2, 4.0);
let pm = hayro::render(page, &cache, &interp, &render, &hayro::PixmapSettings { x_scale: scale, y_scale: scale, bg_color: hayro::vello_cpu::color::palette::css::WHITE });
let (w, h) = (pm.width() as u32, pm.height() as u32);
let mut px = pm.take_rgba8(hayro::vello_cpu::peniko::ImageAlphaType::AlphaPremultiplied);
// Paper is opaque: composite onto white (premultiplied: add what alpha left uncovered).
for c in px.as_chunks_mut::<4>().0 {
let rest = 255 - c[3];
c[0] = c[0].saturating_add(rest);
c[1] = c[1].saturating_add(rest);
c[2] = c[2].saturating_add(rest);
c[3] = 255;
}
let Some(img) = image::RgbaImage::from_raw(w, h, px) else { continue };
if !each(i, total, img) {
break;
}
}
Ok(())
}
/// How many pages a PDF has, without rendering any of them.
pub fn pdf_page_count(path: &Path) -> Result<usize, String> {
let data = std::fs::read(path).map_err(|e| format!("讀不到檔案:{e}"))?;
let pdf = hayro::hayro_syntax::Pdf::new(data).map_err(|e| format!("這個 PDF 打不開({e:?})"))?;
let total = pdf.pages().len();
if total == 0 {
return Err("這個 PDF 沒有頁面".into());
}
Ok(total)
}
/// Render a single 0-indexed page of a PDF at `width` pixels wide; returns `(total_pages, rgba)`.
pub fn pdf_single_page(path: &Path, page_idx: usize, width: f32) -> Result<(usize, image::RgbaImage), String> {
let data = std::fs::read(path).map_err(|e| format!("讀不到檔案:{e}"))?;
let pdf = hayro::hayro_syntax::Pdf::new(data).map_err(|e| format!("這個 PDF 打不開({e:?})"))?;
let pages = pdf.pages();
let total = pages.len();
let Some(page) = pages.get(page_idx) else {
return Err("找不到這一頁".into());
};
let cache = hayro::RenderCache::new();
let interp = hayro::hayro_interpret::InterpreterSettings::default();
let render = hayro::RenderSettings::default();
let (pw, ph) = page.render_dimensions();
let scale = (width / pw.max(1.0)).min(4000.0 / ph.max(1.0)).clamp(0.2, 4.0);
let pm = hayro::render(page, &cache, &interp, &render, &hayro::PixmapSettings { x_scale: scale, y_scale: scale, bg_color: hayro::vello_cpu::color::palette::css::WHITE });
let (w, h) = (pm.width() as u32, pm.height() as u32);
let mut px = pm.take_rgba8(hayro::vello_cpu::peniko::ImageAlphaType::AlphaPremultiplied);
for c in px.as_chunks_mut::<4>().0 {
let rest = 255 - c[3];
c[0] = c[0].saturating_add(rest);
c[1] = c[1].saturating_add(rest);
c[2] = c[2].saturating_add(rest);
c[3] = 255;
}
let img = image::RgbaImage::from_raw(w, h, px).ok_or_else(|| "頁面渲染失敗".to_string())?;
Ok((total, img))
}
/// A Word document (.docx) as Markdown: headings, bulleted and numbered lists, tables, bold
/// and italics. Read straight from the file's XML, so no Word or LibreOffice is needed.
const MAX_DOCX_XML_BYTES: u64 = 32 * 1024 * 1024;
const MAX_SHEET_UNZIPPED_BYTES: u64 = 128 * 1024 * 1024;
pub fn docx_markdown(path: &Path) -> Result<String, String> {
use std::io::Read;
let f = std::fs::File::open(path).map_err(|e| format!("讀不到檔案:{e}"))?;
let mut zip = zip::ZipArchive::new(f).map_err(|_| "這個 Word 檔打不開(不是有效的 .docx)".to_string())?;
let mut xml = String::new();
{
let doc = zip.by_name("word/document.xml").map_err(|_| "這個 Word 檔裡找不到內文".to_string())?;
if doc.size() > MAX_DOCX_XML_BYTES {
return Err("這個 Word 檔展開後太大(超過 32 MB),請用其他 App 打開。".into());
}
doc.take(MAX_DOCX_XML_BYTES + 1).read_to_string(&mut xml).map_err(|e| e.to_string())?;
if xml.len() as u64 > MAX_DOCX_XML_BYTES {
return Err("這個 Word 檔展開後太大(超過 32 MB),請用其他 App 打開。".into());
}
}
// Which numbering ids are numbered (not bullets).
let mut numbered = std::collections::HashSet::new();
if let Ok(n) = zip.by_name("word/numbering.xml") {
if n.size() <= MAX_DOCX_XML_BYTES {
let mut s = String::new();
let _ = n.take(MAX_DOCX_XML_BYTES).read_to_string(&mut s);
numbered = numbered_lists(&s);
}
}
Ok(clip(docx_xml_markdown(&xml, &numbered)))
}
/// numIds whose first level is a number format (decimal, letters…), not a bullet.
fn numbered_lists(numbering: &str) -> std::collections::HashSet<String> {
let mut abs_numbered = std::collections::HashSet::new();
for chunk in numbering.split("<w:abstractNum ").skip(1) {
let id = attr(chunk, "w:abstractNumId").unwrap_or_default();
let fmt = chunk.split("<w:numFmt ").nth(1).and_then(|c| attr(c, "w:val")).unwrap_or_default();
if fmt != "bullet" && !fmt.is_empty() && fmt != "none" {
abs_numbered.insert(id);
}
}
let mut out = std::collections::HashSet::new();
for chunk in numbering.split("<w:num ").skip(1) {
let id = attr(chunk, "w:numId").unwrap_or_default();
let abs = chunk.split("<w:abstractNumId ").nth(1).and_then(|c| attr(c, "w:val")).unwrap_or_default();
if abs_numbered.contains(&abs) {
out.insert(id);
}
}
out
}
fn attr(tag: &str, name: &str) -> Option<String> {
let i = tag.find(&format!("{name}=\""))? + name.len() + 2;
let end = tag[i..].find('"')? + i;
Some(tag[i..end].to_string())
}
fn unescape(s: &str) -> String {
s.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&apos;", "'").replace("&#39;", "'").replace("&nbsp;", " ").replace("&amp;", "&")
}
fn docx_xml_markdown(xml: &str, numbered: &std::collections::HashSet<String>) -> String {
let mut out = String::new();
// Paragraph state.
let mut para = String::new();
let mut style = String::new();
let mut num: Option<(String, usize)> = None;
// The biggest font size in the paragraph (half-points): big text without a heading style is a heading.
let mut big = 0u32;
let (mut bold, mut italic, mut in_rpr, mut in_text) = (false, false, false, false);
let mut counters: std::collections::HashMap<(String, usize), usize> = Default::default();
// Tables: a stack of (rows, current row, current cell).
let mut table: Vec<Vec<String>> = vec![];
let mut row: Vec<String> = vec![];
let mut tdepth = 0usize;
let mut i = 0;
let b = xml.as_bytes();
while i < xml.len() {
if b[i] == b'<' {
let end = match xml[i..].find('>') {
Some(e) => i + e,
None => break,
};
let tag = &xml[i + 1..end];
let closing = tag.starts_with('/');
let name = tag.trim_start_matches('/').split(|c: char| c.is_whitespace() || c == '/').next().unwrap_or("");
match (name, closing) {
("w:p", false) if !tag.ends_with('/') => {
para.clear();
style.clear();
num = None;
big = 0;
}
("w:sz", _) if in_rpr => big = big.max(attr(tag, "w:val").and_then(|v| v.parse().ok()).unwrap_or(0)),
("w:pStyle", _) => style = attr(tag, "w:val").unwrap_or_default().to_lowercase(),
("w:numId", _) => {
let id = attr(tag, "w:val").unwrap_or_default();
let lvl = num.as_ref().map(|n| n.1).unwrap_or(0);
if id != "0" {
num = Some((id, lvl));
}
}
("w:ilvl", _) => {
let l = attr(tag, "w:val").and_then(|v| v.parse().ok()).unwrap_or(0);
num = Some((num.map(|n| n.0).unwrap_or_default(), l));
}
("w:rPr", false) => in_rpr = !tag.ends_with('/'),
("w:rPr", true) => in_rpr = false,
("w:b", _) if in_rpr => bold = attr(tag, "w:val").map(|v| v != "0" && v != "false").unwrap_or(true),
("w:i", _) if in_rpr => italic = attr(tag, "w:val").map(|v| v != "0" && v != "false").unwrap_or(true),
("w:r", false) => {
bold = false;
italic = false;
}
("w:t", false) => in_text = !tag.ends_with('/'),
("w:t", true) => in_text = false,
("w:tab", _) => para.push('\t'),
("w:br", _) | ("w:cr", _) => para.push_str(if tdepth > 0 { " " } else { " \n" }),
("w:p", true) => {
let mut text = para.trim().to_string();
// Lists typed as "•<tab>item".
if let Some(rest) = text.strip_prefix('•').or_else(|| text.strip_prefix('·')).or_else(|| text.strip_prefix('▪')) {
text = format!("- {}", rest.trim_start());
}
if tdepth > 0 {
if let Some(c) = row.last_mut() {
if !c.is_empty() && !text.is_empty() {
c.push(' ');
}
c.push_str(&text);
}
} else if !text.is_empty() {
let heading = style.strip_prefix("heading").and_then(|n| n.parse::<usize>().ok()).or(if style == "title" { Some(1) } else if style == "subtitle" { Some(2) } else { None })
.or(if text.chars().count() <= 80 && !text.starts_with("- ") {
match big {
40.. => Some(1),
32..=39 => Some(2),
28..=31 => Some(3),
_ => None,
}
} else {
None
});
if let Some(h) = heading {
out.push_str(&format!("{} {}\n\n", "#".repeat(h.clamp(1, 3)), text.replace("**", "")));
} else if style.starts_with("listbullet") || style.starts_with("清單項目符號") {
out.push_str(&format!("- {text}\n"));
} else if style.starts_with("listnumber") || style.starts_with("清單號碼") {
let c = counters.entry((style.clone(), 0)).or_insert(0);
*c += 1;
out.push_str(&format!("{}. {text}\n", c));
} else if text.starts_with("- ") {
out.push_str(&text);
out.push('\n');
} else if let Some((id, lvl)) = num.clone().filter(|n| !n.0.is_empty()) {
let indent = " ".repeat(lvl);
if numbered.contains(&id) {
let c = counters.entry((id, lvl)).or_insert(0);
*c += 1;
out.push_str(&format!("{indent}{}. {text}\n", c));
} else {
out.push_str(&format!("{indent}- {text}\n"));
}
} else {
if out.ends_with('\n') && !out.ends_with("\n\n") && !out.is_empty() {
out.push('\n');
}
out.push_str(&text);
out.push_str("\n\n");
}
}
para.clear();
}
("w:tbl", false) => {
tdepth += 1;
if tdepth == 1 {
table.clear();
}
}
("w:tbl", true) => {
tdepth = tdepth.saturating_sub(1);
if tdepth == 0 && !table.is_empty() {
out.push('\n');
out.push_str(&md_table(&table));
out.push('\n');
}
}
("w:tr", false) if tdepth == 1 => row.clear(),
("w:tr", true) if tdepth == 1 => table.push(std::mem::take(&mut row)),
("w:tc", false) if tdepth == 1 => row.push(String::new()),
_ => {}
}
i = end + 1;
} else {
let next = xml[i..].find('<').map(|n| i + n).unwrap_or(xml.len());
if in_text {
let t = unescape(&xml[i..next]);
if bold && !t.trim().is_empty() {
para.push_str(&format!("**{t}**"));
} else if italic && !t.trim().is_empty() {
para.push_str(&format!("*{t}*"));
} else {
para.push_str(&t);
}
}
i = next;
}
}
out.replace("****", "").trim().to_string()
}
/// Rows → a Markdown table (the first row as header).
fn md_table(rows: &[Vec<String>]) -> String {
let n = rows.iter().map(|r| r.len()).max().unwrap_or(0).max(1);
let line = |r: &Vec<String>| {
let mut cells: Vec<String> = r.iter().map(|c| c.replace('|', "\\|").replace('\n', " ")).collect();
cells.resize(n, String::new());
format!("| {} |\n", cells.join(" | "))
};
let mut s = line(&rows[0]);
s.push_str(&format!("|{}\n", " --- |".repeat(n)));
for r in &rows[1..] {
s.push_str(&line(r));
}
s
}
/// Find `<tag` followed by `>` or a space, ASCII case-insensitive, on the original string.
/// (Lowercasing the whole page first shifts byte offsets — "İ" becomes 3 bytes when lowered —
/// and cutting the original at those offsets panics.)
fn find_open_tag(s: &str, tag: &str) -> Option<usize> {
let (b, t) = (s.as_bytes(), tag.as_bytes());
(0..b.len()).find(|&i| {
b[i] == b'<'
&& b.len() >= i + 1 + t.len()
&& b[i + 1..].iter().zip(t).all(|(a, c)| a.eq_ignore_ascii_case(c))
&& matches!(b.get(i + 1 + t.len()), Some(c) if *c == b'>' || c.is_ascii_whitespace())
})
}
/// `needle` (ASCII) in `hay`, ASCII case-insensitive, as a byte offset.
fn find_ci(hay: &str, needle: &str) -> Option<usize> {
let (h, n) = (hay.as_bytes(), needle.as_bytes());
if n.is_empty() || h.len() < n.len() {
return None;
}
(0..=h.len() - n.len()).find(|&i| h[i..i + n.len()].iter().zip(n).all(|(a, c)| a.eq_ignore_ascii_case(c)))
}
/// A web page as Markdown: headings, paragraphs, lists, tables, bold, links ("text (url)").
/// Scripts, styles and the <head> are dropped.
pub fn html_markdown(html: &str) -> String {
let mut s = html.to_string();
for tag in ["head", "script", "style", "noscript", "svg", "template"] {
while let Some(a) = find_open_tag(&s, tag) {
let end = find_ci(&s[a..], &format!("</{tag}>")).map(|e| a + e + tag.len() + 3).unwrap_or(s.len());
s.replace_range(a..end, "");
}
}
let mut out = String::new();
let mut lists: Vec<(bool, usize)> = vec![];
let mut table: Vec<Vec<String>> = vec![];
let mut row: Vec<String> = vec![];
let mut in_table = 0usize;
let mut cell = String::new();
let mut href: Option<String> = None;
let mut pre = false;
let mut i = 0;
let push = |out: &mut String, cell: &mut String, in_table: usize, t: &str| {
if in_table > 0 {
cell.push_str(t)
} else {
out.push_str(t)
}
};
while i < s.len() {
if s.as_bytes()[i] == b'<' {
let Some(e) = s[i..].find('>') else { break };
let tag = s[i + 1..i + e].to_string();
i += e + 1;
if tag.starts_with('!') {
continue;
}
let closing = tag.starts_with('/');
let name = tag.trim_start_matches('/').split(|c: char| c.is_whitespace() || c == '/').next().unwrap_or("").to_lowercase();
match (name.as_str(), closing) {
("h1" | "h2" | "h3" | "h4" | "h5" | "h6", false) => {
let n: usize = name[1..].parse().unwrap_or(1);
out.push_str(&format!("\n\n{} ", "#".repeat(n.min(3))));
}
("h1" | "h2" | "h3" | "h4" | "h5" | "h6", true) => out.push_str("\n\n"),
("p" | "div" | "section" | "article" | "header" | "footer" | "main" | "nav" | "blockquote" | "figure", _) => {
if in_table > 0 {
cell.push(' ')
} else {
out.push_str("\n\n")
}
}
("br", _) => push(&mut out, &mut cell, in_table, if in_table > 0 { " " } else { "\n" }),
("hr", _) => out.push_str("\n\n---\n\n"),
("ul", false) => lists.push((false, 0)),
("ol", false) => lists.push((true, 0)),
("ul" | "ol", true) => {
lists.pop();
out.push('\n');
}
("li", false) => {
let depth = lists.len().saturating_sub(1);
let marker = match lists.last_mut() {
Some((true, n)) => {
*n += 1;
format!("{n}. ")
}
_ => "- ".into(),
};
out.push_str(&format!("\n{}{marker}", " ".repeat(depth)));
}
("b" | "strong", _) => push(&mut out, &mut cell, in_table, "**"),
("pre", false) => {
pre = true;
out.push_str("\n\n```\n");
}
("pre", true) => {
pre = false;
out.push_str("\n```\n\n");
}
("a", false) => href = attr(&tag.replace('\'', "\""), "href").filter(|h| h.starts_with("http")),
("a", true) => {
if let Some(h) = href.take() {
push(&mut out, &mut cell, in_table, &format!(" ({h})"));
}
}
("img", _) => {
if let Some(alt) = attr(&tag, "alt").filter(|a| !a.trim().is_empty()) {
push(&mut out, &mut cell, in_table, &format!("[圖片:{alt}]"));
}
}
("table", false) => {
in_table += 1;
if in_table == 1 {
table.clear();
}
}
("table", true) => {
in_table = in_table.saturating_sub(1);
if in_table == 0 && !table.is_empty() {
out.push_str("\n\n");
out.push_str(&md_table(&table));
out.push('\n');
}
}
("tr", false) if in_table == 1 => row.clear(),
("tr", true) if in_table == 1 => {
if !row.is_empty() {
table.push(std::mem::take(&mut row));
}
}
("td" | "th", false) if in_table == 1 => cell.clear(),
("td" | "th", true) if in_table == 1 => row.push(unescape(&std::mem::take(&mut cell)).split_whitespace().collect::<Vec<_>>().join(" ")),
_ => {}
}
} else {
let next = s[i..].find('<').map(|n| i + n).unwrap_or(s.len());
let raw = &s[i..next];
let t = if pre { unescape(raw) } else { unescape(&raw.split_whitespace().collect::<Vec<_>>().join(" ")) };
let t = if !pre && raw.starts_with(char::is_whitespace) && !t.is_empty() { format!(" {t}") } else { t };
let t = if !pre && raw.ends_with(char::is_whitespace) && !t.trim().is_empty() { format!("{t} ") } else { t };
push(&mut out, &mut cell, in_table, &t);
i = next;
}
}
let mut lines: Vec<String> = out.lines().map(|l| l.trim_end().to_string()).map(|l| if l.trim_start().starts_with(['-', '#', '|']) || l.trim_start().chars().next().is_some_and(|c| c.is_ascii_digit()) { l } else { l.trim_start().to_string() }).collect();
lines.dedup_by(|a, b| a.is_empty() && b.is_empty());
clip(lines.join("\n").replace("** **", " ").replace("****", "").trim().to_string())
}
fn load_sheet(path: &Path, name: &str) -> Result<Preview, String> {
// calamine parses the whole workbook on the UI thread: a huge .xlsx froze the window.
// (CSV/TSV are fine: read_text reads only the head.)
let ext = name.rsplit('.').next().unwrap_or("").to_lowercase();
if matches!(ext.as_str(), "xlsx" | "xls" | "ods") && std::fs::metadata(path).map(|m| m.len() > 50 << 20).unwrap_or(false) {
return Err("這個試算表太大(超過 50 MB),在 AnyBot 裡預覽會卡住;請用其他 App 打開。".into());
}
if matches!(ext.as_str(), "xlsx" | "ods") {
if let Ok(f) = std::fs::File::open(path) {
if let Ok(mut z) = zip::ZipArchive::new(f) {
let mut total = 0u64;
for i in 0..z.len() {
let sz = z.by_index_raw(i).map(|e| e.size()).unwrap_or(0);
total = total.saturating_add(sz);
if total > MAX_SHEET_UNZIPPED_BYTES {
return Err("這個試算表展開後太大(超過 128 MB),在 AnyBot 裡預覽會卡住;請用其他 App 打開。".into());
}
}
}
}
}
if ext == "csv" || ext == "tsv" {
let text = read_text(path)?;
let sep = if ext == "tsv" { '\t' } else { ',' };
let rows: Vec<Vec<String>> = text.lines().take(MAX_ROWS).map(|l| split_csv(l, sep).into_iter().take(MAX_COLS).collect()).collect();
return Ok(Preview::Table(vec![("工作表".into(), rows)]));
}
use calamine::{open_workbook_auto, Data, Reader};
let mut wb = open_workbook_auto(path).map_err(|e| format!("打不開這個試算表:{e}"))?;
let mut sheets = vec![];
for sheet in wb.sheet_names().to_vec() {
let Ok(range) = wb.worksheet_range(&sheet) else { continue };
let rows: Vec<Vec<String>> = range
.rows()
.take(MAX_ROWS)
.map(|r| {
r.iter()
.take(MAX_COLS)
.map(|c| match c {
Data::Empty => String::new(),
Data::Float(f) if f.fract() == 0.0 && f.abs() < 1e15 => format!("{}", *f as i64),
Data::DateTime(d) => excel_date(d.as_f64()),
other => other.to_string(),
})
.collect()
})
.collect();
sheets.push((sheet, rows));
}
if sheets.is_empty() {
return Err("這個試算表是空的".into());
}
Ok(Preview::Table(sheets))
}
/// An Excel date number (days since 1899-12-30) as "2026-10-31" or "2026-10-29 20:13".
pub fn excel_date(v: f64) -> String {
// A cell formatted as a date can hold any number (Excel cells go to 1e308); beyond any
// real date, show the number — the date maths would overflow chrono and panic.
if !v.is_finite() || v.abs() > 3_000_000.0 {
return if v.fract().abs() < 0.000001 { format!("{}", v as i64) } else { format!("{v}") };
}
let base = chrono::NaiveDate::from_ymd_opt(1899, 12, 30).unwrap().and_hms_opt(0, 0, 0).unwrap();
let t = base + chrono::Duration::milliseconds((v * 86_400_000.0).round() as i64);
if v.fract().abs() < 1e-9 {
t.format("%Y-%m-%d").to_string()
} else {
t.format("%Y-%m-%d %H:%M").to_string()
}
}
/// One CSV line → cells (quotes and doubled quotes handled).
pub fn split_csv(line: &str, sep: char) -> Vec<String> {
let mut out = vec![];
let mut cur = String::new();
let mut quoted = false;
let mut chars = line.chars().peekable();
while let Some(c) = chars.next() {
match c {
'"' if quoted && chars.peek() == Some(&'"') => {
cur.push('"');
chars.next();
}
'"' => quoted = !quoted,
c if c == sep && !quoted => out.push(std::mem::take(&mut cur)),
c => cur.push(c),
}
}
out.push(cur);
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn csv_html_and_kinds() {
assert_eq!(split_csv(r#"a,"b, c","say ""hi""",d"#, ','), vec!["a", "b, c", "say \"hi\"", "d"]);
let t = html_markdown("<html><head><title>x</title><style>p{}</style></head><body><script>x()</script><h1>標題</h1><p>第一段&amp;<b>更多</b></p><ul><li>一</li><li>二</li></ul><ol><li>甲</li></ol><table><tr><th>A</th><th>B</th></tr><tr><td>1</td><td>2</td></tr></table></body></html>");
assert!(t.contains("# 標題") && t.contains("第一段&**更多**") && t.contains("- 一") && t.contains("1. 甲") && t.contains("| A | B |") && t.contains("| 1 | 2 |") && !t.contains("x()"), "{t}");
assert_eq!(kind_of("報表.XLSX"), "sheet");
for (f, k) in [("a.svg", "image"), ("a.heic", "image"), ("a.webm", "video"), ("a.opus", "audio"), ("a.docx", "docx"), ("a.json", "json"), ("a.mdx", "markdown"), ("Dockerfile", "text"), ("a.tsx", "text"), ("a.zip", "other")] {
assert_eq!(kind_of(f), k, "{f}");
}
let docx = r#"<w:document><w:body><w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>報告</w:t></w:r></w:p><w:p><w:r><w:t xml:space="preserve">內容 </w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>重點</w:t></w:r></w:p><w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>第一項</w:t></w:r></w:p><w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="2"/></w:numPr></w:pPr><w:r><w:t>步驟</w:t></w:r></w:p><w:tbl><w:tr><w:tc><w:p><w:r><w:t>名稱</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>數量</w:t></w:r></w:p></w:tc></w:tr><w:tr><w:tc><w:p><w:r><w:t>蘋果 &amp; 梨</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>3</w:t></w:r></w:p></w:tc></w:tr></w:tbl></w:body></w:document>"#;
let numbering = r#"<w:abstractNum w:abstractNumId="7"><w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/></w:lvl></w:abstractNum><w:abstractNum w:abstractNumId="8"><w:lvl w:ilvl="0"><w:numFmt w:val="decimal"/></w:lvl></w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="7"/></w:num><w:num w:numId="2"><w:abstractNumId w:val="8"/></w:num>"#;
let md = docx_xml_markdown(docx, &numbered_lists(numbering));
assert!(md.contains("# 報告") && md.contains("內容 **重點**") && md.contains("- 第一項") && md.contains("1. 步驟") && md.contains("| 名稱 | 數量 |") && md.contains("| 蘋果 & 梨 | 3 |"), "{md}");
assert_eq!(excel_date(46326.0), "2026-10-31");
assert_eq!(kind_label("notes.md"), "Markdown");
let dir = std::env::temp_dir().join(format!("anybot-preview-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let csv = dir.join("a.csv");
std::fs::write(&csv, "名稱,數量\n蘋果,3\n").unwrap();
match load(&csv, "a.csv") {
Preview::Table(s) => assert_eq!(s[0].1[1], vec!["蘋果", "3"]),
other => panic!("{other:?}"),
}
let md = dir.join("n.md");
std::fs::write(&md, "# 你好").unwrap();
assert_eq!(load(&md, "n.md"), Preview::Markdown("# 你好".into()));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn showing_a_file_is_not_running_it() {
let dir = std::env::temp_dir().join(format!("anybot-opens-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("Thing.app")).unwrap();
let file = |name: &str, executable: bool| {
let p = dir.join(name);
std::fs::write(&p, "#!/bin/sh\necho hi\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(if executable { 0o755 } else { 0o644 })).unwrap();
}
let _ = executable;
p
};
// What Terminal, the Finder or an installer would start.
for name in ["run.command", "RUN.COMMAND", "setup.pkg", "tool.jar", "x.terminal", "go.desktop"] {
assert!(runs_when_opened(&file(name, false)), "{name}");
}
assert!(runs_when_opened(&dir.join("Thing.app")));
// What is only shown, executable bit or not (some disks mark every file executable).
for name in ["report.html", "chart.png", "notes.md", "data.xlsx"] {
assert!(!runs_when_opened(&file(name, false)) && !runs_when_opened(&file(name, true)), "{name}");
}
assert!(!runs_when_opened(&dir), "a plain folder opens in the file manager");
assert!(!runs_when_opened(&file("script.sh", false)) && !runs_when_opened(&file("LICENSE", false)));
// An executable that isn't a document runs in Terminal when opened.
#[cfg(unix)]
assert!(runs_when_opened(&file("deploy", true)) && runs_when_opened(&file("script.sh", true)));
let _ = std::fs::remove_dir_all(&dir);
}
/// Every sample file in $ANYBOT_FIXTURES opens: `cargo test --release fixtures -- --ignored --nocapture`.
#[test]
#[ignore]
fn fixtures() {
let dir = std::env::var("ANYBOT_FIXTURES").expect("ANYBOT_FIXTURES");
let mut names: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.path()).collect();
names.sort();
let mut bad = vec![];
for path in names {
let name = path.file_name().unwrap().to_string_lossy().to_string();
let started = std::time::Instant::now();
let what = match load(&path, &name) {
Preview::Image => decode_image(&path).map(|i| format!("image {}x{}", i.width(), i.height())).unwrap_or_else(|| "IMAGE FAILED".into()),
Preview::Pdf => {
let words = crate::attach::read_text(&path.display().to_string(), &name).map(|t| t.chars().filter(|c| !c.is_whitespace()).take(12).collect::<String>()).unwrap_or_else(|| "NO TEXT".into());
println!(" pdf text for the bot: {words}");
let mut n = (0, 0, 0);
match pdf_pages(&path, 1400.0, 300, |_, total, img| {
n = (n.0 + 1, total, img.height());
true
}) {
Ok(()) => format!("pdf {} of {} pages, {}px tall", n.0, n.1, n.2),
Err(e) => format!("PDF FAILED {e}"),
}
}
Preview::Audio => {
let f = std::fs::File::open(&path).unwrap();
match rodio::Decoder::try_from(f) {
Ok(d) => format!("audio {:?}", rodio::Source::total_duration(&d)),
Err(e) => format!("AUDIO FAILED {e}"),
}
}
Preview::Other(m) => format!("OTHER {m}"),
Preview::Table(t) => format!("table {} rows", t[0].1.len()),
Preview::Markdown(m) | Preview::Html(m) => format!("doc {:?} / bot reads: {}", m.chars().take(50).collect::<String>(), crate::attach::read_text(&path.display().to_string(), &name).map(|t| t.chars().count()).unwrap_or(0)),
Preview::Text(t) => format!("text {:?}", t.chars().take(40).collect::<String>()),
Preview::Video => "video".into(),
};
if what.contains("FAILED") || what.starts_with("OTHER") {
bad.push(name.clone());
}
println!("{name:10} {:>5}ms {what}", started.elapsed().as_millis());
}
println!("not opening: {bad:?}");
}
}