From 6b211305f3af5af3dac5d463cd57958abbc488dd Mon Sep 17 00:00:00 2001 From: Deepanshu Mishra Date: Thu, 19 Nov 2026 11:55:12 +0530 Subject: [PATCH 1/4] feat: Read Word, PowerPoint and Excel files natively, with a designed and a terminal look leaf now opens .docx, .pptx and .xlsx/.xls/.ods/.csv/.tsv itself on macOS and Linux, with no LibreOffice, Keynote, Pages or Numbers. - Decks: each slide drawn from its XML with master, layout and theme (shapes, pictures, fonts, tables, charts, SmartArt), speaker notes below. - Word: styles, numbering, tables, pictures and fields laid out on the document's own page size and margins, drawn page by page. - Spreadsheets: a grid with column letters and row numbers; Excel cell fonts, fills, borders, alignment, column widths and row heights. - `o` switches any office file between the designed look and the terminal's font (markdown text and tables) on the same page; `i` paints the designed page in terminal colors. The footer shows both keys. - Older and Apple formats (.doc, .ppt, .key, .pages, .numbers) say what to save them as. Docs, CHANGELOG and completions list only what's read. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + Cargo.lock | 153 ++++ Cargo.toml | 5 +- README.md | 14 +- completions/_leaf | 3 +- completions/leaf.fish | 4 +- lua/leaf/init.lua | 4 +- skills/leaf/SKILL.md | 4 +- src/chart.rs | 734 ++++++++++++++++ src/doc.rs | 33 +- src/drawing.rs | 1373 +++++++++++++++++++++++++++++ src/grid.rs | 718 ++++++++++++++++ src/main.rs | 19 +- src/office.rs | 147 ++++ src/ooxml.rs | 616 +++++++++++++ src/pdf.rs | 14 +- src/picker.rs | 1 + src/sheet.rs | 625 ++++++++++++++ src/slides.rs | 1498 ++++++++++++++++++++++++++++++++ src/typeset.rs | 666 ++++++++++++++ src/viewer.rs | 42 + src/word.rs | 1906 +++++++++++++++++++++++++++++++++++++++++ 22 files changed, 8565 insertions(+), 15 deletions(-) create mode 100644 src/chart.rs create mode 100644 src/drawing.rs create mode 100644 src/grid.rs create mode 100644 src/office.rs create mode 100644 src/ooxml.rs create mode 100644 src/sheet.rs create mode 100644 src/slides.rs create mode 100644 src/typeset.rs create mode 100644 src/word.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index c364731..0d3f10b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Open Word documents (`.docx`), slide decks (`.pptx`) and spreadsheets (`.xlsx`, `.xls`, `.ods`, `.csv`, `.tsv`). leaf reads them itself on macOS and Linux, with no LibreOffice, Keynote or Numbers. Each shows as designed, in its own fonts, colors and layout; `o` switches to the terminal's font, and `i` paints the designed page in the terminal's colors. Decks show one slide per page with speaker notes, Word documents keep their pages, and spreadsheets keep their cell styles and column widths. - Configure the document reader's maximum width in `$XDG_CONFIG_HOME/leaf/config.toml` (default `~/.config/leaf/config.toml`). Omitted settings keep the 76-column layout. - Keep the reading position within PDF and EPUB pages when resizing in scroll mode. - `<` and `>` narrow or widen the reading column, and `=` fits it to the screen, so wide diagrams can be read without quitting. diff --git a/Cargo.lock b/Cargo.lock index e96ad7d..df80121 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -98,6 +98,16 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "atoi_simd" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cdb3708a128e559a30fb830e8a77a5022ee6902806925c216658652b452a44" +dependencies = [ + "debug_unsafe", + "rustversion", +] + [[package]] name = "atomic" version = "0.6.1" @@ -293,6 +303,23 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "calamine" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f431b67cba6122a1f7d26b7adafc71bbdf07026095fe811f5efc025d8748e1d8" +dependencies = [ + "atoi_simd", + "byteorder", + "codepage", + "encoding_rs", + "fast-float2", + "log", + "quick-xml", + "serde", + "zip", +] + [[package]] name = "castaway" version = "0.2.4" @@ -364,6 +391,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "codepage" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdff162541cd8b79de82e2edcc7eff3a8c2a6dc3d75152636028f96d93de3b26" +dependencies = [ + "encoding_rs", +] + [[package]] name = "color_quant" version = "1.1.0" @@ -400,6 +436,15 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "constant_time_eq" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9eb6feb175df65d0a3ccd3e73484e940d0ac664e8034f0519fd49a93db3071d9" +dependencies = [ + "rustversion", +] + [[package]] name = "convert_case" version = "0.10.0" @@ -461,6 +506,12 @@ dependencies = [ "libc", ] +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "coreaudio-rs" version = "0.14.2" @@ -856,6 +907,12 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" +[[package]] +name = "debug_unsafe" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eed2c4702fa172d1ce21078faa7c5203e69f5394d48cc436d25928394a867a2" + [[package]] name = "deltae" version = "0.3.2" @@ -1066,6 +1123,20 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -1128,6 +1199,12 @@ dependencies = [ "regex", ] +[[package]] +name = "fast-float2" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6e8948ce679d00a02a94739ea185595dca7118ed04feb991127e443bd3d761f" + [[package]] name = "fastrand" version = "2.5.0" @@ -1432,9 +1509,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -1923,6 +2002,7 @@ name = "leaf-reader" version = "0.17.2" dependencies = [ "base64 0.22.1", + "calamine", "crossterm", "dither-ratatui", "dom_smoothie", @@ -1942,6 +2022,7 @@ dependencies = [ "serde", "serde_json", "sha2 0.11.1", + "skrifa", "symphonia", "thiserror 2.0.21", "toml", @@ -1951,6 +2032,7 @@ dependencies = [ "ureq", "url", "wasmtime", + "zip", ] [[package]] @@ -2223,6 +2305,12 @@ dependencies = [ "target-features", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "mupdf" version = "0.8.0" @@ -2983,6 +3071,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "encoding_rs", + "memchr", +] + [[package]] name = "quote" version = "1.0.47" @@ -3312,12 +3410,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd" dependencies = [ "bytemuck", + "gif", + "image-webp", "log", "pico-args", "rgb", "svgtypes", "tiny-skia", "usvg", + "zune-jpeg", ] [[package]] @@ -4265,6 +4366,12 @@ dependencies = [ "webpki-roots 0.26.11", ] +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + [[package]] name = "typenum" version = "1.20.1" @@ -5284,6 +5391,20 @@ name = "zeroize" version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] name = "zerotrie" @@ -5318,6 +5439,26 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "zip" +version = "9.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08687262e7c0f1284b259686f322805a8adaa8ef4d7210e76448950b3f083bf7" +dependencies = [ + "constant_time_eq", + "crc32fast", + "flate2", + "getrandom 0.4.3", + "indexmap", + "libc", + "memchr", + "nix 0.31.3", + "typed-path", + "windows-sys 0.61.2", + "zeroize", + "zopfli", +] + [[package]] name = "zlib-rs" version = "0.6.8" @@ -5330,6 +5471,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zune-core" version = "0.5.3" diff --git a/Cargo.toml b/Cargo.toml index 38d982b..12a42ff 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ path = "src/main.rs" [dependencies] base64 = "0.22" +calamine = "0.38" crossterm = "0.29" dither-ratatui = "0.1.0" dom_smoothie = "0.18" @@ -28,12 +29,13 @@ pulldown-cmark = { version = "0.13", default-features = false } ratatui = "0.30" ratatui-image = { version = "12.0.0-rc.2", default-features = false, features = ["crossterm"] } regex = "1" -resvg = { version = "0.48", default-features = false, features = ["text", "system-fonts", "memmap-fonts"] } +resvg = { version = "0.48", default-features = false, features = ["text", "system-fonts", "memmap-fonts", "raster-images"] } rodio = { version = "0.23.0", default-features = false, features = ["playback"] } rusqlite = { version = "0.40", features = ["bundled"] } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0.154", features = ["preserve_order"] } sha2 = "0.11.1" +skrifa = { version = "0.44", default-features = false, features = ["std"] } symphonia = { version = "0.6.1", default-features = false, features = ["mp3"] } thiserror = "2" toml = { version = "1.2.1", default-features = false, features = ["std", "parse", "serde"] } @@ -43,6 +45,7 @@ unicode-width = "0.2" ureq = "3" url = "2" wasmtime = { version = "50.0.0", default-features = false, features = ["cranelift", "parallel-compilation", "runtime", "std"] } +zip = { version = "9.7", default-features = false, features = ["deflate"] } # Load fontconfig at run time instead of linking it, so building on Linux # doesn't need its development package (libfontconfig1-dev). mupdf's diff --git a/README.md b/README.md index 8795856..e3c79a7 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,8 @@ If `leaf` isn't found after installing, add `~/.cargo/bin` to your PATH (fish: ` ln -s (pwd)/completions/leaf.fish ~/.config/fish/completions/ # fish: tab-completes .pdf and .md files leaf open paper.pdf leaf open README.md +leaf open talk.pptx +leaf open budget.xlsx leaf open https://example.com/post ``` @@ -77,7 +79,17 @@ PDFs are converted to markdown (headings from font size, paragraphs rejoined, ru Markdown files (`.md`, `.markdown`) show as written, with GitHub's extensions: tables, task lists, strikethrough, footnotes and alerts (`> [!NOTE]`), plus definition lists and math (kept as source). Front matter is hidden, HTML blocks such as a README's centered logo are read as markdown, and images next to the file show inline (PNG, JPEG, GIF, WebP). -Local Markdown, PDF, EPUB, and picture files reload in place after changes settle. Reloading pauses while you select text or use a dialog. Failed reloads wait five seconds before retrying, unless the file changes again. PDF and EPUB replacements load in the background while you keep reading the current document. +Office files open too, for reading. leaf reads them itself, the same on macOS and Linux, with nothing else installed: + +- **Slide decks** (`.pptx`, `.pptm`, `.ppsx`, `.ppsm`, `.potx`, `.potm`) show one slide per page, with speaker notes beneath. `←/→` move between slides, and `=` widens a slide to the screen. +- **Word documents** (`.docx`, `.docm`, `.dotx`, `.dotm`) show page by page, on the document's own page size and margins, with its lists, tables and pictures. +- **Spreadsheets** (`.xlsx`, `.xlsm`, `.xlsb`, `.xls`, `.ods`) and **CSV/TSV** files show each sheet in pages of 60 rows and 8 columns. The header row tops every page, and the first column starts every page of a wide sheet. Semicolon-separated CSV is detected. + +Each opens as designed: drawn as a picture in its own fonts, colors and layout, with an Excel workbook's cell fills, borders and column widths. `o` switches to the terminal's font and colors, as markdown text and tables; the page stays the same. In the designed look, `i` switches between real colors and the picture painted in the terminal's colors, as with PDFs. The footer shows both keys. + +Older formats (`.doc`, `.ppt`, `.rtf`, `.odt`, `.odp`) and Apple's (`.pages`, `.key`, `.numbers`) aren't read; save them as `.docx`, `.pptx` or `.xlsx` from the app that made them. + +Local Markdown, PDF, EPUB, office, and picture files reload in place after changes settle. Reloading pauses while you select text or use a dialog. Failed reloads wait five seconds before retrying, unless the file changes again. PDF and EPUB replacements load in the background while you keep reading the current document. `mermaid` code blocks are drawn as diagrams in the terminal's colors, with [Pele](https://github.com/obsidianmd/pele) run under `bun` or `node`; without either, or for a diagram Pele can't read, the block shows as code. diff --git a/completions/_leaf b/completions/_leaf index d1e613a..15bb8e3 100644 --- a/completions/_leaf +++ b/completions/_leaf @@ -52,7 +52,8 @@ _leaf() { # HEIC, HEIF, AVIF and JPEG XL need macOS's sips. local pictures='png|jpg|jpeg|jpe|jfif|gif|webp|bmp|ico|tif|tiff|tga|pnm|pbm|pgm|ppm|pam|qoi|hdr|exr|dds|ff|svg' [[ $OSTYPE == darwin* ]] && pictures+='|jxl|heic|heif|avif' - _arguments "*:document:_files -g \"(#i)*.(pdf|epub|md|markdown|$pictures)\"" + local office='docx|docm|dotx|dotm|pptx|pptm|ppsx|ppsm|potx|potm|xlsx|xlsm|xlsb|xls|xla|xlam|ods|csv|tsv' + _arguments "*:document:_files -g \"(#i)*.(pdf|epub|md|markdown|$office|$pictures)\"" ;; diff) _leaf_diff diff --git a/completions/leaf.fish b/completions/leaf.fish index eb5e607..00cbd26 100644 --- a/completions/leaf.fish +++ b/completions/leaf.fish @@ -1,7 +1,7 @@ # Completions for leaf. Install: ln -s (pwd)/completions/leaf.fish ~/.config/fish/completions/ complete -c leaf -f -complete -c leaf -n __fish_use_subcommand -a open -d 'Read a PDF, markdown file or web page' -complete -c leaf -n '__fish_seen_subcommand_from open' -a '(__fish_complete_suffix .pdf .epub .md .markdown .png .jpg .jpeg .jpe .jfif .gif .webp .bmp .ico .tif .tiff .tga .pnm .pbm .pgm .ppm .pam .qoi .hdr .exr .dds .ff .svg)' +complete -c leaf -n __fish_use_subcommand -a open -d 'Read a PDF, office file, markdown file or web page' +complete -c leaf -n '__fish_seen_subcommand_from open' -a '(__fish_complete_suffix .pdf .epub .md .markdown .docx .docm .dotx .dotm .pptx .pptm .ppsx .ppsm .potx .potm .xlsx .xlsm .xlsb .xls .xla .xlam .ods .csv .tsv .png .jpg .jpeg .jpe .jfif .gif .webp .bmp .ico .tif .tiff .tga .pnm .pbm .pgm .ppm .pam .qoi .hdr .exr .dds .ff .svg)' # HEIC, HEIF, AVIF and JPEG XL need macOS's sips. test (uname) = Darwin; and complete -c leaf -n '__fish_seen_subcommand_from open' -a '(__fish_complete_suffix .jxl .heic .heif .avif)' complete -c leaf -n __fish_use_subcommand -a diff -d 'Review a diff' diff --git a/lua/leaf/init.lua b/lua/leaf/init.lua index 16b296f..aba2811 100644 --- a/lua/leaf/init.lua +++ b/lua/leaf/init.lua @@ -205,9 +205,9 @@ function M.setup(opts) name = "leaf_open", title = "Leaf: Open Document…", description = "Open leaf's home in this pane: today's reading, a heat map of the days you read," - .. " and a search over recent documents and this folder's PDFs, EPUBs and markdown files.", + .. " and a search over recent documents and this folder's PDFs, EPUBs, markdown and office files.", category = "Leaf", - keywords = "leaf pdf markdown epub read document article book file picker", + keywords = "leaf pdf markdown epub word powerpoint excel slides spreadsheet read document article book file picker", args = { target = "string?" }, run = function(ctx, args) local target = args.target or "" diff --git a/skills/leaf/SKILL.md b/skills/leaf/SKILL.md index c55be57..f9cb5f2 100644 --- a/skills/leaf/SKILL.md +++ b/skills/leaf/SKILL.md @@ -5,7 +5,7 @@ description: Use leaf, a terminal reader and code reviewer, to show the person d # leaf -leaf reads PDFs, EPUBs, Markdown files and web articles in the terminal, and reviews diffs and GitHub pull requests. The person reads in leaf. You start it, hand it files, and read what they leave behind. +leaf reads PDFs, EPUBs, Markdown files, Word documents, slide decks, spreadsheets and web articles in the terminal, and reviews diffs and GitHub pull requests. The person reads in leaf. You start it, hand it files, and read what they leave behind. ## Before you run it @@ -21,7 +21,7 @@ leaf is a full-screen terminal app. Your shell tool has no terminal, so a bare ` | Command | What it opens | |---|---| -| `leaf open `, or just `leaf ` | A PDF, EPUB or Markdown file, or a web article. It reopens where the person left off. | +| `leaf open `, or just `leaf ` | A PDF, EPUB, Markdown file, Word document, slide deck or spreadsheet, or a web article. It reopens where the person left off. | | `leaf diff` | Unstaged changes. `--staged`, `--branch` (this branch against its base), `--base `, a range such as `main...HEAD`, a path, a `.patch` file or a GitHub PR, commit or compare link. `--inline` uses one column. | | `leaf pr` | The person's open pull requests and issues. `leaf pr 12`, `leaf pr owner/repo#12` or a PR link opens one, with Summary, Timeline and Comments tabs, plus Code and Checks for a pull request. In the list, `←/→` switch pull requests and issues, `tab` switches open and merged/closed, `R` reloads. | | `leaf plan ` | Plan review, block by block. | diff --git a/src/chart.rs b/src/chart.rs new file mode 100644 index 0000000..69955c4 --- /dev/null +++ b/src/chart.rs @@ -0,0 +1,734 @@ +//! Office charts (`c:chartSpace`) drawn from the values cached in the file: +//! bar and column, line, area, pie and doughnut charts, with title, axis, +//! gridlines and legend. Charts of other kinds draw the first of these they +//! hold, or nothing. + +use std::fmt::Write as _; +use std::rc::Rc; + +use crate::drawing::{Canvas, Rect, fill_node}; +use crate::ooxml::{Color, Local, Theme, md_escape, roxmltree}; +use crate::typeset::{self, Run, Style}; +use roxmltree::Node; + +#[derive(Debug, Clone, Copy, PartialEq)] +enum Kind { + Bar { horizontal: bool, stacked: bool }, + Line, + Area, + Pie { hole: f32 }, +} + +#[derive(Debug, Clone)] +struct Series { + name: String, + values: Vec>, + color: Option, + /// Pie slices' own colors, by point. + points: Vec<(usize, Color)>, +} + +#[derive(Debug, Clone)] +struct Chart { + title: Option, + kind: Kind, + categories: Vec, + series: Vec, + legend: bool, +} + +fn cached(node: Option) -> Vec<(usize, String)> { + let Some(node) = node else { return Vec::new() }; + let Some(cache) = node + .descendants() + .find(|n| n.has_tag_name_local("strCache") || n.has_tag_name_local("numCache")) + else { + return Vec::new(); + }; + cache + .kids("pt") + .filter_map(|pt| { + let idx = pt.attribute("idx")?.parse().ok()?; + let v = pt.child("v")?.text().unwrap_or("").to_owned(); + Some((idx, v)) + }) + .collect() +} + +fn rich_text(node: Node) -> String { + node.descendants() + .filter(|n| n.has_tag_name_local("t")) + .filter_map(|n| n.text()) + .collect::>() + .join("") +} + +fn parse(xml: &str, theme: &Theme) -> Option { + let doc = roxmltree::Document::parse(xml).ok()?; + let chart = doc.root_element().child("chart")?; + let plot = chart.child("plotArea")?; + let (node, kind) = plot.children().find_map(|n| { + let kind = match n.local() { + "barChart" | "bar3DChart" => { + let horizontal = n.child("barDir").and_then(|d| d.attribute("val")) == Some("bar"); + let stacked = matches!( + n.child("grouping").and_then(|g| g.attribute("val")), + Some("stacked" | "percentStacked") + ); + Kind::Bar { + horizontal, + stacked, + } + } + "lineChart" | "line3DChart" | "scatterChart" | "radarChart" => Kind::Line, + "areaChart" | "area3DChart" => Kind::Area, + "pieChart" | "pie3DChart" | "ofPieChart" => Kind::Pie { hole: 0.0 }, + "doughnutChart" => Kind::Pie { + hole: n + .child("holeSize") + .and_then(|h| h.attribute("val")) + .and_then(|v| v.parse::().ok()) + .map_or(0.5, |v| v / 100.0), + }, + _ => return None, + }; + Some((n, kind)) + })?; + let mut categories: Vec = Vec::new(); + let mut series = Vec::new(); + for ser in node.kids("ser") { + let name = cached(ser.child("tx")) + .into_iter() + .next() + .map(|(_, v)| v) + .or_else(|| ser.child("tx").map(rich_text)) + .unwrap_or_else(|| format!("Series {}", series.len() + 1)); + let cats = cached(ser.child("cat").or_else(|| ser.child("xVal"))); + let vals = cached(ser.child("val").or_else(|| ser.child("yVal"))); + let count = vals.iter().map(|(i, _)| i + 1).max().unwrap_or(0); + let mut values = vec![None; count]; + for (i, v) in vals { + if let Some(slot) = values.get_mut(i) { + *slot = v.trim().parse::().ok(); + } + } + if categories.is_empty() && !cats.is_empty() { + let n = cats.iter().map(|(i, _)| i + 1).max().unwrap_or(0); + categories = vec![String::new(); n]; + for (i, v) in cats { + categories[i] = v; + } + } + let color = ser + .child("spPr") + .and_then(fill_node) + .filter(|f| f.local() == "solidFill") + .and_then(|f| theme.color(f, None)); + let points = ser + .kids("dPt") + .filter_map(|p| { + let idx = p.child("idx")?.attribute("val")?.parse().ok()?; + let fill = p.child("spPr").and_then(fill_node)?; + Some((idx, theme.color(fill, None)?)) + }) + .collect(); + series.push(Series { + name, + values, + color, + points, + }); + } + if series.is_empty() { + return None; + } + let longest = series.iter().map(|s| s.values.len()).max().unwrap_or(0); + if categories.len() < longest { + categories.extend((categories.len()..longest).map(|i| (i + 1).to_string())); + } + let deleted = chart + .child("autoTitleDeleted") + .and_then(|d| d.attribute("val")) + == Some("1"); + let title = chart + .child("title") + .map(rich_text) + .filter(|t| !t.trim().is_empty()) + .or_else(|| { + (!deleted && chart.child("title").is_some() && series.len() == 1) + .then(|| series[0].name.clone()) + }); + Some(Chart { + title, + kind, + categories, + series, + legend: chart.child("legend").is_some(), + }) +} + +fn accent(theme: &Theme, i: usize) -> Color { + theme + .scheme(&format!("accent{}", i % 6 + 1)) + .unwrap_or(Color::rgb(68, 114, 196)) +} + +/// A tidy scale for values from `low` to `high`: its ends and step. +fn nice_scale(low: f64, high: f64) -> (f64, f64, f64) { + let (low, high) = (low.min(0.0), high.max(0.0)); + let span = (high - low).max(1e-9); + let raw = span / 5.0; + let magnitude = 10f64.powf(raw.log10().floor()); + let step = [1.0, 2.0, 2.5, 5.0, 10.0] + .iter() + .map(|m| m * magnitude) + .find(|s| *s >= raw) + .unwrap_or(magnitude * 10.0); + ( + (low / step).floor() * step, + (high / step).ceil() * step, + step, + ) +} + +fn label(value: f64) -> String { + if value.abs() >= 1e6 { + format!("{}M", trim(value / 1e6)) + } else if value.abs() >= 1e4 { + format!("{}K", trim(value / 1e3)) + } else { + trim(value) + } +} + +fn trim(v: f64) -> String { + let s = format!("{v:.2}"); + s.trim_end_matches('0').trim_end_matches('.').to_owned() +} + +fn text(canvas: &mut Canvas, s: &str, x: f32, y: f32, style: &Rc