Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

feat(markdown): draw Mermaid diagrams in previews and notes

RoversX76d7b255a85d
diff --git a/Cargo.lock b/Cargo.lock
index 7e0b5a38..f6aa3075 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -174,6 +174,15 @@ version = "1.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
+[[package]]
+name = "approx"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"
+dependencies = [
+ "num-traits",
+]
+
[[package]]
name = "arbitrary"
version = "1.4.2"
@@ -221,6 +230,15 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b"
+[[package]]
+name = "ascii-canvas"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8824ecca2e851cec16968d54a01dd372ef8f95b244fb84b84e70128be347c3c6"
+dependencies = [
+ "term",
+]
+
[[package]]
name = "ash"
version = "0.38.0+1.3.281"
@@ -589,6 +607,12 @@ dependencies = [
"sha2 0.11.0",
]
+[[package]]
+name = "beef"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"
+
[[package]]
name = "benchmarking"
version = "0.4.13"
@@ -754,6 +778,12 @@ version = "3.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43"
+[[package]]
+name = "by_address"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"
+
[[package]]
name = "bytemuck"
version = "1.24.0"
@@ -1574,7 +1604,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb2a7d3066da2de787b7f032c736763eb7ae5d355f81a68bab2675a96008b0bf"
dependencies = [
"lab",
- "phf",
+ "phf 0.11.3",
+]
+
+[[package]]
+name = "cssparser"
+version = "0.36.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dae61cf9c0abb83bd659dab65b7e4e38d8236824c85f0f804f173567bda257d2"
+dependencies = [
+ "cssparser-macros",
+ "dtoa-short",
+ "itoa",
+ "phf 0.13.1",
+ "smallvec",
+]
+
+[[package]]
+name = "cssparser-macros"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331"
+dependencies = [
+ "quote",
+ "syn 2.0.110",
]
[[package]]
@@ -1920,6 +1973,46 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
+[[package]]
+name = "dtoa"
+version = "1.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590"
+
+[[package]]
+name = "dtoa-short"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87"
+dependencies = [
+ "dtoa",
+]
+
+[[package]]
+name = "dugong"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8182775cd5c441f69e5be06b29f1452503568c4270168cef67a557cd8fbcaba0"
+dependencies = [
+ "dugong-graphlib",
+ "rustc-hash 2.1.1",
+ "serde",
+ "serde_json",
+ "web-time",
+]
+
+[[package]]
+name = "dugong-graphlib"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "faffb9e2480ff1c6901e6376f143614df5331052e60e0dd5086f12399a18c61d"
+dependencies = [
+ "hashbrown 0.16.1",
+ "rustc-hash 2.1.1",
+ "serde",
+ "serde_json",
+]
+
[[package]]
name = "dwrote"
version = "0.11.5"
@@ -2022,7 +2115,16 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99e1f1df1f181f2539bac8bf027d31ca5ffbf9e559e3f2d09413b9107b5c02f4"
dependencies = [
- "phf",
+ "phf 0.11.3",
+]
+
+[[package]]
+name = "ena"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eabffdaee24bd1bf95c5ef7cec31260444317e72ea56c4c91750e8b7ee58d5f1"
+dependencies = [
+ "log",
]
[[package]]
@@ -2538,6 +2640,29 @@ dependencies = [
"pkg-config",
]
+[[package]]
+name = "fontconfig-parser"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646"
+dependencies = [
+ "roxmltree",
+]
+
+[[package]]
+name = "fontdb"
+version = "0.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "457e789b3d1202543297a350643cf459f836cade38934e7a4cf6a39e7cde2905"
+dependencies = [
+ "fontconfig-parser",
+ "log",
+ "memmap2 0.9.9",
+ "slotmap",
+ "tinyvec",
+ "ttf-parser",
+]
+
[[package]]
name = "foreign-types"
version = "0.3.2"
@@ -2771,6 +2896,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "getopts"
+version = "0.2.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"
+dependencies = [
+ "unicode-width",
+]
+
[[package]]
name = "getrandom"
version = "0.2.16"
@@ -2864,6 +2998,114 @@ dependencies = [
"xml-rs",
]
+[[package]]
+name = "glam"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "333928d5eb103c5d4050533cec0384302db6be8ef7d3cebd30ec6a35350353da"
+
+[[package]]
+name = "glam"
+version = "0.15.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3abb554f8ee44336b72d522e0a7fe86a29e09f839a36022fa869a7dfe941a54b"
+
+[[package]]
+name = "glam"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4126c0479ccf7e8664c36a2d719f5f2c140fbb4f9090008098d2c291fa5b3f16"
+
+[[package]]
+name = "glam"
+version = "0.17.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e01732b97afd8508eee3333a541b9f7610f454bb818669e66e90f5f57c93a776"
+
+[[package]]
+name = "glam"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "525a3e490ba77b8e326fb67d4b44b4bd2f920f44d4cc73ccec50adc68e3bee34"
+
+[[package]]
+name = "glam"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b8509e6791516e81c1a630d0bd7fbac36d2fa8712a9da8662e716b52d5051ca"
+
+[[package]]
+name = "glam"
+version = "0.20.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f43e957e744be03f5801a55472f593d43fabdebf25a4585db250f04d86b1675f"
+
+[[package]]
+name = "glam"
+version = "0.21.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "518faa5064866338b013ff9b2350dc318e14cc4fcd6cb8206d7e7c9886c98815"
+
+[[package]]
+name = "glam"
+version = "0.22.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f597d56c1bd55a811a1be189459e8fad2bbc272616375602443bdfb37fa774"
+
+[[package]]
+name = "glam"
+version = "0.23.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e4afd9ad95555081e109fe1d21f2a30c691b5f0919c67dfa690a2e1eb6bd51c"
+
+[[package]]
+name = "glam"
+version = "0.24.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5418c17512bdf42730f9032c74e1ae39afc408745ebb2acf72fbc4691c17945"
+
+[[package]]
+name = "glam"
+version = "0.25.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3"
+
+[[package]]
+name = "glam"
+version = "0.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e05e7e6723e3455f4818c7b26e855439f7546cf617ef669d1adedb8669e5cb9"
+
+[[package]]
+name = "glam"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "779ae4bf7e8421cf91c0b3b64e7e8b40b862fba4d393f59150042de7c4965a94"
+
+[[package]]
+name = "glam"
+version = "0.29.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8babf46d4c1c9d92deac9f7be466f76dfc4482b6452fc5024b5e8daf6ffeb3ee"
+
+[[package]]
+name = "glam"
+version = "0.30.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
+
+[[package]]
+name = "glam"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "556f6b2ea90b8d15a74e0e7bb41671c9bdf38cd9f78c284d750b9ce58a2b5be7"
+
+[[package]]
+name = "glam"
+version = "0.32.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f70749695b063ecbf6b62949ccccde2e733ec3ecbbd71d467dca4e5c6c97cca0"
+
[[package]]
name = "glium"
version = "0.35.0"
@@ -3100,9 +3342,9 @@ dependencies = [
[[package]]
name = "hashbrown"
-version = "0.16.0"
+version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
"allocator-api2",
"equivalent",
@@ -3207,6 +3449,19 @@ dependencies = [
"windows-link 0.1.3",
]
+[[package]]
+name = "htmlize"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e815d50d9e411ba2690d730e6ec139c08260dddb756df315dbd16d01a587226"
+dependencies = [
+ "memchr",
+ "pastey",
+ "phf 0.13.1",
+ "phf_codegen 0.13.1",
+ "serde_json",
+]
+
[[package]]
name = "http"
version = "1.3.1"
@@ -3586,7 +3841,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6717a8d2a5a929a1a2eb43a12812498ed141a0bcfb7e8f7844fbdbe4303bba9f"
dependencies = [
"equivalent",
- "hashbrown 0.16.0",
+ "hashbrown 0.16.1",
"serde",
"serde_core",
]
@@ -3735,6 +3990,15 @@ dependencies = [
"either",
]
+[[package]]
+name = "itertools"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "itertools"
version = "0.12.1"
@@ -3809,6 +4073,17 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "json5"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96b0db21af676c1ce64250b5f40f3ce2cf27e4e47cb91ed91eb6fe9350b430c1"
+dependencies = [
+ "pest",
+ "pest_derive",
+ "serde",
+]
+
[[package]]
name = "k9"
version = "0.12.0"
@@ -3832,7 +4107,7 @@ version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fe90c1150662e858c7d5f945089b7517b0a80d8bf7ba4b1b5ffc984e7230a5b"
dependencies = [
- "hashbrown 0.16.0",
+ "hashbrown 0.16.1",
"portable-atomic",
"thiserror 2.0.20",
]
@@ -3894,6 +4169,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "kurbo"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bd85a5776cd9500c2e2059c8c76c3b01528566b7fcbaf8098b55a33fc298849b"
+dependencies = [
+ "arrayvec",
+]
+
[[package]]
name = "kurbo"
version = "0.11.3"
@@ -3905,12 +4189,55 @@ dependencies = [
"smallvec",
]
+[[package]]
+name = "kurbo"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"
+dependencies = [
+ "arrayvec",
+ "euclid",
+ "polycool",
+ "smallvec",
+]
+
[[package]]
name = "lab"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf36173d4167ed999940f804952e6b08197cae5ad5d572eb4db150ce8ad5d58f"
+[[package]]
+name = "lalrpop"
+version = "0.20.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55cb077ad656299f160924eb2912aa147d7339ea7d69e1b5517326fdcec3c1ca"
+dependencies = [
+ "ascii-canvas",
+ "bit-set 0.5.3",
+ "ena",
+ "itertools 0.11.0",
+ "lalrpop-util",
+ "petgraph",
+ "pico-args",
+ "regex",
+ "regex-syntax",
+ "string_cache",
+ "term",
+ "tiny-keccak",
+ "unicode-xid",
+ "walkdir",
+]
+
+[[package]]
+name = "lalrpop-util"
+version = "0.20.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "507460a910eb7b32ee961886ff48539633b788a36b65692b95f225b844c82553"
+dependencies = [
+ "regex-automata",
+]
+
[[package]]
name = "lazy_static"
version = "1.5.0"
@@ -3973,7 +4300,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a599cb10a9cd92b1300debcef28da8f70b935ec937f44fcd1b70a7c986a11c5c"
dependencies = [
"core2",
- "hashbrown 0.16.0",
+ "hashbrown 0.16.1",
"rle-decode-fast",
]
@@ -4162,6 +4489,58 @@ dependencies = [
"luahelper",
]
+[[package]]
+name = "logos"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7251356ef8cb7aec833ddf598c6cb24d17b689d20b993f9d11a3d764e34e6458"
+dependencies = [
+ "logos-derive",
+]
+
+[[package]]
+name = "logos-codegen"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59f80069600c0d66734f5ff52cc42f2dabd6b29d205f333d61fd7832e9e9963f"
+dependencies = [
+ "beef",
+ "fnv",
+ "lazy_static",
+ "proc-macro2",
+ "quote",
+ "regex-syntax",
+ "syn 2.0.110",
+]
+
+[[package]]
+name = "logos-derive"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24fb722b06a9dc12adb0963ed585f19fc61dc5413e6a9be9422ef92c091e731d"
+dependencies = [
+ "logos-codegen",
+]
+
+[[package]]
+name = "lol_html"
+version = "2.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6888e8653f6e49cb2924c660fc367a8beeb6239b71e117fa082153c6ea44d427"
+dependencies = [
+ "bitflags 2.13.1",
+ "cfg-if",
+ "cssparser",
+ "encoding_rs",
+ "foldhash 0.2.0",
+ "hashbrown 0.16.1",
+ "memchr",
+ "mime",
+ "precomputed-hash",
+ "selectors",
+ "thiserror 2.0.20",
+]
+
[[package]]
name = "loop9"
version = "0.1.5"
@@ -4177,7 +4556,7 @@ version = "0.16.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1dc47f592c06f33f8e3aea9591776ec7c9f9e4124778ff8a3c3b87159f7e593"
dependencies = [
- "hashbrown 0.16.0",
+ "hashbrown 0.16.1",
]
[[package]]
@@ -4237,12 +4616,35 @@ dependencies = [
"libc",
]
+[[package]]
+name = "manatee"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85f575aa9013f7fc6f6804dcc8fc47299ee61692c2a7cb017573dc5f3a85a5a4"
+dependencies = [
+ "indexmap 2.12.0",
+ "nalgebra",
+ "rustc-hash 2.1.1",
+ "thiserror 2.0.20",
+ "web-time",
+]
+
[[package]]
name = "maplit"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
+[[package]]
+name = "matrixmultiply"
+version = "0.3.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"
+dependencies = [
+ "autocfg",
+ "rawpointer",
+]
+
[[package]]
name = "maybe-rayon"
version = "0.1.1"
@@ -4287,15 +4689,80 @@ dependencies = [
name = "memmem"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a64a92489e2744ce060c349162be1c5f33c6969234104dbd99ddb5feb08b8c15"
+checksum = "a64a92489e2744ce060c349162be1c5f33c6969234104dbd99ddb5feb08b8c15"
+
+[[package]]
+name = "memoffset"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "merman"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "316af7de4c273fb450fa7db94441df29bd09d5dcc5fd7f31f946766dea7272b3"
+dependencies = [
+ "chrono",
+ "merman-core",
+ "merman-render",
+ "thiserror 2.0.20",
+]
+
+[[package]]
+name = "merman-core"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b7ca468603ca22bad2578b3d3fbc0b436e28b5ccb726e2cf99d7bb75fa8c167"
+dependencies = [
+ "chrono",
+ "euclid",
+ "htmlize",
+ "indexmap 2.12.0",
+ "json5",
+ "lalrpop",
+ "lalrpop-util",
+ "logos",
+ "lol_html",
+ "regex",
+ "rustc-hash 2.1.1",
+ "ryu-js",
+ "serde",
+ "serde_json",
+ "serde_yaml",
+ "thiserror 2.0.20",
+ "tracing",
+ "url",
+ "uuid",
+ "web-time",
+]
[[package]]
-name = "memoffset"
-version = "0.9.1"
+name = "merman-render"
+version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+checksum = "46cda864705a73dd80ec8985463d4bf735e991954d5bf63ca5604bf59287582a"
dependencies = [
- "autocfg",
+ "base64 0.22.1",
+ "chrono",
+ "dugong",
+ "indexmap 2.12.0",
+ "manatee",
+ "merman-core",
+ "pulldown-cmark 0.12.2",
+ "roughr-merman",
+ "rustc-hash 2.1.1",
+ "ryu-js",
+ "serde",
+ "serde_json",
+ "svgtypes 0.11.0",
+ "thiserror 2.0.20",
+ "unicode-width",
+ "url",
+ "web-time",
]
[[package]]
@@ -4547,6 +5014,39 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "nalgebra"
+version = "0.34.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df76ea0ff5c7e6b88689085804d6132ded0ddb9de5ca5b8aeb9eeadc0508a70a"
+dependencies = [
+ "approx",
+ "glam 0.14.0",
+ "glam 0.15.2",
+ "glam 0.16.0",
+ "glam 0.17.3",
+ "glam 0.18.0",
+ "glam 0.19.0",
+ "glam 0.20.5",
+ "glam 0.21.3",
+ "glam 0.22.0",
+ "glam 0.23.0",
+ "glam 0.24.2",
+ "glam 0.25.0",
+ "glam 0.27.0",
+ "glam 0.28.0",
+ "glam 0.29.3",
+ "glam 0.30.10",
+ "glam 0.31.1",
+ "glam 0.32.1",
+ "matrixmultiply",
+ "num-complex",
+ "num-rational",
+ "num-traits",
+ "simba",
+ "typenum",
+]
+
[[package]]
name = "names"
version = "0.12.0"
@@ -5095,6 +5595,35 @@ dependencies = [
"windows-strings 0.5.1",
]
+[[package]]
+name = "palette"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddeed8580d347d2abf3dcf06a5f0b3dc020258338526b277847cd4248a70fc64"
+dependencies = [
+ "approx",
+ "palette_derive",
+ "palette_math",
+]
+
+[[package]]
+name = "palette_derive"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88537020289b719d81be994ccf1bbf4990f477e2f69ee52fe3e45f43a02e56be"
+dependencies = [
+ "by_address",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.110",
+]
+
+[[package]]
+name = "palette_math"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e6eb142958d64335fb0e345c5b9ead2ecd6fc438c307e9d7d3c4fd428dbaf12"
+
[[package]]
name = "parking"
version = "2.2.1"
@@ -5148,6 +5677,12 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+[[package]]
+name = "pastey"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
+
[[package]]
name = "pbkdf2"
version = "0.13.0"
@@ -5226,6 +5761,16 @@ dependencies = [
"sha2 0.10.9",
]
+[[package]]
+name = "petgraph"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db"
+dependencies = [
+ "fixedbitset",
+ "indexmap 2.12.0",
+]
+
[[package]]
name = "phc"
version = "0.6.1"
@@ -5242,10 +5787,21 @@ version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078"
dependencies = [
- "phf_macros",
+ "phf_macros 0.11.3",
"phf_shared 0.11.3",
]
+[[package]]
+name = "phf"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
+dependencies = [
+ "phf_macros 0.13.1",
+ "phf_shared 0.13.1",
+ "serde",
+]
+
[[package]]
name = "phf_codegen"
version = "0.10.0"
@@ -5266,6 +5822,16 @@ dependencies = [
"phf_shared 0.11.3",
]
+[[package]]
+name = "phf_codegen"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"
+dependencies = [
+ "phf_generator 0.13.1",
+ "phf_shared 0.13.1",
+]
+
[[package]]
name = "phf_generator"
version = "0.10.0"
@@ -5286,6 +5852,16 @@ dependencies = [
"rand 0.8.5",
]
+[[package]]
+name = "phf_generator"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
+dependencies = [
+ "fastrand",
+ "phf_shared 0.13.1",
+]
+
[[package]]
name = "phf_macros"
version = "0.11.3"
@@ -5299,6 +5875,19 @@ dependencies = [
"syn 2.0.110",
]
+[[package]]
+name = "phf_macros"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
+dependencies = [
+ "phf_generator 0.13.1",
+ "phf_shared 0.13.1",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.110",
+]
+
[[package]]
name = "phf_shared"
version = "0.10.0"
@@ -5317,6 +5906,15 @@ dependencies = [
"siphasher 1.0.1",
]
+[[package]]
+name = "phf_shared"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
+dependencies = [
+ "siphasher 1.0.1",
+]
+
[[package]]
name = "pico-args"
version = "0.5.0"
@@ -5492,6 +6090,15 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "polycool"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"
+dependencies = [
+ "arrayvec",
+]
+
[[package]]
name = "polyval"
version = "0.7.3"
@@ -5565,6 +6172,12 @@ dependencies = [
"zerocopy",
]
+[[package]]
+name = "precomputed-hash"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
+
[[package]]
name = "predicates"
version = "3.1.3"
@@ -5712,6 +6325,19 @@ dependencies = [
"thiserror 1.0.69",
]
+[[package]]
+name = "pulldown-cmark"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f86ba2052aebccc42cbbb3ed234b8b13ce76f75c3551a303cb2bcffcff12bb14"
+dependencies = [
+ "bitflags 2.13.1",
+ "getopts",
+ "memchr",
+ "pulldown-cmark-escape",
+ "unicase",
+]
+
[[package]]
name = "pulldown-cmark"
version = "0.13.4"
@@ -5723,6 +6349,12 @@ dependencies = [
"unicase",
]
+[[package]]
+name = "pulldown-cmark-escape"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
+
[[package]]
name = "pure-rust-locales"
version = "0.8.2"
@@ -5920,7 +6552,7 @@ checksum = "5ef8dea09a92caaf73bff7adb70b76162e5937524058a7e5bff37869cbbec293"
dependencies = [
"bitflags 2.13.1",
"compact_str",
- "hashbrown 0.16.0",
+ "hashbrown 0.16.1",
"indoc",
"itertools 0.14.0",
"kasuari",
@@ -5961,7 +6593,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7dbfa023cd4e604c2553483820c5fe8aa9d71a42eea5aa77c6e7f35756612db"
dependencies = [
"bitflags 2.13.1",
- "hashbrown 0.16.0",
+ "hashbrown 0.16.1",
"indoc",
"instability",
"itertools 0.14.0",
@@ -6037,6 +6669,12 @@ version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+[[package]]
+name = "rawpointer"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
+
[[package]]
name = "rayon"
version = "1.11.0"
@@ -6200,7 +6838,7 @@ dependencies = [
"log",
"pico-args",
"rgb",
- "svgtypes",
+ "svgtypes 0.15.3",
"tiny-skia",
"usvg",
]
@@ -6244,6 +6882,21 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3582f63211428f83597b51b2ddb88e2a91a9d52d12831f9d08f5e624e8977422"
+[[package]]
+name = "roughr-merman"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0a1b0137cf48e915300be3fe4cf9f8f9a2af242ebf41b6f8fa716c2fd482f00b"
+dependencies = [
+ "euclid",
+ "getrandom 0.2.16",
+ "num-traits",
+ "palette",
+ "rand 0.8.5",
+ "svgtypes 0.11.0",
+ "svgtypes 0.16.1",
+]
+
[[package]]
name = "roxmltree"
version = "0.20.0"
@@ -6525,6 +7178,21 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
+[[package]]
+name = "ryu-js"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714"
+
+[[package]]
+name = "safe_arch"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323"
+dependencies = [
+ "bytemuck",
+]
+
[[package]]
name = "salsa20"
version = "0.11.0"
@@ -6634,6 +7302,25 @@ dependencies = [
"libc",
]
+[[package]]
+name = "selectors"
+version = "0.35.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fdfed56cd634f04fe8b9ddf947ae3dc493483e819593d2ba17df9ad05db8b2"
+dependencies = [
+ "bitflags 2.13.1",
+ "cssparser",
+ "derive_more",
+ "log",
+ "new_debug_unreachable",
+ "phf 0.13.1",
+ "phf_codegen 0.13.1",
+ "precomputed-hash",
+ "rustc-hash 2.1.1",
+ "servo_arc",
+ "smallvec",
+]
+
[[package]]
name = "self_cell"
version = "1.3.0"
@@ -6830,6 +7517,15 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "servo_arc"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930"
+dependencies = [
+ "stable_deref_trait",
+]
+
[[package]]
name = "sha1"
version = "0.10.6"
@@ -6985,6 +7681,19 @@ dependencies = [
"rand_core 0.10.1",
]
+[[package]]
+name = "simba"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c99284beb21666094ba2b75bbceda012e610f5479dfcc2d6e2426f53197ffd95"
+dependencies = [
+ "approx",
+ "num-complex",
+ "num-traits",
+ "paste",
+ "wide",
+]
+
[[package]]
name = "simd-adler32"
version = "0.3.7"
@@ -7327,6 +8036,18 @@ dependencies = [
"float-cmp 0.9.0",
]
+[[package]]
+name = "string_cache"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f"
+dependencies = [
+ "new_debug_unreachable",
+ "parking_lot",
+ "phf_shared 0.11.3",
+ "precomputed-hash",
+]
+
[[package]]
name = "strip-ansi-escapes"
version = "0.1.0"
@@ -7396,13 +8117,33 @@ version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0193cc4331cfd2f3d2011ef287590868599a2f33c3e69bc22c1a3d3acf9e02fb"
+[[package]]
+name = "svgtypes"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed4b0611e7f3277f68c0fa18e385d9e2d26923691379690039548f867cef02a7"
+dependencies = [
+ "kurbo 0.9.5",
+ "siphasher 0.3.11",
+]
+
[[package]]
name = "svgtypes"
version = "0.15.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc"
dependencies = [
- "kurbo",
+ "kurbo 0.11.3",
+ "siphasher 1.0.1",
+]
+
+[[package]]
+name = "svgtypes"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "695b5790b3131dafa99b3bbfd25a216edb3d216dad9ca208d4657bfb8f2abc3d"
+dependencies = [
+ "kurbo 0.13.1",
"siphasher 1.0.1",
]
@@ -7575,6 +8316,17 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "term"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c59df8ac95d96ff9bede18eb7300b0fda5e5d8d90960e76f8e14ae765eedbf1f"
+dependencies = [
+ "dirs-next",
+ "rustversion",
+ "winapi",
+]
+
[[package]]
name = "termcolor"
version = "1.4.1"
@@ -7602,7 +8354,7 @@ checksum = "d4ea810f0692f9f51b382fff5893887bb4580f5fa246fde546e0b13e7fcee662"
dependencies = [
"fnv",
"nom 7.1.3",
- "phf",
+ "phf 0.11.3",
"phf_codegen 0.11.3",
]
@@ -7645,7 +8397,7 @@ dependencies = [
"ordered-float 4.6.0",
"pest",
"pest_derive",
- "phf",
+ "phf 0.11.3",
"sha2 0.10.9",
"signal-hook",
"siphasher 1.0.1",
@@ -7688,7 +8440,7 @@ dependencies = [
"ordered-float 4.6.0",
"pest",
"pest_derive",
- "phf",
+ "phf 0.11.3",
"serde",
"sha2 0.10.9",
"signal-hook",
@@ -8094,6 +8846,15 @@ dependencies = [
"time-core",
]
+[[package]]
+name = "tiny-keccak"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
+dependencies = [
+ "crunchy",
+]
+
[[package]]
name = "tiny-skia"
version = "0.11.4"
@@ -8713,6 +9474,12 @@ version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539"
+[[package]]
+name = "unicode-bidi"
+version = "0.3.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
+
[[package]]
name = "unicode-bidi-mirroring"
version = "0.4.0"
@@ -8775,12 +9542,24 @@ dependencies = [
"unicode-width",
]
+[[package]]
+name = "unicode-vo"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94"
+
[[package]]
name = "unicode-width"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
[[package]]
name = "uniffi"
version = "0.32.1"
@@ -8973,16 +9752,21 @@ dependencies = [
"base64 0.22.1",
"data-url",
"flate2",
+ "fontdb",
"imagesize",
- "kurbo",
+ "kurbo 0.11.3",
"log",
"pico-args",
"roxmltree",
+ "rustybuzz",
"simplecss",
"siphasher 1.0.1",
"strict-num",
- "svgtypes",
+ "svgtypes 0.15.3",
"tiny-skia-path",
+ "unicode-bidi",
+ "unicode-script",
+ "unicode-vo",
"xmlwriter",
]
@@ -9327,6 +10111,16 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
[[package]]
name = "weedle2"
version = "5.0.0"
@@ -9456,7 +10250,7 @@ name = "wezterm-char-props"
version = "0.1.3"
dependencies = [
"k9",
- "phf",
+ "phf 0.11.3",
"serde",
"ucd-trie",
]
@@ -9683,7 +10477,10 @@ dependencies = [
"lfucache",
"libc",
"log",
+ "lru",
"luahelper",
+ "merman",
+ "merman-render",
"metrics",
"mlua",
"mux",
@@ -9693,11 +10490,11 @@ dependencies = [
"ordered-float 4.6.0",
"parking_lot",
"percent-encoding",
- "phf",
+ "phf 0.11.3",
"phf_codegen 0.10.0",
"portable-pty",
"promise",
- "pulldown-cmark",
+ "pulldown-cmark 0.13.4",
"qrcode",
"rangeset",
"ratelim",
@@ -9728,6 +10525,7 @@ dependencies = [
"thiserror 1.0.69",
"tiny-skia",
"trash",
+ "ttf-parser",
"umask",
"unic-langid",
"unicode-linebreak",
@@ -10172,6 +10970,16 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "wide"
+version = "0.7.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03"
+dependencies = [
+ "bytemuck",
+ "safe_arch",
+]
+
[[package]]
name = "winapi"
version = "0.3.9"
diff --git a/Cargo.toml b/Cargo.toml
index 8dac61a4..2e09490f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -54,6 +54,83 @@ debug = "line-tables-only"
split-debuginfo = "packed"
strip = "symbols"
+# Mermaid support (merman and what only it links in) is a lot of code for
+# little time: a diagram is drawn off the UI thread, and parsing one on it
+# takes under 10 ms even at this level, for the longest drawn. Optimized for
+# size, it adds about half as much to the binary. `dist` inherits these.
+[profile.release.package.approx]
+opt-level = "z"
+[profile.release.package.beef]
+opt-level = "z"
+[profile.release.package.by_address]
+opt-level = "z"
+[profile.release.package.cssparser]
+opt-level = "z"
+[profile.release.package.dtoa]
+opt-level = "z"
+[profile.release.package.dtoa-short]
+opt-level = "z"
+[profile.release.package.dugong]
+opt-level = "z"
+[profile.release.package.dugong-graphlib]
+opt-level = "z"
+[profile.release.package.getopts]
+opt-level = "z"
+[profile.release.package.htmlize]
+opt-level = "z"
+[profile.release.package.json5]
+opt-level = "z"
+[profile.release.package.lalrpop-util]
+opt-level = "z"
+[profile.release.package.logos]
+opt-level = "z"
+[profile.release.package.lol_html]
+opt-level = "z"
+[profile.release.package.manatee]
+opt-level = "z"
+[profile.release.package.matrixmultiply]
+opt-level = "z"
+[profile.release.package.merman]
+opt-level = "z"
+[profile.release.package.merman-core]
+opt-level = "z"
+[profile.release.package.merman-render]
+opt-level = "z"
+[profile.release.package.nalgebra]
+opt-level = "z"
+[profile.release.package.palette]
+opt-level = "z"
+[profile.release.package.palette_math]
+opt-level = "z"
+[profile.release.package.pastey]
+opt-level = "z"
+[profile.release.package.polycool]
+opt-level = "z"
+[profile.release.package.precomputed-hash]
+opt-level = "z"
+[profile.release.package.pulldown-cmark-escape]
+opt-level = "z"
+[profile.release.package.rawpointer]
+opt-level = "z"
+[profile.release.package.roughr-merman]
+opt-level = "z"
+[profile.release.package.ryu-js]
+opt-level = "z"
+[profile.release.package.safe_arch]
+opt-level = "z"
+[profile.release.package.selectors]
+opt-level = "z"
+[profile.release.package.servo_arc]
+opt-level = "z"
+[profile.release.package.simba]
+opt-level = "z"
+[profile.release.package.unicode-vo]
+opt-level = "z"
+[profile.release.package.web-time]
+opt-level = "z"
+[profile.release.package.wide]
+opt-level = "z"
+
[profile.dev]
debug = 0
# https://jakedeichert.com/blog/reducing-rust-incremental-compilation-times-on-macos-by-70-percent/
@@ -232,6 +309,11 @@ reqwest = "0.12"
rustybuzz = "0.20"
resize = "0.5"
resvg = { version = "0.45.1", default-features = false }
+# Mermaid diagrams in Markdown, parsed and laid out in Rust and drawn to
+# SVG; resvg rasterizes them.
+merman = { version = "0.7.0", default-features = false, features = ["render"] }
+merman-render = { version = "0.7.0", default-features = false }
+ttf-parser = "0.25"
rstest = "0.21"
ruzstd = "0.8"
rusqlite = "0.32"
diff --git a/env-bootstrap/src/lib.rs b/env-bootstrap/src/lib.rs
index 597e2642..9cbfe136 100644
--- a/env-bootstrap/src/lib.rs
+++ b/env-bootstrap/src/lib.rs
@@ -165,9 +165,36 @@ pub fn set_lang_from_locale() {
}
}
+thread_local! {
+ static QUIET_PANICS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// Run `f` with this thread's panics kept out of the log and off the screen.
+/// For code the caller already guards with `catch_unwind` because what it is
+/// fed can break it (a parser reading a note): the message may quote that
+/// input, so the caller notes the failure itself, without it.
+pub fn with_quiet_panics<R>(f: impl FnOnce() -> R) -> R {
+ struct Restore(bool);
+ impl Drop for Restore {
+ fn drop(&mut self) {
+ QUIET_PANICS.with(|quiet| quiet.set(self.0));
+ }
+ }
+ let _restore = Restore(QUIET_PANICS.with(|quiet| quiet.replace(true)));
+ f()
+}
+
+/// Whether a panic on this thread happens inside `with_quiet_panics`.
+pub fn panics_are_quiet() -> bool {
+ QUIET_PANICS.with(|quiet| quiet.get())
+}
+
fn register_panic_hook() {
let default_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
+ if panics_are_quiet() {
+ return;
+ }
let payload = info.payload();
// panic! with a format string produces a String payload, not &str;
// handle both or e.g. wgpu validation errors log as "!?"
diff --git a/env-bootstrap/src/ringlog.rs b/env-bootstrap/src/ringlog.rs
index 9905fde7..0a772e35 100644
--- a/env-bootstrap/src/ringlog.rs
+++ b/env-bootstrap/src/ringlog.rs
@@ -285,6 +285,10 @@ fn setup_pretty() -> (LevelFilter, Logger) {
("gfx_backend_metal", LevelFilter::Error),
("tracing", LevelFilter::Error),
("zbus", LevelFilter::Error),
+ // Their warnings quote the SVG they read, and a Note's Mermaid diagram
+ // is drawn through them: the note's text must not reach the log.
+ ("usvg", LevelFilter::Off),
+ ("resvg", LevelFilter::Off),
] {
filters.filter_module(module, level);
}
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftl
index e2c094b9..b4f4f4d1 100644
--- a/thinkterm-i18n/i18n/de-DE.ftl
+++ b/thinkterm-i18n/i18n/de-DE.ftl
@@ -377,6 +377,9 @@ project-root-open-settings = Systemeinstellungen öffnen
project-root-server-refused = Die Ablehnung kam vom Sitzungsserver von ThinkTerm (thinkterm-mux-server), der den Zugriff unter eigenem Namen anfordert: Erlauben Sie ihn, wenn macOS fragt, oder schalten Sie ihn in den Systemeinstellungen unter „Dateien und Ordner“ ein.
project-root-other-folder = Das ist ein anderer Ordner. Das Projekt zeigt weiterhin auf den oben genannten, und dessen Zugriff hat sich nicht geändert.
right-notes-note-unreadable = Diese Notiz lässt sich nicht öffnen
+right-notes-mermaid-diagram = Mermaid-Diagramm
+right-notes-mermaid-unreadable = Nicht lesbar
+right-notes-mermaid-too-large = Zu groß zum Zeichnen
right-choose-existing-vault = Vorhandenen Vault auswählen…
right-create-new-vault = Neuen Vault erstellen…
right-laying-out-note = Notiz wird gesetzt…
diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftl
index e97a92e1..7514eded 100644
--- a/thinkterm-i18n/i18n/en-US.ftl
+++ b/thinkterm-i18n/i18n/en-US.ftl
@@ -377,6 +377,9 @@ project-root-open-settings = Open System Settings
project-root-server-refused = The refusal came from ThinkTerm's session server (thinkterm-mux-server), which asks for access under its own name: allow it when macOS asks, or switch it on under Files and Folders in System Settings.
project-root-other-folder = That is a different folder. The Project still points at the one above, and its access has not changed.
right-notes-note-unreadable = This note can't be opened
+right-notes-mermaid-diagram = Mermaid diagram
+right-notes-mermaid-unreadable = Can’t be read
+right-notes-mermaid-too-large = Too large to draw
right-choose-existing-vault = Choose Existing Vault…
right-create-new-vault = Create New Vault…
right-laying-out-note = Laying out note…
diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftl
index 9c82b02d..59807ef5 100644
--- a/thinkterm-i18n/i18n/fr-FR.ftl
+++ b/thinkterm-i18n/i18n/fr-FR.ftl
@@ -377,6 +377,9 @@ project-root-open-settings = Ouvrir Réglages Système
project-root-server-refused = Le refus vient du serveur de sessions de ThinkTerm (thinkterm-mux-server), qui demande l'accès en son propre nom : autorisez-le quand macOS le demande, ou activez-le dans Réglages Système › Fichiers et dossiers.
project-root-other-folder = Il s’agit d’un autre dossier. Le projet pointe toujours vers celui ci-dessus et son accès n’a pas changé.
right-notes-note-unreadable = Cette note ne peut pas être ouverte
+right-notes-mermaid-diagram = Diagramme Mermaid
+right-notes-mermaid-unreadable = Illisible
+right-notes-mermaid-too-large = Trop grand pour être dessiné
right-choose-existing-vault = Choisir un coffre existant…
right-create-new-vault = Créer un nouveau coffre…
right-laying-out-note = Mise en page de la note…
diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftl
index 5ed2d3e5..d2088f42 100644
--- a/thinkterm-i18n/i18n/ja-JP.ftl
+++ b/thinkterm-i18n/i18n/ja-JP.ftl
@@ -368,6 +368,9 @@ project-root-open-settings = システム設定を開く
project-root-server-refused = 拒否されたのは ThinkTerm のセッションサーバ(thinkterm-mux-server)です。自身の名前でアクセスを求めるため、macOS が確認したら許可するか、システム設定の「ファイルとフォルダ」で有効にしてください。
project-root-other-folder = それは別のフォルダです。プロジェクトは上記のフォルダを指したままで、そのアクセス権は変わっていません。
right-notes-note-unreadable = このノートは開けません
+right-notes-mermaid-diagram = Mermaid 図
+right-notes-mermaid-unreadable = 読み込めません
+right-notes-mermaid-too-large = 大きすぎて描画できません
right-choose-existing-vault = 既存の保管庫を選択…
right-create-new-vault = 新しい保管庫を作成…
right-laying-out-note = ノートをレイアウト中…
diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftl
index c779bca3..afd732c5 100644
--- a/thinkterm-i18n/i18n/zh-CN.ftl
+++ b/thinkterm-i18n/i18n/zh-CN.ftl
@@ -368,6 +368,9 @@ project-root-open-settings = 打开系统设置
project-root-server-refused = 被拒绝的是 ThinkTerm 的会话服务(thinkterm-mux-server),它以自己的名义申请权限:在 macOS 询问时点允许,或在系统设置的"文件和文件夹"中为它打开开关。
project-root-other-folder = 那是另一个文件夹。Project 仍然指向上面这个,它的访问权限没有变化。
right-notes-note-unreadable = 这篇笔记无法打开
+right-notes-mermaid-diagram = Mermaid 图表
+right-notes-mermaid-unreadable = 无法读取
+right-notes-mermaid-too-large = 太大,无法绘制
right-choose-existing-vault = 选择现有库…
right-create-new-vault = 新建库…
right-laying-out-note = 正在排版笔记…
diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.toml
index b081e9ad..3fb55e72 100644
--- a/wezterm-gui/Cargo.toml
+++ b/wezterm-gui/Cargo.toml
@@ -93,7 +93,12 @@ ratelim.workspace = true
rayon.workspace = true
regex.workspace = true
reqwest = { workspace = true, features = ["blocking"] }
-resvg.workspace = true
+# Text, for the labels in Mermaid diagrams.
+resvg = { workspace = true, features = ["text", "system-fonts", "memmap-fonts"] }
+merman.workspace = true
+lru.workspace = true
+merman-render.workspace = true
+ttf-parser.workspace = true
semver.workspace = true
serde = {workspace=true, features = ["rc", "derive"]}
serde_json.workspace = true
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 6c998adb..889d8f11 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -1474,6 +1474,9 @@ fn fatal_toast_notification(title: &str, message: &str) {
fn notify_on_panic() {
let default_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
+ if env_bootstrap::panics_are_quiet() {
+ return;
+ }
if let Some(s) = info.payload().downcast_ref::<&str>() {
fatal_toast_notification("Wezterm panic", s);
}
diff --git a/wezterm-gui/src/markdown_editor/host.rs b/wezterm-gui/src/markdown_editor/host.rs
index eda6691e..8ae16b08 100644
--- a/wezterm-gui/src/markdown_editor/host.rs
+++ b/wezterm-gui/src/markdown_editor/host.rs
@@ -86,6 +86,11 @@ pub(crate) struct NoteHostState {
pub wrap_cache: VisualWrapCache,
pub projection_revision: Option<u64>,
pub visual_key: Option<(u64, super::EditorMode, usize)>,
+ /// The Mermaid verdicts `visual` was laid out with: when a diagram that
+ /// parsed turns out not to draw, the layout is rebuilt to show its code.
+ diagram_epoch: u64,
+ /// The verdicts the background parse in flight lays out with.
+ parse_diagram_epoch: u64,
wrapped_key: Option<(u64, super::EditorMode, usize, usize)>,
pub line_layouts: Vec<NoteLineLayout>,
pub line_geometry_key: Option<u64>,
@@ -181,6 +186,8 @@ impl Default for NoteHostState {
wrap_cache: VisualWrapCache::default(),
projection_revision: None,
visual_key: None,
+ diagram_epoch: 0,
+ parse_diagram_epoch: 0,
wrapped_key: None,
line_layouts: vec![],
line_geometry_key: None,
@@ -294,12 +301,15 @@ impl NoteHostState {
// Deliberately uncached: this is a partial seed projection that the
// full background parse replaces.
self.reveal_key_cache = None;
- let active_start = self.projection.caret_reveal_start(0);
+ // The caret the full parse will use, so a read-only preview reveals
+ // nothing here either (a diagram first on the page stays a diagram).
+ let caret = self.reveal_caret();
+ let active_start = self.projection.caret_reveal_start(caret);
self.visual = Arc::new(build_visual_document(
source,
&self.projection,
self.view.mode,
- 0,
+ caret,
));
// Record the FULL document size (the gate metrics must not lie about
// what the display represents), but keep the seed itself on the
@@ -503,6 +513,18 @@ impl NoteHostState {
}
self.visual_key = None;
}
+ let diagram_epoch = super::mermaid::verdict_epoch();
+ if self.diagram_epoch != diagram_epoch {
+ self.diagram_epoch = diagram_epoch;
+ if source.len() > BACKGROUND_PARSE_THRESHOLD_BYTES {
+ // Laid out again off the UI thread, as a long note always is;
+ // the current layout shows until then.
+ self.projection_revision = None;
+ self.parse_requested_revision = Some(revision);
+ return;
+ }
+ self.visual_key = None;
+ }
let caret = self.reveal_caret();
let active_start = match self.reveal_key_cache {
Some((cached_revision, cached_caret, result))
@@ -568,6 +590,7 @@ impl NoteHostState {
return None;
}
self.parse_in_flight_revision = Some(snapshot.revision);
+ self.parse_diagram_epoch = super::mermaid::verdict_epoch();
let document = self
.document
.as_ref()
@@ -611,6 +634,9 @@ impl NoteHostState {
// more was asked for after it started.
self.links_resolution_pending = std::mem::take(&mut self.links_requested_during_parse);
self.visual = Arc::new(visual);
+ // Laid out with the verdicts of when it was asked for: any change
+ // since shows at the next refresh.
+ self.diagram_epoch = self.parse_diagram_epoch;
self.refresh_wrap_work_metrics(display_source_len);
self.projection_revision = Some(revision);
self.visual_key = Some((revision, mode, active_start));
@@ -1192,6 +1218,34 @@ mod state_tests {
host
}
+ #[test]
+ fn a_diagram_found_not_to_draw_is_laid_out_again_as_code() {
+ // Parses, but relates to a requirement nobody defined.
+ let source = "Intro\n\n```mermaid\nrequirementDiagram\n requirement two {\n id: 2\n text: t\n risk: low\n verifymethod: test\n }\n two - satisfies -> elsewhere\n```\n";
+ let mut host = host_with_source(source);
+ let diagram = |host: &NoteHostState| {
+ host.visual
+ .lines
+ .iter()
+ .any(|line| line.kind == crate::markdown_editor::surface::VisualLineKind::Image)
+ };
+ assert!(diagram(&host));
+ let code = source
+ .split("```mermaid\n")
+ .nth(1)
+ .unwrap()
+ .trim_end_matches("```\n");
+ let room = super::super::mermaid::DiagramBox {
+ width: 800.0,
+ height: 800.0,
+ scale: 1.0,
+ };
+ let style = super::super::mermaid::DiagramStyle { dark: false };
+ assert!(super::super::mermaid::render(code, style, room).is_err());
+ host.refresh_projection();
+ assert!(!diagram(&host));
+ }
+
#[test]
fn large_document_seeds_first_screen_before_full_background_parse() {
let paragraph = "First-screen text with **formatting** and enough words to wrap.\n\n";
diff --git a/wezterm-gui/src/markdown_editor/mermaid.rs b/wezterm-gui/src/markdown_editor/mermaid.rs
new file mode 100644
index 00000000..c3779237
--- /dev/null
+++ b/wezterm-gui/src/markdown_editor/mermaid.rs
@@ -0,0 +1,937 @@
+//! Mermaid diagrams in Markdown: a fenced block whose language is `mermaid`
+//! is drawn as its diagram rather than as code. merman parses Mermaid and
+//! lays it out in Rust, down to an SVG; resvg rasterizes that.
+//!
+//! Drawing runs off the UI thread and one diagram at a time, so a note full
+//! of diagrams costs one diagram's working memory at once. A diagram is drawn
+//! at the size it is shown, not larger, since its pixels end up in the shared
+//! glyph atlas, which does not shrink. What is kept is a PNG, which the note's
+//! image cache holds and counts like any other image; the SVG and its parsed
+//! tree are dropped as soon as the pixels exist.
+//!
+//! A diagram is the note's text, so it is treated as untrusted: pictures it
+//! names are never loaded, one too big to lay out quickly is not drawn, and a
+//! panic inside merman makes a block that cannot be read rather than a lost
+//! window.
+
+use anyhow::{anyhow, Context, Result};
+use merman::render::{
+ HeadlessRenderer, HostThemeAppearance, HostThemeOutput, HostThemeProfile, HostThemeRoles,
+};
+use merman_render::text::{
+ DeterministicTextMeasurer, TextMeasurer, TextMetrics, TextStyle, WrapMode,
+};
+use resvg::{tiny_skia, usvg};
+use std::collections::HashMap;
+use std::hash::{DefaultHasher, Hash, Hasher};
+use std::num::NonZeroUsize;
+use std::panic::AssertUnwindSafe;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, TryLockError};
+
+/// The longest side a diagram is rasterized with, in pixels, whatever room
+/// it is shown in: half the glyph atlas's usual 2048, which text shares.
+const MAX_RASTER_SIDE: f32 = 1024.0;
+/// The most pixels one diagram is rasterized with (2.4 MB once decoded), so a
+/// few on screen at once still leave the glyph atlas room for text.
+const MAX_RASTER_PIXELS: f32 = 600_000.0;
+/// The longest Mermaid block drawn; a longer one stays code. It is parsed on
+/// the UI thread when a note is laid out, which at this length takes up to
+/// about 8 ms.
+const MAX_SOURCE_BYTES: usize = 16 * 1024;
+/// The most links one diagram is drawn with. Laying a graph out costs more
+/// the more its links cross: 150 among 50 boxes take about 0.4 s, 300 among
+/// 100 over 5 s, and nothing can stop merman once it has started.
+const MAX_LINKS: usize = 150;
+/// How many label advances the fallback measurer remembers before it starts
+/// over.
+const MAX_REMEMBERED_ADVANCES: usize = 4096;
+/// The largest font file the fallback measurer keeps in memory; a larger one
+/// is read again for each character it has not measured yet.
+const MAX_KEPT_FONT_BYTES: usize = 2 * 1024 * 1024;
+/// The size Mermaid sets labels in, in points; a diagram is scaled from it to
+/// the size of the text around it.
+pub(crate) const LABEL_SIZE: f32 = 16.0;
+/// How many verdicts are remembered.
+const VERDICT_CAPACITY: usize = 256;
+
+/// Mermaid's own font stack, whose metrics merman ships, spelled as the fonts
+/// name themselves: faces are found by exact name.
+const MERMAID_FONT_FAMILY: &str = "\"Trebuchet MS\", Verdana, Arial, sans-serif";
+/// Where Trebuchet MS is missing (most Linux systems), the first of these
+/// that is installed draws the labels, and is also what they are measured
+/// with, so boxes fit what is drawn.
+const FALLBACK_FAMILIES: &[&str] = &[
+ "Liberation Sans",
+ "Arimo",
+ "DejaVu Sans",
+ "Noto Sans",
+ "Ubuntu",
+ "Cantarell",
+ "FreeSans",
+];
+
+pub(crate) fn is_mermaid(language: Option<&str>) -> bool {
+ language.is_some_and(|language| language.eq_ignore_ascii_case("mermaid"))
+}
+
+pub(crate) fn content_hash(text: &str) -> u64 {
+ let mut hasher = DefaultHasher::new();
+ text.hash(&mut hasher);
+ hasher.finish()
+}
+
+/// What is known of a Mermaid block.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Verdict {
+ Draws,
+ /// merman cannot read it, or cannot draw what it read.
+ Unreadable,
+ /// Too long, or with too many links, to lay out quickly.
+ TooLarge,
+}
+
+static VERDICTS: Mutex<Option<lru::LruCache<u64, Verdict>>> = Mutex::new(None);
+/// Moves on each time a diagram that parsed turns out not to draw.
+static VERDICT_EPOCH: AtomicU64 = AtomicU64::new(0);
+
+fn remembered_verdict(key: u64) -> Option<Verdict> {
+ VERDICTS
+ .lock()
+ .unwrap_or_else(|err| err.into_inner())
+ .as_mut()
+ .and_then(|verdicts| verdicts.get(&key).copied())
+}
+
+fn remember_verdict(key: u64, verdict: Verdict) {
+ VERDICTS
+ .lock()
+ .unwrap_or_else(|err| err.into_inner())
+ .get_or_insert_with(|| {
+ lru::LruCache::new(NonZeroUsize::new(VERDICT_CAPACITY).expect("not zero"))
+ })
+ .put(key, verdict);
+}
+
+/// How many links a parsed diagram has: its longest list of edges, relations
+/// or relationships, whichever the diagram keeps them in.
+fn links(model: &serde_json::Value) -> usize {
+ ["edges", "relations", "relationships"]
+ .iter()
+ .filter_map(|key| model.get(key)?.as_array().map(Vec::len))
+ .max()
+ .unwrap_or(0)
+}
+
+/// What merman makes of `source`, without laying it out.
+fn judge(source: &str, engine: &merman::Engine) -> Verdict {
+ if source.len() > MAX_SOURCE_BYTES {
+ return Verdict::TooLarge;
+ }
+ guarded(source, || {
+ match engine.parse_diagram_sync(source, merman::ParseOptions::default()) {
+ Ok(Some(parsed)) if links(&parsed.model) > MAX_LINKS => Verdict::TooLarge,
+ Ok(Some(_)) => Verdict::Draws,
+ _ => Verdict::Unreadable,
+ }
+ })
+ .unwrap_or(Verdict::Unreadable)
+}
+
+/// Whether `source` is a Mermaid diagram to draw. Asked each time a note's
+/// layout is rebuilt, so verdicts are remembered by content; parsing alone is
+/// cheap next to drawing.
+pub(crate) fn draws(source: &str) -> bool {
+ if source.len() > MAX_SOURCE_BYTES {
+ return false;
+ }
+ let key = content_hash(source);
+ let verdict = remembered_verdict(key).unwrap_or_else(|| {
+ let verdict = judge(source, &merman::Engine::new());
+ remember_verdict(key, verdict);
+ verdict
+ });
+ verdict == Verdict::Draws
+}
+
+/// What stops `source` from drawing, if that is already known. Never parses,
+/// so it costs nothing to ask on every edit.
+pub(crate) fn known_problem(source: &str) -> Option<Verdict> {
+ if source.len() > MAX_SOURCE_BYTES {
+ return Some(Verdict::TooLarge);
+ }
+ remembered_verdict(content_hash(source)).filter(|verdict| *verdict != Verdict::Draws)
+}
+
+/// `f`, run on a diagram's `source`, or `None` if merman panicked. Some text
+/// does make it panic (an ER diagram with CJK attribute types, in 0.7), and
+/// the message would quote the note, so the log only learns that it happened.
+fn guarded<R>(source: &str, f: impl FnOnce() -> R) -> Option<R> {
+ let result = env_bootstrap::with_quiet_panics(|| std::panic::catch_unwind(AssertUnwindSafe(f)));
+ if result.is_err() {
+ log::warn!(
+ "merman panicked on a Mermaid diagram ({} bytes)",
+ source.len()
+ );
+ }
+ result.ok()
+}
+
+/// Where the verdicts stand; a note's layout is rebuilt when this moves.
+pub(crate) fn verdict_epoch() -> u64 {
+ VERDICT_EPOCH.load(Ordering::Relaxed)
+}
+
+/// Let go of the font index, the one large thing drawing keeps between
+/// diagrams, when a note's memory is released; the next diagram finds it
+/// again. Verdicts stay: they are few and small, and one saying a diagram
+/// does not draw is what keeps it shown as code in every window. Fonts being
+/// found for a diagram right now are left to the next release, not waited on.
+pub(crate) fn release() {
+ match FONTS.try_lock() {
+ Ok(mut fonts) => {
+ fonts.take();
+ }
+ Err(TryLockError::Poisoned(fonts)) => {
+ fonts.into_inner().take();
+ }
+ Err(TryLockError::WouldBlock) => {}
+ }
+}
+
+/// The fonts diagrams are drawn with. Only the faces' names and locations are
+/// indexed; font files are mapped, and read as glyphs are used.
+struct Fonts {
+ db: Arc<usvg::fontdb::Database>,
+ /// The family labels are drawn in, as the installed fonts spell it.
+ family: String,
+ /// `None` when Mermaid's own font is installed and merman's metrics for it
+ /// apply; otherwise the family drawn with and a measurer for it.
+ fallback: Option<(String, Arc<FontMeasurer>)>,
+}
+
+static FONTS: Mutex<Option<Arc<Fonts>>> = Mutex::new(None);
+
+/// The fonts, found on first use and kept until `release`.
+fn fonts() -> Arc<Fonts> {
+ let mut fonts = FONTS.lock().unwrap_or_else(|err| err.into_inner());
+ Arc::clone(fonts.get_or_insert_with(|| Arc::new(Fonts::load())))
+}
+
+impl Fonts {
+ fn load() -> Self {
+ let mut db = usvg::fontdb::Database::new();
+ db.load_system_fonts();
+ // A family as the installed fonts spell it, since that is how usvg
+ // looks faces up.
+ let installed = |family: &str| {
+ db.faces().find_map(|face| {
+ face.families
+ .iter()
+ .find(|(name, _)| name.eq_ignore_ascii_case(family))
+ .map(|(name, _)| name.clone())
+ })
+ };
+ let trebuchet = installed("Trebuchet MS");
+ let family = match &trebuchet {
+ Some(trebuchet) => trebuchet.clone(),
+ None => FALLBACK_FAMILIES
+ .iter()
+ .find_map(|family| installed(family))
+ .or_else(|| {
+ db.faces()
+ .find_map(|face| face.families.first().map(|(name, _)| name.clone()))
+ })
+ .unwrap_or_else(|| "sans-serif".to_string()),
+ };
+ // What the diagram's font stack ends in, too.
+ db.set_sans_serif_family(family.clone());
+ let db = Arc::new(db);
+ let fallback = trebuchet.is_none().then(|| {
+ let measurer = Arc::new(FontMeasurer::new(&db, &family));
+ (family.clone(), measurer)
+ });
+ Fonts {
+ db,
+ family,
+ fallback,
+ }
+ }
+}
+
+/// Which look a diagram is drawn in; part of what its cached image is keyed
+/// by.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub(crate) struct DiagramStyle {
+ pub dark: bool,
+}
+
+fn theme(style: DiagramStyle, font_family: &str) -> HostThemeProfile {
+ // A clear canvas: the diagram is drawn on whatever the note shows (left
+ // unset, Mermaid's default paints the root white).
+ let canvas = Some("transparent".to_string());
+ let text = if style.dark { "#e3e5e8" } else { "#1f2328" };
+ let cluster = if style.dark { "#2f3238" } else { "#eef0f3" };
+ let surface = if style.dark { "#2b2d31" } else { "#f3f4f6" };
+ let roles = if style.dark {
+ HostThemeRoles {
+ canvas,
+ surface: Some(surface.into()),
+ surface_alt: Some("#33363d".into()),
+ text: Some(text.into()),
+ subtle_text: Some("#a6abb3".into()),
+ border: Some("#5c616b".into()),
+ line: Some("#9aa0a8".into()),
+ edge_label_background: Some("#26282c".into()),
+ cluster_background: Some(cluster.into()),
+ cluster_border: Some("#565b64".into()),
+ note_background: Some("#3a3325".into()),
+ note_border: Some("#b8954f".into()),
+ note_text: Some("#f0e4c8".into()),
+ ..HostThemeRoles::default()
+ }
+ } else {
+ HostThemeRoles {
+ canvas,
+ surface: Some(surface.into()),
+ surface_alt: Some("#e8eaee".into()),
+ text: Some(text.into()),
+ subtle_text: Some("#57606a".into()),
+ border: Some("#9ca3af".into()),
+ line: Some("#4b5563".into()),
+ edge_label_background: Some("#ffffff".into()),
+ cluster_background: Some(cluster.into()),
+ cluster_border: Some("#b6bcc6".into()),
+ note_background: Some("#fff6d5".into()),
+ note_border: Some("#d4b35a".into()),
+ note_text: Some("#3b2f0b".into()),
+ ..HostThemeRoles::default()
+ }
+ };
+ // Series colours carry white labels in pies, timelines and kanban
+ // columns, so both looks use ones dark enough for that; twelve, as many as
+ // Mermaid has, so no column falls back to its grey.
+ HostThemeProfile::builder()
+ .appearance(if style.dark {
+ HostThemeAppearance::Dark
+ } else {
+ HostThemeAppearance::Light
+ })
+ .font_family(font_family)
+ .roles(roles)
+ .series_palette([
+ "#3b82f6", "#10b981", "#d97706", "#db2777", "#7c3aed", "#0891b2", "#4f46e5", "#059669",
+ "#b45309", "#be185d", "#6d28d9", "#0e7490",
+ ])
+ // Titles and Venn labels read these, not the text role, and are
+ // otherwise near-black even in the dark look.
+ .theme_variable("titleColor", text)
+ .theme_variable("vennTitleTextColor", text)
+ .theme_variable("vennSetTextColor", text)
+ // A state holding others is drawn as a group is, not in Mermaid's
+ // pale default, and named in the text colour, not near-black.
+ .theme_variable("compositeBackground", cluster)
+ .theme_variable("altBackground", cluster)
+ .theme_variable("compositeTitleBackground", surface)
+ .theme_variable("stateLabelColor", text)
+ .site_config("themeCSS", fixed_text_css(style, text))
+ .site_config("c4", c4_colors())
+ .output(HostThemeOutput::resvg_safe_editor())
+ .build()
+}
+
+/// Rules for text merman colours in ways no theme variable reaches.
+/// Event-modeling lane names are styled with `color`, which SVG text does not
+/// use, so without a fill they are black. C4 boundary names and relation
+/// labels are fixed at #444444, unreadable on the dark look's ground.
+fn fixed_text_css(style: DiagramStyle, text: &str) -> String {
+ let mut css = format!(".em-swimlane text{{fill:{text};}}");
+ if style.dark {
+ css.push_str(&format!("text[fill=\"#444444\"]{{fill:{text};}}"));
+ }
+ css
+}
+
+/// C4 shapes' colours, in both looks. merman always letters them in white,
+/// so they keep dark fills: shades of blue, grey for what is external. Left
+/// to the host roles they would take the light look's pale surface, and their
+/// text would vanish.
+fn c4_colors() -> serde_json::Value {
+ let mut colors = serde_json::Map::new();
+ for (kind, fill) in [
+ ("person", "#0b3d91"),
+ ("system", "#1d4ed8"),
+ ("container", "#2563eb"),
+ ("component", "#2f6fdb"),
+ ] {
+ for shape in ["", "_db", "_queue"] {
+ if kind == "person" && !shape.is_empty() {
+ continue;
+ }
+ for (prefix, fill) in [
+ (format!("{kind}{shape}"), fill),
+ (format!("external_{kind}{shape}"), "#5b6470"),
+ ] {
+ colors.insert(format!("{prefix}_bg_color"), fill.into());
+ colors.insert(format!("{prefix}_border_color"), fill.into());
+ }
+ }
+ }
+ serde_json::Value::Object(colors)
+}
+
+/// The room a diagram is shown in, in pixels, and the pixels one of its
+/// points takes, which sets how big its labels are.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct DiagramBox {
+ pub width: f32,
+ pub height: f32,
+ pub scale: f32,
+}
+
+/// A drawn diagram, PNG-encoded, and its size in pixels. `natural` is its own
+/// size in points, which gives its size in any other box without drawing it.
+pub(crate) struct RenderedDiagram {
+ pub png: Vec<u8>,
+ pub width: u32,
+ pub height: u32,
+ pub natural: (f32, f32),
+}
+
+/// The scale a diagram of `natural` size is drawn at in `room`: the room's,
+/// lowered until the diagram fits the room and the limits above. Never
+/// raised: a small diagram stays its own size.
+fn raster_scale(natural: (f32, f32), room: DiagramBox) -> f32 {
+ let (width, height) = natural;
+ let mut scale = room.scale.max(0.1);
+ if width > 0.0 {
+ scale = scale.min(room.width.clamp(1.0, MAX_RASTER_SIDE) / width);
+ }
+ if height > 0.0 {
+ scale = scale.min(room.height.clamp(1.0, MAX_RASTER_SIDE) / height);
+ }
+ let area = width * height;
+ if area > 0.0 {
+ scale = scale.min((MAX_RASTER_PIXELS / area).sqrt());
+ }
+ scale
+}
+
+/// The pixels a diagram of `natural` size is drawn with in `room`.
+pub(crate) fn raster_size(natural: (f32, f32), room: DiagramBox) -> (u32, u32) {
+ let scale = raster_scale(natural, room);
+ (
+ (natural.0 * scale).round().max(1.0) as u32,
+ (natural.1 * scale).round().max(1.0) as u32,
+ )
+}
+
+/// Whether a diagram drawn `drawn` pixels wide is drawn again to be `wanted`
+/// wide. Small differences are left to scaling, so dragging a pane edge
+/// redraws it now and then rather than on every step.
+pub(crate) fn needs_redraw(drawn: u32, wanted: u32) -> bool {
+ let (drawn, wanted) = (drawn as f32, wanted as f32);
+ (drawn - wanted).abs() > (wanted / 16.0).max(8.0)
+}
+
+/// `source` as SVG, themed and measured for the fonts it will be drawn with.
+fn render_svg(source: &str, style: DiagramStyle, fonts: &Fonts) -> Result<String> {
+ let family = fonts
+ .fallback
+ .as_ref()
+ .map(|(family, _)| format!("\"{family}\", sans-serif"))
+ .unwrap_or_else(|| MERMAID_FONT_FAMILY.to_string());
+ let renderer = HeadlessRenderer::new()
+ .with_host_theme(&theme(style, &family))
+ .with_diagram_id("note-diagram");
+ let renderer = match &fonts.fallback {
+ Some((_, measurer)) => renderer.with_text_measurer(measurer.clone()),
+ None => renderer.with_vendored_text_measurer(),
+ };
+ renderer
+ .render_svg_sync(source)
+ .map_err(|err| anyhow!("{err}"))?
+ .ok_or_else(|| anyhow!("no Mermaid diagram found"))
+}
+
+/// Draw `source` to fit `room`. Blocking and CPU-bound: call it off the UI
+/// thread. Diagrams are drawn one at a time. One that does not draw is
+/// remembered so, and shows as code from then on.
+pub(crate) fn render(
+ source: &str,
+ style: DiagramStyle,
+ room: DiagramBox,
+) -> Result<RenderedDiagram> {
+ static ONE_AT_A_TIME: Mutex<()> = Mutex::new(());
+ let _turn = ONE_AT_A_TIME.lock().unwrap_or_else(|err| err.into_inner());
+
+ // Judged again rather than trusted: the verdict it was asked for on may
+ // have been forgotten since.
+ let judged = judge(source, &merman::Engine::new());
+ let drawn = match judged {
+ Verdict::Draws => guarded(source, || draw(source, style, room))
+ .unwrap_or_else(|| Err(anyhow!("drawing the diagram panicked"))),
+ Verdict::TooLarge => Err(anyhow!("the diagram is too large to draw")),
+ Verdict::Unreadable => Err(anyhow!("the diagram cannot be read")),
+ };
+ if drawn.is_err() {
+ let verdict = match judged {
+ Verdict::TooLarge => Verdict::TooLarge,
+ _ => Verdict::Unreadable,
+ };
+ remember_verdict(content_hash(source), verdict);
+ VERDICT_EPOCH.fetch_add(1, Ordering::Relaxed);
+ }
+ drawn
+}
+
+/// What usvg reads the diagram's SVG with: the system fonts, and no pictures
+/// at all. usvg would otherwise load any path a diagram names, and a device
+/// such as /dev/zero never ends.
+fn svg_options(fontdb: Arc<usvg::fontdb::Database>, family: &str) -> usvg::Options<'static> {
+ usvg::Options {
+ fontdb,
+ // For text that names no font (some diagrams' does not): the labels'
+ // own family, not usvg's Times New Roman.
+ font_family: family.to_string(),
+ image_href_resolver: usvg::ImageHrefResolver {
+ resolve_data: Box::new(|_, _, _| None),
+ resolve_string: Box::new(|_, _| None),
+ },
+ ..usvg::Options::default()
+ }
+}
+
+fn draw(source: &str, style: DiagramStyle, room: DiagramBox) -> Result<RenderedDiagram> {
+ let fonts = fonts();
+ let svg = render_svg(source, style, &fonts)?;
+ let options = svg_options(Arc::clone(&fonts.db), &fonts.family);
+ let tree = usvg::Tree::from_str(&svg, &options).context("read the diagram's SVG")?;
+ drop(svg);
+ let natural = (tree.size().width(), tree.size().height());
+ let scale = raster_scale(natural, room);
+ let (width, height) = raster_size(natural, room);
+ let mut pixmap =
+ tiny_skia::Pixmap::new(width, height).context("allocate the diagram's pixels")?;
+ resvg::render(
+ &tree,
+ tiny_skia::Transform::from_scale(scale, scale),
+ &mut pixmap.as_mut(),
+ );
+ drop(tree);
+ let png = pixmap.encode_png().context("encode the diagram")?;
+ Ok(RenderedDiagram {
+ png,
+ width,
+ height,
+ natural,
+ })
+}
+
+/// Measures labels with the font they are drawn in, where Mermaid's own font
+/// (whose metrics merman ships) is missing. Advances come straight from the
+/// font, remembered per character; a character the font lacks is drawn from a
+/// fallback font, and is counted as a full em when it is a wide (CJK)
+/// character, as most such fonts draw it, else as a typical Latin advance.
+struct FontMeasurer {
+ regular: Option<Face>,
+ bold: Option<Face>,
+ advances: Mutex<HashMap<(char, bool), f64>>,
+}
+
+/// One face of the measured family.
+enum Face {
+ /// Its font file, read once: small, and otherwise mapped and parsed again
+ /// for every character not yet measured.
+ Kept { data: Vec<u8>, index: u32 },
+ /// Too large to keep; read from the index each time.
+ Indexed {
+ db: Arc<usvg::fontdb::Database>,
+ id: usvg::fontdb::ID,
+ },
+}
+
+impl Face {
+ fn advance_em(&self, ch: char) -> Option<f64> {
+ let advance = |data: &[u8], index: u32| {
+ let font = ttf_parser::Face::parse(data, index).ok()?;
+ let glyph = font.glyph_index(ch)?;
+ let advance = font.glyph_hor_advance(glyph)?;
+ Some(advance as f64 / font.units_per_em().max(1) as f64)
+ };
+ match self {
+ Face::Kept { data, index } => advance(data, *index),
+ Face::Indexed { db, id } => db.with_face_data(*id, advance).flatten(),
+ }
+ }
+}
+
+impl FontMeasurer {
+ fn new(db: &Arc<usvg::fontdb::Database>, family: &str) -> Self {
+ let face = |weight: usvg::fontdb::Weight| {
+ let id = db.query(&usvg::fontdb::Query {
+ families: &[usvg::fontdb::Family::Name(family)],
+ weight,
+ ..usvg::fontdb::Query::default()
+ })?;
+ let kept = db.with_face_data(id, |data, index| {
+ (data.len() <= MAX_KEPT_FONT_BYTES).then(|| Face::Kept {
+ data: data.to_vec(),
+ index,
+ })
+ })?;
+ Some(kept.unwrap_or_else(|| Face::Indexed {
+ db: Arc::clone(db),
+ id,
+ }))
+ };
+ Self {
+ regular: face(usvg::fontdb::Weight::NORMAL),
+ bold: face(usvg::fontdb::Weight::BOLD),
+ advances: Mutex::new(HashMap::new()),
+ }
+ }
+
+ /// `ch`'s advance in ems.
+ fn advance_em(&self, ch: char, bold: bool) -> f64 {
+ if let Some(em) = self
+ .advances
+ .lock()
+ .unwrap_or_else(|err| err.into_inner())
+ .get(&(ch, bold))
+ {
+ return *em;
+ }
+ let face = if bold {
+ self.bold.as_ref().or(self.regular.as_ref())
+ } else {
+ self.regular.as_ref()
+ };
+ let em = face
+ .and_then(|face| face.advance_em(ch))
+ .unwrap_or_else(|| {
+ if unicode_width::UnicodeWidthChar::width(ch) == Some(2) {
+ 1.0
+ } else {
+ 0.55
+ }
+ });
+ let mut advances = self.advances.lock().unwrap_or_else(|err| err.into_inner());
+ if advances.len() >= MAX_REMEMBERED_ADVANCES {
+ advances.clear();
+ }
+ advances.insert((ch, bold), em);
+ em
+ }
+
+ fn width(&self, text: &str, style: &TextStyle, bold: bool) -> f64 {
+ text.chars()
+ .map(|ch| self.advance_em(ch, bold))
+ .sum::<f64>()
+ * style.font_size
+ }
+}
+
+fn is_bold(style: &TextStyle) -> bool {
+ style.font_weight.as_deref().is_some_and(|weight| {
+ weight.eq_ignore_ascii_case("bold")
+ || weight.eq_ignore_ascii_case("bolder")
+ || weight.parse::<u32>().is_ok_and(|weight| weight >= 600)
+ })
+}
+
+impl TextMeasurer for FontMeasurer {
+ fn measure(&self, text: &str, style: &TextStyle) -> TextMetrics {
+ self.measure_wrapped(text, style, None, WrapMode::SvgLike)
+ }
+
+ fn measure_wrapped(
+ &self,
+ text: &str,
+ style: &TextStyle,
+ max_width: Option<f64>,
+ wrap_mode: WrapMode,
+ ) -> TextMetrics {
+ let bold = is_bold(style);
+ let space = self.width(" ", style, bold);
+ let max_width = max_width.filter(|width| width.is_finite() && *width > 0.0);
+ let mut widest = 0.0f64;
+ let mut line_count = 0usize;
+ // Lines as merman splits them: at `<br>` too, without trailing blanks.
+ for line in &DeterministicTextMeasurer::normalized_text_lines(text) {
+ let Some(max_width) = max_width else {
+ widest = widest.max(self.width(line, style, bold));
+ line_count += 1;
+ continue;
+ };
+ // Greedy wrap at spaces, as SVG and HTML labels do; a word wider
+ // than the line stands alone.
+ let mut current = 0.0f64;
+ let mut started = false;
+ for word in line.split(' ').filter(|word| !word.is_empty()) {
+ let word_width = self.width(word, style, bold);
+ if started && current + space + word_width > max_width {
+ widest = widest.max(current);
+ line_count += 1;
+ current = word_width;
+ } else {
+ current += if started {
+ space + word_width
+ } else {
+ word_width
+ };
+ }
+ started = true;
+ }
+ widest = widest.max(current);
+ line_count += 1;
+ }
+ let line_height = match wrap_mode {
+ WrapMode::HtmlLike => 1.5,
+ _ => 1.1,
+ };
+ let line_count = line_count.max(1);
+ TextMetrics {
+ width: widest,
+ height: line_count as f64 * style.font_size * line_height,
+ line_count,
+ }
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+
+ #[test]
+ fn only_mermaid_blocks_are_diagrams() {
+ assert!(is_mermaid(Some("mermaid")));
+ assert!(is_mermaid(Some("Mermaid")));
+ assert!(!is_mermaid(Some("rust")));
+ assert!(!is_mermaid(None));
+ }
+
+ #[test]
+ fn parse_verdicts_are_remembered() {
+ assert!(draws("flowchart TD\n A --> B"));
+ assert!(!draws("flowchart TD\n A --> \n B -->> ((("));
+ assert!(!draws("just some prose"));
+ // Asked again, from the cache.
+ assert!(draws("flowchart TD\n A --> B"));
+ }
+
+ #[test]
+ fn diagrams_are_drawn_at_the_size_they_are_shown() {
+ let room = DiagramBox {
+ width: 800.0,
+ height: 1440.0,
+ scale: 2.0,
+ };
+ // Small: its own size at the display's density, never enlarged.
+ assert_eq!(raster_size((300.0, 200.0), room), (600, 400));
+ // Wide: as wide as the room.
+ assert_eq!(raster_size((1000.0, 200.0), room), (800, 160));
+ // Tall: as tall as the room allows.
+ assert_eq!(raster_size((200.0, 1000.0), room), (205, 1024));
+ // However big the room, within the limits.
+ let (width, height) = raster_size(
+ (3000.0, 3000.0),
+ DiagramBox {
+ width: 9000.0,
+ height: 9000.0,
+ scale: 2.0,
+ },
+ );
+ assert!(width as f32 <= MAX_RASTER_SIDE && height as f32 <= MAX_RASTER_SIDE);
+ // Rounding each side may add a pixel's worth.
+ assert!((width * height) as f32 <= MAX_RASTER_PIXELS * 1.01);
+ }
+
+ #[test]
+ fn pictures_named_in_a_diagram_are_never_loaded() {
+ let options = svg_options(Arc::new(usvg::fontdb::Database::new()), "sans-serif");
+ let resolver = &options.image_href_resolver;
+ assert!((resolver.resolve_string)("picture.png", &options).is_none());
+ let png = Arc::new(b"\x89PNG\r\n\x1a\n".to_vec());
+ assert!((resolver.resolve_data)("image/png", png, &options).is_none());
+ }
+
+ #[test]
+ fn a_diagram_that_does_not_draw_is_remembered_as_unreadable() {
+ // Parses, but relates to a requirement nobody defined.
+ let source = "requirementDiagram\n requirement one {\n id: 1\n text: t\n risk: high\n verifymethod: test\n }\n one - satisfies -> nowhere\n";
+ assert!(draws(source));
+ assert_eq!(known_problem(source), None);
+ let epoch = verdict_epoch();
+ let room = DiagramBox {
+ width: 800.0,
+ height: 800.0,
+ scale: 1.0,
+ };
+ assert!(render(source, DiagramStyle { dark: false }, room).is_err());
+ assert!(!draws(source));
+ assert_eq!(known_problem(source), Some(Verdict::Unreadable));
+ assert!(verdict_epoch() > epoch);
+ }
+
+ #[test]
+ fn very_long_blocks_are_not_drawn() {
+ let long = format!(
+ "flowchart TD\n{}",
+ " A --> B\n".repeat(MAX_SOURCE_BYTES / 10)
+ );
+ assert!(long.len() > MAX_SOURCE_BYTES);
+ assert!(!draws(&long));
+ assert_eq!(known_problem(&long), Some(Verdict::TooLarge));
+ }
+
+ #[test]
+ fn diagrams_with_too_many_links_are_not_drawn() {
+ let mut dense = String::from("flowchart TD\n");
+ for link in 0..=MAX_LINKS {
+ dense.push_str(&format!(
+ " N{} --> N{}\n",
+ link % 20,
+ (link * 7 + 3) % 20
+ ));
+ }
+ assert!(dense.len() <= MAX_SOURCE_BYTES);
+ assert!(!draws(&dense));
+ assert_eq!(known_problem(&dense), Some(Verdict::TooLarge));
+ // The same number of boxes, with fewer links, draws.
+ let sparse: String = dense
+ .lines()
+ .take(MAX_LINKS / 2)
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(draws(&sparse));
+ }
+
+ #[test]
+ fn a_panic_in_merman_is_a_block_that_cannot_be_read() {
+ // merman 0.7 slices this ER diagram's CJK attribute type mid-character.
+ let source = "erDiagram\n顧客 {\n 文字列 名前\n}";
+ assert!(!draws(source));
+ let room = DiagramBox {
+ width: 800.0,
+ height: 800.0,
+ scale: 1.0,
+ };
+ assert!(render(source, DiagramStyle { dark: false }, room).is_err());
+ }
+
+ #[test]
+ fn c4_shapes_and_titles_keep_readable_colours() {
+ let fonts = fonts();
+ let c4 = "C4Context\n title Context\n Person(user, \"User\")\n System(app, \"App\")\n Rel(user, app, \"Uses\")";
+ let venn = "venn-beta\n title Overlap\n set Desirable\n set Feasible\n union Desirable,Feasible[\"Buildable\"]";
+ for dark in [true, false] {
+ let style = DiagramStyle { dark };
+ // merman letters C4 shapes in white: their fills stay dark.
+ let svg = render_svg(c4, style, &fonts).unwrap();
+ assert!(
+ svg.contains("#0b3d91") && svg.contains("#1d4ed8"),
+ "dark={dark}"
+ );
+ // Titles take the look's text colour, not near-black.
+ let text = if dark { "#e3e5e8" } else { "#1f2328" };
+ let svg = render_svg(venn, style, &fonts).unwrap();
+ let title = svg
+ .split('<')
+ .find(|element| element.starts_with("text class=\"venn-title\""))
+ .expect("a title");
+ assert!(title.contains(&format!("fill:{text}")), "dark={dark}");
+ }
+ }
+
+ #[test]
+ fn redraws_wait_for_a_real_change() {
+ assert!(!needs_redraw(800, 800));
+ assert!(!needs_redraw(800, 780));
+ assert!(!needs_redraw(100, 94));
+ assert!(needs_redraw(800, 600));
+ assert!(needs_redraw(400, 800));
+ }
+
+ #[test]
+ fn a_diagram_is_drawn_to_a_png() {
+ let room = DiagramBox {
+ width: 2000.0,
+ height: 2000.0,
+ scale: 2.0,
+ };
+ let drawn = render(
+ "flowchart LR\n A[打开终端] --> B{Ready?}\n B -->|yes| C[Done]",
+ DiagramStyle { dark: true },
+ room,
+ )
+ .unwrap();
+ assert!(drawn.width > 0 && drawn.height > 0);
+ assert_eq!(
+ (drawn.width, drawn.height),
+ raster_size(drawn.natural, room)
+ );
+ assert!(drawn.png.starts_with(b"\x89PNG"));
+ // Compressed, a diagram is far smaller than its pixels.
+ assert!(drawn.png.len() < (drawn.width * drawn.height) as usize);
+ assert!(render("not a diagram at all", DiagramStyle { dark: false }, room).is_err());
+ }
+
+ #[test]
+ fn diagrams_are_drawn_on_a_clear_background() {
+ let room = DiagramBox {
+ width: 1000.0,
+ height: 1000.0,
+ scale: 1.0,
+ };
+ for dark in [true, false] {
+ let drawn = render("flowchart LR\n A --> B", DiagramStyle { dark }, room).unwrap();
+ let image = image::load_from_memory(&drawn.png).unwrap().to_rgba8();
+ // A corner is outside every node and edge: nothing is painted there.
+ assert_eq!(image.get_pixel(0, 0)[3], 0, "dark={dark}");
+ assert_eq!(
+ image.get_pixel(image.width() - 1, image.height() - 1)[3],
+ 0,
+ "dark={dark}"
+ );
+ }
+ }
+
+ #[test]
+ fn measured_widths_follow_the_font() {
+ let fonts = fonts();
+ let family = fonts
+ .db
+ .faces()
+ .find_map(|face| face.families.first().map(|(name, _)| name.clone()))
+ .expect("a system font");
+ let measurer = FontMeasurer::new(&fonts.db, &family);
+ let style = TextStyle {
+ font_size: 16.0,
+ ..TextStyle::default()
+ };
+ let short = measurer.measure("Start", &style);
+ let long = measurer.measure("Start the whole build again", &style);
+ assert!(short.width > 0.0 && long.width > short.width);
+ assert_eq!(short.line_count, 1);
+ // Wrapping at a width narrower than the text makes more lines.
+ let wrapped = measurer.measure_wrapped(
+ "Start the whole build again",
+ &style,
+ Some(short.width * 2.0),
+ WrapMode::SvgLike,
+ );
+ assert!(wrapped.line_count > 1);
+ assert!(wrapped.width <= long.width);
+ // Wide characters count a full em each where the font lacks them.
+ assert!(measurer.advance_em('中', false) > 0.5);
+ // `<br>` breaks a line as a newline does; a trailing newline does not.
+ assert_eq!(measurer.measure("Start<br/>again", &style).line_count, 2);
+ assert_eq!(measurer.measure("Start\n", &style).line_count, 1);
+ // What is remembered stays bounded, however many characters pass.
+ for code in 0x4e00..0x4e00 + MAX_REMEMBERED_ADVANCES as u32 + 16 {
+ measurer.advance_em(char::from_u32(code).unwrap(), false);
+ }
+ assert!(measurer.advances.lock().unwrap().len() <= MAX_REMEMBERED_ADVANCES);
+ }
+}
diff --git a/wezterm-gui/src/markdown_editor/mod.rs b/wezterm-gui/src/markdown_editor/mod.rs
index a3e62770..d1249cc4 100644
--- a/wezterm-gui/src/markdown_editor/mod.rs
+++ b/wezterm-gui/src/markdown_editor/mod.rs
@@ -6,6 +6,7 @@
mod document;
mod host;
+pub(crate) mod mermaid;
mod projection;
mod remote_image;
mod spellcheck;
diff --git a/wezterm-gui/src/markdown_editor/surface.rs b/wezterm-gui/src/markdown_editor/surface.rs
index 446a14d2..f14609a0 100644
--- a/wezterm-gui/src/markdown_editor/surface.rs
+++ b/wezterm-gui/src/markdown_editor/surface.rs
@@ -600,6 +600,9 @@ pub(crate) fn build_visual_document(
}
let visible = projection.visible_source_ranges(source, caret, false);
+ // Where the caret's syntax starts: what the host keys this document by, so
+ // anything decided by the caret must be decided by this instead.
+ let reveal_start = projection.caret_reveal_start(caret);
let mut objects: Vec<&ProjectedObject> = projection.objects.iter().collect();
objects.sort_by_key(|object| {
let range = object.source();
@@ -713,6 +716,34 @@ pub(crate) fn build_visual_document(
}],
});
}
+ // A Mermaid block is its diagram, unless the caret is in it
+ // (to edit it), its fence is not closed (still being
+ // written, or cut off where a long note's first screen
+ // ends), or it does not draw (then it stays code, and its
+ // header says why).
+ ProjectedObject::CodeBlock(code)
+ if super::mermaid::is_mermaid(code.language.as_deref())
+ && !range.contains(&reveal_start)
+ && code.source.end > code.content.end
+ && super::mermaid::draws(&code.text) =>
+ {
+ flush_line_if_content(&mut lines, &mut line, idx);
+ lines.push(VisualLine {
+ source: range.clone(),
+ block: BlockKind::Paragraph,
+ kind: VisualLineKind::Image,
+ continuation_indent_bits: 0.0f32.to_bits(),
+ runs: vec![VisualRun {
+ source: range.clone(),
+ text: Arc::new(format!(
+ "▧ {}",
+ crate::i18n::tr("right-notes-mermaid-diagram")
+ )),
+ style: InlineStyle::default(),
+ atomic: true,
+ }],
+ });
+ }
ProjectedObject::CodeBlock(code) => {
flush_line_if_content(&mut lines, &mut line, idx);
let mut content_start = code.content.start;
@@ -1278,6 +1309,101 @@ mod tests {
);
}
+ #[test]
+ fn mermaid_blocks_are_drawn_unless_edited_or_unreadable() {
+ let source = "Before\n\n```mermaid\nflowchart TD\n A --> B\n```\n\nAfter\n";
+ let projection = MarkdownProjection::parse(source);
+ let fence = source.find("```mermaid").unwrap();
+ // Read and away from the caret, the block is one diagram line.
+ let doc = build_visual_document(source, &projection, EditorMode::ReadOnly, usize::MAX);
+ let diagrams: Vec<_> = doc
+ .lines
+ .iter()
+ .filter(|line| line.kind == VisualLineKind::Image)
+ .collect();
+ assert_eq!(diagrams.len(), 1);
+ assert_eq!(diagrams[0].source.start, fence);
+ assert!(!doc.lines.iter().any(|line| line.text().contains("A --> B")));
+ assert!(doc.lines.iter().any(|line| line.text() == "After"));
+ // The caret in the block shows its code, to edit.
+ let caret = source.find("A --> B").unwrap();
+ let doc = build_visual_document(source, &projection, EditorMode::LivePreview, caret);
+ assert!(doc
+ .lines
+ .iter()
+ .all(|line| line.kind != VisualLineKind::Image));
+ assert!(doc.lines.iter().any(|line| line.text().contains("A --> B")));
+ // Unreadable, it stays code.
+ let bad = "```mermaid\nflowchart TD\n A --> \n B -->> (((\n```\n";
+ let projection = MarkdownProjection::parse(bad);
+ let doc = build_visual_document(bad, &projection, EditorMode::ReadOnly, usize::MAX);
+ assert!(doc
+ .lines
+ .iter()
+ .all(|line| line.kind != VisualLineKind::Image));
+ let code_lines = doc
+ .lines
+ .iter()
+ .filter(|line| line.block == BlockKind::CodeBlock)
+ .count();
+ assert_eq!(code_lines, 3);
+ assert!(doc
+ .lines
+ .iter()
+ .any(|line| line.text().contains("B -->> (((")));
+ }
+
+ #[test]
+ fn an_unclosed_mermaid_block_is_not_drawn() {
+ let closed = "```mermaid\nflowchart TD\n A --> B\n```";
+ let open = "```mermaid\nflowchart TD\n A --> B\n";
+ for (source, drawn) in [(closed, true), (open, false)] {
+ let projection = MarkdownProjection::parse(source);
+ let doc = build_visual_document(source, &projection, EditorMode::ReadOnly, usize::MAX);
+ let images = doc
+ .lines
+ .iter()
+ .any(|line| line.kind == VisualLineKind::Image);
+ assert_eq!(images, drawn, "{source:?}");
+ }
+ }
+
+ #[test]
+ fn mermaid_blocks_follow_the_hosts_reveal_key() {
+ let source =
+ "Intro **bold**\n\n```mermaid\nflowchart TD\n A --> B\n```\n**Bold** after\n";
+ let projection = MarkdownProjection::parse(source);
+ let mut seen: HashMap<usize, (usize, Vec<String>)> = HashMap::new();
+ for caret in 0..=source.len() {
+ let doc = build_visual_document(source, &projection, EditorMode::LivePreview, caret);
+ let lines = doc
+ .lines
+ .iter()
+ .map(|line| format!("{:?} {}", line.kind, line.text()))
+ .collect::<Vec<_>>();
+ // Carets the host treats alike get the same document.
+ let key = projection.caret_reveal_start(caret);
+ match seen.get(&key) {
+ Some((first, expected)) => {
+ assert_eq!(&lines, expected, "caret {caret} vs {first}")
+ }
+ None => {
+ seen.insert(key, (caret, lines));
+ }
+ }
+ }
+ // On the closing fence the code shows; on the next line, the diagram.
+ let closing_end = source.find("```\n**").unwrap() + 3;
+ let shows_diagram = |caret| {
+ build_visual_document(source, &projection, EditorMode::LivePreview, caret)
+ .lines
+ .iter()
+ .any(|line| line.kind == VisualLineKind::Image)
+ };
+ assert!(!shows_diagram(closing_end));
+ assert!(shows_diagram(closing_end + 1));
+ }
+
#[test]
fn read_only_joins_soft_line_breaks_into_one_line() {
let source = "One line\nwraps here.\n\n- item that\n continues\n\n> quoted\n> more\n\nhard \nbreak\n";
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index f2336ee4..a3216dac 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -1121,12 +1121,82 @@ pub(crate) struct RightSidebarFilePreviewImage {
pub width: u32,
pub height: u32,
pub encoded_bytes: usize,
+ /// How far a note may enlarge it to fill the column: a photo or logo
+ /// reads better bigger; a diagram, drawn at the size it is shown, would
+ /// only blur.
+ pub max_upscale: f32,
+ /// A diagram's own size in points, from which it is drawn again when the
+ /// room it is shown in changes; `None` for a picture, which has only its
+ /// pixels.
+ pub natural_size: Option<(f32, f32)>,
}
-#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+#[derive(Clone)]
pub(crate) enum RightSidebarNoteImageSource {
Local(PathBuf),
Remote(String),
+ /// A Mermaid block, drawn: its text and the look it is drawn in. Its size
+ /// follows the room it is shown in, without a new entry per size.
+ Mermaid {
+ /// The text's hash, worked out once. It stands for the text in
+ /// lookups, made every frame, which then never read the whole text.
+ hash: u64,
+ source: Arc<str>,
+ style: crate::markdown_editor::mermaid::DiagramStyle,
+ },
+}
+
+impl PartialEq for RightSidebarNoteImageSource {
+ fn eq(&self, other: &Self) -> bool {
+ match (self, other) {
+ (Self::Local(path), Self::Local(other)) => path == other,
+ (Self::Remote(url), Self::Remote(other)) => url == other,
+ (
+ Self::Mermaid {
+ hash,
+ source,
+ style,
+ },
+ Self::Mermaid {
+ hash: other_hash,
+ source: other_source,
+ style: other_style,
+ },
+ ) => hash == other_hash && style == other_style && source.len() == other_source.len(),
+ _ => false,
+ }
+ }
+}
+
+impl Eq for RightSidebarNoteImageSource {}
+
+impl std::hash::Hash for RightSidebarNoteImageSource {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ std::mem::discriminant(self).hash(state);
+ match self {
+ Self::Local(path) => path.hash(state),
+ Self::Remote(url) => url.hash(state),
+ Self::Mermaid { hash, style, .. } => {
+ hash.hash(state);
+ style.hash(state);
+ }
+ }
+ }
+}
+
+// By hand, so a diagram's text (a note's content) never reaches a log line.
+impl std::fmt::Debug for RightSidebarNoteImageSource {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Local(path) => f.debug_tuple("Local").field(path).finish(),
+ Self::Remote(url) => f.debug_tuple("Remote").field(url).finish(),
+ Self::Mermaid { source, style, .. } => f
+ .debug_struct("Mermaid")
+ .field("bytes", &source.len())
+ .field("style", style)
+ .finish(),
+ }
+ }
}
#[derive(Clone, Copy, Debug)]
@@ -2812,6 +2882,12 @@ pub struct TermWindow {
right_sidebar_note_images_loading: HashSet<RightSidebarNoteImageSource>,
right_sidebar_note_image_order: VecDeque<RightSidebarNoteImageSource>,
right_sidebar_note_image_failures: HashMap<RightSidebarNoteImageSource, Instant>,
+ /// Moves on each time the Note image cache is emptied, so a load started
+ /// before that does not refill it.
+ right_sidebar_note_image_epoch: u64,
+ /// The room diagrams were last shown in, and since when: a diagram is
+ /// drawn again for a new width only once the width holds still.
+ right_sidebar_note_diagram_room: Option<(crate::markdown_editor::mermaid::DiagramBox, Instant)>,
right_sidebar_note_code_highlight: ui::right_sidebar::NoteCodeHighlightState,
right_sidebar_note_paint_cache: ui::right_sidebar::NotePaintCache,
/// Which surface's state is in the `right_sidebar_note*` fields right now;
@@ -4333,6 +4409,8 @@ impl TermWindow {
right_sidebar_note_images_loading: HashSet::new(),
right_sidebar_note_image_order: VecDeque::new(),
right_sidebar_note_image_failures: HashMap::new(),
+ right_sidebar_note_image_epoch: 0,
+ right_sidebar_note_diagram_room: None,
right_sidebar_note_code_highlight: ui::right_sidebar::NoteCodeHighlightState::default(),
right_sidebar_note_paint_cache: ui::right_sidebar::NotePaintCache::default(),
note_surface_installed: ui::right_sidebar::NoteSurface::Note,
diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
index e95b6e87..09a5f48f 100644
--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs
+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs
@@ -177,6 +177,9 @@ const NOTE_TABLE_MIN_COLUMN_WIDTH: usize = 120;
const NOTE_TABLE_MAX_COLUMN_WIDTH: usize = 480;
const NOTE_TABLE_SCROLLBAR_HEIGHT: usize = 3;
const NOTE_CODE_HEADER_HEIGHT: usize = 38;
+/// A code block's header names its language in small print, a caption to the
+/// code rather than a heading over it: this much of the note's text size.
+const NOTE_CODE_LABEL_SCALE: f64 = 0.8;
const NOTE_CODE_HORIZONTAL_PADDING: usize = 12;
const NOTE_CODE_VERTICAL_PADDING: usize = 9;
const NOTE_CODE_CONTROL_SIZE: usize = 28;
@@ -188,6 +191,11 @@ const NOTE_CODE_HIGHLIGHT_REPAINT_MS: u64 = 8;
const NOTE_AUTOSAVE_MS: u64 = 500;
const NOTE_SPELLCHECK_DEBOUNCE_MS: u64 = 300;
const NOTE_IMAGE_CACHE_CAPACITY: usize = 32;
+/// How far a Markdown image may be enlarged to fill the column.
+const NOTE_IMAGE_MAX_UPSCALE: f32 = 3.0;
+/// How long the width diagrams are shown at must hold still before they are
+/// drawn again for it, so a drag redraws them once, at its end.
+const NOTE_DIAGRAM_SETTLE: Duration = Duration::from_millis(300);
const NOTE_IMAGE_CACHE_MAX_ENCODED_BYTES: usize = 64 * 1024 * 1024;
const NOTE_VAULT_SPLIT_MIN_WIDTH: usize = 620;
const NOTE_VAULT_TREE_WIDTH: usize = 230;
@@ -604,18 +612,18 @@ fn note_image_display_size(
image_height: u32,
available_width: f32,
available_height: f32,
+ max_upscale: f32,
) -> (f32, f32) {
if image_width == 0 || image_height == 0 || available_width <= 0.0 || available_height <= 0.0 {
return (0.0, 0.0);
}
// Markdown images should be useful at reading distance, including small
- // logos and diagrams. Allow moderate upscaling while bounding both axes;
- // giant/tall images remain contained inside the current viewport.
- const MAX_UPSCALE: f32 = 3.0;
+ // logos, so they may be enlarged (up to `max_upscale`) while both axes
+ // stay bounded; giant/tall images remain inside the current viewport.
let scale = (available_width / image_width as f32)
.min(available_height / image_height as f32)
- .min(MAX_UPSCALE);
+ .min(max_upscale);
(
(image_width as f32 * scale).max(1.0),
(image_height as f32 * scale).max(1.0),
@@ -630,7 +638,14 @@ fn note_image_row_height(
) -> f32 {
image
.map(|image| {
- note_image_display_size(image.width, image.height, available_width, available_height).1
+ note_image_display_size(
+ image.width,
+ image.height,
+ available_width,
+ available_height,
+ image.max_upscale,
+ )
+ .1
})
.unwrap_or(text_height)
.max(text_height)
@@ -702,7 +717,9 @@ fn note_open_pending_for_vault(opening: Option<&(PathBuf, String)>, vault_root:
#[derive(Debug, Clone)]
struct NoteCodeRowPaintLayout {
block_start: usize,
- language: String,
+ /// What the block's header says: its language, and for a Mermaid block
+ /// that cannot be drawn, that it cannot.
+ label: String,
code: Arc<ProjectedCodeBlock>,
row_index: usize,
row_count: usize,
@@ -1980,6 +1997,9 @@ impl crate::TermWindow {
self.right_sidebar_note_images_loading.clear();
self.right_sidebar_note_image_order.clear();
self.right_sidebar_note_image_failures.clear();
+ self.right_sidebar_note_image_epoch = self.right_sidebar_note_image_epoch.wrapping_add(1);
+ self.right_sidebar_note_diagram_room = None;
+ crate::markdown_editor::mermaid::release();
self.right_sidebar_note_code_highlight = NoteCodeHighlightState::default();
self.right_sidebar_note_paint_cache = NotePaintCache::default();
self.ui_shape_caches.borrow_mut().clear_note();
@@ -8401,6 +8421,11 @@ impl crate::TermWindow {
.fonts
.resolve_font(&self.config.font)
.context("Note code font")?;
+ let code_label_font = self
+ .fonts
+ .title_font_with_size(base_font_size * NOTE_CODE_LABEL_SCALE)
+ .context("Note code label font")?;
+ let code_label_metrics = RenderMetrics::with_font_metrics(&code_label_font.metrics());
let h1_metrics = RenderMetrics::with_font_metrics(&h1_font.metrics());
let h2_metrics = RenderMetrics::with_font_metrics(&h2_font.metrics());
let h3_metrics = RenderMetrics::with_font_metrics(&h3_font.metrics());
@@ -8639,6 +8664,8 @@ impl crate::TermWindow {
let active_document = self.right_sidebar_note.document.clone();
let mut component_hasher = DefaultHasher::new();
wrap_key.hash(&mut component_hasher);
+ // Diagrams are drawn in the note's look.
+ use_dark_syntax_theme.hash(&mut component_hasher);
(Arc::as_ptr(&visual) as usize).hash(&mut component_hasher);
self.right_sidebar_note
.projection_revision
@@ -8837,18 +8864,30 @@ impl crate::TermWindow {
} else {
code_vertical_padding * 2.0 + code_line_height * row_count as f32
};
- let language = code
- .language
- .as_deref()
- .unwrap_or("code")
- .to_ascii_uppercase();
+ let language = code.language.as_deref().unwrap_or("code");
+ // Only what is already known: while the block is edited its
+ // text changes with every key, and parsing it here would too.
+ let problem = crate::markdown_editor::mermaid::is_mermaid(Some(language))
+ .then(|| crate::markdown_editor::mermaid::known_problem(&code.text))
+ .flatten();
+ let label = match problem {
+ Some(crate::markdown_editor::mermaid::Verdict::TooLarge) => format!(
+ "{language} ⚠ {}",
+ crate::i18n::tr("right-notes-mermaid-too-large")
+ ),
+ Some(_) => format!(
+ "{language} ⚠ {}",
+ crate::i18n::tr("right-notes-mermaid-unreadable")
+ ),
+ None => language.to_string(),
+ };
let code = Arc::new(code.clone());
for (row_index, visual_index) in row_indices.into_iter().enumerate() {
code_rows.insert(
visual_index,
NoteCodeRowPaintLayout {
block_start: code.source.start,
- language: language.clone(),
+ label: label.clone(),
code: Arc::clone(&code),
row_index,
row_count,
@@ -8862,6 +8901,12 @@ impl crate::TermWindow {
}
let mut image_sources = HashMap::new();
+ let diagram_starts: HashSet<usize> = visual
+ .lines
+ .iter()
+ .filter(|line| line.kind == VisualLineKind::Image)
+ .map(|line| line.source.start)
+ .collect();
if let Some(document) = active_document.as_ref() {
// Embeds resolve to canonical paths; the root may not be one
// (a preview's project root is spelled as the user opened it).
@@ -8895,6 +8940,25 @@ impl crate::TermWindow {
})
}
}
+ // Only a block shown as its diagram: one being edited
+ // or shown as code has no picture to find.
+ ProjectedObject::CodeBlock(code)
+ if crate::markdown_editor::mermaid::is_mermaid(
+ code.language.as_deref(),
+ ) && diagram_starts.contains(&code.source.start) =>
+ {
+ let source: Arc<str> = Arc::from(code.text.as_str());
+ Some((
+ code.source.start,
+ RightSidebarNoteImageSource::Mermaid {
+ hash: crate::markdown_editor::mermaid::content_hash(&source),
+ source,
+ style: crate::markdown_editor::mermaid::DiagramStyle {
+ dark: use_dark_syntax_theme,
+ },
+ },
+ ))
+ }
ProjectedObject::WikiLink {
source,
embed: true,
@@ -8937,6 +9001,24 @@ impl crate::TermWindow {
let image_max_height = (body_height as f32 * 0.72)
.max(ui_metrics.cell_size.height as f32)
.min(self.ui_f32(720.0));
+ // Whole pixels, so a diagram drawn to fill it is shown unscaled; its
+ // labels come out the size of the note's text.
+ let diagram_room = crate::markdown_editor::mermaid::DiagramBox {
+ width: wrap_width.floor(),
+ height: image_max_height.floor(),
+ scale: base_font_size as f32 * self.dimensions.dpi as f32
+ / 72.0
+ / crate::markdown_editor::mermaid::LABEL_SIZE,
+ };
+ let diagram_room_since = match self.right_sidebar_note_diagram_room {
+ Some((room, since)) if room == diagram_room => since,
+ _ => {
+ let now = Instant::now();
+ self.right_sidebar_note_diagram_room = Some((diagram_room, now));
+ now
+ }
+ };
+ let diagram_room_settled = diagram_room_since.elapsed() >= NOTE_DIAGRAM_SETTLE;
let line_gap = self.ui_px(NOTE_LINE_GAP) as f32;
let mut geometry_hasher = DefaultHasher::new();
wrap_key.hash(&mut geometry_hasher);
@@ -9250,17 +9332,18 @@ impl crate::TermWindow {
)
},
)?;
- let language_x = leading_x + control_size + self.ui_px(4);
+ let label_x = leading_x + control_size + self.ui_px(4);
self.paint_sidebar_text(
layers,
- ui_font,
- ui_metrics,
- &code_row.language,
- language_x,
+ &code_label_font,
+ code_label_metrics,
+ &code_row.label,
+ label_x,
header_y
- + header_height.saturating_sub(ui_metrics.cell_size.height as usize)
+ + header_height
+ .saturating_sub(code_label_metrics.cell_size.height as usize)
/ 2,
- copy_x.saturating_sub(language_x + self.ui_px(4)),
+ copy_x.saturating_sub(label_x + self.ui_px(4)),
muted_fg,
)?;
self.filled_rectangle(
@@ -9290,9 +9373,22 @@ impl crate::TermWindow {
.as_ref()
.and_then(|source| self.right_sidebar_note_images.get(source))
.cloned();
- if note_image.is_none() {
- if let Some(source) = note_image_source.clone() {
- self.schedule_right_sidebar_note_image(source);
+ if let Some(source) = note_image_source.clone() {
+ // Load what is missing. A diagram drawn for another width is
+ // drawn again once the width holds still, shown scaled meanwhile.
+ let redraw = note_image.as_ref().is_some_and(|image| {
+ image.natural_size.is_some_and(|natural| {
+ crate::markdown_editor::mermaid::needs_redraw(
+ image.width,
+ crate::markdown_editor::mermaid::raster_size(natural, diagram_room).0,
+ )
+ })
+ });
+ if redraw && !diagram_room_settled {
+ // Paint again once it has held still, should nothing else.
+ self.update_next_frame_time(Some(diagram_room_since + NOTE_DIAGRAM_SETTLE));
+ } else if note_image.is_none() || redraw {
+ self.schedule_right_sidebar_note_image(source, diagram_room);
}
}
@@ -10192,12 +10288,30 @@ impl crate::TermWindow {
self.request_right_sidebar_note_open(vault.root, relative_path, create, project_id, false)
}
- fn schedule_right_sidebar_note_image(&mut self, source: RightSidebarNoteImageSource) {
- if self.right_sidebar_note_images.contains_key(&source)
- || self
- .right_sidebar_note_image_failures
- .get(&source)
- .is_some_and(|failed| failed.elapsed() < Duration::from_secs(60))
+ /// Load `source`'s image, or draw it to fit `room` when it is a diagram;
+ /// what arrives replaces what is cached. One load per source at a time.
+ fn schedule_right_sidebar_note_image(
+ &mut self,
+ source: RightSidebarNoteImageSource,
+ room: crate::markdown_editor::mermaid::DiagramBox,
+ ) {
+ // Diagrams are drawn one at a time anyway: starting just one keeps the
+ // rest from each parking a thread until its turn.
+ let is_diagram = |source: &RightSidebarNoteImageSource| {
+ matches!(source, RightSidebarNoteImageSource::Mermaid { .. })
+ };
+ if is_diagram(&source)
+ && self
+ .right_sidebar_note_images_loading
+ .iter()
+ .any(is_diagram)
+ {
+ return;
+ }
+ if self
+ .right_sidebar_note_image_failures
+ .get(&source)
+ .is_some_and(|failed| failed.elapsed() < Duration::from_secs(60))
|| !self
.right_sidebar_note_images_loading
.insert(source.clone())
@@ -10208,10 +10322,27 @@ impl crate::TermWindow {
self.right_sidebar_note_images_loading.remove(&source);
return;
};
+ let epoch = self.right_sidebar_note_image_epoch;
promise::spawn::spawn(async move {
let load_source = source.clone();
let result = promise::spawn::spawn_into_new_thread(move || match load_source {
RightSidebarNoteImageSource::Local(path) => load_file_preview_image(&path),
+ RightSidebarNoteImageSource::Mermaid { source, style, .. } => {
+ let stage = crate::input_diagnostics::StageTimer::begin("note_diagram");
+ let drawn = crate::markdown_editor::mermaid::render(&source, style, room);
+ stage.finish(drawn.is_ok());
+ let drawn = drawn?;
+ // Kept compressed, and counted as such, as a file image is.
+ let encoded_bytes = drawn.png.len();
+ Ok(RightSidebarFilePreviewImage {
+ data: Arc::new(ImageData::with_data(ImageDataType::EncodedFile(drawn.png))),
+ width: drawn.width,
+ height: drawn.height,
+ encoded_bytes,
+ max_upscale: 1.0,
+ natural_size: Some(drawn.natural),
+ })
+ }
RightSidebarNoteImageSource::Remote(url) => {
let image = load_remote_image(&url)?;
let encoded_bytes = image.bytes.len();
@@ -10222,11 +10353,17 @@ impl crate::TermWindow {
width,
height,
encoded_bytes,
+ max_upscale: NOTE_IMAGE_MAX_UPSCALE,
+ natural_size: None,
})
}
})
.await;
window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {
+ // The cache was emptied meanwhile: nothing is waiting for this.
+ if term_window.right_sidebar_note_image_epoch != epoch {
+ return;
+ }
term_window
.right_sidebar_note_images_loading
.remove(&source);
@@ -10261,10 +10398,27 @@ impl crate::TermWindow {
}
}
Err(err) => {
+ // Only failures recent enough to hold a retry back.
+ let now = Instant::now();
+ term_window
+ .right_sidebar_note_image_failures
+ .retain(|_, failed| {
+ now.duration_since(*failed) < Duration::from_secs(60)
+ });
term_window
.right_sidebar_note_image_failures
- .insert(source.clone(), Instant::now());
- log::warn!("unable to render Note image {:?}: {err:#}", source);
+ .insert(source.clone(), now);
+ match &source {
+ // A diagram's errors quote it, and it is the
+ // note's own text: say only that it failed.
+ RightSidebarNoteImageSource::Mermaid { source, .. } => {
+ log::warn!(
+ "unable to draw a Mermaid diagram ({} bytes)",
+ source.len()
+ )
+ }
+ _ => log::warn!("unable to render Note image {:?}: {err:#}", source),
+ }
}
}
term_window.invalidate_window();
@@ -10289,9 +10443,11 @@ impl crate::TermWindow {
return Ok(());
}
let (draw_width, draw_height) =
- note_image_display_size(image.width, image.height, width, height);
- let draw_x = x + (width - draw_width) / 2.0;
- let draw_y = y + (height - draw_height) / 2.0;
+ note_image_display_size(image.width, image.height, width, height, image.max_upscale);
+ // On whole pixels, so a diagram drawn at the size it is shown maps
+ // one texel to one pixel instead of blurring across two.
+ let draw_x = (x + (width - draw_width) / 2.0).round();
+ let draw_y = (y + (height - draw_height) / 2.0).round();
let Some(gl_state) = self.render_state.as_ref() else {
return Ok(());
};
@@ -19618,6 +19774,8 @@ fn remote_preview_from_bytes(
width,
height,
encoded_bytes,
+ max_upscale: NOTE_IMAGE_MAX_UPSCALE,
+ natural_size: None,
}),
message: None,
truncated: false,
@@ -19702,6 +19860,8 @@ fn load_file_preview_image(path: &Path) -> anyhow::Result<RightSidebarFilePrevie
width,
height,
encoded_bytes,
+ max_upscale: NOTE_IMAGE_MAX_UPSCALE,
+ natural_size: None,
})
}
@@ -21799,13 +21959,16 @@ mod tests {
#[test]
fn note_images_scale_responsively_without_escaping_the_viewport() {
- assert_eq!(note_image_display_size(0, 100, 600.0, 500.0), (0.0, 0.0));
assert_eq!(
- note_image_display_size(200, 100, 600.0, 500.0),
+ note_image_display_size(0, 100, 600.0, 500.0, super::NOTE_IMAGE_MAX_UPSCALE),
+ (0.0, 0.0)
+ );
+ assert_eq!(
+ note_image_display_size(200, 100, 600.0, 500.0, super::NOTE_IMAGE_MAX_UPSCALE),
(600.0, 300.0)
);
assert_eq!(
- note_image_display_size(1200, 2400, 600.0, 500.0),
+ note_image_display_size(1200, 2400, 600.0, 500.0, super::NOTE_IMAGE_MAX_UPSCALE),
(250.0, 500.0)
);
}