From d61f65d4f527408ebe9947f6a64a2dd3f68987f7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:31:59 -0500 Subject: [PATCH 001/357] build(desktop): freeze the macOS engine as a flattened one-folder in src-tauri/engine (0.7.0) A one-file engine unpacks RDKit, Indigo, numpy and Python to a new temporary folder at every launch, and macOS scans every unpacked library again, which made the app take about 30 seconds to open; the one-folder engine is unpacked once, at install, with no links and no Python.framework so Tauri can ship it as resources, and is signed file by file when APPLE_SIGNING_IDENTITY is set. --- setup/freeze_backend | 58 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/setup/freeze_backend b/setup/freeze_backend index dbb60c56..1544732e 100755 --- a/setup/freeze_backend +++ b/setup/freeze_backend @@ -1,6 +1,47 @@ #!/usr/bin/env bash set -e source "$(dirname "$0")/lib.sh" +sign_engine() { + local ent="$FORMCHEM_ROOT/src-tauri/entitlements.plist" f info signed=0 kept=0 + local files=() + while IFS= read -r f; do + if file -b "$f" | grep -Eq 'Mach-O.*(executable|shared library|bundle)'; then files+=("$f"); fi + done < <(find "$1" -type f | awk -F/ '{print NF "\t" $0}' | sort -rn | cut -f2-) + for f in "${files[@]}"; do + info="$(codesign -d --verbose=4 "$f" 2>&1 || true)" + if printf '%s\n' "$info" | grep -q '^Timestamp=' \ + && printf '%s\n' "$info" | grep -Eq '^CodeDirectory .*flags=[^ ]*runtime' \ + && ! printf '%s\n' "$info" | grep -q '^Signature=adhoc' \ + && codesign -d --entitlements - "$f" 2>/dev/null | grep -q 'com.apple.security.cs.disable-library-validation'; then + kept=$((kept + 1)) + continue + fi + codesign --force --timestamp --options runtime --entitlements "$ent" --sign "$APPLE_SIGNING_IDENTITY" "$f" + signed=$((signed + 1)) + done + for f in "${files[@]}"; do codesign --verify --strict "$f" || fc_die "engine file failed its signature check: $f"; done + fc_say "engine signed: ${#files[@]} Mach-O files, $signed signed here, $kept already signed by PyInstaller" +} +flatten_engine() { + local dir="$1" fw="$1/_internal/Python.framework" lib="$1/_internal/Python" link f + if [ -d "$fw" ]; then + [ -f "$fw/Python" ] || fc_die "Python.framework has no Python library: $fw" + rm -f "$lib" + cp "$fw/Python" "$lib" + rm -rf "$fw" + codesign --force --sign - "$lib" + fi + while IFS= read -r link; do + cp -RL "$link" "$link.flat" && rm -f "$link" && mv "$link.flat" "$link" + done < <(find "$dir" -type l) + [ -z "$(find "$dir" -type l | head -1)" ] || fc_die "engine still holds symbolic links after flattening: $dir" + f="$(find "$dir" -name '*.framework' | head -1)" + [ -z "$f" ] || fc_die "engine holds a .framework that cannot ship as Tauri resources: $f" + while IFS= read -r f; do + [ "$f" = "$lib" ] && continue + if file -b "$f" | grep -q 'Mach-O' && otool -L "$f" | grep -q 'Python.framework'; then fc_die "$f links Python.framework, which the engine no longer ships"; fi + done < <(find "$dir" -type f) +} fc_venv python -c "import PyInstaller" 2>/dev/null || fc_die "PyInstaller missing, run ./formchem install-desktop" triple="$(fc_target_triple)" || fc_die "rustc not found; install Rust or set FORMCHEM_TARGET" @@ -12,9 +53,14 @@ sep=":" ext="$(fc_exe)" extra=() if [ -d "$FORMCHEM_ROOT/backend/app/fonts" ]; then extra+=(--add-data "$FORMCHEM_ROOT/backend/app/fonts${sep}fonts"); fi +mode=--onefile +if [ "$(fc_os)" = macos ]; then + mode=--onedir + [ -z "${APPLE_SIGNING_IDENTITY:-}" ] || extra+=(--codesign-identity "$APPLE_SIGNING_IDENTITY" --osx-entitlements-file "$FORMCHEM_ROOT/src-tauri/entitlements.plist") +fi if [ "$(fc_os)" = windows ] && [ "${FORMCHEM_ENGINE_WINDOWED:-1}" != 0 ]; then extra+=(--noconsole); fi rm -rf build/pyinstaller dist-engine -pyinstaller --noconfirm --clean --onefile --name formchem-engine \ +pyinstaller --noconfirm --clean "$mode" --name formchem-engine \ --distpath dist-engine --workpath build/pyinstaller --specpath build/pyinstaller \ --add-data "$FORMCHEM_ROOT/frontend/dist${sep}frontend_dist" \ --add-data "$FORMCHEM_ROOT/THIRD-PARTY-NOTICES.txt${sep}." \ @@ -23,6 +69,16 @@ pyinstaller --noconfirm --clean --onefile --name formchem-engine \ --collect-all rdkit --collect-all indigo \ ${extra[@]+"${extra[@]}"} \ "$FORMCHEM_ROOT/backend/formchem_engine.py" +if [ "$mode" = --onedir ]; then + out="$FORMCHEM_ROOT/src-tauri/engine" + rm -rf "$out" + cp -R dist-engine/formchem-engine "$out" + flatten_engine "$out" + [ -z "${APPLE_SIGNING_IDENTITY:-}" ] || sign_engine "$out" + "$out/formchem-engine" --selfcheck || fc_die "the frozen engine failed its self-check; see the line above" + fc_say "engine folder ready: $out" + exit 0 +fi mkdir -p "$FORMCHEM_ROOT/src-tauri/binaries" out="$FORMCHEM_ROOT/src-tauri/binaries/formchem-engine-${triple}${ext}" cp "dist-engine/formchem-engine${ext}" "$out" From a2f5001dcceebef7c9b3bf716d1803d7249b66fe Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:33:59 -0500 Subject: [PATCH 002/357] refactor(setup): move engine flattening and signing into lib.sh helpers (0.7.0) build_app freezes the engine on its own, so the flatten, sign and self-check steps of the one-folder engine live in setup/lib.sh as fc_flatten_engine, fc_sign_engine and fc_engine_folder for both scripts to share; the pipes read to the end so pipefail cannot turn an early grep exit into a missed match. --- setup/freeze_backend | 49 +------------------------------------------ setup/lib.sh | 50 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 48 deletions(-) diff --git a/setup/freeze_backend b/setup/freeze_backend index 1544732e..aaba705b 100755 --- a/setup/freeze_backend +++ b/setup/freeze_backend @@ -1,47 +1,6 @@ #!/usr/bin/env bash set -e source "$(dirname "$0")/lib.sh" -sign_engine() { - local ent="$FORMCHEM_ROOT/src-tauri/entitlements.plist" f info signed=0 kept=0 - local files=() - while IFS= read -r f; do - if file -b "$f" | grep -Eq 'Mach-O.*(executable|shared library|bundle)'; then files+=("$f"); fi - done < <(find "$1" -type f | awk -F/ '{print NF "\t" $0}' | sort -rn | cut -f2-) - for f in "${files[@]}"; do - info="$(codesign -d --verbose=4 "$f" 2>&1 || true)" - if printf '%s\n' "$info" | grep -q '^Timestamp=' \ - && printf '%s\n' "$info" | grep -Eq '^CodeDirectory .*flags=[^ ]*runtime' \ - && ! printf '%s\n' "$info" | grep -q '^Signature=adhoc' \ - && codesign -d --entitlements - "$f" 2>/dev/null | grep -q 'com.apple.security.cs.disable-library-validation'; then - kept=$((kept + 1)) - continue - fi - codesign --force --timestamp --options runtime --entitlements "$ent" --sign "$APPLE_SIGNING_IDENTITY" "$f" - signed=$((signed + 1)) - done - for f in "${files[@]}"; do codesign --verify --strict "$f" || fc_die "engine file failed its signature check: $f"; done - fc_say "engine signed: ${#files[@]} Mach-O files, $signed signed here, $kept already signed by PyInstaller" -} -flatten_engine() { - local dir="$1" fw="$1/_internal/Python.framework" lib="$1/_internal/Python" link f - if [ -d "$fw" ]; then - [ -f "$fw/Python" ] || fc_die "Python.framework has no Python library: $fw" - rm -f "$lib" - cp "$fw/Python" "$lib" - rm -rf "$fw" - codesign --force --sign - "$lib" - fi - while IFS= read -r link; do - cp -RL "$link" "$link.flat" && rm -f "$link" && mv "$link.flat" "$link" - done < <(find "$dir" -type l) - [ -z "$(find "$dir" -type l | head -1)" ] || fc_die "engine still holds symbolic links after flattening: $dir" - f="$(find "$dir" -name '*.framework' | head -1)" - [ -z "$f" ] || fc_die "engine holds a .framework that cannot ship as Tauri resources: $f" - while IFS= read -r f; do - [ "$f" = "$lib" ] && continue - if file -b "$f" | grep -q 'Mach-O' && otool -L "$f" | grep -q 'Python.framework'; then fc_die "$f links Python.framework, which the engine no longer ships"; fi - done < <(find "$dir" -type f) -} fc_venv python -c "import PyInstaller" 2>/dev/null || fc_die "PyInstaller missing, run ./formchem install-desktop" triple="$(fc_target_triple)" || fc_die "rustc not found; install Rust or set FORMCHEM_TARGET" @@ -70,13 +29,7 @@ pyinstaller --noconfirm --clean "$mode" --name formchem-engine \ ${extra[@]+"${extra[@]}"} \ "$FORMCHEM_ROOT/backend/formchem_engine.py" if [ "$mode" = --onedir ]; then - out="$FORMCHEM_ROOT/src-tauri/engine" - rm -rf "$out" - cp -R dist-engine/formchem-engine "$out" - flatten_engine "$out" - [ -z "${APPLE_SIGNING_IDENTITY:-}" ] || sign_engine "$out" - "$out/formchem-engine" --selfcheck || fc_die "the frozen engine failed its self-check; see the line above" - fc_say "engine folder ready: $out" + fc_engine_folder dist-engine/formchem-engine exit 0 fi mkdir -p "$FORMCHEM_ROOT/src-tauri/binaries" diff --git a/setup/lib.sh b/setup/lib.sh index a51168ca..6e22bc92 100755 --- a/setup/lib.sh +++ b/setup/lib.sh @@ -34,3 +34,53 @@ fc_target_triple() { rustc -vV | awk '/^host:/ {print $2}' } fc_exe() { [ "$(fc_os)" = windows ] && echo ".exe" || echo ""; } +fc_sign_engine() { + local ent="$FORMCHEM_ROOT/src-tauri/entitlements.plist" f info signed=0 kept=0 + local files=() + while IFS= read -r f; do + if file -b "$f" | grep -E 'Mach-O.*(executable|shared library|bundle)' >/dev/null; then files+=("$f"); fi + done < <(find "$1" -type f | awk -F/ '{print NF "\t" $0}' | sort -rn | cut -f2-) + for f in ${files[@]+"${files[@]}"}; do + info="$(codesign -d --verbose=4 "$f" 2>&1 || true)" + if printf '%s\n' "$info" | grep '^Timestamp=' >/dev/null \ + && printf '%s\n' "$info" | grep -E '^CodeDirectory .*flags=[^ ]*runtime' >/dev/null \ + && ! printf '%s\n' "$info" | grep '^Signature=adhoc' >/dev/null \ + && codesign -d --entitlements - "$f" 2>/dev/null | grep 'com.apple.security.cs.disable-library-validation' >/dev/null; then + kept=$((kept + 1)) + continue + fi + codesign --force --timestamp --options runtime --entitlements "$ent" --sign "$APPLE_SIGNING_IDENTITY" "$f" + signed=$((signed + 1)) + done + for f in ${files[@]+"${files[@]}"}; do codesign --verify --strict "$f" || fc_die "engine file failed its signature check: $f"; done + fc_say "engine signed: ${#files[@]} Mach-O files, $signed signed here, $kept already signed by PyInstaller" +} +fc_flatten_engine() { + local dir="$1" fw="$1/_internal/Python.framework" lib="$1/_internal/Python" link f + if [ -d "$fw" ]; then + [ -f "$fw/Python" ] || fc_die "Python.framework has no Python library: $fw" + rm -f "$lib" + cp "$fw/Python" "$lib" + rm -rf "$fw" + codesign --force --sign - "$lib" + fi + while IFS= read -r link; do + cp -RL "$link" "$link.flat" && rm -f "$link" && mv "$link.flat" "$link" + done < <(find "$dir" -type l) + [ -z "$(find "$dir" -type l | head -1)" ] || fc_die "engine still holds symbolic links after flattening: $dir" + f="$(find "$dir" -name '*.framework' | head -1)" + [ -z "$f" ] || fc_die "engine holds a .framework that cannot ship as Tauri resources: $f" + while IFS= read -r f; do + [ "$f" = "$lib" ] && continue + if file -b "$f" | grep 'Mach-O' >/dev/null && otool -L "$f" | grep 'Python.framework' >/dev/null; then fc_die "$f links Python.framework, which the engine no longer ships"; fi + done < <(find "$dir" -type f) +} +fc_engine_folder() { + local out="$FORMCHEM_ROOT/src-tauri/engine" + rm -rf "$out" + cp -R "$1" "$out" + fc_flatten_engine "$out" + [ -z "${APPLE_SIGNING_IDENTITY:-}" ] || fc_sign_engine "$out" + "$out/formchem-engine" --selfcheck >/dev/null || { "$out/formchem-engine" --selfcheck || true; fc_die "the frozen engine failed its self-check; see the line above"; } + fc_say "engine folder ready: $out ($(du -sh "$out" | awk '{print $1}'))" +} From 67a1b7f8cb143a84d312df3665747a548162e124 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:34:23 -0500 Subject: [PATCH 003/357] build(desktop): build_app freezes the macOS engine one-folder too (0.7.0) build_app has its own freeze step, so on macOS it now freezes --onedir with the same templates, fonts and notices data and hands the result to fc_engine_folder, and --clean removes src-tauri/engine; Linux keeps the one-file sidecar. --- build_app | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/build_app b/build_app index bb0e3f52..f30c7a0f 100755 --- a/build_app +++ b/build_app @@ -162,7 +162,7 @@ fi step "preparing" if [ "$CLEAN" = 1 ]; then say "removing earlier build output" - rm -rf src-tauri/target frontend/dist backend/build backend/dist-engine src-tauri/binaries/formchem-engine-* + rm -rf src-tauri/target frontend/dist backend/build backend/dist-engine src-tauri/binaries/formchem-engine-* src-tauri/engine fi mkdir -p src-tauri/binaries [ -f THIRD-PARTY-NOTICES.txt ] || die "THIRD-PARTY-NOTICES.txt is missing; run python3 setup/notices.py after ./formchem install, then run ./build_app again" @@ -226,12 +226,17 @@ step "freezing the engine into the app" SEP=":" EXTRA=() [ -d backend/app/fonts ] && EXTRA+=(--add-data "$ROOT/backend/app/fonts${SEP}fonts") +MODE=--onefile +if [ "$OS" = macos ]; then + MODE=--onedir + [ -z "${APPLE_SIGNING_IDENTITY:-}" ] || EXTRA+=(--codesign-identity "$APPLE_SIGNING_IDENTITY" --osx-entitlements-file "$ROOT/src-tauri/entitlements.plist") +fi freeze() { ( cd backend rm -rf build/pyinstaller build/pyinstaller-cache dist-engine PYINSTALLER_CONFIG_DIR="$ROOT/backend/build/pyinstaller-cache" \ - "$VPY" -m PyInstaller --noconfirm --clean --onefile --log-level WARN --name formchem-engine \ + "$VPY" -m PyInstaller --noconfirm --clean "$MODE" --log-level WARN --name formchem-engine \ --distpath dist-engine --workpath build/pyinstaller --specpath build/pyinstaller \ --add-data "$ROOT/frontend/dist${SEP}frontend_dist" \ --add-data "$ROOT/THIRD-PARTY-NOTICES.txt${SEP}." \ @@ -246,11 +251,15 @@ if ! freeze; then say "PyInstaller stopped; clearing its cache and freezing the engine once more" freeze || die "freezing the engine failed twice; the log above shows the error" fi -SIDECAR="src-tauri/binaries/formchem-engine-$TRIPLE" -cp backend/dist-engine/formchem-engine "$SIDECAR" -chmod +x "$SIDECAR" -"$SIDECAR" --selfcheck >/dev/null || { "$SIDECAR" --selfcheck || true; die "the frozen engine is missing modules (see above)"; } -say "engine ready: $SIDECAR ($(du -h "$SIDECAR" | awk '{print $1}'))" +if [ "$MODE" = --onedir ]; then + ( source setup/lib.sh && fc_engine_folder backend/dist-engine/formchem-engine ) || die "the engine folder could not be made ready (see above)" +else + SIDECAR="src-tauri/binaries/formchem-engine-$TRIPLE" + cp backend/dist-engine/formchem-engine "$SIDECAR" + chmod +x "$SIDECAR" + "$SIDECAR" --selfcheck >/dev/null || { "$SIDECAR" --selfcheck || true; die "the frozen engine is missing modules (see above)"; } + say "engine ready: $SIDECAR ($(du -h "$SIDECAR" | awk '{print $1}'))" +fi step "building and bundling the app ($BUNDLES)" if [ ! -f src-tauri/icons/icon.icns ] || [ ! -f src-tauri/icons/icon.ico ] || [ ! -f src-tauri/icons/128x128.png ]; then From 016374bc7f81d973e5fba8e2274a11dffb597261 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:34:34 -0500 Subject: [PATCH 004/357] build(desktop): ship the macOS engine folder as Resources/engine instead of a sidecar (0.7.0) tauri.macos.conf.json empties externalBin and adds src-tauri/engine as the resource engine, beside the licence and notices files tauri.conf.json already ships, so the .app carries the one-folder engine unpacked once at install. --- src-tauri/tauri.macos.conf.json | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 src-tauri/tauri.macos.conf.json diff --git a/src-tauri/tauri.macos.conf.json b/src-tauri/tauri.macos.conf.json new file mode 100644 index 00000000..b7a9f0d0 --- /dev/null +++ b/src-tauri/tauri.macos.conf.json @@ -0,0 +1,11 @@ +{ + "bundle": { + "externalBin": [], + "resources": { + "../LICENSE": "LICENSE", + "../NOTICE.md": "NOTICE.md", + "../THIRD-PARTY-NOTICES.txt": "THIRD-PARTY-NOTICES.txt", + "engine": "engine" + } + } +} From 025eef892639edd65dc35a95671dc70fc471d2a6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:34:34 -0500 Subject: [PATCH 005/357] chore(git): ignore the frozen engine folder src-tauri/engine (0.7.0) The macOS freeze writes a few hundred megabytes of generated engine files there, which must never be committed. --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index ec9e86cb..c50f165b 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,7 @@ src-tauri/gen/ src-tauri/permissions/autogenerated/ src-tauri/binaries/* !src-tauri/binaries/.gitkeep +src-tauri/engine/ src-tauri/flatpak/formchem.deb .flatpak-builder/ *.flatpak From 2045197bbc82d5d2485ca04de5a112989defafd2 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:35:23 -0500 Subject: [PATCH 006/357] feat(desktop): start the one-folder engine from Resources/engine, else the sidecar (0.7.0) packaged::engine_folder finds formchem-engine in the bundle's Resources/engine or in engine/ beside the binary, where tauri dev copies resources, and the shell starts it with the same environment as before; Windows and Linux builds, which ship no folder, start the one-file sidecar as they did. --- src-tauri/src/main.rs | 27 ++++++++++++++------------- src-tauri/src/packaged.rs | 12 ++++++++++++ 2 files changed, 26 insertions(+), 13 deletions(-) create mode 100644 src-tauri/src/packaged.rs diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index b86d2644..90842a7c 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -1,6 +1,7 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] mod engine_start; +mod packaged; mod reveal; mod traffic_lights; #[cfg(windows)] @@ -335,19 +336,19 @@ fn main() { .setup(|app| { let handle = app.handle().clone(); reveal::round_splash(&handle); - let started = app - .shell() - .sidecar("formchem-engine") - .map_err(|_| engine_start::Failure::Missing) - .and_then(|engine| { - engine - .env("FORMCHEM_PORT", "0") - .env("FORMCHEM_PORT_PREFER", "8221") - .env("FORMCHEM_WINDOW_KEY_STDOUT", "1") - .env(engine_start::SHELL_ENV, std::process::id().to_string()) - .spawn() - .map_err(|err| engine_start::Failure::NotStarted(err.to_string())) - }); + let engine = match packaged::engine_folder() { + Some(program) => Ok(app.shell().command(program)), + None => app.shell().sidecar("formchem-engine").map_err(|_| engine_start::Failure::Missing), + }; + let started = engine.and_then(|engine| { + engine + .env("FORMCHEM_PORT", "0") + .env("FORMCHEM_PORT_PREFER", "8221") + .env("FORMCHEM_WINDOW_KEY_STDOUT", "1") + .env(engine_start::SHELL_ENV, std::process::id().to_string()) + .spawn() + .map_err(|err| engine_start::Failure::NotStarted(err.to_string())) + }); let (mut rx, child) = match started { Ok(pair) => pair, Err(failure) => { diff --git a/src-tauri/src/packaged.rs b/src-tauri/src/packaged.rs new file mode 100644 index 00000000..77efe325 --- /dev/null +++ b/src-tauri/src/packaged.rs @@ -0,0 +1,12 @@ +use std::path::PathBuf; + +const ENGINE: &str = if cfg!(windows) { "formchem-engine.exe" } else { "formchem-engine" }; + +pub fn engine_folder() -> Option { + let exe = std::env::current_exe().ok()?; + let dir = exe.parent()?; + [dir.join("../Resources/engine"), dir.join("engine")] + .into_iter() + .map(|folder| folder.join(ENGINE)) + .find(|program| program.is_file()) +} From 125a217b64c6c5af7b9c14db92d685895812fefa Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:35:30 -0500 Subject: [PATCH 007/357] build(desktop): desktop dev on macOS freezes when the engine folder is missing (0.7.0) tauri dev on macOS now ships src-tauri/engine as a resource and fails without it, and a one-file binary left from an earlier build no longer counts as a frozen engine there. --- setup/desktop_dev | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/setup/desktop_dev b/setup/desktop_dev index 42521e39..8d240292 100755 --- a/setup/desktop_dev +++ b/setup/desktop_dev @@ -2,6 +2,10 @@ set -e source "$(dirname "$0")/lib.sh" triple="$(fc_target_triple)" || fc_die "rustc not found; run ./formchem install-desktop" -[ -x "$FORMCHEM_ROOT/src-tauri/binaries/formchem-engine-${triple}$(fc_exe)" ] || "$FORMCHEM_ROOT/setup/freeze_backend" +if [ "$(fc_os)" = macos ]; then + [ -x "$FORMCHEM_ROOT/src-tauri/engine/formchem-engine" ] || "$FORMCHEM_ROOT/setup/freeze_backend" +else + [ -x "$FORMCHEM_ROOT/src-tauri/binaries/formchem-engine-${triple}$(fc_exe)" ] || "$FORMCHEM_ROOT/setup/freeze_backend" +fi cd "$FORMCHEM_ROOT" exec frontend/node_modules/.bin/tauri dev "$@" From 0b6033475b36ee6d077a5bef5a8f221529ddcdd4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:35:35 -0500 Subject: [PATCH 008/357] build(setup): clean removes the frozen engine folder src-tauri/engine (0.7.0) The macOS one-folder engine is build output like the one-file sidecar, so clean and clean.bat remove it with the rest. --- setup/clean | 2 +- setup/clean.bat | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup/clean b/setup/clean index c4bc6523..fa140184 100755 --- a/setup/clean +++ b/setup/clean @@ -2,7 +2,7 @@ set -e source "$(dirname "$0")/lib.sh" cd "$FORMCHEM_ROOT" -for p in frontend/dist backend/build backend/dist-engine src-tauri/target src-tauri/gen; do rm -rf "$p"; done +for p in frontend/dist backend/build backend/dist-engine src-tauri/target src-tauri/gen src-tauri/engine; do rm -rf "$p"; done find backend -name __pycache__ -type d -prune -exec rm -rf {} + 2>/dev/null || true for f in src-tauri/binaries/formchem-engine-*; do [ -e "$f" ] && rm -f "$f"; done rm -f build_app.log diff --git a/setup/clean.bat b/setup/clean.bat index 8ea660ec..c743d6f0 100644 --- a/setup/clean.bat +++ b/setup/clean.bat @@ -1,7 +1,7 @@ @echo off setlocal cd /d "%~dp0.." -for %%p in (frontend\dist backend\build backend\dist-engine src-tauri\target src-tauri\gen) do if exist %%p rmdir /s /q %%p +for %%p in (frontend\dist backend\build backend\dist-engine src-tauri\target src-tauri\gen src-tauri\engine) do if exist %%p rmdir /s /q %%p for /d /r backend %%d in (__pycache__) do if exist "%%d" rmdir /s /q "%%d" del /q src-tauri\binaries\formchem-engine-* 2>nul del /q build_app.log 2>nul From 76eb1f457f050de49f2564e570b8ff1870eea703 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:35:48 -0500 Subject: [PATCH 009/357] build(setup): desktop check reports a macOS engine folder the bundle cannot carry (0.7.0) Tauri copies resources file by file, dropping linked folders and breaking framework signatures, so desktop_check now fails on a src-tauri/engine with no program, symbolic links or a .framework and points at ./formchem freeze. --- setup/desktop_check | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/setup/desktop_check b/setup/desktop_check index 8e1eebb7..bee31476 100755 --- a/setup/desktop_check +++ b/setup/desktop_check @@ -53,6 +53,14 @@ else warn "could not read the Tauri CLI or crate version; run ./formchem install" fi +if [ "$(fc_os)" = macos ] && [ -d src-tauri/engine ]; then + if [ ! -x src-tauri/engine/formchem-engine ]; then + fail "src-tauri/engine has no formchem-engine program; run ./formchem freeze" + elif [ -n "$(find src-tauri/engine -type l | head -1)" ] || [ -n "$(find src-tauri/engine -name '*.framework' | head -1)" ]; then + fail "src-tauri/engine holds symbolic links or a .framework, which the app bundle cannot carry; run ./formchem freeze" + fi +fi + if [ "$bad" -ne 0 ]; then fc_say "fix the problems above, then run ./formchem desktop build again" exit 1 From 09a4371fa5395c84cce097da862f68816abba54d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:35:52 -0500 Subject: [PATCH 010/357] docs(cli): say where ./formchem freeze puts the engine on macOS (0.7.0) On macOS the freeze now writes the one-folder engine to src-tauri/engine, so the help line no longer calls it only a sidecar binary. --- formchem | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/formchem b/formchem index b2f41818..9cf0e09f 100755 --- a/formchem +++ b/formchem @@ -16,7 +16,7 @@ usage: ./formchem [command] [options] frontend boot the frontend only build production build of the frontend into frontend/dist serve serve the built frontend from the backend on 127.0.0.1:8220 - freeze freeze the backend into the Tauri sidecar binary formchem-engine + freeze freeze the backend into the desktop engine formchem-engine (src-tauri/engine on macOS, the sidecar binary elsewhere) desktop dev|build|check run, bundle (the same as ./build_app, takes --config FILE|JSON) or check the toolchain for the desktop app doctor check the toolchain, installs and ports counts [--check] the README's code sizes (--check: exit 1 if README.md has drifted) From 2d187eb3661fb516a7d1f4826882348998828eb0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:43:36 -0500 Subject: [PATCH 011/357] feat(canvas): keep the dark page state in one module (0.7.0) The dark page is on unless formchem.darkPage holds 0, mirrors itself on the root as data-page-dark, follows other windows through the storage event and owns the picture re-inversion filters. --- frontend/src/canvas/dark-page.ts | 61 ++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 frontend/src/canvas/dark-page.ts diff --git a/frontend/src/canvas/dark-page.ts b/frontend/src/canvas/dark-page.ts new file mode 100644 index 00000000..f4f7c90b --- /dev/null +++ b/frontend/src/canvas/dark-page.ts @@ -0,0 +1,61 @@ +import { el } from '../ui/dom'; + +export const DARK_PAGE_KEY = 'formchem.darkPage'; +const ATTR = 'data-page-dark'; + +const listeners = new Set<(on: boolean) => void>(); +let wired = false; + +function stored(): boolean { + try { return localStorage.getItem(DARK_PAGE_KEY) !== '0'; } catch { return true; } +} + +function paint(on: boolean): boolean { + const root = document.documentElement; + if (root.hasAttribute(ATTR) === on) return false; + if (on) root.setAttribute(ATTR, ''); + else root.removeAttribute(ATTR); + return true; +} + +function changed(on: boolean): void { + for (const fn of [...listeners]) fn(on); +} + +export function darkPageOn(): boolean { + return document.documentElement.hasAttribute(ATTR); +} + +export function setDarkPage(on: boolean): boolean { + try { localStorage.setItem(DARK_PAGE_KEY, on ? '1' : '0'); } catch { void 0; } + if (paint(on)) changed(on); + return on; +} + +export function toggleDarkPage(): boolean { + return setDarkPage(!darkPageOn()); +} + +export function onDarkPage(fn: (on: boolean) => void): () => void { + listeners.add(fn); + return () => { listeners.delete(fn); }; +} + +const UNDARK = '0.7175 -1.7875 -0.18 0 1.125 -0.5325 -0.5375 -0.18 0 1.125 -0.5325 -1.7875 1.07 0 1.125 0 0 0 1 0'; +const UNDARK_OLED = '0.574 -1.43 -0.144 0 1 -0.426 -0.43 -0.144 0 1 -0.426 -1.43 0.856 0 1 0 0 0 1 0'; + +function defs(): SVGSVGElement { + const filter = (id: string, values: string): string => ``; + return el(``) as unknown as SVGSVGElement; +} + +export function initDarkPage(host: Element): void { + if (wired) return; + wired = true; + host.appendChild(defs()); + if (paint(stored())) changed(darkPageOn()); + window.addEventListener('storage', (e) => { + if (e.key !== DARK_PAGE_KEY && e.key !== null) return; + if (paint(stored())) changed(darkPageOn()); + }); +} From e169b90ba40b59a63e6b69c39d1fc8eea4f3a14c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:43:36 -0500 Subject: [PATCH 012/357] refactor(render): draw the selection, hover, warning and preview marks in their own svg (0.7.0) The dark page filters the drawing svg as one box; with the marks in a sibling svg above it they keep their real accent and warning colours. --- frontend/src/canvas/render/renderer.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/frontend/src/canvas/render/renderer.ts b/frontend/src/canvas/render/renderer.ts index 43737e4a..b20da7d3 100644 --- a/frontend/src/canvas/render/renderer.ts +++ b/frontend/src/canvas/render/renderer.ts @@ -52,6 +52,7 @@ export interface FormChemRenderer extends Renderer { const LAYERS = ['page', 'objects', 'bonds', 'atoms', 'text', 'stereo', 'selection', 'hover', 'warnings', 'preview'] as const; type LayerName = (typeof LAYERS)[number]; +const MARK_LAYERS: ReadonlySet = new Set(['selection', 'hover', 'warnings', 'preview']); function effectiveDoc(state: RenderState): FormChemDocument { if (!state.preview?.length) return state.doc; @@ -146,6 +147,8 @@ export function shownStyle(style: Style, d: RenderDisplay | undefined): ShownSty export function createRenderer(): FormChemRenderer { let svg: SVGSVGElement | null = null; let root: SVGGElement | null = null; + let marksSvg: SVGSVGElement | null = null; + let marksRoot: SVGGElement | null = null; const layers = {} as Record; let pageRect: SVGRectElement | null = null; let pageId: Id | null = null; @@ -647,10 +650,15 @@ export function createRenderer(): FormChemRenderer { svg = el; svg.classList.add('fc-canvas'); root = svgEl('g', { class: 'fc-root' }); + if (svg.parentNode) { + marksSvg = svgEl('svg', { class: 'fc-canvas fc-canvas-marks', 'aria-hidden': 'true' }); + marksRoot = svgEl('g', { class: 'fc-root' }); + marksSvg.appendChild(marksRoot); + } for (const name of LAYERS) { const g = svgEl('g', { class: `fc-layer fc-layer-${name}` }); layers[name] = g; - root.appendChild(g); + (marksRoot && MARK_LAYERS.has(name) ? marksRoot : root).appendChild(g); } pageRect = svgEl('rect', { class: 'fc-page' }); layers.page.appendChild(pageRect); @@ -665,6 +673,7 @@ export function createRenderer(): FormChemRenderer { warnings = new MarkLayer(layers.warnings, 'fc-warn', 1.25); preview = new MarkLayer(layers.preview, 'fc-preview', 0.8); svg.appendChild(root); + if (marksSvg) svg.after(marksSvg); watchFonts(); if (last) render(last); }, @@ -676,7 +685,10 @@ export function createRenderer(): FormChemRenderer { if (!root || !svg) return; const tf = `translate(${fmt(v.x)} ${fmt(v.y)}) scale(${v.zoom})`; if (root.getAttribute('transform') !== tf) root.setAttribute('transform', tf); - svg.style.setProperty('--fc-zoom', String(v.zoom * (window.devicePixelRatio || 1))); + if (marksRoot && marksRoot.getAttribute('transform') !== tf) marksRoot.setAttribute('transform', tf); + const zoom = String(v.zoom * (window.devicePixelRatio || 1)); + svg.style.setProperty('--fc-zoom', zoom); + marksSvg?.style.setProperty('--fc-zoom', zoom); }, labelBox(frag: Id, atom: Id) { const b = frags.get(frag)?.atoms.get(atom)?.view.box; @@ -717,6 +729,9 @@ export function createRenderer(): FormChemRenderer { stereoInputs = []; chemMarks?.clear(); chemMarks = null; + marksSvg?.remove(); + marksSvg = null; + marksRoot = null; svg = null; root = null; pageRect = null; From 4f852693de88456348f19b3d307607e3f79e2b00 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:43:36 -0500 Subject: [PATCH 013/357] style(canvas): show the paper and drawing dark on screen when the dark page is on (0.7.0) One invert and hue-rotate filter on the paper and the drawing svg keeps element colours recognisable; pictures go through the inverse matrix, the text editor matches the page and print stays untouched. --- frontend/src/styles/canvas-view.css | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/frontend/src/styles/canvas-view.css b/frontend/src/styles/canvas-view.css index afc792f0..57ac4f07 100644 --- a/frontend/src/styles/canvas-view.css +++ b/frontend/src/styles/canvas-view.css @@ -10,8 +10,19 @@ background-size: var(--fc-grid-step, 9.6px) var(--fc-grid-step, 9.6px); background-position: -0.5px -0.5px; } -.fc-canvas-svg, .fc-canvas-overlay { position: absolute; inset: 0; display: block; width: 100%; height: 100%; overflow: visible; } -.fc-canvas-svg { z-index: var(--z-local-2); } +@media screen { + :root[data-page-dark] .fc-canvas-paper { box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.16), 0 10px 36px rgba(255, 255, 255, 0.4); } + :root[data-page-dark] .fc-canvas-paper, :root[data-page-dark] .fc-canvas-svg { filter: invert(0.9) hue-rotate(180deg); } + :root[data-page-dark][data-oled] .fc-canvas-paper, :root[data-page-dark][data-oled] .fc-canvas-svg { filter: invert(1) hue-rotate(180deg); } + :root[data-page-dark] .fc-canvas-svg image { filter: url(#fc-page-undark); } + :root[data-page-dark][data-oled] .fc-canvas-svg image { filter: url(#fc-page-undark-oled); } + :root[data-page-dark] .fc-text-edit { background: #1a1a1a; color: #e6e6e6; } + :root[data-page-dark][data-oled] .fc-text-edit { background: #000000; color: #ffffff; } +} +.fc-canvas-svg, .fc-canvas-marks, .fc-canvas-overlay { position: absolute; inset: 0; display: block; width: 100%; height: 100%; overflow: visible; } +.fc-canvas-svg, .fc-canvas-marks { z-index: var(--z-local-2); } +.fc-canvas-marks { pointer-events: none; } +.fc-canvas-defs { position: absolute; width: 0; height: 0; overflow: hidden; pointer-events: none; } .fc-canvas-svg .fc-layer-page { display: none; } .fc-canvas-overlay { z-index: var(--z-local-4); pointer-events: none; } .fc-canvas-band { fill: color-mix(in srgb, var(--fc-sel) 10%, transparent); stroke: var(--fc-sel); stroke-width: 1; stroke-dasharray: 4 3; vector-effect: non-scaling-stroke; } From 9d254269eadde6049f8afd2b594967e7636be598 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:43:36 -0500 Subject: [PATCH 014/357] feat(canvas): add the dark-page command with an on parameter (0.7.0) Agents and the palette can toggle or set the dark page; the command reports its checked state and refreshes menus when the page changes from any source. --- frontend/src/app/canvas-commands.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/frontend/src/app/canvas-commands.ts b/frontend/src/app/canvas-commands.ts index 0f410628..cee7a089 100644 --- a/frontend/src/app/canvas-commands.ts +++ b/frontend/src/app/canvas-commands.ts @@ -1,3 +1,4 @@ +import { darkPageOn, initDarkPage, onDarkPage, setDarkPage, toggleDarkPage } from '../canvas/dark-page'; import { fragmentsTouched, isEmpty } from '../canvas/selection'; import { align, distribute, flipHorizontal, flipVertical, rotate90, type AlignHow } from '../canvas/tools'; import { atomsOfSelection, commitDraft, draftFor } from '../canvas/tools/common'; @@ -15,6 +16,7 @@ import { post } from '../io/api'; import { setAnalysisOpen } from '../ui/analysis-panel'; import type { FindBar } from '../ui/find-bar'; import { toast } from '../ui/toast'; +import { commandStateChanged } from './commands-shell'; export interface CanvasCommandDeps { view: CanvasView; @@ -30,6 +32,16 @@ function rulerCommands(rulers: Rulers): CommandDef[] { ]; } +function darkPageCommand(): CommandDef { + return { + id: 'dark-page', label: () => t('Dark Page'), group: 'View', icon: 'moon', + description: 'Shows the drawing page dark with light bonds and labels, keeping element colours recognisable and pictures as they are. It only changes how the page looks on screen in this window and the others on this device; exports, printing and copies keep the real colours. On by default; the choice is remembered.', + params: { on: { type: 'boolean', description: 'Turn the dark page on or off instead of toggling' } }, + checked: darkPageOn, + run: (p) => ({ on: typeof p?.on === 'boolean' ? setDarkPage(p.on) : toggleDarkPage() }), + }; +} + function findCommands(bar: FindBar, open: () => boolean): CommandDef[] { const NEED_DRAWING = 'Open or create a drawing first'; const NEED_QUERY = 'Open the find bar and type what to find first'; @@ -184,6 +196,10 @@ export function registerCanvasCommands(deps: CanvasCommandDeps): () => void { tool('add-reaction-arrow', 'Add Reaction Arrow', 'arrow', 'arrow-forward', 'Reaction'), ...(deps.find ? findCommands(deps.find, open) : []), ...(deps.rulers ? rulerCommands(deps.rulers) : []), + darkPageCommand(), ]; - return commands.register(...defs); + initDarkPage(view.root); + const offDark = onDarkPage(() => commandStateChanged()); + const off = commands.register(...defs); + return () => { offDark(); off(); }; } From fb3ad336785ca6515bfc7e4b9670cd997e60d122 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:43:36 -0500 Subject: [PATCH 015/357] feat(menus): list Dark Page beside Show Grid in the View and canvas menus (0.7.0) The native macOS menu is built from the same definitions, so it gets the checked item too. --- frontend/src/app/menus.ts | 2 +- frontend/src/canvas/context.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/app/menus.ts b/frontend/src/app/menus.ts index 966e03aa..031d843f 100644 --- a/frontend/src/app/menus.ts +++ b/frontend/src/app/menus.ts @@ -20,7 +20,7 @@ export function buildMenus(extensionItems?: MenuSource, recentItems?: MenuSource return [ { label: 'File', items: () => ['home', 'new-document', 'open', recent(), '-', 'new-window', 'close-window', 'close-document', '-', 'save', 'save-as', 'save-copy', '-', 'import', EXPORT, 'print', '-', 'preferences'] }, { label: 'Edit', items: ['undo', 'redo', '-', 'cut', 'copy', COPY_AS, 'paste', 'duplicate', 'delete', '-', 'select-all', '-', 'find', 'find-next', 'find-previous', 'replace', ...CHEM_MENU_ITEMS.edit] }, - { label: 'View', items: () => ['zoom-in', 'zoom-out', 'zoom-fit', 'zoom-100', '-', 'show-grid', 'show-rulers', 'clear-guides', '-', ...CHEM_MENU_ITEMS.view, '-', 'toggle-analysis', 'show-stoichiometry', '-', 'view-terminal', 'new-terminal', 'claude-code', 'agent-chat', 'command-palette', ...(isMacDesktop() ? ['-', 'menus-in-window'] : [])] }, + { label: 'View', items: () => ['zoom-in', 'zoom-out', 'zoom-fit', 'zoom-100', '-', 'show-grid', 'dark-page', 'show-rulers', 'clear-guides', '-', ...CHEM_MENU_ITEMS.view, '-', 'toggle-analysis', 'show-stoichiometry', '-', 'view-terminal', 'new-terminal', 'claude-code', 'agent-chat', 'command-palette', ...(isMacDesktop() ? ['-', 'menus-in-window'] : [])] }, { label: 'Insert', items: ['insert-smiles', 'insert-name', 'insert-template', '-', 'insert-text', 'insert-arrow', 'insert-shape', 'insert-table', 'insert-image'] }, { label: 'Structure', items: ['clean-structure', 'layout-structure', '-', ...CHEM_MENU_ITEMS.structure, '-', 'check-structure', 'compute-properties', '-', 'flip-horizontal', 'flip-vertical'] }, { label: 'Reaction', items: ['add-reaction-arrow', 'perceive-reactions', 'set-reaction-roles', '-', 'map-atoms', 'clear-mapping', '-', 'check-reaction', 'balance-reaction', '-', 'show-stoichiometry', 'stoichiometry-grid', '-', 'paste-reaction', REACTION_COPY, REACTION_EXPORT] }, diff --git a/frontend/src/canvas/context.ts b/frontend/src/canvas/context.ts index 373fde75..54d0e960 100644 --- a/frontend/src/canvas/context.ts +++ b/frontend/src/canvas/context.ts @@ -254,7 +254,7 @@ function backgroundItems(host: CanvasMenuHost, temp: Temp[]): MenuItem[] { const zout = cmdOr('zoom-out', temp, { label: () => t('Zoom Out'), run: () => host.zoomOut() }); const fit = cmdOr('zoom-fit', temp, { label: () => t('Fit to Window'), run: () => host.zoomFit() }); const actual = cmdOr('zoom-100', temp, { label: () => t('Actual Size'), run: () => host.zoom100() }); - return ['paste', all, '-', zin, zout, fit, actual, '-', 'show-grid']; + return ['paste', all, '-', zin, zout, fit, actual, '-', 'show-grid', 'dark-page']; } export function canvasMenuItems(host: CanvasMenuHost, hit: Hit): { items: MenuItem[]; temp: Temp[] } { From 7ff9f0ec4503c5ec3d6e05bb34c6d28889b57d23 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:43:36 -0500 Subject: [PATCH 016/357] feat(prefs): add a Dark page switch to the Interface section (0.7.0) The switch follows the View menu and the command while Preferences is open. --- frontend/src/ui/prefs/index.ts | 6 ++++++ frontend/src/ui/prefs/sections.ts | 1 + 2 files changed, 7 insertions(+) diff --git a/frontend/src/ui/prefs/index.ts b/frontend/src/ui/prefs/index.ts index 862f768d..eb49397b 100644 --- a/frontend/src/ui/prefs/index.ts +++ b/frontend/src/ui/prefs/index.ts @@ -1,3 +1,4 @@ +import { darkPageOn, onDarkPage, setDarkPage } from '../../canvas/dark-page'; import { commands } from '../../commands/registry'; import { setLanguage, storedLanguage, t } from '../../i18n'; import { confirmAction, Dialog, segOn, segSet } from '../dialogs'; @@ -29,6 +30,7 @@ class PreferencesDialog extends Dialog { private readonly claudeFields: HTMLInputElement[]; private readonly programFields: HTMLInputElement[]; private readonly menus: HTMLInputElement; + private readonly darkPage: HTMLInputElement; private readonly wire: { rail: HTMLElement; port: HTMLElement; shade: SVGPathElement; line: SVGPathElement }; private current = ''; private spyRaf = 0; @@ -99,6 +101,7 @@ class PreferencesDialog extends Dialog { this.seal = q(box, '.fc-prefs-seal'); this.claude = q(box, '.fc-prefs-claude'); this.menus = q(box, '[data-local="menus"]'); + this.darkPage = q(box, '[data-local="darkPage"]'); this.prefInputs = qa(box, '[data-pref]'); this.claudeFields = qa(box, '[data-c]'); this.programFields = qa(box, '[data-p]'); @@ -135,6 +138,8 @@ class PreferencesDialog extends Dialog { setLocal(MENUS_IN_WINDOW_KEY, this.menus.checked ? '1' : '0'); toast(t('Menus move the next time FormChem starts.')); }); + this.darkPage.addEventListener('change', () => { setDarkPage(this.darkPage.checked); }); + onDarkPage((on) => setChecked(this.darkPage, on)); } private wirePrefs(): void { @@ -192,6 +197,7 @@ class PreferencesDialog extends Dialog { setValue(this.lang, storedLanguage()); segSet(this.density, readDensity()); setChecked(this.menus, local(MENUS_IN_WINDOW_KEY) === '1'); + setChecked(this.darkPage, darkPageOn()); } private syncPrefs(): void { diff --git a/frontend/src/ui/prefs/sections.ts b/frontend/src/ui/prefs/sections.ts index b2ba3a54..f56f52fc 100644 --- a/frontend/src/ui/prefs/sections.ts +++ b/frontend/src/ui/prefs/sections.ts @@ -40,6 +40,7 @@ function iface(): string { return grp('Theme', `
${h('Theme')}
${themeSwatchesHtml(c.theme, c.accentColor)}
${h('Accent')}
${accents}
` + note('Theme and accent are shared with the other Form apps on this device.')) + + grp('Page', check('darkPage', 'Dark page', 'data-local') + note('Shows the drawing page dark with light bonds and labels on screen. Exports, printing and copies keep the real colours.')) + grp('Language and Density', `
${h('Density')}
`) + `

${h('Menus')}

${check('menus', 'Menus in the window', 'data-local')}${note('On the macOS desktop app the menus sit in the system menu bar. On, they show in the window instead, from the next start.')}
`; From 00592e4d3f44fbc529bb7c6ce4458cf752f6b58c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:43:36 -0500 Subject: [PATCH 017/357] feat(window): set the dark page before first paint (0.7.0) The boot script reads formchem.darkPage with the theme, so a drawing never flashes white on start. --- frontend/index.html | 3 +++ 1 file changed, 3 insertions(+) diff --git a/frontend/index.html b/frontend/index.html index 3b93a2cf..7a2710d0 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -57,6 +57,9 @@ try { tauriMac = '__TAURI_INTERNALS__' in window && /Mac/.test(navigator.platform); } catch (e) {} if (tauriMac) root.classList.add('has-overlay-titlebar'); try { if (tauriMac && localStorage.getItem('formchem.menusInWindow') !== '1') root.classList.add('has-native-menus'); } catch (e) {} + var darkPage = true; + try { darkPage = localStorage.getItem('formchem.darkPage') !== '0'; } catch (e) {} + if (darkPage) root.setAttribute('data-page-dark', ''); for (i = 0; i < NAMES.length; i++) root.style.setProperty(NAMES[i], p[i]); root.style.setProperty('--bg-node', p[10] || p[1]); root.style.setProperty('--shadow-lg', LIGHT[theme] ? '0 4px 14px rgba(96, 90, 70, 0.16)' : '0 8px 32px rgba(0, 0, 0, 0.5)'); From b6706dd4aa7ecee4e4b73ca59baba1beb0ae7f18 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:46:06 -0500 Subject: [PATCH 018/357] docs(canvas): say pictures stay close to their real colours under the dark page (0.7.0) Very saturated light colours in pictures cannot survive the page filter exactly, so agents are told what to expect. --- frontend/src/app/canvas-commands.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/app/canvas-commands.ts b/frontend/src/app/canvas-commands.ts index cee7a089..1906b28b 100644 --- a/frontend/src/app/canvas-commands.ts +++ b/frontend/src/app/canvas-commands.ts @@ -35,7 +35,7 @@ function rulerCommands(rulers: Rulers): CommandDef[] { function darkPageCommand(): CommandDef { return { id: 'dark-page', label: () => t('Dark Page'), group: 'View', icon: 'moon', - description: 'Shows the drawing page dark with light bonds and labels, keeping element colours recognisable and pictures as they are. It only changes how the page looks on screen in this window and the others on this device; exports, printing and copies keep the real colours. On by default; the choice is remembered.', + description: 'Shows the drawing page dark with light bonds and labels, keeping element colours recognisable and pictures close to their real colours. It only changes how the page looks on screen in this window and the others on this device; exports, printing and copies keep the real colours. On by default; the choice is remembered.', params: { on: { type: 'boolean', description: 'Turn the dark page on or off instead of toggling' } }, checked: darkPageOn, run: (p) => ({ on: typeof p?.on === 'boolean' ? setDarkPage(p.on) : toggleDarkPage() }), From 648d3225af3b62c203bc260c7e9cdee7ecd70f84 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:34:33 -0500 Subject: [PATCH 019/357] refactor(canvas): share the box resize step of the object handles as setBox (0.7.0) Scaling a selection resizes shapes, images, brackets, TLC plates and tables the same way the 0.5.0 corner handles do, so the step becomes one reusable function. --- frontend/src/canvas/tools/handles.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/frontend/src/canvas/tools/handles.ts b/frontend/src/canvas/tools/handles.ts index 934a2e02..e8ef394a 100644 --- a/frontend/src/canvas/tools/handles.ts +++ b/frontend/src/canvas/tools/handles.ts @@ -114,7 +114,11 @@ export function dragHandle(d: Draft, h: ObjectHandle, p: Point, m: HandleDrag): if (!BOXED.has(o.kind) || h.kind.length > 2 || !/^[nsew]+$/.test(h.kind)) return; const r = objectBounds(d.doc, o); if (!r) return; - const next = resizeBox(r, h.kind as BoxHandle, p, m.shift || o.kind === 'image'); + setBox(d, o, r, resizeBox(r, h.kind as BoxHandle, p, m.shift || o.kind === 'image')); +} + +export function setBox(d: Draft, o: DocObject, r: Rect, next: Rect): void { + const set = (key: string, value: unknown): void => d.push({ op: 'set', path: objectPath(o.id, key), value }); if (o.kind === 'table') { const kx = next.w / Math.max(r.w, 1e-9); const ky = next.h / Math.max(r.h, 1e-9); @@ -124,6 +128,7 @@ export function dragHandle(d: Draft, h: ObjectHandle, p: Point, m: HandleDrag): set('rows', o.rows.map((row) => ({ ...row, h: row.h * ky }))); return; } + if (!BOXED.has(o.kind)) return; set('x', next.x); set('y', next.y); set('w', next.w); From 00878a387d4d25d33005a86b0190c0be19398f5d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:35:28 -0500 Subject: [PATCH 020/357] feat(canvas): scale a selection with its sizes, styles and bond length (0.7.0) The old scaleSelection only moved coordinates; the new scale module also resizes boxes, plus signs, orbitals and arrows, keeps the fragment bond length in step, and optionally scales line widths and label and text fonts through per-object style overrides. --- frontend/src/canvas/tools/index.ts | 1 + frontend/src/canvas/tools/scale.ts | 266 +++++++++++++++++++++++++ frontend/src/canvas/tools/transform.ts | 9 - 3 files changed, 267 insertions(+), 9 deletions(-) create mode 100644 frontend/src/canvas/tools/scale.ts diff --git a/frontend/src/canvas/tools/index.ts b/frontend/src/canvas/tools/index.ts index 99aebd1f..446a5653 100644 --- a/frontend/src/canvas/tools/index.ts +++ b/frontend/src/canvas/tools/index.ts @@ -137,3 +137,4 @@ export { TlcTool, addSpot, rfAt } from './tlc'; export { HandTool, ZoomTool } from './view'; export { HOVER_KEY_MAP, hoverKey, TWO_LETTER_MS } from './hotkeys'; export * from './transform'; +export * from './scale'; diff --git a/frontend/src/canvas/tools/scale.ts b/frontend/src/canvas/tools/scale.ts new file mode 100644 index 00000000..61a23f09 --- /dev/null +++ b/frontend/src/canvas/tools/scale.ts @@ -0,0 +1,266 @@ +import { isFragment, resolveStyle, type DocObject, type FormChemDocument, type Font, type Id, type Point, type Run, type Style } from '../../engine/model'; +import { objectPath } from '../../engine/ops'; +import { dist, dot, rectCentre, sub, type Rect } from '../geom'; +import { selectionKey, type Selection, type ToolContext } from '../types'; +import { atomsOfSelection, commitDraft, draftFor, makeSelection, objectBounds, selectionEmpty, topLevelObjects } from './common'; +import type { Draft } from './draft'; +import { setBox } from './handles'; +import { mapSelection, selectionBounds } from './transform'; + +export const SCALE_MIN = 0.05; +export const SCALE_MAX = 20; +export const SCALE_STEP = 1.1; +export const SCALE_HANDLE_PAD_PX = 8; +const MIN_EXTENT = 0.5; +const EPS = 1e-3; + +export type ScaleCorner = 'nw' | 'ne' | 'se' | 'sw'; +export interface ScaleHandle { corner: ScaleCorner; fx: 0 | 1; fy: 0 | 1; base: Point; at: Point } +export interface ScaleOpts { labels: boolean } +export interface ScaleResult { k: number; bondLength: number | null } + +const CORNERS: [ScaleCorner, 0 | 1, 0 | 1][] = [['nw', 0, 0], ['ne', 1, 0], ['se', 1, 1], ['sw', 0, 1]]; + +export const SCALE_CURSORS: Record = { nw: 'nwse-resize', se: 'nwse-resize', ne: 'nesw-resize', sw: 'nesw-resize' }; + +type StyleKey = 'bond_length' | 'line_width' | 'bold_width' | 'hash_spacing' | 'margin_width' | 'bond_spacing_abs' | 'label_font' | 'caption_font'; + +const GEOMETRY: Partial> = { fragment: ['bond_length'] }; +const LABELS: Partial> = { + fragment: ['line_width', 'bold_width', 'hash_spacing', 'margin_width', 'bond_spacing_abs', 'label_font'], + text: ['caption_font'], + caption: ['caption_font'], + table: ['line_width', 'caption_font'], + tlc: ['line_width', 'caption_font'], + bracket: ['bond_length', 'line_width', 'bold_width', 'caption_font'], + arrow: ['bond_length', 'line_width', 'bold_width'], + line: ['line_width'], + shape: ['line_width'], + plus: ['line_width'], + orbital: ['line_width'], +}; + +const round = (v: number): number => Math.round(v * 1000) / 1000; +export const clampScale = (k: number): number => Math.min(SCALE_MAX, Math.max(SCALE_MIN, k)); + +function holdsFragment(doc: FormChemDocument, id: Id, depth = 0): boolean { + const o = doc.objects[id]; + if (!o || depth > 32) return false; + if (isFragment(o)) return Object.keys(o.atoms).length > 0; + return o.kind === 'group' && o.children.some((c) => holdsFragment(doc, c, depth + 1)); +} + +export function hasStructure(doc: FormChemDocument, sel: Selection): boolean { + return sel.atoms.size > 0 || sel.bonds.size > 0 || [...sel.objects].some((id) => holdsFragment(doc, id)); +} + +export function fragmentAtoms(doc: FormChemDocument, sel: Selection): Map> { + const out = atomsOfSelection(doc, sel); + const walk = (id: Id, depth: number): void => { + const o = doc.objects[id]; + if (!o || depth > 32) return; + if (isFragment(o)) out.set(id, new Set(Object.keys(o.atoms))); + else if (o.kind === 'group') for (const c of o.children) walk(c, depth + 1); + }; + for (const id of sel.objects) { + const o = doc.objects[id]; + if (o?.kind === 'group') walk(id, 0); + } + return out; +} + +export function selectionBondLength(doc: FormChemDocument, sel: Selection): number | null { + const lens: number[] = []; + let fallback: number | null = null; + for (const [fid, atoms] of fragmentAtoms(doc, sel)) { + const f = doc.objects[fid]; + if (!isFragment(f)) continue; + fallback ??= resolveStyle(doc, f).bond_length; + for (const b of Object.values(f.bonds)) { + const a = f.atoms[b.a], c = f.atoms[b.b]; + if (a && c && atoms.has(b.a) && atoms.has(b.b)) lens.push(Math.hypot(a.x - c.x, a.y - c.y)); + } + } + if (!lens.length) return fallback; + lens.sort((a, b) => a - b); + const m = lens.length >> 1; + return lens.length % 2 ? lens[m] : (lens[m - 1] + lens[m]) / 2; +} + +export function scaleHandles(doc: FormChemDocument, sel: Selection, zoom: number): ScaleHandle[] { + if (!hasStructure(doc, sel)) return []; + const r = selectionBounds(doc, sel); + if (!r || Math.max(r.w, r.h) < MIN_EXTENT) return []; + const pad = SCALE_HANDLE_PAD_PX / Math.max(zoom, 1e-6); + return CORNERS.map(([corner, fx, fy]) => { + const base: Point = [r.x + r.w * fx, r.y + r.h * fy]; + return { corner, fx, fy, base, at: [base[0] + (fx ? pad : -pad), base[1] + (fy ? pad : -pad)] }; + }); +} + +export function scaleHandleAt(doc: FormChemDocument, sel: Selection, p: Point, zoom: number, slopPx: number): ScaleHandle | null { + let best: ScaleHandle | null = null; + let bestD = slopPx / Math.max(zoom, 1e-6); + for (const h of scaleHandles(doc, sel, zoom)) { + const d = dist(h.at, p); + if (d <= bestD) { bestD = d; best = h; } + } + return best; +} + +export function scaleFromDrag(h: ScaleHandle, r: Rect, p: Point, aboutCentre: boolean, coarse: boolean): { k: number; centre: Point } { + const centre: Point = aboutCentre ? rectCentre(r) : [r.x + r.w * (1 - h.fx), r.y + r.h * (1 - h.fy)]; + const v = sub(h.base, centre); + const vv = dot(v, v); + if (vv < 1e-9) return { k: 1, centre }; + const q = sub(sub(p, sub(h.at, h.base)), centre); + const raw = dot(q, v) / vv; + const k = coarse ? Math.round(raw * 10) / 10 : Math.round(raw * 100) / 100; + return { k: clampScale(k), centre }; +} + +function restyle(d: Draft, base: FormChemDocument, obj: DocObject, k: number, labels: boolean): void { + const keys = [...(GEOMETRY[obj.kind] ?? []), ...(labels ? LABELS[obj.kind] ?? [] : [])]; + if (!keys.length) return; + const own = resolveStyle(base, obj); + const plain = resolveStyle(base); + const next: Record = { ...(obj.style ?? {}) }; + for (const key of keys) { + if (key === 'label_font' || key === 'caption_font') { + const f: Font = own[key]; + const size = round(f.size * k); + const ref = plain[key]; + if (Math.abs(size - ref.size) < EPS && f.family === ref.family && !!f.bold === !!ref.bold && !!f.italic === !!ref.italic) delete next[key]; + else next[key] = { ...f, size }; + continue; + } + const cur = own[key as keyof Style] as number | undefined; + if (cur === undefined) continue; + const v = round(cur * k); + const ref = plain[key as keyof Style] as number | undefined; + if (ref !== undefined && Math.abs(v - ref) < EPS) delete next[key]; + else next[key] = v; + } + const path = objectPath(obj.id, 'style'); + if (Object.keys(next).length) d.push({ op: 'set', path, value: next }); + else if (obj.style) d.push({ op: 'set', path }); +} + +function scaledRuns(runs: Run[] | undefined, k: number): Run[] | null { + if (!runs?.some((r) => r.size)) return null; + return runs.map((r) => (r.size ? { ...r, size: round(r.size * k) } : r)); +} + +function resizeObject(d: Draft, base: FormChemDocument, id: Id, k: number, labels: boolean, depth = 0): void { + const was = base.objects[id]; + const cur = d.doc.objects[id]; + if (!was || !cur || depth > 32 || isFragment(was)) return; + const set = (key: string, value: unknown): void => d.push({ op: 'set', path: objectPath(id, key), value }); + switch (cur.kind) { + case 'group': + for (const c of cur.children) resizeObject(d, base, c, k, labels, depth + 1); + return; + case 'shape': + case 'image': + case 'bracket': + case 'tlc': + case 'table': { + const r = objectBounds(d.doc, cur); + if (!r) break; + const [cx, cy] = rectCentre(r); + const w = r.w * k, h = r.h * k; + setBox(d, cur, r, { x: cx - w / 2, y: cy - h / 2, w, h }); + if (cur.kind === 'shape' && cur.radius) set('radius', cur.radius * k); + if (labels && cur.kind === 'shape' && cur.stroke?.width) set('stroke', { ...cur.stroke, width: round(cur.stroke.width * k) }); + if (labels && cur.kind === 'table') { + if (cur.padding) set('padding', round(cur.padding * k)); + const now = d.doc.objects[id]; + if (now?.kind === 'table' && now.rows.some((row) => row.cells.some((c) => c.runs?.some((r) => r.size)))) { + set('rows', now.rows.map((row) => ({ ...row, cells: row.cells.map((c) => (c.runs ? { ...c, runs: scaledRuns(c.runs, k) ?? c.runs } : c)) }))); + } + } + break; + } + case 'text': + case 'caption': { + if (!labels) break; + const r = objectBounds(d.doc, cur); + if (!r) break; + const anchored = cur.kind === 'caption' && !!cur.target && !!cur.offset; + const runs = scaledRuns(cur.runs, k); + if (runs) set('runs', runs); + if (cur.w !== undefined) set('w', cur.w * k); + set('x', r.x + r.w / 2 - (r.w * k) / 2); + set('y', anchored ? r.y : r.y + r.h / 2 - (r.h * k) / 2); + break; + } + case 'plus': + set('size', round((cur.size ?? 0.6 * resolveStyle(base, was).bond_length) * k)); + break; + case 'orbital': + set('size', round(cur.size * k)); + break; + case 'arrow': + if (cur.shorter) set('shorter', cur.shorter * k); + if (labels) { + if (cur.head_length) set('head_length', round(cur.head_length * k)); + if (cur.head_width) set('head_width', round(cur.head_width * k)); + if (cur.line_width) set('line_width', round(cur.line_width * k)); + } + break; + case 'line': + if (labels && cur.stroke?.width) set('stroke', { ...cur.stroke, width: round(cur.stroke.width * k) }); + break; + default: + break; + } + restyle(d, base, was, k, labels); +} + +export function scaleSelection(d: Draft, sel: Selection, k: number, centre: Point | undefined, opts: ScaleOpts): void { + const r = selectionBounds(d.doc, sel); + if (!r || !(k > 0) || Math.abs(k - 1) < 1e-9) return; + const c = centre ?? rectCentre(r); + const base = d.doc; + mapSelection(d, sel, (p) => [c[0] + (p[0] - c[0]) * k, c[1] + (p[1] - c[1]) * k]); + for (const [fid, atoms] of fragmentAtoms(base, sel)) { + const f = base.objects[fid]; + if (isFragment(f) && atoms.size === Object.keys(f.atoms).length) restyle(d, base, f, k, opts.labels); + } + for (const id of sel.objects) resizeObject(d, base, id, k, opts.labels); +} + +export function scaleTargets(doc: FormChemDocument, sel: Selection, page: Id): Selection[] { + if (!selectionEmpty(sel)) return [sel]; + const out: Selection[] = []; + for (const id of topLevelObjects(doc, page)) { + const o = doc.objects[id]; + if (!o || o.locked || o.hidden || !holdsFragment(doc, id)) continue; + if (isFragment(o)) out.push(makeSelection(Object.keys(o.atoms).map((a) => selectionKey(id, a)), Object.keys(o.bonds).map((b) => selectionKey(id, b)))); + else out.push(makeSelection([], [], [id])); + } + return out; +} + +export function targetsBondLength(doc: FormChemDocument, targets: Selection[]): number | null { + if (!targets.length) return null; + const all = makeSelection(targets.flatMap((s) => [...s.atoms]), targets.flatMap((s) => [...s.bonds]), targets.flatMap((s) => [...s.objects])); + return selectionBondLength(doc, all); +} + +export function scaleBy(ctx: ToolContext, how: { k?: number; bondLength?: number }, opts: ScaleOpts, label = 'Scale'): ScaleResult | null { + const doc = ctx.client.doc; + const targets = scaleTargets(doc, ctx.selection(), ctx.page()); + if (!targets.length) return null; + const was = targetsBondLength(doc, targets); + let k = how.k ?? (how.bondLength && was ? how.bondLength / was : 1); + if (!Number.isFinite(k) || k <= 0) return null; + k = clampScale(k); + const d = draftFor(ctx); + for (const s of targets) { + const r = selectionBounds(d.doc, s); + if (r) scaleSelection(d, s, k, rectCentre(r), opts); + } + if (!commitDraft(ctx, label, d)) return null; + return { k, bondLength: was === null ? null : was * k }; +} diff --git a/frontend/src/canvas/tools/transform.ts b/frontend/src/canvas/tools/transform.ts index 6c177acc..ceb67638 100644 --- a/frontend/src/canvas/tools/transform.ts +++ b/frontend/src/canvas/tools/transform.ts @@ -202,13 +202,6 @@ export function flipSelection(d: Draft, sel: Selection, axis: 'h' | 'v', opts: { mapSelection(d, sel, (p) => flipAbout(p, c, axis), { mirror: axis, invertWedges: !opts.keepWedges }); } -export function scaleSelection(d: Draft, sel: Selection, k: number, centre?: Point): void { - const r = selectionBounds(d.doc, sel); - if (!r || k <= 0 || k === 1) return; - const c = centre ?? rectCentre(r); - mapSelection(d, sel, (p) => [c[0] + (p[0] - c[0]) * k, c[1] + (p[1] - c[1]) * k]); -} - export type AlignHow = 'left' | 'centre' | 'right' | 'top' | 'middle' | 'bottom'; function moveUnit(d: Draft, u: Unit, dx: number, dy: number): void { @@ -267,8 +260,6 @@ export const rotate90 = (ctx: ToolContext, dir: 'left' | 'right'): boolean => export const rotateBy = (ctx: ToolContext, deg: number): boolean => run(ctx, 'Rotate', (d, s) => rotateSelection(d, s, deg)); -export const scaleBy = (ctx: ToolContext, k: number): boolean => run(ctx, 'Scale', (d, s) => scaleSelection(d, s, k)); - export const align = (ctx: ToolContext, how: AlignHow): boolean => run(ctx, 'Align', (d, s) => alignSelection(d, s, how)); export const distribute = (ctx: ToolContext, axis: 'h' | 'v'): boolean => run(ctx, 'Distribute', (d, s) => distributeSelection(d, s, axis)); From ece9e1b9d89aa07cccf9a6b49482dde3772773a4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:35:43 -0500 Subject: [PATCH 021/357] feat(engine): accept the scaleLabels preference in the settings store (0.7.0) The window keeps whether scaling a structure also scales its labels and text as an engine preference so every window and a restart see the same choice. --- backend/app/routers/system.py | 1 + 1 file changed, 1 insertion(+) diff --git a/backend/app/routers/system.py b/backend/app/routers/system.py index bcbf9b38..71998d71 100644 --- a/backend/app/routers/system.py +++ b/backend/app/routers/system.py @@ -19,6 +19,7 @@ "lineWidth": ("num", 0.1, 8.0), "boldWidth": ("num", 0.5, 16.0), "labelSize": ("num", 4.0, 48.0), + "scaleLabels": ("bool",), "colorAtoms": ("bool",), "carbonLabels": ("enum", ("none", "terminal", "all")), "valenceWarnings": ("bool",), From 294022b7132cd18cf9157b36bb8188c13db86fac Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:35:43 -0500 Subject: [PATCH 022/357] feat(prefs): add Scale labels and text with structures, on by default (0.7.0) The owner wants a scaled structure to look visibly larger, so labels, line widths and text grow with it unless this Drawing preference is turned off. --- frontend/src/ui/prefs/sections.ts | 2 ++ frontend/src/ui/prefs/store.ts | 1 + 2 files changed, 3 insertions(+) diff --git a/frontend/src/ui/prefs/sections.ts b/frontend/src/ui/prefs/sections.ts index f56f52fc..b6753819 100644 --- a/frontend/src/ui/prefs/sections.ts +++ b/frontend/src/ui/prefs/sections.ts @@ -50,6 +50,8 @@ function drawing(): string { return grp('Style', pick('drawStyle', 'Default style', [['journal1996', 'Journal standard (1996)'], ['journalCompact', 'Journal variant B'], ['presentation', 'Large screen'], ['largePrint', 'New document']]) + num('bondLength', 'Bond length', 'pt', 4, 72, 0.1) + num('lineWidth', 'Line width', 'pt', 0.1, 8, 0.05) + num('boldWidth', 'Bold width', 'pt', 0.5, 16, 0.1) + num('labelSize', 'Label font size', 'pt', 4, 48, 0.5) + note('New drawings start from the default style with these values on top. Choosing a style fills them in from it.')) + + grp('Scaling', check('scaleLabels', 'Scale labels and text with structures') + + note('Arrange > Scale and the corner handles make the drawing itself larger or smaller. On, line widths, atom labels and text grow with it; off, they keep the drawing style. Zoom only changes the view.')) + grp('Atoms', check('colorAtoms', 'Colour atoms by element') + pick('carbonLabels', 'Show carbon labels', [['none', 'None'], ['terminal', 'Terminal carbons'], ['all', 'All carbons']])); } diff --git a/frontend/src/ui/prefs/store.ts b/frontend/src/ui/prefs/store.ts index 3a36c97a..4263338c 100644 --- a/frontend/src/ui/prefs/store.ts +++ b/frontend/src/ui/prefs/store.ts @@ -13,6 +13,7 @@ export const ENGINE_DEFAULTS = { lineWidth: 0.6, boldWidth: 2, labelSize: 10, + scaleLabels: true, colorAtoms: false, carbonLabels: 'none', valenceWarnings: true, From 53e92f9547b4b61ab20967100b0f1bc9d8b05fc6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:37:15 -0500 Subject: [PATCH 023/357] feat(canvas): draw corner scale handles, a selection frame and a scale readout (0.7.0) A selection that holds a structure now shows four corner handles in the object handle style on a light frame, away from the rotate handle, and the view can show the scale and bond length beside the pointer. --- frontend/src/canvas/view.ts | 47 ++++++++++++++++++++++++++--- frontend/src/styles/canvas-view.css | 4 +++ 2 files changed, 47 insertions(+), 4 deletions(-) diff --git a/frontend/src/canvas/view.ts b/frontend/src/canvas/view.ts index 581addd9..06c209fb 100644 --- a/frontend/src/canvas/view.ts +++ b/frontend/src/canvas/view.ts @@ -3,7 +3,7 @@ import { bondBetween, emptyDocument, neighbours, newId, type Atom, type FormChem import { atomPath, bondPath, objectPath, pagePath, type Op } from '../engine/ops'; import { t } from '../i18n'; import { contextMenuOpen } from '../ui/context-menu'; -import { el, isMac, q, setClass, setStyleVar } from '../ui/dom'; +import { el, isMac, overlayRoot, q, setClass, setHidden, setStyleVar, setText } from '../ui/dom'; import { modalOpen } from '../ui/menu'; import { openCanvasMenu } from './context'; import { fmt } from './render/geom'; @@ -11,6 +11,7 @@ import { hitExists, hitTest, NO_HIT, objectBounds, sameHit, styleFor, visibleOrd import { EMPTY_SELECTION, isEmpty, prune, sameSelection, selectAllOnPage } from './selection'; import { TextEditor, type TextEditOptions } from './text-editor'; import { objectHandles } from './tools/handles'; +import { scaleHandles } from './tools/scale'; import type { Band, Hit, RenderDisplay, Renderer, Selection, Tool, ToolContext, ToolDef, ToolPointer, Viewport } from './types'; export const PT_PX = 96 / 72; @@ -27,14 +28,18 @@ const HANDLE_STEM = 24; const OBJECT_HANDLE_PX = 7; const OBJECT_HANDLE_TOOLS = new Set(['select', 'lasso']); const REVEAL_PAD = 24; +const READOUT_OFFSET = { x: 16, y: 18 }; export type { Band }; export interface Insets { top: number; right: number; bottom: number; left: number } +export interface Readout { percent?: number; bond?: number | null } + export interface ViewToolContext extends ToolContext { readonly view: CanvasView; band(b: Band | null): void; + readout(r: Readout | null, at?: Point): void; } export interface ViewPointer extends ToolPointer { clicks: number; pointerType: string } @@ -158,6 +163,8 @@ export class CanvasView { private readonly bandPath: SVGPathElement; private readonly cursorPath: SVGPathElement; private readonly handlePath: SVGPathElement; + private readonly framePath: SVGPathElement; + private readonly readoutEl: HTMLElement; private readonly live: HTMLElement; private readonly docLayers: SVGGElement[] = []; private insets_: Insets = { top: 0, right: 0, bottom: 0, left: 0 }; @@ -213,7 +220,11 @@ export class CanvasView { this.cursorPath.setAttribute('class', 'fc-canvas-keycursor'); this.handlePath = document.createElementNS(SVG_NS, 'path'); this.handlePath.setAttribute('class', 'fc-canvas-handle'); - this.overlay.append(this.cursorPath, this.handlePath, this.bandPath); + this.framePath = document.createElementNS(SVG_NS, 'path'); + this.framePath.setAttribute('class', 'fc-canvas-frame'); + this.overlay.append(this.cursorPath, this.framePath, this.handlePath, this.bandPath); + this.readoutEl = el(''); + overlayRoot().appendChild(this.readoutEl); this.live = el('
'); this.root.append(this.svg, this.overlay, this.live); host.classList.add('has-canvas'); @@ -237,6 +248,7 @@ export class CanvasView { editText: (at, initial, done) => view.editText(at, initial, done), setTool: (id) => { view.setTool(id); }, band: (b) => view.setBand(b), + readout: (r, at) => view.setReadout(r, at), }; this.editor = new TextEditor({ @@ -654,16 +666,42 @@ export class CanvasView { const r = 4.5; d = `M${x.toFixed(1)} ${(y + r).toFixed(1)}V${(y + HANDLE_STEM).toFixed(1)}M${(x + r).toFixed(1)} ${y.toFixed(1)}A${r} ${r} 0 1 0 ${(x - r).toFixed(1)} ${y.toFixed(1)}A${r} ${r} 0 1 0 ${(x + r).toFixed(1)} ${y.toFixed(1)}Z`; } + let frame = ''; if (this.doc_ && this.activated && OBJECT_HANDLE_TOOLS.has(this.toolId)) { + const s = OBJECT_HANDLE_PX / 2; for (const h of objectHandles(this.doc, this.sel)) { const [x, y] = this.toScreen(h.at); - const s = OBJECT_HANDLE_PX / 2; d += h.kind === 'bend' ? `M${(x + s).toFixed(1)} ${y.toFixed(1)}A${s} ${s} 0 1 0 ${(x - s).toFixed(1)} ${y.toFixed(1)}A${s} ${s} 0 1 0 ${(x + s).toFixed(1)} ${y.toFixed(1)}Z` : `M${(x - s).toFixed(1)} ${(y - s).toFixed(1)}h${2 * s}v${2 * s}h${-2 * s}Z`; } + const corners = at ? scaleHandles(this.doc, this.sel, this.vp.zoom).map((h) => this.toScreen(h.at)) : []; + for (const [x, y] of corners) d += `M${(x - s).toFixed(1)} ${(y - s).toFixed(1)}h${2 * s}v${2 * s}h${-2 * s}Z`; + if (corners.length === 4) { + frame = corners.map(([x, y], i) => `${i ? 'L' : 'M'}${x.toFixed(1)} ${y.toFixed(1)}`).join('') + 'Z'; + } } if (this.handlePath.getAttribute('d') !== d) this.handlePath.setAttribute('d', d); + if (this.framePath.getAttribute('d') !== frame) this.framePath.setAttribute('d', frame); + } + + setReadout(r: Readout | null, at?: Point): void { + const box = this.readoutEl; + if (!r || !at) { + setHidden(box, true); + return; + } + const k = box.firstElementChild as HTMLElement; + const bond = box.lastElementChild as HTMLElement; + setText(k, r.percent === undefined ? '' : `${t('Scale')} ${Math.round(r.percent)}%`); + setHidden(k, r.percent === undefined); + setText(bond, r.bond ? `${t('Bond')} ${r.bond.toFixed(1)} pt` : ''); + setHidden(bond, !r.bond); + const c = this.toClient(at); + const x = Math.round(c.x + READOUT_OFFSET.x), y = Math.round(c.y + READOUT_OFFSET.y); + const tr = `translate(${x}px, ${y}px)`; + if (box.style.transform !== tr) box.style.transform = tr; + setHidden(box, false); } private settledRev(): number { @@ -1154,7 +1192,7 @@ export class CanvasView { add(r, 'pointerenter', () => { this.inside = true; this.syncCursor(); }); add(r, 'pointerleave', () => { this.inside = false; - if (!this.gesture) this.setHover(NO_HIT); + if (!this.gesture) { this.setHover(NO_HIT); this.setReadout(null); } this.syncCursor(); }); add(r, 'wheel', (e) => this.onWheel(e), { passive: false }); @@ -1193,6 +1231,7 @@ export class CanvasView { for (const f of this.off.splice(0)) f(); this.editor.destroy(); this.renderer.destroy(); + this.readoutEl.remove(); this.root.parentElement?.classList.remove('has-canvas'); this.root.remove(); } diff --git a/frontend/src/styles/canvas-view.css b/frontend/src/styles/canvas-view.css index 57ac4f07..e2583c6f 100644 --- a/frontend/src/styles/canvas-view.css +++ b/frontend/src/styles/canvas-view.css @@ -28,6 +28,10 @@ .fc-canvas-band { fill: color-mix(in srgb, var(--fc-sel) 10%, transparent); stroke: var(--fc-sel); stroke-width: 1; stroke-dasharray: 4 3; vector-effect: non-scaling-stroke; } .fc-canvas:not(.has-band) .fc-canvas-band { display: none; } .fc-canvas-handle { fill: var(--bg-secondary); stroke: var(--fc-sel); stroke-width: 1.4; } +.fc-canvas-frame { fill: none; stroke: color-mix(in srgb, var(--fc-sel) 45%, transparent); stroke-width: 1; shape-rendering: crispEdges; } +.fc-scale-readout { position: fixed; left: 0; top: 0; z-index: var(--z-raised); display: flex; gap: var(--space-2); padding: 2px 6px; border: 1px solid var(--line-2); border-radius: var(--radius-xs); background: var(--surface-1); color: var(--text-primary); box-shadow: var(--shadow-sm); font-size: var(--fc-11); line-height: 16px; font-variant-numeric: tabular-nums; white-space: nowrap; pointer-events: none; will-change: transform; } +.fc-scale-readout[hidden], .fc-scale-readout > [hidden] { display: none; } +.fc-scale-readout-bond { color: var(--text-secondary); } .fc-canvas.is-space, .fc-canvas.is-space * { cursor: grab; } .fc-canvas.is-space:active, .fc-canvas.is-space:active * { cursor: grabbing; } .fc-canvas-svg text { cursor: inherit; } From ab430f5b6b815b9c58e8b02966570238f59bbdcd Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:37:15 -0500 Subject: [PATCH 024/357] feat(canvas): drag a corner handle to scale the selected structures (0.7.0) Dragging scales uniformly about the opposite corner (Alt: the centre, Shift: 10 percent steps) with a live preview and readout, commits one Scale transaction on release, and Escape cancels. --- frontend/src/canvas/tools/select.ts | 42 ++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/frontend/src/canvas/tools/select.ts b/frontend/src/canvas/tools/select.ts index 810463c6..b0ec272b 100644 --- a/frontend/src/canvas/tools/select.ts +++ b/frontend/src/canvas/tools/select.ts @@ -10,6 +10,9 @@ import { dragHandle, handleAt, handleLabel, HANDLE_CURSORS, type ObjectHandle } import { groupHit } from './objects'; import { hoverKey } from './hotkeys'; import { nudge, rotateHandle, rotateSelection, selectionBounds, translateSelection } from './transform'; +import { scaleFromDrag, scaleHandleAt, scaleSelection, selectionBondLength, SCALE_CURSORS, type ScaleHandle } from './scale'; +import { pref } from '../../ui/prefs/store'; +import type { Readout, ViewToolContext } from '../view'; export const HANDLE_SLOP_PX = 8; export const DOUBLE_CLICK_MS = 400; @@ -19,10 +22,15 @@ const MARQUEE_ID = 'o_preview_marquee'; type Mode = | { kind: 'move'; start: ToolPointer; sel: Selection; dragging: boolean; duplicate: boolean } | { kind: 'rotate'; start: ToolPointer; sel: Selection; centre: Point } + | { kind: 'scale'; start: ToolPointer; sel: Selection; handle: ScaleHandle; bounds: Rect; bond: number | null } | { kind: 'handle'; start: ToolPointer; handle: ObjectHandle } | { kind: 'marquee'; start: ToolPointer; base: Selection; add: boolean; touch: boolean } | { kind: 'lasso'; start: ToolPointer; base: Selection; add: boolean; touch: boolean; points: Point[] }; +function readout(ctx: ToolContext, r: Readout | null, at?: Point): void { + (ctx as Partial).readout?.(r, at); +} + function hitSelected(sel: Selection, h: Hit): boolean { if (h.kind === 'atom') return sel.atoms.has(selectionKey(h.frag, h.atom)); if (h.kind === 'bond') return sel.bonds.has(selectionKey(h.frag, h.bond)); @@ -160,6 +168,13 @@ export class SelectTool implements Tool { this.mode = { kind: 'handle', start: p, handle: grip }; return; } + const corner = scaleHandleAt(ctx.client.doc, sel, p.doc, ctx.viewport().zoom, HANDLE_SLOP_PX); + const box = corner ? selectionBounds(ctx.client.doc, sel) : null; + if (corner && box) { + this.mode = { kind: 'scale', start: p, sel, handle: corner, bounds: box, bond: selectionBondLength(ctx.client.doc, sel) }; + readout(ctx, { percent: 100, bond: this.mode.bond }, p.doc); + return; + } if (!selectionEmpty(sel)) { const h = rotateHandle(ctx.client.doc, sel, ctx.viewport().zoom); const r = selectionBounds(ctx.client.doc, sel); @@ -191,11 +206,18 @@ export class SelectTool implements Tool { const m = this.mode; if (!m) { ctx.setHover(p.hit); - const grip = handleAt(ctx.client.doc, ctx.selection(), p.doc, ctx.viewport().zoom, HANDLE_SLOP_PX); - ctx.setCursor(grip ? HANDLE_CURSORS[grip.kind] : this.cursor); + const sel = ctx.selection(); + const grip = handleAt(ctx.client.doc, sel, p.doc, ctx.viewport().zoom, HANDLE_SLOP_PX); + const corner = grip ? null : scaleHandleAt(ctx.client.doc, sel, p.doc, ctx.viewport().zoom, HANDLE_SLOP_PX); + ctx.setCursor(grip ? HANDLE_CURSORS[grip.kind] : corner ? SCALE_CURSORS[corner.corner] : this.cursor); + readout(ctx, corner ? { bond: selectionBondLength(ctx.client.doc, sel) } : null, p.doc); return; } - if (m.kind === 'handle') { + if (m.kind === 'scale') { + const { d, k } = this.scaleDraft(ctx, m, p); + previewDraft(ctx, d); + readout(ctx, { percent: k * 100, bond: m.bond === null ? null : m.bond * k }, p.doc); + } else if (m.kind === 'handle') { if (moved(m.start, p)) previewDraft(ctx, this.handleDraft(ctx, m, p)); } else if (m.kind === 'move') { if (!m.dragging && !moved(m.start, p)) return; @@ -228,7 +250,11 @@ export class SelectTool implements Tool { const m = this.mode; this.mode = null; if (!m) return; - if (m.kind === 'handle') { + if (m.kind === 'scale') { + readout(ctx, null); + if (moved(m.start, p)) commitDraft(ctx, 'Scale', this.scaleDraft(ctx, m, p).d); + else ctx.client.preview(null); + } else if (m.kind === 'handle') { if (moved(m.start, p)) commitDraft(ctx, handleLabel(m.handle), this.handleDraft(ctx, m, p)); else ctx.client.preview(null); } else if (m.kind === 'move') { @@ -269,6 +295,7 @@ export class SelectTool implements Tool { } private cancel(ctx: ToolContext): void { + readout(ctx, null); if (this.mode && (this.mode.kind === 'marquee' || this.mode.kind === 'lasso')) { clearBand(ctx); ctx.setSelection(this.mode.base); @@ -317,6 +344,13 @@ export class SelectTool implements Tool { return d; } + private scaleDraft(ctx: ToolContext, m: Extract, p: ToolPointer): { d: Draft; k: number } { + const d = draftFor(ctx); + const { k, centre } = scaleFromDrag(m.handle, m.bounds, p.doc, p.alt, p.shift); + scaleSelection(d, m.sel, k, centre, { labels: pref('scaleLabels') }); + return { d, k }; + } + private rotateDraft(ctx: ToolContext, m: Extract, p: ToolPointer): Draft { const d = draftFor(ctx); let deg = angleFrom(m.centre, p.doc) - angleFrom(m.centre, m.start.doc); From 9d4f1c5a5b0a16a95ce7e3005d7d46f7b8b8b9dd Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:37:49 -0500 Subject: [PATCH 025/357] feat(ui): add the Scale dialog with linked percent and bond length fields (0.7.0) Arrange > Scale needs a place to type an exact percent or a target bond length in points, choose whether labels follow, and see that zoom is a different thing. --- frontend/src/styles/dialogs.css | 5 ++ frontend/src/ui/scale-dialog.ts | 118 ++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 frontend/src/ui/scale-dialog.ts diff --git a/frontend/src/styles/dialogs.css b/frontend/src/styles/dialogs.css index 364b39e0..b2e3a5a8 100644 --- a/frontend/src/styles/dialogs.css +++ b/frontend/src/styles/dialogs.css @@ -44,6 +44,11 @@ select.fc-input { padding-right: 6px; } .fc-dialog .fc-seg button:focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } .fc-dialog .fc-check { display: inline-flex; align-items: center; gap: var(--space-2); color: var(--text-secondary); font-size: var(--fc-13); cursor: pointer; } .fc-dialog .fc-check:hover { color: var(--text-primary); } +.fc-scale-num { display: flex; align-items: center; gap: var(--space-2); } +.fc-scale-num > .fc-input { width: 112px; font-variant-numeric: tabular-nums; } +.fc-scale-unit { color: var(--text-muted); font-size: var(--fc-12); } +.fc-scale-now { margin-top: 0; font-variant-numeric: tabular-nums; } +.fc-dialog .fc-scale-labels { margin-top: var(--space-1); } .fc-dialog input[type="checkbox"] { flex: none; width: 16px; height: 16px; margin: 0; accent-color: var(--accent-color); cursor: pointer; } .fc-dialog .fc-swatch { display: inline-block; flex: none; width: 22px; height: 22px; padding: 0; border: 1px solid color-mix(in srgb, var(--text-primary) 12%, transparent); border-radius: var(--radius-sm); background: var(--swatch, var(--surface-2)); cursor: pointer; } .fc-dialog .fc-swatch:hover { outline: 1px solid var(--cta-bg); outline-offset: 1px; } diff --git a/frontend/src/ui/scale-dialog.ts b/frontend/src/ui/scale-dialog.ts new file mode 100644 index 00000000..d339824c --- /dev/null +++ b/frontend/src/ui/scale-dialog.ts @@ -0,0 +1,118 @@ +import { t } from '../i18n'; +import { Dialog } from './dialogs'; +import { el, q, setChecked, setDisabled, setHidden, setText, setValue } from './dom'; + +export interface ScaleRequest { bondLength: number | null; labels: boolean; page: boolean } +export interface ScaleAnswer { percent?: number; bondLength?: number; labels: boolean } + +export const PERCENT_MIN = 5; +export const PERCENT_MAX = 2000; + +const fmt = (v: number, digits: number): string => String(Math.round(v * 10 ** digits) / 10 ** digits); + +class ScaleDialog extends Dialog { + private readonly percent: HTMLInputElement; + private readonly bond: HTMLInputElement; + private readonly bondRow: HTMLElement; + private readonly labels: HTMLInputElement; + private readonly now: HTMLElement; + private readonly scope: HTMLElement; + private readonly ok: HTMLButtonElement; + private base: number | null = null; + private by: 'percent' | 'bond' = 'percent'; + private resolve: ((v: ScaleAnswer | null) => void) | null = null; + + constructor() { + super(t('Scale'), 420); + const num = (unit: string, max: number): HTMLElement => + el(`${unit}`); + this.now = el('

'); + this.body.appendChild(this.now); + const pct = num('%', PERCENT_MAX); + this.percent = q(pct, 'input'); + this.field(t('Scale'), pct); + const bl = num('pt', 1000); + this.bond = q(bl, 'input'); + this.bondRow = this.field(t('Bond length'), bl); + this.labels = el(''); + const check = el(''); + check.appendChild(this.labels); + check.appendChild(document.createTextNode(t('Scale labels and text with structures'))); + this.body.appendChild(check); + this.scope = el('

'); + this.body.appendChild(this.scope); + this.percent.addEventListener('input', () => { this.by = 'percent'; this.sync(); }); + this.bond.addEventListener('input', () => { this.by = 'bond'; this.sync(); }); + for (const input of [this.percent, this.bond]) { + input.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.isComposing) { e.preventDefault(); if (!this.ok.disabled) this.ok.click(); } }); + } + this.button(t('Cancel'), 'ghost', () => this.finish(null)); + this.ok = this.button(t('Scale'), 'primary', () => this.finish(this.answer())); + this.onClose = () => this.finish(null); + } + + ask(req: ScaleRequest): Promise { + this.resolve?.(null); + this.base = req.bondLength; + this.by = 'percent'; + this.percent.value = '100'; + this.bond.value = this.base ? fmt(this.base, 2) : ''; + setChecked(this.labels, req.labels); + setText(this.now, this.base ? `${t('Bond length now')}: ${fmt(this.base, 2)} pt` : ''); + setHidden(this.now, !this.base); + setHidden(this.bondRow, !this.base); + setText(this.scope, `${req.page ? t('Nothing is selected, so every structure on the page is scaled about its own centre.') : t('The selection is scaled about its centre.')} ${t('Zoom only changes the view, not the drawing.')}`); + this.sync(); + this.open(this.percent); + this.percent.select(); + return new Promise((r) => { this.resolve = r; }); + } + + private value(input: HTMLInputElement): number | null { + const n = Number.parseFloat(input.value); + return Number.isFinite(n) && n > 0 ? n : null; + } + + private factor(): number | null { + if (this.by === 'bond') { + const b = this.value(this.bond); + return b && this.base ? b / this.base : null; + } + const p = this.value(this.percent); + return p ? p / 100 : null; + } + + private sync(): void { + const k = this.factor(); + if (k && this.base) { + if (this.by === 'percent') setValue(this.bond, fmt(this.base * k, 2)); + else setValue(this.percent, fmt(k * 100, 1)); + } + const ok = k !== null && k * 100 >= PERCENT_MIN && k * 100 <= PERCENT_MAX; + setDisabled(this.ok, !ok); + } + + private answer(): ScaleAnswer | null { + const labels = this.labels.checked; + if (this.by === 'bond') { + const b = this.value(this.bond); + return b ? { bondLength: b, labels } : null; + } + const p = this.value(this.percent); + return p ? { percent: p, labels } : null; + } + + private finish(v: ScaleAnswer | null): void { + const r = this.resolve; + this.resolve = null; + if (this.isOpen) this.close(); + r?.(v); + } +} + +let dialog: ScaleDialog | null = null; + +export function askScale(req: ScaleRequest): Promise { + dialog ??= new ScaleDialog(); + return dialog.ask(req); +} From bae615220e7a9143146d609b594156a0ca2f7cd7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:38:38 -0500 Subject: [PATCH 026/357] feat(ui): add scale, scale up and scale down icons (0.7.0) The new Arrange commands need inline currentColor glyphs that read as resizing a drawing rather than zooming the view. --- frontend/src/ui/icons.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/frontend/src/ui/icons.ts b/frontend/src/ui/icons.ts index f5975859..c4816937 100644 --- a/frontend/src/ui/icons.ts +++ b/frontend/src/ui/icons.ts @@ -305,6 +305,9 @@ export const ICONS: Record = { stereoGroup: L(''), hydrogenAdd: L(''), hydrogenRemove: L(''), + scale: L(''), + scaleUp: L(''), + scaleDown: L(''), expandAbbr: L(''), contractAbbr: L(''), atomList: L(''), From 959da3873279de244e73c7cf1550e5a1ee8f0ca0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:38:38 -0500 Subject: [PATCH 027/357] feat(commands): add scale-selection, Scale Up and Down 10% and the labels toggle (0.7.0) People and agents can now make structures larger on the sheet by percent or to a target bond length in one undo step; the shortcuts are Alt+Mod+= and Alt+Mod+- because Mod+= and Mod+- stay zoom. --- frontend/src/app/canvas-commands.ts | 57 +++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/frontend/src/app/canvas-commands.ts b/frontend/src/app/canvas-commands.ts index 1906b28b..1a8a0d31 100644 --- a/frontend/src/app/canvas-commands.ts +++ b/frontend/src/app/canvas-commands.ts @@ -7,6 +7,7 @@ import type { Rulers } from '../canvas/rulers'; import { placeImage } from '../canvas/tools/image'; import { duplicateSelection } from '../canvas/tools/select'; import { translateSelection } from '../canvas/tools/transform'; +import { scaleBy, scaleTargets, targetsBondLength, SCALE_STEP } from '../canvas/tools/scale'; import type { CanvasView } from '../canvas/view'; import { commands, type CommandDef } from '../commands/registry'; import type { Fragment, Id, Point } from '../engine/model'; @@ -15,6 +16,9 @@ import { t } from '../i18n'; import { post } from '../io/api'; import { setAnalysisOpen } from '../ui/analysis-panel'; import type { FindBar } from '../ui/find-bar'; +import { pref, setPref } from '../ui/prefs/store'; +import { askScale, PERCENT_MAX, PERCENT_MIN } from '../ui/scale-dialog'; +import { flashHint } from '../ui/status'; import { toast } from '../ui/toast'; import { commandStateChanged } from './commands-shell'; @@ -53,6 +57,58 @@ function findCommands(bar: FindBar, open: () => boolean): CommandDef[] { ]; } +const BOND_MIN = 1; +const BOND_MAX = 500; + +function scaleCommands(view: CanvasView, open: () => boolean): CommandDef[] { + const NEED_STRUCTURE = 'Draw or select a structure first'; + const targets = () => (view.client ? scaleTargets(view.doc, view.selection(), view.context.page()) : []); + const can = (): boolean => open() && targets().length > 0; + const apply = (how: { k?: number; bondLength?: number }, labels: boolean): string => { + const r = scaleBy(view.context, how, { labels }, t('Scale')); + if (!r) return t('Nothing changed.'); + const pct = Math.round(r.k * 1000) / 10; + const text = r.bondLength === null ? `${t('Scaled to')} ${pct}%` : `${t('Scaled to')} ${pct}%, ${t('bond length')} ${r.bondLength.toFixed(1)} pt`; + flashHint(text); + return text; + }; + const numberParam = (v: unknown, name: string, min: number, max: number): number | undefined => { + if (v === undefined || v === null) return undefined; + const n = typeof v === 'number' ? v : Number.parseFloat(String(v)); + if (!Number.isFinite(n) || n < min || n > max) throw new Error(`${name} must be a number from ${min} to ${max}`); + return n; + }; + const scaleRun = async (p?: Record): Promise => { + const percent = numberParam(p?.percent, 'percent', PERCENT_MIN, PERCENT_MAX); + const bondLength = numberParam(p?.bond_length, 'bond_length', BOND_MIN, BOND_MAX); + const labels = typeof p?.labels === 'boolean' ? p.labels : pref('scaleLabels'); + if (percent !== undefined && bondLength !== undefined) throw new Error('give percent or bond_length, not both'); + if (percent !== undefined) return apply({ k: percent / 100 }, labels); + if (bondLength !== undefined) return apply({ bondLength }, labels); + const list = targets(); + const answer = await askScale({ bondLength: targetsBondLength(view.doc, list), labels, page: view.selection().atoms.size + view.selection().bonds.size + view.selection().objects.size === 0 }); + if (!answer) return null; + if (answer.labels !== pref('scaleLabels')) void setPref('scaleLabels', answer.labels).catch(() => undefined); + view.focus(); + return apply(answer.bondLength !== undefined ? { bondLength: answer.bondLength } : { k: (answer.percent ?? 100) / 100 }, answer.labels); + }; + return [ + { + id: 'scale-selection', label: () => t('Scale...'), group: 'Arrange', icon: 'scale', mutates: true, + description: 'Makes the selected structures (with any arrows, shapes and text selected with them) larger or smaller on the sheet, or every structure on the page when nothing is selected, as one undo step. Give percent (100 keeps the size) or bond_length, the target median bond length in points; without either it asks the person. labels says whether line widths, atom labels and text scale too (default: the Scale labels and text with structures preference). Zoom only changes the view; this changes the drawing.', + params: { + percent: { type: 'number', min: PERCENT_MIN, max: PERCENT_MAX, description: 'New size as a percent of the current size, such as 150', example: '150' }, + bond_length: { type: 'number', min: BOND_MIN, max: BOND_MAX, description: 'Target median bond length in points, such as 20', example: '20' }, + labels: { type: 'boolean', description: 'Scale line widths, labels and text too; leave out to follow the preference' }, + }, + when: NEED_STRUCTURE, enabled: can, run: (p) => scaleRun(p), + }, + { id: 'scale-up', label: () => t('Scale Up 10%'), group: 'Arrange', keys: ['Alt+Mod+='], icon: 'scaleUp', mutates: true, description: 'Makes the selected structures, or every structure on the page when nothing is selected, 10 percent larger on the sheet as one undo step. Not zoom.', when: NEED_STRUCTURE, enabled: can, run: () => apply({ k: SCALE_STEP }, pref('scaleLabels')) }, + { id: 'scale-down', label: () => t('Scale Down 10%'), group: 'Arrange', keys: ['Alt+Mod+-'], icon: 'scaleDown', mutates: true, description: 'Makes the selected structures, or every structure on the page when nothing is selected, smaller on the sheet by the inverse of Scale Up, so the two cancel exactly, as one undo step. Not zoom.', when: NEED_STRUCTURE, enabled: can, run: () => apply({ k: 1 / SCALE_STEP }, pref('scaleLabels')) }, + { id: 'scale-labels', label: () => t('Scale Labels and Text with Structures'), group: 'Arrange', description: 'When on, scaling a structure also scales its line widths, atom labels and any selected text; when off they keep the drawing style. The choice is remembered.', checked: () => pref('scaleLabels'), run: () => setPref('scaleLabels', !pref('scaleLabels')) }, + ]; +} + interface LayoutAnswer { coords?: Record; stereo?: Record; warnings?: { text?: string }[] } const LAYOUT_URL = '/api/chem/layout'; @@ -194,6 +250,7 @@ export function registerCanvasCommands(deps: CanvasCommandDeps): () => void { tool('insert-table', 'Table', 'table', 'table', 'Insert'), { id: 'insert-image', label: () => t('Image...'), group: 'Insert', icon: 'image', mutates: true, description: 'Asks the person for a PNG, JPEG, GIF, WebP or SVG picture and places it in the middle of the visible page as one undo step.', when: NEED_DRAWING, enabled: open, run: () => { void placeImage(view.context, visibleCentre(view), null); } }, tool('add-reaction-arrow', 'Add Reaction Arrow', 'arrow', 'arrow-forward', 'Reaction'), + ...scaleCommands(view, open), ...(deps.find ? findCommands(deps.find, open) : []), ...(deps.rulers ? rulerCommands(deps.rulers) : []), darkPageCommand(), From 22cb1c96d81705518779b6f7faae3fa6c418bb2b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:38:51 -0500 Subject: [PATCH 028/357] feat(menus): put Scale, Scale Up, Scale Down and the labels toggle in Arrange (0.7.0) The shared menu definitions feed both the in-window menus and the macOS native menu bar, so the new commands appear in both; Scale also joins the selection context menu. --- frontend/src/app/menus.ts | 2 +- frontend/src/canvas/context.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/app/menus.ts b/frontend/src/app/menus.ts index 031d843f..98bbc6e5 100644 --- a/frontend/src/app/menus.ts +++ b/frontend/src/app/menus.ts @@ -24,7 +24,7 @@ export function buildMenus(extensionItems?: MenuSource, recentItems?: MenuSource { label: 'Insert', items: ['insert-smiles', 'insert-name', 'insert-template', '-', 'insert-text', 'insert-arrow', 'insert-shape', 'insert-table', 'insert-image'] }, { label: 'Structure', items: ['clean-structure', 'layout-structure', '-', ...CHEM_MENU_ITEMS.structure, '-', 'check-structure', 'compute-properties', '-', 'flip-horizontal', 'flip-vertical'] }, { label: 'Reaction', items: ['add-reaction-arrow', 'perceive-reactions', 'set-reaction-roles', '-', 'map-atoms', 'clear-mapping', '-', 'check-reaction', 'balance-reaction', '-', 'show-stoichiometry', 'stoichiometry-grid', '-', 'paste-reaction', REACTION_COPY, REACTION_EXPORT] }, - { label: 'Arrange', items: ['bring-front', 'bring-forward', 'send-backward', 'send-back', '-', ALIGN, 'distribute-h', 'distribute-v', '-', 'rotate-90', '-', 'group', 'ungroup'] }, + { label: 'Arrange', items: ['bring-front', 'bring-forward', 'send-backward', 'send-back', '-', ALIGN, 'distribute-h', 'distribute-v', '-', 'rotate-90', '-', 'scale-selection', 'scale-up', 'scale-down', 'scale-labels', '-', 'group', 'ungroup'] }, { label: 'Analysis', items: ['show-analysis', ...CHEM_MENU_ITEMS.analysis] }, { label: '3D', items: ['view-3d', '-', 'build-3d', 'minimize-3d', 'conformers'] }, { label: 'Window', items: ['next-window', '-', 'agents'] }, diff --git a/frontend/src/canvas/context.ts b/frontend/src/canvas/context.ts index 54d0e960..c3dc8687 100644 --- a/frontend/src/canvas/context.ts +++ b/frontend/src/canvas/context.ts @@ -245,7 +245,7 @@ function selectionItems(host: CanvasMenuHost, temp: Temp[]): MenuItem[] { enabled: () => !isEmpty(host.selection()), run: () => commit(host, t('Delete'), deleteSelectionOps(host.doc, host.selection())), }); - return ['cut', 'copy', 'duplicate', del, '-', 'flip-horizontal', 'flip-vertical', 'rotate-90', '-', 'clean-structure']; + return ['cut', 'copy', 'duplicate', del, '-', 'flip-horizontal', 'flip-vertical', 'rotate-90', 'scale-selection', '-', 'clean-structure']; } function backgroundItems(host: CanvasMenuHost, temp: Temp[]): MenuItem[] { From d891af04eb1f9219d2bdebce208088006b555f56 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:38:58 -0500 Subject: [PATCH 029/357] docs(mcp): name scale-selection, scale-up and scale-down in the agent guide (0.7.0) Agents read this guide before list_commands, so it now says how to make a structure larger on the sheet and that zoom is only the view. --- backend/app/routers/mcp.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index 8fe1f043..4dc621d8 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -44,7 +44,7 @@ FormChem {config.VERSION} draws. Drawings are documents the engine owns (docs/FORMAT.md): the person opens them in the window, draws on the canvas with the tool rail and hover keys, and the engine's chemistry (RDKit) works out SMILES, InChIKey, formula, masses, elemental analysis and CIP labels after every change, shown in the Analysis panel with the calculated properties and the isotope pattern. Drawings hold reaction schemes with perceived or hand-set roles, stereo groups, query atoms and bonds, abbreviations and R-group definitions. Files in molfile, SDF, RXN, SMILES, CML and CDXML open as new drawings. How an agent changes a drawing today: -- run_command with the window's own commands, the same ones the menus run. Call list_commands first: it gives each id, its params and whether it is on right now. insert-smiles {{"smiles": "c1ccccc1O"}} adds a structure to the active drawing (or a new one) and selects it; new-document, open-recent {{"path"}}, save, undo, redo, select-all, delete, duplicate, flip-horizontal, flip-vertical, rotate-90, align-*, distribute-*, clean-structure, layout-structure, check-structure and the zoom commands act on the active drawing and the person's selection. Chemistry commands work the same way: add-hydrogens, remove-hydrogens, expand-abbreviation, contract-abbreviation, assign-wedges, set-stereo-group-and, set-atom-list, define-rgroup, enumerate-markush, set-reaction-roles {{"role", "objects"}}, copy-smarts and compute-properties. Each command is one undo step. +- run_command with the window's own commands, the same ones the menus run. Call list_commands first: it gives each id, its params and whether it is on right now. insert-smiles {{"smiles": "c1ccccc1O"}} adds a structure to the active drawing (or a new one) and selects it; new-document, open-recent {{"path"}}, save, undo, redo, select-all, delete, duplicate, flip-horizontal, flip-vertical, rotate-90, scale-selection {{"percent"}} or {{"bond_length"}} (makes structures larger or smaller on the sheet; zoom only changes the view), scale-up, scale-down, align-*, distribute-*, clean-structure, layout-structure, check-structure and the zoom commands act on the active drawing and the person's selection. Chemistry commands work the same way: add-hydrogens, remove-hydrogens, expand-abbreviation, contract-abbreviation, assign-wedges, set-stereo-group-and, set-atom-list, define-rgroup, enumerate-markush, set-reaction-roles {{"role", "objects"}}, copy-smarts and compute-properties. Each command is one undo step. - The reaction tools below write reaction steps and atom mapping straight into a drawing and read reactions and stoichiometry back. - The analysis tools below read a drawing: properties, the structure check, CIP stereo and substructure hits. They never change it. - Form extensions, through extension_command: an extension may read the drawing and apply transactions to it. From 9089a66769352922235f4d7b5cd607f8a0445938 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:46:18 -0500 Subject: [PATCH 030/357] fix(canvas): skip the scale frame over a single boxed object and round scaled styles to 0.01 (0.7.0) The Taxol run showed a second rectangle around a structure that already has its dashed object box, and style overrides such as a 20.001 pt bond length after Scale to 20 pt. --- frontend/src/canvas/tools/scale.ts | 4 ++-- frontend/src/canvas/view.ts | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/frontend/src/canvas/tools/scale.ts b/frontend/src/canvas/tools/scale.ts index 61a23f09..7ffacecc 100644 --- a/frontend/src/canvas/tools/scale.ts +++ b/frontend/src/canvas/tools/scale.ts @@ -12,7 +12,7 @@ export const SCALE_MAX = 20; export const SCALE_STEP = 1.1; export const SCALE_HANDLE_PAD_PX = 8; const MIN_EXTENT = 0.5; -const EPS = 1e-3; +const EPS = 0.006; export type ScaleCorner = 'nw' | 'ne' | 'se' | 'sw'; export interface ScaleHandle { corner: ScaleCorner; fx: 0 | 1; fy: 0 | 1; base: Point; at: Point } @@ -40,7 +40,7 @@ const LABELS: Partial> = { orbital: ['line_width'], }; -const round = (v: number): number => Math.round(v * 1000) / 1000; +const round = (v: number): number => Math.round(v * 100) / 100; export const clampScale = (k: number): number => Math.min(SCALE_MAX, Math.max(SCALE_MIN, k)); function holdsFragment(doc: FormChemDocument, id: Id, depth = 0): boolean { diff --git a/frontend/src/canvas/view.ts b/frontend/src/canvas/view.ts index 06c209fb..482bd9b7 100644 --- a/frontend/src/canvas/view.ts +++ b/frontend/src/canvas/view.ts @@ -677,7 +677,9 @@ export class CanvasView { } const corners = at ? scaleHandles(this.doc, this.sel, this.vp.zoom).map((h) => this.toScreen(h.at)) : []; for (const [x, y] of corners) d += `M${(x - s).toFixed(1)} ${(y - s).toFixed(1)}h${2 * s}v${2 * s}h${-2 * s}Z`; - if (corners.length === 4) { + const only = this.sel.objects.size === 1 ? `${[...this.sel.objects][0]}/` : ''; + const boxed = !!only && [...this.sel.atoms, ...this.sel.bonds].every((k) => k.startsWith(only)); + if (corners.length === 4 && !boxed) { frame = corners.map(([x, y], i) => `${i ? 'L' : 'M'}${x.toFixed(1)} ${y.toFixed(1)}`).join('') + 'Z'; } } From cc22da302cb47c041832cc1d10a608d296e7b7a1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:40:02 -0500 Subject: [PATCH 031/357] feat(chem): score 2D layouts for crowding and label overlap (0.7.0) Layout choices need a measure: the score counts close atoms, bond crossings, atoms on foreign bonds and label boxes that touch, in bond-length units, so candidates can be compared and the crowded atoms found. --- backend/app/services/chem/layout_score.py | 196 ++++++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 backend/app/services/chem/layout_score.py diff --git a/backend/app/services/chem/layout_score.py b/backend/app/services/chem/layout_score.py new file mode 100644 index 00000000..b804f12d --- /dev/null +++ b/backend/app/services/chem/layout_score.py @@ -0,0 +1,196 @@ +from dataclasses import dataclass, field + +import numpy as np +from rdkit import Chem + +WEIGHTS = {"close": 10.0, "cross": 10.0, "near": 5.0, "label": 3.0} +CLOSE = 0.5 +NEAR = 0.35 +SOFT_RANGE = 1.0 +LABEL_HALF_HEIGHT = 0.25 +LABEL_MARGIN = 0.06 +LABEL_CLEAR = 0.05 +LABEL_SOFT_GAP = 0.4 +UPPER, LOWER, DIGIT, CHARGE = 0.5, 0.38, 0.27, 0.3 + + +@dataclass +class Shape: + n: int + bonds: np.ndarray + apart: np.ndarray + incident: np.ndarray + disjoint: np.ndarray + neighbours: list[list[int]] + labelled: np.ndarray + core: np.ndarray + extra: np.ndarray + + +@dataclass +class Score: + total: float + hard: float + parts: dict = field(default_factory=dict) + crowded: frozenset = frozenset() + + def as_dict(self) -> dict: + return {"total": round(self.total, 3), **self.parts} + + +def _glyphs(text: str) -> float: + return sum(UPPER if c.isupper() else LOWER if c.isalpha() else DIGIT for c in text) + + +def _label(atom: Chem.Atom) -> tuple[bool, float, float]: + z = atom.GetAtomicNum() + if z == 6 and atom.GetDegree() > 0 and not atom.GetIsotope() and not atom.GetNumRadicalElectrons(): + return False, 0.0, 0.0 + symbol = atom.GetSymbol() if z else "R" + try: + h = atom.GetTotalNumHs() + except Exception: + h = 0 + extra = (UPPER + (DIGIT if h > 1 else 0.0)) if h and z not in (0, 1) else 0.0 + if atom.GetFormalCharge(): + extra += CHARGE + return True, _glyphs(symbol), extra + + +def shape(mol: Chem.Mol) -> Shape: + n = mol.GetNumAtoms() + bonds = np.array([(b.GetBeginAtomIdx(), b.GetEndAtomIdx()) for b in mol.GetBonds()], dtype=int).reshape(-1, 2) + apart = np.triu(np.ones((n, n), dtype=bool), 1) + neighbours: list[list[int]] = [[] for _ in range(n)] + for i, j in bonds: + apart[min(i, j), max(i, j)] = False + neighbours[i].append(int(j)) + neighbours[j].append(int(i)) + m = len(bonds) + incident = np.zeros((n, m), dtype=bool) + if m: + incident[bonds[:, 0], np.arange(m)] = True + incident[bonds[:, 1], np.arange(m)] = True + share = incident.T.astype(int) @ incident.astype(int) if m else np.zeros((0, 0), dtype=int) + disjoint = np.triu(share == 0, 1) + info = [_label(a) for a in mol.GetAtoms()] + return Shape(n, bonds, apart, incident, disjoint, neighbours, + np.array([i[0] for i in info], dtype=bool), + np.array([i[1] for i in info], dtype=float), + np.array([i[2] for i in info], dtype=float)) + + +def _unit_scale(pts: np.ndarray, bonds: np.ndarray) -> float: + if not len(bonds): + return 1.0 + d = np.linalg.norm(pts[bonds[:, 0]] - pts[bonds[:, 1]], axis=1) + d = d[d > 1e-6] + return float(np.median(d)) if len(d) else 1.0 + + +def _boxes(s: Shape, pts: np.ndarray) -> np.ndarray: + left = np.zeros(s.n, dtype=bool) + for i in np.nonzero(s.labelled & (s.extra > 0))[0]: + nb = s.neighbours[i] + left[i] = bool(nb) and all(pts[j, 0] > pts[i, 0] + 0.1 for j in nb) + half = s.core / 2 + LABEL_MARGIN + x0 = pts[:, 0] - half - np.where(left, s.extra, 0.0) + x1 = pts[:, 0] + half + np.where(left, 0.0, s.extra) + h = LABEL_HALF_HEIGHT + LABEL_MARGIN + return np.stack([x0, pts[:, 1] - h, x1, pts[:, 1] + h], axis=1) + + +def _segment_hits_box(a: np.ndarray, b: np.ndarray, box: np.ndarray) -> np.ndarray: + d = b - a + t0 = np.zeros(len(a)) + t1 = np.ones(len(a)) + ok = np.ones(len(a), dtype=bool) + for p, q in ((-d[:, 0], a[:, 0] - box[:, 0]), (d[:, 0], box[:, 2] - a[:, 0]), + (-d[:, 1], a[:, 1] - box[:, 1]), (d[:, 1], box[:, 3] - a[:, 1])): + flat = np.abs(p) < 1e-12 + ok &= ~(flat & (q < 0)) + with np.errstate(divide="ignore", invalid="ignore"): + r = np.where(flat, 0.0, q / np.where(flat, 1.0, p)) + t0 = np.where(~flat & (p < 0), np.maximum(t0, r), t0) + t1 = np.where(~flat & (p > 0), np.minimum(t1, r), t1) + return ok & (t0 <= t1) + + +def evaluate(s: Shape, coords: np.ndarray) -> Score: + pts = np.asarray(coords, dtype=float)[:, :2] + pts = pts / _unit_scale(pts, s.bonds) + diff = pts[:, None, :] - pts[None, :, :] + dist = np.sqrt((diff ** 2).sum(-1)) + pair = dist[s.apart] + close = int((pair < CLOSE).sum()) + ci, cj = np.nonzero((dist < CLOSE) & s.apart) + crowded: set[int] = set(ci.tolist()) | set(cj.tolist()) + soft = float((np.clip(SOFT_RANGE - pair, 0.0, None) ** 2).sum()) + cross = near = label = 0 + if len(s.bonds): + a, b = pts[s.bonds[:, 0]], pts[s.bonds[:, 1]] + ab = b - a + length2 = np.maximum((ab ** 2).sum(1), 1e-12) + t = np.clip(((pts[:, None, :] - a[None]) * ab[None]).sum(-1) / length2[None], 0.0, 1.0) + foot = a[None] + t[..., None] * ab[None] + seg = np.sqrt(((pts[:, None, :] - foot) ** 2).sum(-1)) + seg[s.incident] = np.inf + near = int((seg < NEAR).sum()) + ai, bi = np.nonzero(seg < NEAR) + crowded.update(ai.tolist()) + crowded.update(s.bonds[bi].ravel().tolist()) + + def orient(p, q, r): + return (q[..., 0] - p[..., 0]) * (r[..., 1] - p[..., 1]) - (q[..., 1] - p[..., 1]) * (r[..., 0] - p[..., 0]) + + A, B = a[:, None], b[:, None] + C, D = a[None], b[None] + d1, d2 = orient(C, D, A), orient(C, D, B) + d3, d4 = orient(A, B, C), orient(A, B, D) + eps = 1e-9 + proper = (d1 * d2 < -eps) & (d3 * d4 < -eps) + cross = int((proper & s.disjoint).sum()) + x, y = np.nonzero(proper & s.disjoint) + crowded.update(s.bonds[np.concatenate([x, y])].ravel().tolist()) + lab = np.nonzero(s.labelled)[0] + if len(lab): + box = _boxes(s, pts)[lab] + grow = LABEL_CLEAR + bx0, by0, bx1, by1 = (box[:, k] for k in range(4)) + gx = np.maximum(bx0[:, None], bx0[None]) - np.minimum(bx1[:, None], bx1[None]) + gy = np.maximum(by0[:, None], by0[None]) - np.minimum(by1[:, None], by1[None]) + gap = np.maximum(gx, gy) + upper = np.triu(np.ones((len(lab), len(lab)), dtype=bool), 1) + label += int(((gap < 2 * grow) & upper).sum()) + x, y = np.nonzero((gap < LABEL_SOFT_GAP) & upper) + crowded.update(lab[np.concatenate([x, y])].tolist()) + soft += float((np.clip(LABEL_SOFT_GAP - gap[upper], 0.0, None) ** 2).sum()) * 2.0 + if len(s.bonds): + ends = s.labelled[s.bonds] + unit = ab / np.sqrt(length2)[:, None] + trim = 0.32 + sa = a + unit * np.where(ends[:, 0], trim, 0.0)[:, None] + sb = b - unit * np.where(ends[:, 1], trim, 0.0)[:, None] + real = (np.sqrt(length2) > 2 * trim) | ~(ends[:, 0] | ends[:, 1]) + L, M = len(lab), len(s.bonds) + grown = box + np.array([-grow, -grow, grow, grow]) + hit = _segment_hits_box(np.repeat(sa, L, 0), np.repeat(sb, L, 0), np.tile(grown, (M, 1))).reshape(M, L).T + hit &= ~s.incident[lab] + hit &= real[None] + label += int(hit.sum()) + x, y = np.nonzero(hit) + crowded.update(lab[x].tolist()) + crowded.update(s.bonds[y].ravel().tolist()) + hard = WEIGHTS["close"] * close + WEIGHTS["cross"] * cross + WEIGHTS["near"] * near + WEIGHTS["label"] * label + parts = {"close": close, "cross": cross, "near": near, "label": label, "soft": round(soft, 3)} + return Score(hard + soft, hard, parts, frozenset(int(i) for i in crowded)) + + +def conformer_points(mol: Chem.Mol, conf_id: int = -1) -> np.ndarray: + return np.array(mol.GetConformer(conf_id).GetPositions(), dtype=float)[:, :2].reshape(-1, 2) + + +def score_mol(mol: Chem.Mol, conf_id: int = -1) -> Score: + if not mol.GetNumConformers() or not mol.GetNumAtoms(): + return Score(0.0, 0.0, {"close": 0, "cross": 0, "near": 0, "label": 0, "soft": 0.0}) + return evaluate(shape(mol), conformer_points(mol, conf_id)) From d35edfe9fcc6d2f6589484c2bc8af84a5340c6b7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:41:02 -0500 Subject: [PATCH 032/357] feat(chem): pick the best-scoring of several 2D layout candidates (0.7.0) CoordGen alone sometimes crowds a structure; depict now also tries RDKit's own layout with and without ring templates, sampled variants and straightened copies, and keeps CoordGen unless another candidate scores clearly better. --- backend/app/services/chem/layout.py | 69 +++++++++++++++++++++++++---- 1 file changed, 61 insertions(+), 8 deletions(-) diff --git a/backend/app/services/chem/layout.py b/backend/app/services/chem/layout.py index 9e87193c..534e26d0 100644 --- a/backend/app/services/chem/layout.py +++ b/backend/app/services/chem/layout.py @@ -5,25 +5,78 @@ from rdkit.Chem import rdCoordGen, rdDepictor from rdkit.Geometry import Point2D -from app.services.chem import DEFAULT_BOND_LENGTH, convert, warning +from app.services.chem import DEFAULT_BOND_LENGTH, convert, layout_score, warning Point = tuple[float, float] -def depict(mol: Chem.Mol, fixed: dict[int, Point] | None = None) -> None: +CANDIDATE_LIMIT = 300 +SAMPLED_LIMIT = 150 +SWITCH_MARGIN = 0.5 + + +def _coordgen(mol: Chem.Mol, fixed: dict[int, Point] | None) -> None: + params = rdCoordGen.CoordGenParams() + if fixed: + params.SetCoordMap({i: Point2D(x, y) for i, (x, y) in fixed.items()}) + rdCoordGen.AddCoords(mol, params) + + +def _native(mol: Chem.Mol, fixed: dict[int, Point] | None, templates: bool, seed: int = 0) -> None: + coord_map = {i: Point2D(x, y) for i, (x, y) in (fixed or {}).items()} + rdDepictor.Compute2DCoords(mol, coordMap=coord_map, clearConfs=True, forceRDKit=True, useRingTemplates=templates, + nFlipsPerSample=1 if seed else 0, nSample=10 if seed else 0, sampleSeed=seed, bondLength=1.0) + + +def _candidates(mol: Chem.Mol, fixed: dict[int, Point] | None): + n = mol.GetNumAtoms() + makers = [("coordgen", lambda m: _coordgen(m, fixed))] + if 3 <= n <= CANDIDATE_LIMIT: + makers.append(("rdkit-templates", lambda m: _native(m, fixed, True))) + makers.append(("rdkit", lambda m: _native(m, fixed, False))) + if not fixed and n <= SAMPLED_LIMIT: + makers += [(f"rdkit-sampled-{seed}", lambda m, seed=seed: _native(m, None, False, seed)) for seed in (1, 2)] + for name, make in makers: + m = Chem.Mol(mol) + try: + make(m) + except Exception: + continue + if not m.GetNumConformers(): + continue + yield name, m + if fixed or n < 3 or n > CANDIDATE_LIMIT: + continue + straight = Chem.Mol(m) + try: + rdDepictor.StraightenDepiction(straight) + except Exception: + continue + yield name + "-straight", straight + + +def depict(mol: Chem.Mol, fixed: dict[int, Point] | None = None) -> layout_score.Score | None: try: mol.UpdatePropertyCache(strict=False) Chem.FastFindRings(mol) except Exception: pass - try: - params = rdCoordGen.CoordGenParams() - if fixed: - params.SetCoordMap({i: Point2D(x, y) for i, (x, y) in fixed.items()}) - rdCoordGen.AddCoords(mol, params) - except Exception: + shape = None + best: tuple[layout_score.Score, Chem.Mol, str] | None = None + for name, m in _candidates(mol, fixed): + if shape is None: + shape = layout_score.shape(m) + score = layout_score.evaluate(shape, layout_score.conformer_points(m)) + if best is None or score.total < best[0].total - SWITCH_MARGIN: + best = (score, m, name) + if best is None: coord_map = {i: Point2D(x, y) for i, (x, y) in (fixed or {}).items()} rdDepictor.Compute2DCoords(mol, coordMap=coord_map or None, clearConfs=True) + return None + mol.RemoveAllConformers() + mol.AddConformer(Chem.Conformer(best[1].GetConformer()), assignId=True) + best[0].parts["method"] = best[2] + return best[0] def _fit(src: list[Point], dst: list[Point], reflect: bool) -> tuple[float, callable]: From cf419c073898573e5a3762b8c8c147436c5adc81 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:44:17 -0500 Subject: [PATCH 033/357] feat(chem): swing crowded substituents apart after the 2D layout (0.7.0) The Taxol core left an OH label touching the C2 ester oxygen whatever layout engine ran; the chosen layout now gets a few greedy passes that rotate or mirror acyclic branches at their attachment atom while the score drops, keeping bond angles open and every E/Z side. --- backend/app/services/chem/layout.py | 17 ++- backend/app/services/chem/layout_refine.py | 140 +++++++++++++++++++++ 2 files changed, 152 insertions(+), 5 deletions(-) create mode 100644 backend/app/services/chem/layout_refine.py diff --git a/backend/app/services/chem/layout.py b/backend/app/services/chem/layout.py index 534e26d0..3dff97db 100644 --- a/backend/app/services/chem/layout.py +++ b/backend/app/services/chem/layout.py @@ -3,9 +3,9 @@ from rdkit import Chem from rdkit.Chem import rdCoordGen, rdDepictor -from rdkit.Geometry import Point2D +from rdkit.Geometry import Point2D, Point3D -from app.services.chem import DEFAULT_BOND_LENGTH, convert, layout_score, warning +from app.services.chem import DEFAULT_BOND_LENGTH, convert, layout_refine, layout_score, warning Point = tuple[float, float] @@ -73,10 +73,17 @@ def depict(mol: Chem.Mol, fixed: dict[int, Point] | None = None) -> layout_score coord_map = {i: Point2D(x, y) for i, (x, y) in (fixed or {}).items()} rdDepictor.Compute2DCoords(mol, coordMap=coord_map or None, clearConfs=True) return None + score, chosen, name = best + conf = Chem.Conformer(chosen.GetConformer()) + if mol.GetNumAtoms() <= CANDIDATE_LIMIT and shape is not None: + pts, score, tries = layout_refine.refine(mol, shape, layout_score.conformer_points(chosen), score, set(fixed or {})) + if tries: + for i, (x, y) in enumerate(pts): + conf.SetAtomPosition(i, Point3D(float(x), float(y), 0.0)) mol.RemoveAllConformers() - mol.AddConformer(Chem.Conformer(best[1].GetConformer()), assignId=True) - best[0].parts["method"] = best[2] - return best[0] + mol.AddConformer(conf, assignId=True) + score.parts["method"] = name + return score def _fit(src: list[Point], dst: list[Point], reflect: bool) -> tuple[float, callable]: diff --git a/backend/app/services/chem/layout_refine.py b/backend/app/services/chem/layout_refine.py new file mode 100644 index 00000000..013b43a9 --- /dev/null +++ b/backend/app/services/chem/layout_refine.py @@ -0,0 +1,140 @@ +import math + +import numpy as np +from rdkit import Chem + +from app.services.chem import layout_score + +ROTATIONS = ((12.0, 0.1), (-12.0, 0.1), (24.0, 0.25), (-24.0, 0.25), (36.0, 0.4), (-36.0, 0.4)) +REFLECT_COST = 0.05 +SIZE_COST = 0.01 +MIN_ANGLE = math.radians(60.0) +MIN_ANGLE_CROWDED = math.radians(45.0) +MAX_PASSES = 6 +WORK = 6000 + + +def _side(mol: Chem.Mol, start: int, cut: tuple[int, int]) -> list[int]: + seen = {start} + stack = [start] + while stack: + cur = stack.pop() + for nb in mol.GetAtomWithIdx(cur).GetNeighbors(): + j = nb.GetIdx() + if j in seen or {cur, j} == set(cut): + continue + seen.add(j) + stack.append(j) + return sorted(seen) + + +def branches(mol: Chem.Mol, frozen: set[int]) -> list[tuple[np.ndarray, int, int, bool]]: + try: + mol.GetRingInfo().NumRings() + except Exception: + Chem.FastFindRings(mol) + ring = mol.GetRingInfo() + out = [] + for b in mol.GetBonds(): + if ring.NumBondRings(b.GetIdx()): + continue + u, v = b.GetBeginAtomIdx(), b.GetEndAtomIdx() + options = sorted([(_side(mol, v, (u, v)), u, v), (_side(mol, u, (u, v)), v, u)], key=lambda t: (len(t[0]), t[2])) + for side, attach, root in options: + if attach in side or frozen.intersection(side): + continue + out.append((np.array(side, dtype=int), attach, root, b.GetBondType() == Chem.BondType.SINGLE)) + break + out.sort(key=lambda t: (len(t[0]), t[2])) + return out + + +def _ez(mol: Chem.Mol) -> list[tuple[int, int, list[int], list[int]]]: + out = [] + for b in mol.GetBonds(): + if b.GetBondType() != Chem.BondType.DOUBLE: + continue + u, v = b.GetBeginAtomIdx(), b.GetEndAtomIdx() + nu = [a.GetIdx() for a in b.GetBeginAtom().GetNeighbors() if a.GetIdx() != v] + nv = [a.GetIdx() for a in b.GetEndAtom().GetNeighbors() if a.GetIdx() != u] + if nu and nv: + out.append((u, v, nu, nv)) + return out + + +def _sides(pts: np.ndarray, bonds: list[tuple[int, int, list[int], list[int]]]) -> tuple: + def sign(p, q, r): + return bool((q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]) > 0) + + return tuple(tuple(sign(pts[u], pts[v], pts[w]) for w in nu + nv) for u, v, nu, nv in bonds) + + +def _min_angle(pts: np.ndarray, centre: int, nbrs: list[int]) -> float: + if len(nbrs) < 2: + return math.pi + angles = sorted(math.atan2(pts[j][1] - pts[centre][1], pts[j][0] - pts[centre][0]) for j in nbrs) + gaps = [b - a for a, b in zip(angles, angles[1:])] + [angles[0] + 2 * math.pi - angles[-1]] + return min(gaps) + + +def _rotate(pts: np.ndarray, idx: np.ndarray, centre: int, degrees: float) -> np.ndarray: + t = math.radians(degrees) + c, s = math.cos(t), math.sin(t) + out = pts.copy() + p = pts[idx] - pts[centre] + out[idx] = np.stack([p[:, 0] * c - p[:, 1] * s, p[:, 0] * s + p[:, 1] * c], axis=1) + pts[centre] + return out + + +def _reflect(pts: np.ndarray, idx: np.ndarray, a: int, b: int) -> np.ndarray: + d = pts[b] - pts[a] + norm = float(np.hypot(d[0], d[1])) + if norm < 1e-9: + return pts + d = d / norm + out = pts.copy() + p = pts[idx] - pts[a] + out[idx] = pts[a] + 2 * np.outer(p @ d, d) - p + return out + + +def refine(mol: Chem.Mol, shape: layout_score.Shape, pts: np.ndarray, score: layout_score.Score, + frozen: set[int] | None = None) -> tuple[np.ndarray, layout_score.Score, int]: + if not score.crowded or mol.GetNumAtoms() < 3: + return pts, score, 0 + found = branches(mol, frozen or set()) + if not found: + return pts, score, 0 + ez = _ez(mol) + ez_sides = _sides(pts, ez) + budget = max(40, WORK // max(mol.GetNumAtoms(), 1)) + used = 0 + for _ in range(MAX_PASSES): + moved = False + for side, attach, root, single in found: + if used >= budget: + return pts, score, used + if not score.crowded.intersection(side.tolist()) and attach not in score.crowded: + continue + nbrs = shape.neighbours[attach] + floor = min(MIN_ANGLE if len(nbrs) < 4 else MIN_ANGLE_CROWDED, _min_angle(pts, attach, nbrs)) - 1e-6 + moves = [(_rotate(pts, side, attach, deg), cost) for deg, cost in ROTATIONS] + if single and len(side) > 1: + moves.append((_reflect(pts, side, attach, root), REFLECT_COST)) + best = None + for new, cost in moves: + if _min_angle(new, attach, nbrs) < floor or _sides(new, ez) != ez_sides: + continue + trial = layout_score.evaluate(shape, new) + used += 1 + gain = score.total - trial.total - cost - SIZE_COST * len(side) + if trial.hard <= score.hard and gain > 1e-6 and (best is None or gain > best[0]): + best = (gain, new, trial) + if best: + pts, score = best[1], best[2] + moved = True + if not score.crowded: + return pts, score, used + if not moved: + break + return pts, score, used From 3e37405b2536fd4e4b1739cd8ebc2865664a24f8 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:45:30 -0500 Subject: [PATCH 034/357] fix(chem): keep Clean Up close to the drawing when choosing a layout (0.7.0) Clean Up re-lays out each structure and fits it back over the drawing; among equally uncrowded candidates it now takes the one nearest the drawn shape and only swings substituents when something actually overlaps, so a tidy hand drawing is not rearranged. --- backend/app/services/chem/layout.py | 32 +++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/backend/app/services/chem/layout.py b/backend/app/services/chem/layout.py index 3dff97db..b4cc379d 100644 --- a/backend/app/services/chem/layout.py +++ b/backend/app/services/chem/layout.py @@ -55,27 +55,38 @@ def _candidates(mol: Chem.Mol, fixed: dict[int, Point] | None): yield name + "-straight", straight -def depict(mol: Chem.Mol, fixed: dict[int, Point] | None = None) -> layout_score.Score | None: +def _distance(m: Chem.Mol, reference: list[Point]) -> float: + pts = [(float(x), float(y)) for x, y in layout_score.conformer_points(m)] + return min(_fit(pts, reference, False)[0], _fit(pts, reference, True)[0]) + + +def depict(mol: Chem.Mol, fixed: dict[int, Point] | None = None, + reference: list[Point] | None = None) -> layout_score.Score | None: try: mol.UpdatePropertyCache(strict=False) Chem.FastFindRings(mol) except Exception: pass shape = None - best: tuple[layout_score.Score, Chem.Mol, str] | None = None + found: list[tuple[layout_score.Score, Chem.Mol, str]] = [] for name, m in _candidates(mol, fixed): if shape is None: shape = layout_score.shape(m) - score = layout_score.evaluate(shape, layout_score.conformer_points(m)) - if best is None or score.total < best[0].total - SWITCH_MARGIN: - best = (score, m, name) - if best is None: + found.append((layout_score.evaluate(shape, layout_score.conformer_points(m)), m, name)) + if not found: coord_map = {i: Point2D(x, y) for i, (x, y) in (fixed or {}).items()} rdDepictor.Compute2DCoords(mol, coordMap=coord_map or None, clearConfs=True) return None - score, chosen, name = best + keep = bool(reference) and len(reference) == mol.GetNumAtoms() > 2 + if keep: + least = min(f[0].hard for f in found) + near = sorted((f for f in found if f[0].hard <= least), key=lambda f: _distance(f[1], reference)) + else: + floor = min(f[0].total for f in found) + SWITCH_MARGIN + near = [f for f in found if f[0].total <= floor] + score, chosen, name = near[0] conf = Chem.Conformer(chosen.GetConformer()) - if mol.GetNumAtoms() <= CANDIDATE_LIMIT and shape is not None: + if mol.GetNumAtoms() <= CANDIDATE_LIMIT and shape is not None and (score.hard > 0 or not keep): pts, score, tries = layout_refine.refine(mol, shape, layout_score.conformer_points(chosen), score, set(fixed or {})) if tries: for i, (x, y) in enumerate(pts): @@ -211,7 +222,10 @@ def clean(frag: dict, ids: list[str] | None = None, bond_length: float | None = continue sub = _subfragment(frag, comp) conv = _prepared(sub) - depict(conv.mol) + drawn = [(0.0, 0.0)] * conv.mol.GetNumAtoms() + for a in comp: + drawn[conv.index[a]] = (atoms[a]["x"] / length, -atoms[a]["y"] / length) + depict(conv.mol, reference=drawn) new = _scaled(conv.mol, list(range(conv.mol.GetNumAtoms())), length) src = [new[conv.index[a]] for a in comp] dst = [(atoms[a]["x"], atoms[a]["y"]) for a in comp] From d31377da5fb0ed0ad9f99556a45bd71f5d9a04c0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:46:27 -0500 Subject: [PATCH 035/357] feat(chem): report the layout score from the layout route (0.7.0) Lay Out and Clean Up answers now carry the crowding score of the new coordinates, an additive field the window ignores, so agents and diagnostics can see whether a layout came out clean. --- backend/app/routers/chem.py | 3 ++- backend/app/services/chem/layout.py | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/backend/app/routers/chem.py b/backend/app/routers/chem.py index 8ce5ece4..d9667eef 100644 --- a/backend/app/routers/chem.py +++ b/backend/app/routers/chem.py @@ -93,7 +93,8 @@ def layout_fragment(body: dict) -> dict: else: coords = layout.compute_coords(frag, ids, length, _ids(body, "fixed")) stereo, warnings = layout.restereo(frag, coords) - return {"coords": {k: [x, y] for k, (x, y) in coords.items()}, "stereo": stereo, "warnings": warnings} + return {"coords": {k: [x, y] for k, (x, y) in coords.items()}, "stereo": stereo, "warnings": warnings, + "score": layout.score_fragment(frag, coords)} @router.post("/api/chem/convert") diff --git a/backend/app/services/chem/layout.py b/backend/app/services/chem/layout.py index b4cc379d..daec17e2 100644 --- a/backend/app/services/chem/layout.py +++ b/backend/app/services/chem/layout.py @@ -236,6 +236,23 @@ def clean(frag: dict, ids: list[str] | None = None, bond_length: float | None = return out +def score_fragment(frag: dict, coords: dict[str, Point] | None = None) -> dict | None: + atoms = frag.get("atoms") or {} + if not atoms: + return None + try: + conv = _prepared(frag) + if len(conv.index) != conv.mol.GetNumAtoms(): + return None + pts = [(0.0, 0.0)] * conv.mol.GetNumAtoms() + for aid, a in atoms.items(): + x, y = (coords or {}).get(aid, (a["x"], a["y"])) + pts[conv.index[aid]] = (x, -y) + return layout_score.evaluate(layout_score.shape(conv.mol), pts).as_dict() + except Exception: + return None + + def restereo(frag: dict, coords: dict[str, Point]) -> tuple[dict[str, str], list[dict]]: if not any((b.get("stereo") or "none") != "none" for b in (frag.get("bonds") or {}).values()): return {}, [] From 2d60bc689281c7be313e156e94c16ccf5f140286 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:48:49 -0500 Subject: [PATCH 036/357] fix(chem): lay out SMARTS queries with the scored layout (0.7.0) Structures from SMARTS were the one insert path still drawn by RDKit's plain depiction; they now go through the same scored candidates as SMILES, so a query and its matching structure look alike. --- backend/app/services/chem/query.py | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/backend/app/services/chem/query.py b/backend/app/services/chem/query.py index e863d2ac..97ebecf1 100644 --- a/backend/app/services/chem/query.py +++ b/backend/app/services/chem/query.py @@ -1,9 +1,8 @@ import re from rdkit import Chem -from rdkit.Chem import rdDepictor -from app.services.chem import DEFAULT_BOND_LENGTH, convert, perceive, warning +from app.services.chem import DEFAULT_BOND_LENGTH, convert, layout, perceive, warning from app.services.model import ELEMENTS, new_id BT = Chem.BondType @@ -276,12 +275,7 @@ def from_smarts(text: str, bond_length: float = DEFAULT_BOND_LENGTH, origin: tup if mol is None: raise ValueError("not valid SMARTS") notes: list[dict] = [] - try: - mol.UpdatePropertyCache(strict=False) - Chem.FastFindRings(mol) - except Exception: - pass - rdDepictor.Compute2DCoords(mol) + layout.depict(mol) pts = convert._page_coords(mol, bond_length) if pts: dx, dy = origin[0] - min(p[0] for p in pts), origin[1] - min(p[1] for p in pts) From ecb38c860c68161613e4b219950e8a52ebe562b0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:49:34 -0500 Subject: [PATCH 037/357] fix(chem): skip layout scoring for very large structures (0.7.0) Above 300 atoms the candidates cost more than they save and the pairwise score grows quadratically in memory, so those structures keep the plain CoordGen layout and the layout route stops scoring past 600 atoms. --- backend/app/services/chem/layout.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/backend/app/services/chem/layout.py b/backend/app/services/chem/layout.py index daec17e2..0191c8bc 100644 --- a/backend/app/services/chem/layout.py +++ b/backend/app/services/chem/layout.py @@ -11,6 +11,7 @@ CANDIDATE_LIMIT = 300 +SCORE_LIMIT = 600 SAMPLED_LIMIT = 150 SWITCH_MARGIN = 0.5 @@ -31,7 +32,7 @@ def _native(mol: Chem.Mol, fixed: dict[int, Point] | None, templates: bool, seed def _candidates(mol: Chem.Mol, fixed: dict[int, Point] | None): n = mol.GetNumAtoms() makers = [("coordgen", lambda m: _coordgen(m, fixed))] - if 3 <= n <= CANDIDATE_LIMIT: + if n >= 3: makers.append(("rdkit-templates", lambda m: _native(m, fixed, True))) makers.append(("rdkit", lambda m: _native(m, fixed, False))) if not fixed and n <= SAMPLED_LIMIT: @@ -45,7 +46,7 @@ def _candidates(mol: Chem.Mol, fixed: dict[int, Point] | None): if not m.GetNumConformers(): continue yield name, m - if fixed or n < 3 or n > CANDIDATE_LIMIT: + if fixed or n < 3: continue straight = Chem.Mol(m) try: @@ -67,6 +68,13 @@ def depict(mol: Chem.Mol, fixed: dict[int, Point] | None = None, Chem.FastFindRings(mol) except Exception: pass + if mol.GetNumAtoms() > CANDIDATE_LIMIT: + try: + _coordgen(mol, fixed) + except Exception: + coord_map = {i: Point2D(x, y) for i, (x, y) in (fixed or {}).items()} + rdDepictor.Compute2DCoords(mol, coordMap=coord_map or None, clearConfs=True) + return None shape = None found: list[tuple[layout_score.Score, Chem.Mol, str]] = [] for name, m in _candidates(mol, fixed): @@ -238,7 +246,7 @@ def clean(frag: dict, ids: list[str] | None = None, bond_length: float | None = def score_fragment(frag: dict, coords: dict[str, Point] | None = None) -> dict | None: atoms = frag.get("atoms") or {} - if not atoms: + if not atoms or len(atoms) > SCORE_LIMIT: return None try: conv = _prepared(frag) From 511350c8824813f9cd8601b2d568b6aad892a7d4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:47:01 -0500 Subject: [PATCH 038/357] style(panel): make the analysis body a size container and let its rows wrap (0.7.0) The label and value of a row shared one line with a shrinkable label, so a long value ran over its label; rows now sit on a grid that keeps both columns and wraps, and the body is a container so narrow panels can stack long rows. --- frontend/src/styles/panel.css | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/frontend/src/styles/panel.css b/frontend/src/styles/panel.css index 4be73b9e..864ae499 100644 --- a/frontend/src/styles/panel.css +++ b/frontend/src/styles/panel.css @@ -5,13 +5,17 @@ .fc-ap { display: flex; flex-direction: column; flex: none; width: var(--fc-panel-w, 296px); height: 100%; min-height: 0; color: var(--text-primary); } .fc-ap-head { display: flex; align-items: center; justify-content: space-between; flex: none; height: 36px; padding: 0 var(--space-2) 0 var(--space-4); border-bottom: 1px solid var(--line-1); } .fc-ap-title { color: var(--text-secondary); font-size: var(--fc-11); font-weight: 600; letter-spacing: 0.4px; text-transform: uppercase; } -.fc-ap-body { flex: 1 1 auto; min-height: 0; padding: var(--space-3) var(--space-4) var(--space-4); overflow-y: auto; overscroll-behavior: contain; } +.fc-ap-body { flex: 1 1 auto; min-height: 0; padding: var(--space-3) var(--space-4) var(--space-4); overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; container: fc-ap / inline-size; } .fc-ap-empty { margin: 0 0 var(--space-3); color: var(--text-muted); font-size: var(--fc-12); line-height: 1.5; } .fc-ap-rows { display: grid; gap: 0; margin: 0; } -.fc-ap-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: baseline; column-gap: var(--space-3); min-height: 30px; padding: 6px 0; border-bottom: 1px solid var(--line-1); } +.fc-ap-row { display: grid; grid-template-columns: minmax(0, max-content) minmax(min(12ch, 50%), 1fr); align-items: baseline; column-gap: var(--space-3); min-height: var(--space-8); padding: var(--space-1) 0; border-bottom: 1px solid var(--line-1); } .fc-ap-row:last-child { border-bottom: 0; } -.fc-ap-row dt { color: var(--text-secondary); font-size: var(--fc-12); } -.fc-ap-val { margin: 0; color: var(--text-primary); font-family: var(--font-mono); font-size: var(--fc-12); font-variant-numeric: tabular-nums; text-align: right; user-select: text; -webkit-user-select: text; } +.fc-ap-row dt { min-width: 0; color: var(--text-secondary); font: var(--fc-12)/1.35 var(--font-ui); overflow-wrap: anywhere; } +.fc-ap-val { min-width: 0; margin: 0; color: var(--text-primary); font: var(--fc-12)/1.35 var(--font-ui); font-variant-numeric: tabular-nums; text-align: right; overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; } + +@container fc-ap (width < 340px) { + .fc-ap-row[data-row="elemental"] { grid-template-columns: minmax(0, 1fr); row-gap: 2px; } +} @media (max-width: 899px) { .fc-workspace { grid-template-columns: minmax(0, 1fr) 0; } @@ -21,4 +25,5 @@ @media (max-width: 599px) { .fc-panel.is-open { width: min(var(--fc-panel-w, 296px), 100%); } + .fc-ap { width: min(var(--fc-panel-w, 296px), 100vw); } } From 70a83dd181f4b0b07dca2af668dd8768d76a3f62 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:47:01 -0500 Subject: [PATCH 039/357] style(analysis): put property and isotope rows on a wrapping two-column grid (0.7.0) Values were cut with an ellipsis and labels truncated; each row now reserves the value width, wraps long values inside their column, stacks elemental analysis and Lipinski under the label in a narrow panel, and uses tabular figures in the UI font instead of monospace. --- frontend/src/styles/chem-ui.css | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/frontend/src/styles/chem-ui.css b/frontend/src/styles/chem-ui.css index 79b7c0b7..c4745fac 100644 --- a/frontend/src/styles/chem-ui.css +++ b/frontend/src/styles/chem-ui.css @@ -96,11 +96,10 @@ .fc-apx-head { display: flex; align-items: center; justify-content: space-between; min-height: 28px; } .fc-apx-title { color: var(--text-secondary); font-size: var(--fc-11); font-weight: 600; letter-spacing: 0.4px; text-transform: uppercase; } .fc-apx-rows { display: grid; margin: 0; } -.fc-apx-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: baseline; column-gap: var(--space-3); min-height: 28px; padding: 5px 0; border-bottom: 1px solid var(--line-0); } +.fc-apx-row { display: grid; grid-template-columns: minmax(0, max-content) minmax(min(var(--fc-apx-w, 8ch), 50%), 1fr); align-items: baseline; column-gap: var(--space-3); min-height: var(--space-7); padding: var(--space-1) 0; border-bottom: 1px solid var(--line-0); } .fc-apx-row:last-child { border-bottom: 0; } -.fc-apx-row dt { overflow: hidden; color: var(--text-secondary); font-size: var(--fc-12); text-overflow: ellipsis; white-space: nowrap; cursor: help; } -.fc-apx-val { min-width: min(var(--fc-apx-w, 8ch), 100%); max-width: 100%; margin: 0; overflow: hidden; color: var(--text-primary); font: var(--fc-12)/1.35 var(--font-mono); font-variant-numeric: tabular-nums; text-align: right; text-overflow: ellipsis; white-space: nowrap; transition: opacity var(--transition-fast); user-select: text; -webkit-user-select: text; } -.fc-apx-row[data-row="elemental"], .fc-apx-row[data-row="lipinski"] { grid-template-columns: auto minmax(0, 1fr); } +.fc-apx-row dt { min-width: 0; color: var(--text-secondary); font: var(--fc-12)/1.35 var(--font-ui); overflow-wrap: anywhere; cursor: help; } +.fc-apx-val { min-width: 0; margin: 0; color: var(--text-primary); font: var(--fc-12)/1.35 var(--font-ui); font-variant-numeric: tabular-nums; text-align: right; overflow-wrap: anywhere; transition: opacity var(--transition-fast); user-select: text; -webkit-user-select: text; } .fc-apx-row.is-empty .fc-apx-val { color: var(--text-muted); } .fc-apx-row.is-pass .fc-apx-val { color: var(--ok-soft); } .fc-apx-row.is-fail .fc-apx-val { color: var(--warn); } @@ -110,10 +109,14 @@ .fc-ap-rows[hidden] { display: none; } .fc-ap-rows[hidden] + .fc-apx { margin-top: 0; padding-top: 0; border-top: 0; } +@container fc-ap (width < 340px) { + .fc-apx-row:is([data-row="elemental"], [data-row="lipinski"]) { grid-template-columns: minmax(0, 1fr); row-gap: 2px; } +} + .fc-iso { display: grid; gap: 4px; padding-top: var(--space-2); } -.fc-iso-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-3); min-height: 22px; } -.fc-iso-title { color: var(--text-secondary); font-size: var(--fc-12); } -.fc-iso-mono { color: var(--text-muted); font: var(--fc-11)/1.3 var(--font-mono); font-variant-numeric: tabular-nums; } +.fc-iso-head { display: grid; grid-template-columns: minmax(0, max-content) minmax(min(20ch, 50%), 1fr); align-items: baseline; column-gap: var(--space-3); min-height: 22px; } +.fc-iso-title { min-width: 0; color: var(--text-secondary); font: var(--fc-12)/1.35 var(--font-ui); overflow-wrap: anywhere; } +.fc-iso-mono { min-width: 0; color: var(--text-muted); font: var(--fc-11)/1.35 var(--font-ui); font-variant-numeric: tabular-nums; text-align: right; overflow-wrap: anywhere; } .fc-iso-frame { height: 92px; border-radius: var(--radius-sm, 4px); background: var(--accent-tint); } .fc-iso-plot { display: block; width: 100%; height: 92px; overflow: visible; } .fc-iso-axis { stroke: var(--line-1); stroke-width: 1; vector-effect: non-scaling-stroke; } @@ -122,12 +125,17 @@ .fc-iso-stick text { fill: var(--text-muted); font: 9px var(--font-mono); } .fc-iso.is-empty .fc-iso-frame { opacity: 0.5; } .fc-iso-ions { display: grid; margin: 0; } -.fc-iso-ion { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: baseline; column-gap: var(--space-3); min-height: 24px; padding: 3px 0; } -.fc-iso-ion dt { color: var(--text-secondary); font: var(--fc-12)/1.35 var(--font-mono); } -.fc-iso-ion dd { min-width: 10ch; margin: 0; color: var(--text-primary); font: var(--fc-12)/1.35 var(--font-mono); font-variant-numeric: tabular-nums; text-align: right; user-select: text; -webkit-user-select: text; } +.fc-iso-ion { display: grid; grid-template-columns: minmax(0, max-content) minmax(min(10ch, 50%), 1fr); align-items: baseline; column-gap: var(--space-3); min-height: var(--space-6); padding: 3px 0; } +.fc-iso-ion dt { min-width: 0; color: var(--text-secondary); font: var(--fc-12)/1.35 var(--font-ui); font-variant-numeric: tabular-nums; overflow-wrap: anywhere; } +.fc-iso-ion dd { min-width: 0; margin: 0; color: var(--text-primary); font: var(--fc-12)/1.35 var(--font-ui); font-variant-numeric: tabular-nums; text-align: right; overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; } .fc-iso-ion.is-empty dd { color: var(--text-muted); } .fc-apx.is-shown .fc-iso-plot, .fc-apx.is-shown .fc-iso-ion dd { opacity: 0.5; } +@container fc-ap (width < 250px) { + .fc-iso-head { grid-template-columns: minmax(0, 1fr); } + .fc-iso-mono { min-height: calc(var(--fc-11) * 1.35); } +} + .fc-markush { display: grid; gap: var(--space-2); } .fc-markush-sum { margin: 0; color: var(--text-secondary); font-size: var(--fc-12); } .fc-markush-list { display: grid; align-content: start; height: 280px; overflow-y: auto; padding: 4px; border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-field); } From b3de277434b2b400642543b0b02bb985ba44c93b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:47:08 -0500 Subject: [PATCH 040/357] fix(analysis): keep element symbols and units with their numbers when a value wraps (0.7.0) Wrapped values could split C from 66.11% or 853.92 from g/mol; the panel now joins them with a no-break space on screen only, so copied text is unchanged. --- frontend/src/ui/analysis-properties.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/frontend/src/ui/analysis-properties.ts b/frontend/src/ui/analysis-properties.ts index 9d8d914a..99be3bb3 100644 --- a/frontend/src/ui/analysis-properties.ts +++ b/frontend/src/ui/analysis-properties.ts @@ -27,6 +27,9 @@ function merged(doc: FormChemDocument, frags: readonly Fragment[]): Source { return src; } +const NBSP = String.fromCharCode(0xa0); +const glued = (v: string): string => v.replace(/([A-Z][a-z]?) (?=\d)/g, `$1${NBSP}`).replace(/(\d) (?=[^\s\d(][^\s,]*$)/, `$1${NBSP}`); + const sameRefs = (a: readonly unknown[], b: readonly unknown[]): boolean => a.length === b.length && a.every((x, i) => x === b[i]); export function mountAnalysisProperties(host: HTMLElement): PropertiesSection { @@ -62,7 +65,7 @@ export function mountAnalysisProperties(host: HTMLElement): PropertiesSection { const paint = (): void => { for (const { row, dt, dd, def } of cells.values()) { const v = props ? rowValue(def, props) : ''; - setText(dd, v || DASH); + setText(dd, v ? glued(v) : DASH); const method = `${t('Method')}: ${rowMethod(def, props)}`; setTitle(dt, method); setTitle(dd, v ? `${v}\n${method}` : method); From fdc238d34f7a6a6183552804fa623f6f60730d8f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:47:17 -0500 Subject: [PATCH 041/357] fix(analysis): show the [M+H]+ ion in the m/z row of a neutral molecule (0.7.0) A neutral structure has no m/z of its own, so the row showed a lone dash; it now shows the protonated adduct from the isotope pattern, or exact mass plus a proton when the pattern is missing. --- frontend/src/ui/analysis-properties.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/frontend/src/ui/analysis-properties.ts b/frontend/src/ui/analysis-properties.ts index 99be3bb3..d840721e 100644 --- a/frontend/src/ui/analysis-properties.ts +++ b/frontend/src/ui/analysis-properties.ts @@ -30,6 +30,15 @@ function merged(doc: FormChemDocument, frags: readonly Fragment[]): Source { const NBSP = String.fromCharCode(0xa0); const glued = (v: string): string => v.replace(/([A-Z][a-z]?) (?=\d)/g, `$1${NBSP}`).replace(/(\d) (?=[^\s\d(][^\s,]*$)/, `$1${NBSP}`); +const PROTON = 1.007276467; + +function neutralMz(p: Properties, pattern: IsotopePattern | null): string { + const a = pattern?.adducts.find((x) => x.ion === '[M+H]+'); + if (a) return `${a.ion} ${a.mz.toFixed(4)}`; + const m = p.values.exact_mass?.value; + return typeof m === 'number' && !pattern?.charge ? `[M+H]+ ${(m + PROTON).toFixed(4)}` : ''; +} + const sameRefs = (a: readonly unknown[], b: readonly unknown[]): boolean => a.length === b.length && a.every((x, i) => x === b[i]); export function mountAnalysisProperties(host: HTMLElement): PropertiesSection { @@ -64,7 +73,7 @@ export function mountAnalysisProperties(host: HTMLElement): PropertiesSection { const paint = (): void => { for (const { row, dt, dd, def } of cells.values()) { - const v = props ? rowValue(def, props) : ''; + const v = props ? rowValue(def, props) || (def.key === 'mz' ? neutralMz(props, pattern) : '') : ''; setText(dd, v ? glued(v) : DASH); const method = `${t('Method')}: ${rowMethod(def, props)}`; setTitle(dt, method); From bfb171bb992d839b9f07a25fbf6dad05cea2316e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:47:17 -0500 Subject: [PATCH 042/357] fix(analysis): hide the empty hint as soon as a structure is in scope (0.7.0) The hint stayed until derived values arrived and then vanished, moving the properties up after the fact; it now goes in the same frame as the edit. --- frontend/src/ui/analysis-panel.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/frontend/src/ui/analysis-panel.ts b/frontend/src/ui/analysis-panel.ts index 0a1fea84..89eed60a 100644 --- a/frontend/src/ui/analysis-panel.ts +++ b/frontend/src/ui/analysis-panel.ts @@ -163,6 +163,7 @@ export function refreshAnalysis(): void { const fresh = !!derived && found.every((d) => !!d); const counts = documentCounts(s.doc, frags.map((f) => f.id), fresh ? derived : null); if (!fresh) { + if (panel) setHidden(q(panel, '.fc-ap-empty'), true); setStatusFormula(hillFormula(counts), true); return; } From 536bac267aacdb0f217e494f437a36d212753562 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:47:42 -0500 Subject: [PATCH 043/357] style(check): put the problem code under its message in the structure check panel (0.7.0) The unbreakable code took its own column and squeezed the message to a few words a line, worst in German; it now sits on a line of its own under the message and can wrap. --- frontend/src/styles/chem-ui.css | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/frontend/src/styles/chem-ui.css b/frontend/src/styles/chem-ui.css index c4745fac..168ad713 100644 --- a/frontend/src/styles/chem-ui.css +++ b/frontend/src/styles/chem-ui.css @@ -79,7 +79,7 @@ .fc-check-item { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 6px; border-radius: var(--radius-md); } .fc-check-item.is-active { background: var(--accent-wash); } .fc-check-item > .fc-btn[hidden] { display: none; } -.fc-check-main { display: grid; grid-template-columns: 16px minmax(0, 1fr) auto; align-items: start; column-gap: 8px; width: 100%; min-height: 32px; padding: 7px 8px; border: 0; border-radius: var(--radius-md); background: transparent; color: var(--text-secondary); font: var(--fc-12)/1.4 var(--font-ui); text-align: left; cursor: pointer; } +.fc-check-main { display: grid; grid-template-columns: 16px minmax(0, 1fr); align-items: start; column-gap: var(--space-2); width: 100%; min-height: 32px; padding: 7px 8px; border: 0; border-radius: var(--radius-md); background: transparent; color: var(--text-secondary); font: var(--fc-12)/1.4 var(--font-ui); text-align: left; cursor: pointer; } .fc-check-main:hover:not(:disabled) { background: var(--bg-hover); color: var(--text-primary); } .fc-check-main:disabled { cursor: default; } .fc-check-main:focus-visible { outline: 2px solid var(--accent-color); outline-offset: -2px; } @@ -88,7 +88,8 @@ .fc-check-item.is-warning .fc-check-icon { color: var(--warn); } .fc-check-item.is-info .fc-check-icon { color: var(--text-muted); } .fc-check-msg { min-width: 0; overflow-wrap: anywhere; } -.fc-check-code { color: var(--text-muted); font: var(--fc-10)/1.7 var(--font-mono); } +.fc-check-code { grid-column: 2; min-width: 0; color: var(--text-muted); font: var(--fc-10)/1.6 var(--font-mono); overflow-wrap: anywhere; } +.fc-check-code:empty { display: none; } .fc-check-status { min-height: 34px; padding: 8px 12px 10px; border-top: 1px solid var(--line-1); } .fc-check-panel.is-stale .fc-check-status:not(.is-shown) { visibility: hidden; } From 8d1a5e48f25778c4184adc7a5aa6576a9d378e3b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:47:49 -0500 Subject: [PATCH 044/357] style(markush): wrap enumerated SMILES and formulas instead of cutting them off (0.7.0) The SMILES column ended in an ellipsis with no way to read the rest; it now wraps anywhere in monospace, while the index and formula use tabular figures in the UI font. --- frontend/src/styles/chem-ui.css | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/frontend/src/styles/chem-ui.css b/frontend/src/styles/chem-ui.css index 168ad713..a3bc1277 100644 --- a/frontend/src/styles/chem-ui.css +++ b/frontend/src/styles/chem-ui.css @@ -140,10 +140,10 @@ .fc-markush { display: grid; gap: var(--space-2); } .fc-markush-sum { margin: 0; color: var(--text-secondary); font-size: var(--fc-12); } .fc-markush-list { display: grid; align-content: start; height: 280px; overflow-y: auto; padding: 4px; border: 1px solid var(--line-2); border-radius: var(--radius-md); background: var(--surface-field); } -.fc-markush-row { display: grid; grid-template-columns: 4ch 12ch minmax(0, 1fr); column-gap: var(--space-3); align-items: baseline; min-height: 24px; padding: 2px 4px; font: var(--fc-12)/1.4 var(--font-mono); } +.fc-markush-row { display: grid; grid-template-columns: 4ch minmax(0, 12ch) minmax(0, 1fr); column-gap: var(--space-3); align-items: baseline; min-height: var(--space-6); padding: 2px var(--space-1); font: var(--fc-12)/1.4 var(--font-ui); font-variant-numeric: tabular-nums; } .fc-markush-n { color: var(--text-muted); text-align: right; } -.fc-markush-formula { color: var(--text-secondary); } -.fc-markush-smiles { overflow: hidden; color: var(--text-primary); text-overflow: ellipsis; white-space: nowrap; user-select: text; -webkit-user-select: text; } +.fc-markush-formula { min-width: 0; color: var(--text-secondary); overflow-wrap: anywhere; } +.fc-markush-smiles { min-width: 0; color: var(--text-primary); font-family: var(--font-mono); overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; } .fc-markush-note[hidden] { display: none; } .fc-roles { display: grid; gap: var(--space-2); } From 99ca7994510b019d514431f53d09fa4b15fad1e7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:47:59 -0500 Subject: [PATCH 045/357] style(dialogs): wrap key and value rows instead of cutting values with an ellipsis (0.7.0) The MCP address and the engine line with its data folder were truncated in the Agents and MCP dialog when the path was long; both columns now wrap and the value keeps a reserved width. --- frontend/src/styles/dialogs.css | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/frontend/src/styles/dialogs.css b/frontend/src/styles/dialogs.css index b2e3a5a8..ca698488 100644 --- a/frontend/src/styles/dialogs.css +++ b/frontend/src/styles/dialogs.css @@ -61,9 +61,9 @@ select.fc-input { padding-right: 6px; } .fc-badge::before { content: ''; flex: none; width: 6px; height: 6px; border-radius: 50%; background: currentColor; } .fc-badge.is-on { border-color: color-mix(in srgb, var(--ok) 45%, var(--line-2)); background: color-mix(in srgb, var(--ok) 14%, var(--surface-2)); color: color-mix(in srgb, var(--ok) 70%, var(--text-primary)); } .fc-badge.is-off { border-color: var(--line-1); background: var(--surface-1); color: var(--text-muted); } -.fc-kv { display: grid; grid-template-columns: minmax(64px, auto) minmax(0, 1fr); gap: 4px 12px; margin: 0; font-size: var(--fc-12); } -.fc-kv > dt { color: var(--text-muted); } -.fc-kv > dd { min-width: 0; margin: 0; overflow: hidden; color: var(--text-primary); text-overflow: ellipsis; white-space: nowrap; user-select: text; -webkit-user-select: text; } +.fc-kv { display: grid; grid-template-columns: minmax(0, max-content) minmax(min(16ch, 50%), 1fr); align-items: baseline; gap: var(--space-1) var(--space-3); margin: 0; font-size: var(--fc-12); line-height: 1.4; } +.fc-kv > dt { min-width: 0; color: var(--text-muted); overflow-wrap: anywhere; } +.fc-kv > dd { min-width: 0; margin: 0; color: var(--text-primary); overflow-wrap: anywhere; user-select: text; -webkit-user-select: text; } .fc-dlg-stack { display: grid; gap: var(--space-3); } .fc-dlg-section { display: grid; gap: 10px; } From 3c35c3ae4b421ccdfa4f3bb1726dd4dfa8fff8d1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:48:18 -0500 Subject: [PATCH 046/357] style(roles): let the reaction roles rows wrap names and formulas (0.7.0) The formula column could not shrink, so a long one cut the component name to an ellipsis; the name now wraps and the formula is capped and wraps in its own right-aligned column. --- frontend/src/styles/chem-ui.css | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/frontend/src/styles/chem-ui.css b/frontend/src/styles/chem-ui.css index a3bc1277..d7b48cf9 100644 --- a/frontend/src/styles/chem-ui.css +++ b/frontend/src/styles/chem-ui.css @@ -149,7 +149,7 @@ .fc-roles { display: grid; gap: var(--space-2); } .fc-roles-step { margin: 0; } .fc-roles-list { display: grid; align-content: start; gap: 2px; max-height: 320px; overflow-y: auto; } -.fc-roles-row { display: grid; grid-template-columns: minmax(0, 1fr) auto 140px; align-items: center; column-gap: var(--space-3); min-height: 36px; padding: 2px 6px; border-radius: var(--radius-md); } +.fc-roles-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, max-content) 140px; align-items: center; column-gap: var(--space-3); min-height: 36px; padding: 2px 6px; border-radius: var(--radius-md); } .fc-roles-row.is-selected { background: var(--accent-tint); } -.fc-roles-name { overflow: hidden; color: var(--text-primary); font-size: var(--fc-13); text-overflow: ellipsis; white-space: nowrap; } -.fc-roles-detail { color: var(--text-muted); font: var(--fc-12)/1.3 var(--font-mono); } +.fc-roles-name { min-width: 0; color: var(--text-primary); font: var(--fc-13)/1.35 var(--font-ui); overflow-wrap: anywhere; } +.fc-roles-detail { min-width: 0; max-width: 24ch; color: var(--text-muted); font: var(--fc-12)/1.3 var(--font-ui); font-variant-numeric: tabular-nums; text-align: right; overflow-wrap: anywhere; } From d19ac1360bcebb9b4e3883249ccee392b879ad35 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:50:46 -0500 Subject: [PATCH 047/357] style(tokens): add ok, warn and danger ink colours that stay readable in light themes (0.7.0) The pale status colours are made for dark surfaces and nearly vanish on Light, Sand and 90s; the ink tokens equal them in dark themes and mix toward the text colour in light ones. --- frontend/src/styles/tokens.css | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/frontend/src/styles/tokens.css b/frontend/src/styles/tokens.css index c7d5aba2..7f9a31f8 100644 --- a/frontend/src/styles/tokens.css +++ b/frontend/src/styles/tokens.css @@ -122,6 +122,9 @@ --danger: #ef4444; --danger-soft: #f87171; --danger-text: #fca5a5; + --ok-ink: var(--ok-soft); + --warn-ink: var(--warn); + --danger-ink: var(--danger-text); --success-fill: #059669; --success-fill-hover: #047857; --danger-fill: #dc2626; @@ -188,6 +191,9 @@ body.theme-light { --cta-bg: var(--text-primary); --cta-bg-hover: color-mix(in srgb, var(--text-primary) 85%, var(--bg-primary)); --cta-text: var(--bg-secondary); + --ok-ink: color-mix(in srgb, var(--ok) 55%, var(--text-primary)); + --warn-ink: color-mix(in srgb, var(--warn) 45%, var(--text-primary)); + --danger-ink: color-mix(in srgb, var(--danger) 70%, var(--text-primary)); --bg-input: var(--bg-secondary); --bg-hover: rgba(0, 0, 0, 0.06); --bg-scrim: rgba(40, 36, 28, 0.45); From 0cff4b07b7ac6984db003b36c6424957383c9e70 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:52:24 -0500 Subject: [PATCH 048/357] style(analysis): colour the Lipinski verdict and check counts with the readable inks (0.7.0) The Lipinski violations line and the structure check counts and icons used the pale status colours, which were close to invisible on the light themes. --- frontend/src/styles/chem-ui.css | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/frontend/src/styles/chem-ui.css b/frontend/src/styles/chem-ui.css index d7b48cf9..a9575f76 100644 --- a/frontend/src/styles/chem-ui.css +++ b/frontend/src/styles/chem-ui.css @@ -30,7 +30,7 @@ .fc-rgroup-member-label { overflow: hidden; color: var(--text-primary); font-family: var(--font-mono); text-overflow: ellipsis; white-space: nowrap; } .fc-rgroup-member-detail { color: var(--text-muted); font-size: var(--fc-11); } .fc-rgroup-occ-note { margin-top: -6px; padding-left: calc(110px + var(--space-3)); min-height: 17px; } -.fc-note.is-error { color: var(--danger-text); } +.fc-note.is-error { color: var(--danger-ink); } .fc-abbr-name { font-family: var(--font-mono); } .fc-abbr-name.is-invalid { border-color: var(--danger); } @@ -68,8 +68,8 @@ .fc-check-title { overflow: hidden; color: var(--text-primary); font-size: var(--fc-13); font-weight: 600; text-overflow: ellipsis; white-space: nowrap; } .fc-check-counts { display: inline-flex; gap: 8px; margin-right: 6px; font: var(--fc-12)/1 var(--font-mono); } .fc-check-count { display: inline-flex; align-items: center; gap: 3px; min-width: 3.2ch; } -.fc-check-count.is-error { color: var(--danger-text); } -.fc-check-count.is-warning { color: var(--warn); } +.fc-check-count.is-error { color: var(--danger-ink); } +.fc-check-count.is-warning { color: var(--warn-ink); } .fc-check-count.is-info { color: var(--text-secondary); } .fc-check-count.is-zero { color: var(--text-muted); opacity: 0.7; } .fc-check-scope { padding: 8px 12px 0; } @@ -84,8 +84,8 @@ .fc-check-main:disabled { cursor: default; } .fc-check-main:focus-visible { outline: 2px solid var(--accent-color); outline-offset: -2px; } .fc-check-icon { display: inline-grid; place-items: center; height: 17px; } -.fc-check-item.is-error .fc-check-icon { color: var(--danger-text); } -.fc-check-item.is-warning .fc-check-icon { color: var(--warn); } +.fc-check-item.is-error .fc-check-icon { color: var(--danger-ink); } +.fc-check-item.is-warning .fc-check-icon { color: var(--warn-ink); } .fc-check-item.is-info .fc-check-icon { color: var(--text-muted); } .fc-check-msg { min-width: 0; overflow-wrap: anywhere; } .fc-check-code { grid-column: 2; min-width: 0; color: var(--text-muted); font: var(--fc-10)/1.6 var(--font-mono); overflow-wrap: anywhere; } @@ -102,8 +102,8 @@ .fc-apx-row dt { min-width: 0; color: var(--text-secondary); font: var(--fc-12)/1.35 var(--font-ui); overflow-wrap: anywhere; cursor: help; } .fc-apx-val { min-width: 0; margin: 0; color: var(--text-primary); font: var(--fc-12)/1.35 var(--font-ui); font-variant-numeric: tabular-nums; text-align: right; overflow-wrap: anywhere; transition: opacity var(--transition-fast); user-select: text; -webkit-user-select: text; } .fc-apx-row.is-empty .fc-apx-val { color: var(--text-muted); } -.fc-apx-row.is-pass .fc-apx-val { color: var(--ok-soft); } -.fc-apx-row.is-fail .fc-apx-val { color: var(--warn); } +.fc-apx-row.is-pass .fc-apx-val { color: var(--ok-ink); } +.fc-apx-row.is-fail .fc-apx-val { color: var(--warn-ink); } .fc-apx.is-shown .fc-apx-val { opacity: 0.5; } .fc-apx-note { margin-top: 4px; } .fc-apx-note[hidden] { display: none; } From faf87bab269aedc1a15693931688c23cdf1a35a3 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 22:53:28 -0500 Subject: [PATCH 049/357] fix(analysis): fill the m/z row of charged structures from the isotope pattern (0.7.0) The properties reply carries no m/z, so the row stayed a dash for ions too; a charged structure now shows its [M] ion m/z, falling back to exact mass over the charge. --- frontend/src/ui/analysis-properties.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/frontend/src/ui/analysis-properties.ts b/frontend/src/ui/analysis-properties.ts index d840721e..0d8b2ef0 100644 --- a/frontend/src/ui/analysis-properties.ts +++ b/frontend/src/ui/analysis-properties.ts @@ -32,11 +32,18 @@ const glued = (v: string): string => v.replace(/([A-Z][a-z]?) (?=\d)/g, `$1${NBS const PROTON = 1.007276467; -function neutralMz(p: Properties, pattern: IsotopePattern | null): string { +function ionMz(p: Properties, pattern: IsotopePattern | null): string { + const m = p.values.exact_mass?.value; + const given = p.values.charge?.value; + const z = pattern ? pattern.charge : typeof given === 'number' ? given : 0; + if (z) { + const a = pattern?.adducts[0]; + if (a) return a.mz.toFixed(4); + return typeof m === 'number' ? (m / Math.abs(z)).toFixed(4) : ''; + } const a = pattern?.adducts.find((x) => x.ion === '[M+H]+'); if (a) return `${a.ion} ${a.mz.toFixed(4)}`; - const m = p.values.exact_mass?.value; - return typeof m === 'number' && !pattern?.charge ? `[M+H]+ ${(m + PROTON).toFixed(4)}` : ''; + return typeof m === 'number' ? `[M+H]+ ${(m + PROTON).toFixed(4)}` : ''; } const sameRefs = (a: readonly unknown[], b: readonly unknown[]): boolean => a.length === b.length && a.every((x, i) => x === b[i]); @@ -73,7 +80,7 @@ export function mountAnalysisProperties(host: HTMLElement): PropertiesSection { const paint = (): void => { for (const { row, dt, dd, def } of cells.values()) { - const v = props ? rowValue(def, props) || (def.key === 'mz' ? neutralMz(props, pattern) : '') : ''; + const v = props ? rowValue(def, props) || (def.key === 'mz' ? ionMz(props, pattern) : '') : ''; setText(dd, v ? glued(v) : DASH); const method = `${t('Method')}: ${rowMethod(def, props)}`; setTitle(dt, method); From b48f662565836373635825b678fdff67f244abb0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:04:49 -0500 Subject: [PATCH 050/357] feat(menus): fold the menus that do not fit into a More menus button (0.7.0) The menu bar gains a trailing More menus button whose menu lists the folded menus as whole submenus, and arrows, Home, End, F10 and Alt access keys skip to it or open the folded menu inside it, so every menu stays reachable from the keyboard. --- frontend/src/ui/menu.ts | 76 +++++++++++++++++++++++++++++++++-------- 1 file changed, 61 insertions(+), 15 deletions(-) diff --git a/frontend/src/ui/menu.ts b/frontend/src/ui/menu.ts index fd1661fb..6a373a51 100644 --- a/frontend/src/ui/menu.ts +++ b/frontend/src/ui/menu.ts @@ -303,12 +303,17 @@ export class MenuBar { private returnTo: HTMLElement | null = null; private barBack: HTMLElement | null = null; private altLone = false; - - constructor(host: HTMLElement, commands: CommandRegistry, defs: MenuDef[]) { - defs.forEach((def, i) => { - const btn = el(''); - setText(btn, t(def.label)); - btn.dataset.menu = def.label.toLowerCase(); + private readonly moreAt: number; + private keep: number; + + constructor(private readonly host: HTMLElement, commands: CommandRegistry, defs: MenuDef[]) { + this.moreAt = this.keep = defs.length; + const overflow: MenuDef = { label: 'More menus', items: () => this.bars.slice(this.keep, this.moreAt).map((b) => ({ label: b.def.label, items: itemsOf(b.def) })) }; + [...defs, overflow].forEach((def, i) => { + const more = def === overflow; + const btn = el(``); + if (more) { setTitle(btn, t(def.label)); btn.setAttribute('aria-label', t(def.label)); } else setText(btn, t(def.label)); + btn.dataset.menu = more ? 'more' : def.label.toLowerCase(); host.appendChild(btn); const menu = new PopupMenu(commands); menu.setItems(itemsOf(def)); @@ -347,6 +352,47 @@ export class MenuBar { get isOpen(): boolean { return this.openIndex >= 0; } + private live(i: number): boolean { return i === this.moreAt ? this.keep < this.moreAt : i < this.keep; } + + private step(from: number, dir: 1 | -1): number { + const n = this.bars.length; + let i = from; + do i = (i + dir + n) % n; while (!this.live(i)); + return i; + } + + private widths(): { gap: number; each: number[] } { + return { gap: Number.parseFloat(getComputedStyle(this.host).columnGap) || 0, each: this.bars.map((b) => b.btn.getBoundingClientRect().width) }; + } + + need(): number { + const { gap, each } = this.widths(); + return each.slice(0, this.moreAt).reduce((s, w) => s + w + gap, -gap); + } + + fold(room: number): void { + const { gap, each } = this.widths(); + let keep = this.moreAt; + if (each.slice(0, this.moreAt).reduce((s, w) => s + w + gap, -gap) > room) { + let used = each[this.moreAt]; + keep = 0; + while (keep < this.moreAt && used + gap + each[keep] <= room) { used += gap + each[keep]; keep += 1; } + } + if (keep === this.keep) return; + if (this.openIndex >= 0) this.close(); + this.keep = keep; + this.bars.forEach((b, i) => setClass(b.btn, 'is-folded', !this.live(i))); + } + + private reveal(i: number, keyboard: boolean): void { + const more = this.bars[this.moreAt].menu; + const row = more.panel.querySelector(`[data-sub="${CSS.escape(this.bars[i].def.label.toLowerCase())}"]`); + const sub = row ? more.openSubAt(row) : null; + if (!row || !sub || !keyboard) return; + more.focusRow(row); + sub.focusFirst(); + } + private mark(btn: HTMLButtonElement, on: boolean): void { setClass(btn, 'is-open', on); btn.setAttribute('aria-expanded', String(on)); @@ -371,7 +417,7 @@ export class MenuBar { e.preventDefault(); const from = document.activeElement; this.barBack = from instanceof HTMLElement && !this.bars.some((b) => b.btn === from) ? from : this.barBack; - this.bars[0].btn.focus(); + this.bars[this.step(this.bars.length - 1, 1)].btn.focus(); } private leaveBar(): void { @@ -391,11 +437,11 @@ export class MenuBar { if (modalOpen() || e.ctrlKey || e.metaKey || !this.shown()) return; const at = this.bars.findIndex((b) => b.btn === document.activeElement); if (at >= 0 && !e.altKey && !e.shiftKey) { - const focus = (i: number): void => this.bars[(i + this.bars.length) % this.bars.length].btn.focus(); - if (e.key === 'ArrowRight') { stop(); focus(at + 1); return; } - if (e.key === 'ArrowLeft') { stop(); focus(at - 1); return; } - if (e.key === 'Home') { stop(); focus(0); return; } - if (e.key === 'End') { stop(); focus(-1); return; } + const focus = (i: number): void => this.bars[i].btn.focus(); + if (e.key === 'ArrowRight') { stop(); focus(this.step(at, 1)); return; } + if (e.key === 'ArrowLeft') { stop(); focus(this.step(at, -1)); return; } + if (e.key === 'Home') { stop(); focus(this.step(this.bars.length - 1, 1)); return; } + if (e.key === 'End') { stop(); focus(this.step(0, -1)); return; } if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Enter' || e.key === ' ') { stop(); this.open(at, true); return; } if (e.key === 'Escape') { stop(); this.leaveBar(); return; } if (e.key.length === 1 && /\S/.test(e.key)) { @@ -416,14 +462,14 @@ export class MenuBar { if (e.ctrlKey || e.metaKey || e.altKey) return; const cur = this.bars[this.openIndex].menu.deepest(); if (cur.nav(e)) { stop(); return; } - const n = this.bars.length; - if (e.key === 'ArrowRight') { stop(); this.open((this.openIndex + 1) % n, true); } - else if (e.key === 'ArrowLeft') { stop(); this.open((this.openIndex + n - 1) % n, true); } + if (e.key === 'ArrowRight') { stop(); this.open(this.step(this.openIndex, 1), true); } + else if (e.key === 'ArrowLeft') { stop(); this.open(this.step(this.openIndex, -1), true); } else if (e.key === 'Escape') { stop(); this.close(); } else if (e.key === 'Tab') { stop(); this.close(); } } open(i: number, keyboard = false): void { + if (!this.live(i)) { if (i !== this.moreAt) { this.open(this.moreAt, keyboard); this.reveal(i, keyboard); } return; } const from = document.activeElement, keep = this.returnTo; this.shut(); this.returnTo = keep ?? (keyboard && from instanceof HTMLElement && !from.closest('.fc-menu') && !this.bars.some((b) => b.btn === from) ? from : null); From ac1142e938bc5bf038ee4809634c5ef15090e97e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:04:49 -0500 Subject: [PATCH 051/357] feat(titlebar): measure the title bar and fold menus before they reach the title (0.7.0) A ResizeObserver on the title bar works out the room left after the brand, the tools and the title's minimum, folds the brand name and labels first and then menus from the right, all before paint so resizing never shows a clipped or overlapping frame. --- frontend/src/ui/titlebar.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/frontend/src/ui/titlebar.ts b/frontend/src/ui/titlebar.ts index 5f43c784..d4de9b4f 100644 --- a/frontend/src/ui/titlebar.ts +++ b/frontend/src/ui/titlebar.ts @@ -102,6 +102,29 @@ export function mountTitleTools(host: HTMLElement, registry: CommandRegistry): T }; } +export interface FoldingRow { need(): number; fold(room: number): void } + +export function fitMenuRow(bar: HTMLElement, menus: FoldingRow): () => void { + const row = q(bar, '.fc-menubar'), brand = q(bar, '.fc-brand'), tools = q(bar, '.fc-title-tools'); + const px = (v: string): number => Number.parseFloat(v) || 0; + const room = (): number => { + const cs = getComputedStyle(bar); + return bar.clientWidth - px(cs.paddingLeft) - px(cs.paddingRight) - px(cs.columnGap) * 3 - px(cs.getPropertyValue('--fc-title-min')) + - brand.getBoundingClientRect().width - tools.getBoundingClientRect().width; + }; + const fit = (): void => { + setClass(bar, 'is-tight', false); + if (!row.getClientRects().length) return; + if (menus.need() <= room()) { menus.fold(Infinity); return; } + setClass(bar, 'is-tight', true); + menus.fold(room()); + }; + const watch = new ResizeObserver(fit); + watch.observe(bar); + document.fonts?.addEventListener('loadingdone', fit); + return () => { watch.disconnect(); document.fonts?.removeEventListener('loadingdone', fit); }; +} + export function setDocTitle(text: string, dirty = false): void { const root = docTitleHost ?? document.querySelector('.fc-titlebar'); const input = root?.querySelector('.fc-doc-title'); From 009a03c63e1e66b7f3994f613aab2991913cff73 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:04:49 -0500 Subject: [PATCH 052/357] style(titlebar): fold the brand name and labels whenever the menus need the room (0.7.0) The tight stage applies the same folding as the 1439 px breakpoint at any width where the in-window menus would not fit otherwise, and never under the macOS system menu. --- frontend/src/styles/titlebar.css | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/frontend/src/styles/titlebar.css b/frontend/src/styles/titlebar.css index 6c762681..57afbaa3 100644 --- a/frontend/src/styles/titlebar.css +++ b/frontend/src/styles/titlebar.css @@ -29,6 +29,12 @@ body.theme-light .fc-export-btn, .fc-export-btn.is-half-off { box-shadow: none; .fc-tt-label { width: var(--ctl-md); padding: 0; justify-content: center; } } +:root:not(.has-native-menus) .fc-titlebar.is-tight .fc-menubar { gap: 0; } +:root:not(.has-native-menus) .fc-titlebar.is-tight .fc-menu-btn { padding: 0 6px; } +:root:not(.has-native-menus) .fc-titlebar.is-tight .fc-brand-name { display: none; } +:root:not(.has-native-menus) .fc-titlebar.is-tight .fc-tt-label > span:not(.icon) { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } +:root:not(.has-native-menus) .fc-titlebar.is-tight .fc-tt-label { width: var(--ctl-md); padding: 0; justify-content: center; } + @media (max-width: 1099px) { .fc-export-btn > .fc-export-main > span:not(.icon) { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } } From e14ba3b32ab5ef5f728935062d00addde70f56a1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:04:49 -0500 Subject: [PATCH 053/357] fix(window): keep the menu row clear of the document title and the window tools (0.7.0) The brand and tools columns keep their full width, the menu row clips instead of scrolling, and folded buttons leave the flow but stay measurable, so at 1440 px Help no longer shrinks to one letter beside the title. --- frontend/src/styles/shell.css | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/frontend/src/styles/shell.css b/frontend/src/styles/shell.css index 94cc922c..c772f7ec 100644 --- a/frontend/src/styles/shell.css +++ b/frontend/src/styles/shell.css @@ -1,16 +1,17 @@ .fc-app { display: grid; grid-template-rows: var(--fc-titlebar-h) minmax(0, 1fr) var(--fc-status-h); grid-template-columns: minmax(0, 1fr); height: 100%; background: var(--bg-primary); color: var(--text-primary); user-select: none; -webkit-user-select: none; overflow: clip; } :where(.fc-btn, .fc-icon-btn, .fc-tt-btn, .fc-brand, .fc-menu-btn):focus-visible { outline: 2px solid var(--accent-color); outline-offset: 1px; } -.fc-titlebar { --fc-title-min: 160px; position: relative; display: grid; grid-template-columns: auto auto minmax(var(--fc-title-min), 1fr) auto; align-items: center; column-gap: var(--space-3); min-width: 0; padding: 0 var(--space-3); background: linear-gradient(to bottom, var(--surface-2), var(--surface-1)); border-bottom: 1px solid var(--line-0); } +.fc-titlebar { --fc-title-min: 160px; position: relative; display: grid; grid-template-columns: max-content auto minmax(var(--fc-title-min), 1fr) max-content; align-items: center; column-gap: var(--space-3); min-width: 0; padding: 0 var(--space-3); background: linear-gradient(to bottom, var(--surface-2), var(--surface-1)); border-bottom: 1px solid var(--line-0); } :root[data-oled] .fc-titlebar { background: var(--bg-primary); } .fc-brand { display: inline-flex; align-items: center; gap: var(--space-2); height: var(--ctl-md); padding: 0 var(--space-1); border: 0; border-radius: var(--radius); background: transparent; color: var(--accent-color); font: inherit; cursor: pointer; } .fc-brand:hover { background: var(--bg-hover); } .fc-brand-name { color: var(--text-primary); font-size: var(--fc-13); font-weight: 600; letter-spacing: 0.2px; } .fc-mark { display: block; flex: none; } -.fc-menubar { display: flex; align-items: center; gap: 2px; min-width: 0; overflow-x: auto; overflow-y: hidden; scrollbar-width: none; } -.fc-menubar::-webkit-scrollbar { display: none; } +.fc-menubar { position: relative; display: flex; align-items: center; gap: 2px; min-width: 0; margin: -3px; padding: 3px; overflow: clip; } .fc-menu-btn { flex: none; } -.fc-menu-btn { height: var(--ctl-md); padding: 0 var(--space-2); border: 0; border-radius: var(--radius); background: transparent; color: var(--text-secondary); font-size: var(--fc-12); cursor: default; } +.fc-menu-btn { height: var(--ctl-md); padding: 0 var(--space-2); border: 0; border-radius: var(--radius); background: transparent; color: var(--text-secondary); font-size: var(--fc-12); white-space: nowrap; cursor: default; } +.fc-menu-btn.is-folded { position: absolute; top: 0; left: 0; visibility: hidden; pointer-events: none; } +.fc-menu-overflow { display: inline-flex; align-items: center; justify-content: center; } .fc-menu-btn:hover, .fc-menu-btn.is-open { background: var(--bg-tertiary); color: var(--text-primary); } .has-native-menus .fc-titlebar { grid-template-columns: auto minmax(var(--fc-title-min), 1fr) auto; } From 1d6049ebec42cc81cc8c7a3df9ae248e57d17f3f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:04:49 -0500 Subject: [PATCH 054/357] fix(window): fit the menu row to the title bar instead of scrolling it with the wheel (0.7.0) The wheel scroller hid menus off the end of the row; the row now folds them into More menus, so the scroller goes and the title bar fitting is wired in. --- frontend/src/app.ts | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/frontend/src/app.ts b/frontend/src/app.ts index c83bc698..8dfedcbe 100644 --- a/frontend/src/app.ts +++ b/frontend/src/app.ts @@ -28,7 +28,7 @@ import { mountStatus } from './ui/status'; import { insertStoichTable, isStoichOpen, mountStoichPanel, toggleStoich } from './ui/stoich-panel'; import { insertTemplate, templateDialog, type TemplateHooks } from './ui/template-dialog'; import { applyTheme, readDensity, watchSharedTheme } from './ui/themes'; -import { mountTitleTools } from './ui/titlebar'; +import { fitMenuRow, mountTitleTools } from './ui/titlebar'; import { toast } from './ui/toast'; import { checkForUpdates, checkUpdatesAtStart } from './ui/updates'; import { VERSION } from './version'; @@ -312,13 +312,7 @@ export function startApp(): ShellHosts { mountPalette(); const menus = buildMenus(() => ext.menuItems(), () => recentIds); - new MenuBar(h.menubar, commands, menus); - h.menubar.addEventListener('wheel', (e) => { - const bar = h.menubar; - if (bar.scrollWidth <= bar.clientWidth || Math.abs(e.deltaX) >= Math.abs(e.deltaY)) return; - e.preventDefault(); - bar.scrollLeft += e.deltaY; - }, { passive: false }); + fitMenuRow(h.titlebar, new MenuBar(h.menubar, commands, menus)); if (wantsNativeMenus()) { native = new NativeMenus(commands, () => menus); rebuildNative(); From 1b94a005eb547f657aff5739e7656e08174565e5 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:05:59 -0500 Subject: [PATCH 055/357] fix(canvas): leave Escape and the arrow keys to an open menu bar menu (0.7.0) --- frontend/src/canvas/view.ts | 4 ++-- frontend/src/ui/menu.ts | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/frontend/src/canvas/view.ts b/frontend/src/canvas/view.ts index 482bd9b7..a3352549 100644 --- a/frontend/src/canvas/view.ts +++ b/frontend/src/canvas/view.ts @@ -4,7 +4,7 @@ import { atomPath, bondPath, objectPath, pagePath, type Op } from '../engine/ops import { t } from '../i18n'; import { contextMenuOpen } from '../ui/context-menu'; import { el, isMac, overlayRoot, q, setClass, setHidden, setStyleVar, setText } from '../ui/dom'; -import { modalOpen } from '../ui/menu'; +import { menuBarOpen, modalOpen } from '../ui/menu'; import { openCanvasMenu } from './context'; import { fmt } from './render/geom'; import { hitExists, hitTest, NO_HIT, objectBounds, sameHit, styleFor, visibleOrder, type Box } from './hit'; @@ -928,7 +928,7 @@ export class CanvasView { private ours(): boolean { if (!this.root.isConnected || !this.root.getClientRects().length) return false; - if (modalOpen() || contextMenuOpen() || document.body.classList.contains('fc-home-open')) return false; + if (modalOpen() || menuBarOpen() || contextMenuOpen() || document.body.classList.contains('fc-home-open')) return false; const a = document.activeElement; return this.inside || this.root.contains(a) || a === document.body || a === null; } diff --git a/frontend/src/ui/menu.ts b/frontend/src/ui/menu.ts index 6a373a51..72c9d335 100644 --- a/frontend/src/ui/menu.ts +++ b/frontend/src/ui/menu.ts @@ -295,6 +295,9 @@ export class PopupMenu { const itemsOf = (def: MenuDef): MenuItem[] => (typeof def.items === 'function' ? def.items() : def.items); +const BARS: MenuBar[] = []; +export const menuBarOpen = (): boolean => BARS.some((b) => b.isOpen); + export class MenuBar { private readonly bars: Array<{ btn: HTMLButtonElement; menu: PopupMenu; def: MenuDef }> = []; private openIndex = -1; @@ -308,6 +311,7 @@ export class MenuBar { constructor(private readonly host: HTMLElement, commands: CommandRegistry, defs: MenuDef[]) { this.moreAt = this.keep = defs.length; + BARS.push(this); const overflow: MenuDef = { label: 'More menus', items: () => this.bars.slice(this.keep, this.moreAt).map((b) => ({ label: b.def.label, items: itemsOf(b.def) })) }; [...defs, overflow].forEach((def, i) => { const more = def === overflow; From ddd8f1d9cb4ca41c8d6b0a8af5ecefb0b6f48f34 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:06:41 -0500 Subject: [PATCH 056/357] feat(files): add an engine route that writes a file the window chose (0.7.0) The desktop shell has no file writer, so exports, SMARTS and pictures go through POST /api/files/write behind the window key, limited to the home folder unless a save dialog picked the place. --- backend/app/main.py | 2 + backend/app/routers/files.py | 75 ++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 backend/app/routers/files.py diff --git a/backend/app/main.py b/backend/app/main.py index 9eb5b571..9b4bf5c2 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -17,6 +17,7 @@ from app.services import claude_code, consent, history from app.services import terminal as terminals from app.services.chat import engine as chat_engine +from app.routers import files as file_writes mimetypes.add_type("text/javascript", ".js") mimetypes.add_type("text/javascript", ".mjs") @@ -71,6 +72,7 @@ async def lifespan(this: FastAPI): app.include_router(terminal.router) app.include_router(live.router) app.include_router(mcp.router) +app.include_router(file_writes.router) _dist = config.dist_dir() if _dist is not None: diff --git a/backend/app/routers/files.py b/backend/app/routers/files.py new file mode 100644 index 00000000..6388109e --- /dev/null +++ b/backend/app/routers/files.py @@ -0,0 +1,75 @@ +import asyncio +import base64 +import binascii +import os +from pathlib import Path + +from fastapi import APIRouter, Body, Depends, HTTPException, Request + +from app.core import files, window_key + +router = APIRouter() + +WRITE_LIMIT = 200 * 1024 * 1024 +SUFFIXES = { + ".svg", ".svgz", ".png", ".pdf", ".eps", ".ps", + ".mol", ".mdl", ".sdf", ".sd", ".rxn", ".rdf", ".rd", + ".smi", ".smiles", ".cxsmi", ".cxsmiles", ".sma", ".smarts", ".inchi", ".key", + ".cml", ".cdxml", ".cdx", ".helm", ".xyz", ".mol2", ".pdb", + ".txt", ".csv", ".tsv", ".json", ".jdx", ".dx", +} + + +def _guard(request: Request) -> None: + window_key.require(request) + + +def _inside(path: Path, folder: Path) -> bool: + try: + path.relative_to(folder) + return True + except ValueError: + return False + + +def _target(raw: object, picked: bool) -> Path: + if not isinstance(raw, str) or not raw.strip(): + raise HTTPException(400, "Give the absolute path of the file to write.") + given = Path(raw.strip()).expanduser() + if not given.is_absolute(): + raise HTTPException(400, "Give the absolute path of the file to write.") + target = Path(os.path.realpath(given)) + if target.suffix.lower() not in SUFFIXES: + raise HTTPException(400, f"FormChem does not write {target.suffix} files." if target.suffix else "FormChem does not write files without an extension.") + if target.is_dir(): + raise HTTPException(400, f"{target} is a folder.") + if not target.parent.is_dir(): + raise HTTPException(400, f"The folder {target.parent} does not exist.") + if not picked and not _inside(target, Path(os.path.realpath(Path.home()))): + raise HTTPException(403, "FormChem writes outside your home folder only where you chose the place in a save dialog.") + return target + + +def _payload(body: dict) -> bytes: + if isinstance(body.get("text"), str): + return body["text"].encode("utf-8") + raw = body.get("base64") + if not isinstance(raw, str): + raise HTTPException(400, "Send the file as text or as base64.") + try: + return base64.b64decode(raw, validate=True) + except (binascii.Error, ValueError): + raise HTTPException(400, "The base64 data is not valid.") + + +@router.post("/api/files/write", dependencies=[Depends(_guard)]) +async def write_file(body: dict = Body(...)) -> dict: + target = _target(body.get("path"), body.get("picked") is True) + data = _payload(body) + if len(data) > WRITE_LIMIT: + raise HTTPException(413, f"The file is larger than {WRITE_LIMIT // (1024 * 1024)} MB.") + try: + written = await asyncio.to_thread(files.write_atomic, target, data) + except OSError as exc: + raise HTTPException(400, f"Could not write {target.name}: {exc.strerror or exc}") + return {"path": str(written), "bytes": len(data)} From 560439d152c3565f9e3a586e29355dd54fb49f31 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:07:04 -0500 Subject: [PATCH 057/357] feat(save): add the shared save path for exported files (0.7.0) saveFile asks for a place with the native save dialog and writes through the engine in the desktop app, and downloads in a browser, so every export saves the same way. --- frontend/src/app/save-file.ts | 121 ++++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 frontend/src/app/save-file.ts diff --git a/frontend/src/app/save-file.ts b/frontend/src/app/save-file.ts new file mode 100644 index 00000000..620cc893 --- /dev/null +++ b/frontend/src/app/save-file.ts @@ -0,0 +1,121 @@ +import { t } from '../i18n'; +import { post } from '../io/api'; +import { inTauri } from '../ui/dom'; + +export interface SaveFileRequest { + name: string; + mime: string; + data: string | Uint8Array; + kind?: string; +} + +export interface SaveFileResult { saved: boolean; name: string; path?: string; via: 'desktop' | 'download' } + +const WRITE_URL = '/api/files/write'; +const FOLDER_KEY = 'formchem.saveFolder'; +const CHUNK = 0x8000; + +const tauriCore = (): Promise => import('@tauri-apps/api/core'); + +export function safeFileName(raw: string, fallback = 'Untitled'): string { + const text = raw.replace(/[\x00-\x1f<>:"/\\|?*]+/g, ' ').replace(/\s+/g, ' ').trim().replace(/^[ .-]+|[ .]+$/g, ''); + return text.slice(0, 120) || fallback; +} + +const extOf = (name: string): string => { + const at = name.lastIndexOf('.'); + return at > 0 ? name.slice(at + 1).toLowerCase() : ''; +}; + +const sepOf = (path: string): string => (path.includes('\\') && !path.includes('/') ? '\\' : '/'); + +function folderOf(path: string): string { + const at = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); + return at > 0 ? path.slice(0, at) : ''; +} + +function lastFolder(): string { + try { return localStorage.getItem(FOLDER_KEY) ?? ''; } catch { return ''; } +} + +function rememberFolder(folder: string): void { + if (!folder) return; + try { localStorage.setItem(FOLDER_KEY, folder); } catch { return; } +} + +export function toBase64(bytes: Uint8Array): string { + let out = ''; + for (let i = 0; i < bytes.length; i += CHUNK) out += String.fromCharCode(...bytes.subarray(i, i + CHUNK)); + return btoa(out); +} + +async function writeAt(path: string, data: string | Uint8Array): Promise { + const body = typeof data === 'string' ? { path, text: data, picked: true } : { path, base64: toBase64(data), picked: true }; + const out = await post<{ path: string }>(WRITE_URL, body); + return out.path; +} + +async function pickPath(req: SaveFileRequest): Promise { + const { invoke } = await tauriCore(); + const ext = extOf(req.name); + const folder = lastFolder(); + const defaultPath = folder ? `${folder}${sepOf(folder)}${req.name}` : req.name; + const filters = ext ? [{ name: req.kind || ext.toUpperCase(), extensions: [ext] }] : []; + return invoke('plugin:dialog|save', { options: { defaultPath, filters } }); +} + +async function pickFolder(): Promise { + const { invoke } = await tauriCore(); + const folder = lastFolder(); + const found = await invoke('plugin:dialog|open', { + options: { directory: true, multiple: false, title: t('Choose a folder for the files'), ...(folder ? { defaultPath: folder } : {}) }, + }); + return Array.isArray(found) ? found[0] ?? null : found; +} + +function download(req: SaveFileRequest): void { + const part: BlobPart = typeof req.data === 'string' ? req.data : req.data.slice().buffer; + const url = URL.createObjectURL(new Blob([part], { type: req.mime })); + const a = document.createElement('a'); + a.href = url; + a.download = req.name; + a.rel = 'noopener'; + document.body.appendChild(a); + a.click(); + a.remove(); + window.setTimeout(() => URL.revokeObjectURL(url), 2000); +} + +export async function saveFile(req: SaveFileRequest): Promise { + if (!inTauri()) { + download(req); + return { saved: true, name: req.name, via: 'download' }; + } + const path = await pickPath(req); + if (!path) return { saved: false, name: req.name, via: 'desktop' }; + const written = await writeAt(path, req.data); + rememberFolder(folderOf(written)); + return { saved: true, name: written.split(/[\\/]/).pop() ?? req.name, path: written, via: 'desktop' }; +} + +export async function saveFiles(reqs: SaveFileRequest[]): Promise { + if (reqs.length === 1) return [await saveFile(reqs[0])]; + if (!inTauri()) { + const out: SaveFileResult[] = []; + for (const req of reqs) { + download(req); + out.push({ saved: true, name: req.name, via: 'download' }); + await new Promise((r) => window.setTimeout(r, 120)); + } + return out; + } + const folder = await pickFolder(); + if (!folder) return reqs.map((r) => ({ saved: false, name: r.name, via: 'desktop' as const })); + rememberFolder(folder); + const out: SaveFileResult[] = []; + for (const req of reqs) { + const path = await writeAt(`${folder}${sepOf(folder)}${req.name}`, req.data); + out.push({ saved: true, name: req.name, path, via: 'desktop' }); + } + return out; +} From 6fb1ac0969662761c7b1b521e8060c20fb745553 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:07:20 -0500 Subject: [PATCH 058/357] fix(chem): save Export SMARTS through the shared save path in the desktop app (0.7.0) The desktop app copied the SMARTS instead of saving it because the shell had no file writer; it now asks for a place and writes the .sma file. --- frontend/src/app/chem-commands.ts | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/frontend/src/app/chem-commands.ts b/frontend/src/app/chem-commands.ts index 2ad4d2ed..a13a47b3 100644 --- a/frontend/src/app/chem-commands.ts +++ b/frontend/src/app/chem-commands.ts @@ -15,7 +15,6 @@ import { askAbbreviation } from '../ui/abbreviation-dialog'; import { setAnalysisOpen, refreshAnalysis } from '../ui/analysis-panel'; import { askAtomList } from '../ui/atom-list-dialog'; import { copyText, promptName } from '../ui/dialogs'; -import { inTauri } from '../ui/dom'; import { showMarkushResults } from '../ui/markush-dialog'; import type { MenuItem } from '../ui/menu'; import { pref, setPref } from '../ui/prefs/store'; @@ -26,6 +25,7 @@ import { showStructureCheck, type CheckRow } from '../ui/structure-check'; import { toast } from '../ui/toast'; import { formatAnalysisText } from './analysis-text'; import { atomListOps, atomQueryOps, bondQueryOps, bondTopologyOps, clearStereoGroupOps, rgroupAtomOps, rgroupOps, stereoGroupOps, usedRGroups, type GroupKind } from './chem-edits'; +import { safeFileName, saveFile } from './save-file'; export interface ChemHost { readonly client: DocumentClient | null; @@ -514,19 +514,8 @@ export async function exportSmarts(host: ChemHost): Promise { try { const out = await smartsOf(host); if (!out) { toast(t('There is no structure to write as SMARTS.')); return; } - if (inTauri()) { - const ok = await copyText(out.text); - toast(ok ? t('Saving SMARTS files arrives with the file formats in 0.7.0; the SMARTS was copied instead.') : t('Could not copy to the clipboard'), ok ? 'info' : 'error'); - return; - } - const name =`${(host.client?.doc.title || 'query').replace(/[\\/:*?"<>|]+/g, ' ').trim() || 'query'}.sma`; - const url = URL.createObjectURL(new Blob([`${out.text}\n`], { type: 'text/plain' })); - const a = document.createElement('a'); - a.href = url; - a.download = name; - a.click(); - window.setTimeout(() => URL.revokeObjectURL(url), 1000); - toast(`${t('Exported the SMARTS to')} ${name}`); + const done = await saveFile({ name: `${safeFileName(host.client?.doc.title || 'query', 'query')}.sma`, mime: 'text/plain', data: `${out.text}\n`, kind: 'SMARTS' }); + if (done.saved) toast(`${t('Exported the SMARTS to')} ${done.name}`); } catch (e) { toast(`${t('Export SMARTS')}: ${errText(e)}`, 'error'); } From 490f483d8992d5a051aaa80b5ff7083a05baed47 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:08:44 -0500 Subject: [PATCH 059/357] feat(embed): carry the editable drawing inside exported pictures (0.7.0) Exported SVG, PNG, PDF and EPS hold a document.json subset (SVG metadata, PNG iTXt, PDF embedded file, EPS comments) so pasting or opening the picture restores the drawing; paste shares these readers. --- frontend/src/app/embedded-source.ts | 302 ++++++++++++++++++++++++++++ 1 file changed, 302 insertions(+) create mode 100644 frontend/src/app/embedded-source.ts diff --git a/frontend/src/app/embedded-source.ts b/frontend/src/app/embedded-source.ts new file mode 100644 index 00000000..a986ead8 --- /dev/null +++ b/frontend/src/app/embedded-source.ts @@ -0,0 +1,302 @@ +import { splitKey } from '../canvas/selection'; +import type { Selection } from '../canvas/types'; +import { FORMAT, isFragment, type DocObject, type FormChemDocument, type Fragment, type Id, type Page, type Reaction } from '../engine/model'; +import { toBase64 } from './save-file'; + +export const SOURCE_MIME = 'application/x-formchem+json'; +export const PNG_KEYWORD = SOURCE_MIME; +export const SVG_NS_SOURCE = 'https://formai.tools/ns/formchem/1'; + +export type SourceScope = 'page' | 'selection' | 'structure'; +export interface EmbeddedSource { doc: FormChemDocument; scope: SourceScope } + +const PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10]; +const EPS_LINE = '%FormChemSource:'; +const PDF_MARK = '/Subtype /application#2Fx-formchem+json'; +const SCOPES: readonly SourceScope[] = ['page', 'selection', 'structure']; +const enc = new TextEncoder(); +const dec = new TextDecoder(); + +function wholeSet(doc: FormChemDocument, ids: Iterable): Set { + const out = new Set(); + const add = (id: Id): void => { + const o = doc.objects[id]; + if (!o || out.has(id)) return; + out.add(id); + if (o.kind === 'group') for (const k of o.children) add(k); + }; + for (const id of ids) add(id); + return out; +} + +function trimFragment(frag: Fragment, keep: Set): Fragment { + const atoms: Fragment['atoms'] = {}; + for (const [id, a] of Object.entries(frag.atoms)) if (keep.has(id)) atoms[id] = a; + const bonds: Fragment['bonds'] = {}; + for (const [id, b] of Object.entries(frag.bonds)) if (keep.has(b.a) && keep.has(b.b)) bonds[id] = b; + const out: Fragment = { ...frag, atoms, bonds }; + if (frag.stereo_groups) { + const groups = frag.stereo_groups.map((g) => ({ ...g, ...(g.atoms ? { atoms: g.atoms.filter((a) => keep.has(a)) } : {}) })).filter((g) => !g.atoms || g.atoms.length); + if (groups.length) out.stereo_groups = groups; + else delete out.stereo_groups; + } + return out; +} + +function pickObjects(doc: FormChemDocument, page: Page, pick: Selection | Id[] | null): { ids: Set; trimmed: Map } { + const trimmed = new Map(); + if (pick === null) return { ids: wholeSet(doc, page.order), trimmed }; + if (Array.isArray(pick)) return { ids: wholeSet(doc, pick), trimmed }; + const atoms = new Map>(); + const bonds = new Map>(); + for (const k of pick.atoms) { + const [f, a] = splitKey(k); + if (!atoms.has(f)) atoms.set(f, new Set()); + atoms.get(f)!.add(a); + } + for (const k of pick.bonds) { + const [f, b] = splitKey(k); + if (!bonds.has(f)) bonds.set(f, new Set()); + bonds.get(f)!.add(b); + } + const ids = wholeSet(doc, pick.objects); + for (const fid of new Set([...atoms.keys(), ...bonds.keys()])) { + const frag = doc.objects[fid]; + if (!isFragment(frag) || ids.has(fid)) continue; + const keep = new Set(atoms.get(fid) ?? []); + for (const bid of bonds.get(fid) ?? []) { + const b = frag.bonds[bid]; + if (b) { keep.add(b.a); keep.add(b.b); } + } + if (!keep.size) continue; + ids.add(fid); + if (keep.size < Object.keys(frag.atoms).length) trimmed.set(fid, trimFragment(frag, keep)); + } + return { ids, trimmed }; +} + +function reactionsWithin(reactions: Reaction[] | undefined, ids: Set): Reaction[] { + const out: Reaction[] = []; + for (const r of reactions ?? []) { + const steps = r.steps.filter((s) => ids.has(s.arrow)).map((s) => ({ + ...s, + reactants: s.reactants.filter((x) => ids.has(x)), + products: s.products.filter((x) => ids.has(x)), + agents: s.agents.filter((x) => ids.has(x)), + ...(s.conditions ? { conditions: s.conditions.filter((x) => ids.has(x)) } : {}), + })); + if (steps.length) out.push({ ...r, steps }); + } + return out; +} + +export function subsetDocument(doc: FormChemDocument, page: Id, pick: Selection | Id[] | null, scope: SourceScope): FormChemDocument { + const p = doc.pages.find((x) => x.id === page) ?? doc.pages[0]; + if (!p) return { ...doc, pages: [], objects: {}, media: undefined }; + const { ids, trimmed } = pickObjects(doc, p, pick); + for (const id of [...ids]) if (doc.objects[id]?.kind === 'image') ids.delete(id); + const objects: Record = {}; + for (const id of ids) { + const o = trimmed.get(id) ?? doc.objects[id]; + objects[id] = o.kind === 'group' ? { ...o, children: o.children.filter((k) => ids.has(k)) } : o; + } + const nested = new Set(); + for (const o of Object.values(objects)) if (o.kind === 'group') for (const k of o.children) nested.add(k); + const order = p.order.filter((id) => ids.has(id)); + for (const id of ids) if (!order.includes(id) && !nested.has(id)) order.push(id); + const reactions = reactionsWithin(p.reactions, ids); + const pageOut: Page = { ...p, order }; + if (reactions.length) pageOut.reactions = reactions; + else delete pageOut.reactions; + const out: FormChemDocument = { ...doc, pages: [pageOut], objects, meta: { ...doc.meta, embedded: { scope, from: doc.id } } }; + delete out.media; + return out; +} + +export const sourceText = (doc: FormChemDocument): string => JSON.stringify(doc); + +export function readSourceText(text: string): EmbeddedSource | null { + let raw: unknown; + try { raw = JSON.parse(text); } catch { return null; } + if (!raw || typeof raw !== 'object') return null; + const doc = raw as FormChemDocument; + if (doc.format !== FORMAT || !Array.isArray(doc.pages) || !doc.pages.length || !doc.objects || typeof doc.objects !== 'object') return null; + const said = (doc.meta?.embedded as { scope?: unknown } | undefined)?.scope; + const scope = SCOPES.includes(said as SourceScope) ? said as SourceScope : 'page'; + return { doc, scope }; +} + +function bytesOf(b64: string): Uint8Array | null { + try { + const bin = atob(b64.replace(/\s+/g, '')); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; + } catch { return null; } +} + +export function embedInSvg(svg: string, doc: FormChemDocument): string { + const open = /]*>/.exec(svg); + if (!open) return svg; + const at = open.index + open[0].length; + const block = `${toBase64(enc.encode(sourceText(doc)))}`; + return `${svg.slice(0, at)}${block}${svg.slice(at)}`; +} + +export function extractFromSvg(svg: string): EmbeddedSource | null { + let payload: string | null = null; + if (typeof DOMParser !== 'undefined') { + const xml = new DOMParser().parseFromString(svg, 'image/svg+xml'); + const found = xml.getElementsByTagNameNS(SVG_NS_SOURCE, 'source')[0]; + if (found) payload = found.textContent; + } + if (payload === null) { + const m = /<(?:[\w-]+:)?source\b[^>]*application\/x-formchem\+json[^>]*>([^<]*) { + const table = new Uint32Array(256); + for (let n = 0; n < 256; n++) { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + table[n] = c >>> 0; + } + return table; +})(); + +function crc32(bytes: Uint8Array): number { + let c = 0xffffffff; + for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8); + return (c ^ 0xffffffff) >>> 0; +} + +function chunk(type: string, data: Uint8Array): Uint8Array { + const out = new Uint8Array(12 + data.length); + const view = new DataView(out.buffer); + view.setUint32(0, data.length); + out.set(enc.encode(type), 4); + out.set(data, 8); + view.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length))); + return out; +} + +interface PngChunk { type: string; start: number; end: number; data: Uint8Array } + +function pngChunks(png: Uint8Array): PngChunk[] | null { + if (png.length < 8 || PNG_SIGNATURE.some((b, i) => png[i] !== b)) return null; + const view = new DataView(png.buffer, png.byteOffset, png.byteLength); + const out: PngChunk[] = []; + let at = 8; + while (at + 12 <= png.length) { + const len = view.getUint32(at); + const type = String.fromCharCode(png[at + 4], png[at + 5], png[at + 6], png[at + 7]); + const end = at + 12 + len; + if (end > png.length) return null; + out.push({ type, start: at, end, data: png.subarray(at + 8, at + 8 + len) }); + at = end; + if (type === 'IEND') break; + } + return out; +} + +function itxtKeyword(data: Uint8Array): string { + const zero = data.indexOf(0); + return zero > 0 ? String.fromCharCode(...data.subarray(0, zero)) : ''; +} + +export function embedInPng(png: Uint8Array, doc: FormChemDocument | null, dpi?: number): Uint8Array { + const chunks = pngChunks(png); + if (!chunks || chunks[0]?.type !== 'IHDR') return png; + const extra: Uint8Array[] = []; + if (dpi && dpi > 0) { + const phys = new Uint8Array(9); + const ppm = Math.round(dpi / 0.0254); + const view = new DataView(phys.buffer); + view.setUint32(0, ppm); + view.setUint32(4, ppm); + phys[8] = 1; + extra.push(chunk('pHYs', phys)); + } + extra.push(chunk('tEXt', enc.encode('Software\0FormChem'))); + if (doc) { + const head = enc.encode(`${PNG_KEYWORD}\0\0\0\0\0`); + const body = enc.encode(sourceText(doc)); + const data = new Uint8Array(head.length + body.length); + data.set(head, 0); + data.set(body, head.length); + extra.push(chunk('iTXt', data)); + } + const kept = chunks.filter((c) => c.type !== 'pHYs' && !(c.type === 'iTXt' && itxtKeyword(c.data) === PNG_KEYWORD) && !(c.type === 'tEXt' && itxtKeyword(c.data) === 'Software')); + const parts: Uint8Array[] = [png.subarray(0, 8), png.subarray(kept[0].start, kept[0].end), ...extra, ...kept.slice(1).map((c) => png.subarray(c.start, c.end))]; + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + let at = 0; + for (const p of parts) { out.set(p, at); at += p.length; } + return out; +} + +export function extractFromPng(png: Uint8Array): EmbeddedSource | null { + for (const c of pngChunks(png) ?? []) { + if (c.type !== 'iTXt' || itxtKeyword(c.data) !== PNG_KEYWORD) continue; + let at = PNG_KEYWORD.length + 1; + if (c.data[at] !== 0) return null; + at += 2; + at = c.data.indexOf(0, at) + 1; + at = c.data.indexOf(0, at) + 1; + if (at <= 0) return null; + return readSourceText(dec.decode(c.data.subarray(at))); + } + return null; +} + +function latin1(bytes: Uint8Array, from = 0, to = bytes.length): string { + let out = ''; + for (let i = from; i < to; i += 0x8000) out += String.fromCharCode(...bytes.subarray(i, Math.min(to, i + 0x8000))); + return out; +} + +export function extractFromPdf(pdf: Uint8Array): EmbeddedSource | null { + const text = latin1(pdf); + const mark = text.indexOf(PDF_MARK); + if (mark < 0) return null; + const open = text.lastIndexOf('<<', mark); + const close = text.indexOf('>>', mark); + const len = /\/Length\s+(\d+)/.exec(text.slice(open, close)); + const stream = text.indexOf('stream', close); + if (!len || stream < 0) return null; + let start = stream + 6; + if (text[start] === '\r') start++; + if (text[start] === '\n') start++; + return readSourceText(dec.decode(pdf.subarray(start, start + Number(len[1])))); +} + +export function extractFromEps(eps: string): EmbeddedSource | null { + const lines = eps.split(/\r\n|\r|\n/).filter((l) => l.startsWith(EPS_LINE)).map((l) => l.slice(EPS_LINE.length).trim()); + if (!lines.length) return null; + const bytes = bytesOf(lines.join('')); + return bytes ? readSourceText(dec.decode(bytes)) : null; +} + +const startsWith = (bytes: Uint8Array, text: string): boolean => text.split('').every((ch, i) => bytes[i] === ch.charCodeAt(0)); + +export async function extractSource(data: Blob | Uint8Array | string): Promise { + if (typeof data === 'string') { + const s = data.trimStart(); + if (s.startsWith('%!PS')) return extractFromEps(s); + if (s.startsWith('{')) return readSourceText(s); + return / bytes[i] === b)) return extractFromPng(bytes); + if (startsWith(bytes, '%PDF')) return extractFromPdf(bytes); + if (bytes[0] === 0xc5 && bytes[1] === 0xd0 && bytes[2] === 0xd3 && bytes[3] === 0xc6) { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const at = view.getUint32(4, true), len = view.getUint32(8, true); + return extractFromEps(latin1(bytes, at, at + len)); + } + return extractSource(dec.decode(bytes.subarray(0, Math.min(bytes.length, 64 * 1024 * 1024)))); +} From 5d442af6cc5905537c02b742b09b3ee675731d98 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:09:21 -0500 Subject: [PATCH 060/357] feat(documents): open SVG, PNG, PDF and EPS pictures that carry a FormChem drawing (0.7.0) The engine reads the document.json kept inside FormChem exports and opens it as a new drawing, from a path or an upload, and says plainly when a picture holds none. --- backend/app/routers/documents.py | 3 +- backend/app/services/embedded_source.py | 148 ++++++++++++++++++++++++ backend/app/services/store.py | 9 ++ 3 files changed, 159 insertions(+), 1 deletion(-) create mode 100644 backend/app/services/embedded_source.py diff --git a/backend/app/routers/documents.py b/backend/app/routers/documents.py index e8f0d444..692e284d 100644 --- a/backend/app/routers/documents.py +++ b/backend/app/routers/documents.py @@ -7,6 +7,7 @@ from app.core import config, files, window_key from app.routers.live import HANDLERS from app.services import importers, package +from app.services import embedded_source from app.services import ops as opsmod from app.services.hub import Client from app.services.store import STORE, StoreError @@ -86,7 +87,7 @@ async def upload_document(request: Request) -> dict: upload = found[0] name = files.safe_name(Path(upload.filename or "").name, "Imported") suffix = Path(name).suffix.lower() - if suffix != package.EXT and not importers.can_import(name): + if suffix != package.EXT and not importers.can_import(name) and not embedded_source.can_open(name): raise HTTPException(400, f"FormChem cannot open {suffix or 'this kind of'} files.") data = await upload.read(UPLOAD_LIMIT + 1) if len(data) > UPLOAD_LIMIT: diff --git a/backend/app/services/embedded_source.py b/backend/app/services/embedded_source.py new file mode 100644 index 00000000..e1716ae4 --- /dev/null +++ b/backend/app/services/embedded_source.py @@ -0,0 +1,148 @@ +import base64 +import binascii +import json +import re +import struct +from pathlib import Path + +from app import __version__ +from app.services import model + +MIME = "application/x-formchem+json" +PNG_KEYWORD = MIME.encode("latin-1") +SVG_NS = "https://formai.tools/ns/formchem/1" +SUFFIXES = (".svg", ".png", ".pdf", ".eps") +READ_LIMIT = 64 * 1024 * 1024 +EPS_LINE = b"%FormChemSource:" +PDF_MARK = b"/Subtype /application#2Fx-formchem+json" +PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" +EPS_BINARY = b"\xc5\xd0\xd3\xc6" +_SVG_SOURCE = re.compile(rb"<(?:[\w-]+:)?source\b[^>]*application/x-formchem\+json[^>]*>([^<]*)<", re.S) +_PDF_LENGTH = re.compile(rb"/Length\s+(\d+)") + + +def can_open(path: str | Path) -> bool: + return Path(path).suffix.lower() in SUFFIXES + + +def read_text(data: bytes | str) -> dict | None: + try: + doc = json.loads(data) + except (ValueError, UnicodeDecodeError): + return None + if not isinstance(doc, dict) or doc.get("format") != "formchem": + return None + if not isinstance(doc.get("pages"), list) or not doc["pages"] or not isinstance(doc.get("objects"), dict): + return None + return doc + + +def _b64(raw: bytes) -> bytes | None: + try: + return base64.b64decode(re.sub(rb"\s+", b"", raw), validate=True) + except (binascii.Error, ValueError): + return None + + +def from_svg(data: bytes) -> dict | None: + found = _SVG_SOURCE.search(data) + if not found: + return None + raw = _b64(found.group(1)) + return read_text(raw) if raw else None + + +def from_png(data: bytes) -> dict | None: + if not data.startswith(PNG_SIGNATURE): + return None + at = len(PNG_SIGNATURE) + while at + 12 <= len(data): + (length,) = struct.unpack(">I", data[at:at + 4]) + kind = data[at + 4:at + 8] + body = data[at + 8:at + 8 + length] + at += 12 + length + if kind == b"IEND": + break + if kind != b"iTXt" or not body.startswith(PNG_KEYWORD + b"\0"): + continue + rest = body[len(PNG_KEYWORD) + 1:] + compressed = rest[:1] == b"\1" + rest = rest[2:] + rest = rest[rest.index(b"\0") + 1:] + rest = rest[rest.index(b"\0") + 1:] + if compressed: + import zlib + rest = zlib.decompress(rest) + return read_text(rest) + return None + + +def from_pdf(data: bytes) -> dict | None: + mark = data.find(PDF_MARK) + if mark < 0: + return None + start = data.rfind(b"<<", 0, mark) + end = data.find(b">>", mark) + length = _PDF_LENGTH.search(data, start, end) + stream = data.find(b"stream", end) + if not length or stream < 0: + return None + at = stream + 6 + if data[at:at + 1] == b"\r": + at += 1 + if data[at:at + 1] == b"\n": + at += 1 + return read_text(data[at:at + int(length.group(1))]) + + +def from_eps(data: bytes) -> dict | None: + if data.startswith(EPS_BINARY): + offset, length = struct.unpack(" dict | None: + if data.startswith(PNG_SIGNATURE): + return from_png(data) + if data.startswith(b"%PDF"): + return from_pdf(data) + if data.startswith(b"%!PS") or data.startswith(EPS_BINARY): + return from_eps(data) + head = data.lstrip()[:1] + if head == b"{": + return read_text(data) + return from_svg(data) + + +def open_picture(path: str | Path) -> tuple[dict, list[str]]: + p = Path(path) + with open(p, "rb") as fh: + data = fh.read(READ_LIMIT + 1) + if len(data) > READ_LIMIT: + raise ValueError(f"{p.name} is larger than {READ_LIMIT // (1024 * 1024)} MB.") + doc = extract(data) + if doc is None: + raise ValueError(f"{p.name} has no FormChem drawing inside; only pictures exported by FormChem can be opened as drawings.") + version = doc.get("format_version") + if isinstance(version, int) and not isinstance(version, bool) and version > model.FORMAT_VERSION: + raise ValueError(f"{p.name} was made by a newer FormChem; update FormChem to open it.") + doc = dict(doc) + doc.pop("derived", None) + doc.pop("media", None) + doc["id"] = model.new_id("d") + doc["title"] = p.stem + now = model.now_iso() + doc["created"] = now + doc["modified"] = now + meta = dict(doc.get("meta") or {}) + meta["app"] = f"formchem {__version__}" + doc["meta"] = meta + errors = model.validate(doc) + if errors: + raise ValueError(f"The drawing inside {p.name} is not valid: {errors[0]}") + return doc, [f"Opened the drawing kept inside {p.name}."] diff --git a/backend/app/services/store.py b/backend/app/services/store.py index 99591ff5..a9a57ab2 100644 --- a/backend/app/services/store.py +++ b/backend/app/services/store.py @@ -11,6 +11,7 @@ from app.core import config, files from app.services import history, importers, library, model, package from app.services import ops as opsmod +from app.services import embedded_source from app.services.hub import HUB HISTORY_LIMIT = 500 @@ -211,6 +212,14 @@ async def open(self, path: str | Path) -> dict: _remember(p) await self._announce("opened", s) return {**self.info(s), "imported": str(p), "warnings": warnings} + if embedded_source.can_open(p): + try: + doc, warnings = await asyncio.to_thread(embedded_source.open_picture, p) + except (OSError, ValueError) as exc: + raise StoreError(str(exc)) from exc + s = self.add(doc, dirty=True) + await self._announce("opened", s) + return {**self.info(s), "imported": str(p), "warnings": warnings} if p.suffix.lower() != package.EXT: raise StoreError(f"FormChem cannot open {p.suffix or 'this kind of'} files.") try: From 9f5785d40dc6c45bf9d2c79fcad690ca3c4c051a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:14:33 -0500 Subject: [PATCH 061/357] feat(pictures): subset and outline the bundled label fonts with fontTools (0.7.0) Exported SVG embeds WOFF subsets of Arimo and Tinos (OFL allows it), and PDF and EPS draw labels from the same glyph outlines, so every export measures like the canvas. --- backend/app/services/pictures/__init__.py | 0 backend/app/services/pictures/fonts.py | 194 ++++++++++++++++++++++ 2 files changed, 194 insertions(+) create mode 100644 backend/app/services/pictures/__init__.py create mode 100644 backend/app/services/pictures/fonts.py diff --git a/backend/app/services/pictures/__init__.py b/backend/app/services/pictures/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/backend/app/services/pictures/fonts.py b/backend/app/services/pictures/fonts.py new file mode 100644 index 00000000..0fb949d5 --- /dev/null +++ b/backend/app/services/pictures/fonts.py @@ -0,0 +1,194 @@ +import io +import logging +import threading +from functools import lru_cache +from pathlib import Path + +from app.core import config + +FAMILY_MAP = { + "arial": "Arimo", + "helvetica": "Arimo", + "helvetica neue": "Arimo", + "arimo": "Arimo", + "sans-serif": "Arimo", + "times": "Tinos", + "times new roman": "Tinos", + "tinos": "Tinos", + "serif": "Tinos", +} +FILES = { + ("Arimo", False): ("Arimo-VariableFont_wght.ttf", True), + ("Arimo", True): ("Arimo-Italic-VariableFont_wght.ttf", True), + ("Tinos", False): ("Tinos-Regular.ttf", False), + ("Tinos", True): ("Tinos-Italic.ttf", False), +} +TINOS_BOLD = {False: "Tinos-Bold.ttf", True: "Tinos-BoldItalic.ttf"} +PDF_BASE = { + ("Arimo", False, False): "Helvetica", + ("Arimo", True, False): "Helvetica-Bold", + ("Arimo", False, True): "Helvetica-Oblique", + ("Arimo", True, True): "Helvetica-BoldOblique", + ("Tinos", False, False): "Times-Roman", + ("Tinos", True, False): "Times-Bold", + ("Tinos", False, True): "Times-Italic", + ("Tinos", True, True): "Times-BoldItalic", +} +_LOCK = threading.Lock() +logging.getLogger("fontTools").setLevel(logging.ERROR) + + +class FontsMissing(RuntimeError): + pass + + +def available() -> bool: + try: + import fontTools # noqa: F401 + except ImportError: + return False + return fonts_dir() is not None + + +def fonts_dir() -> Path | None: + places = [] + dist = config.dist_dir() + if dist is not None: + places.append(dist / "fonts") + places.append(Path(__file__).resolve().parents[4] / "frontend" / "public" / "fonts") + for place in places: + if (place / "Arimo-VariableFont_wght.ttf").is_file(): + return place + return None + + +def bundled(family_list: str) -> str: + for raw in (family_list or "").split(","): + name = raw.strip().strip("'\"").lower() + if name in FAMILY_MAP: + return FAMILY_MAP[name] + return "Arimo" + + +def is_bold(weight: str | None) -> bool: + if not weight: + return False + w = weight.strip().lower() + if w in ("bold", "bolder"): + return True + try: + return int(w) >= 600 + except ValueError: + return False + + +def pdf_base(family: str, bold: bool, italic: bool) -> str: + return PDF_BASE[(bundled(family), bold, italic)] + + +@lru_cache(maxsize=8) +def face_bytes(family: str, bold: bool, italic: bool) -> bytes: + try: + from fontTools.ttLib import TTFont + from fontTools.varLib import instancer + except ImportError as exc: + raise FontsMissing("fontTools is not installed in the engine") from exc + folder = fonts_dir() + if folder is None: + raise FontsMissing("the bundled label fonts were not found") + fam = bundled(family) + if fam == "Tinos" and bold: + return (folder / TINOS_BOLD[italic]).read_bytes() + name, variable = FILES[(fam, italic)] + if not variable: + return (folder / name).read_bytes() + with _LOCK: + font = TTFont(str(folder / name)) + static = instancer.instantiateVariableFont(font, {"wght": 700 if bold else 400}, inplace=False, updateFontNames=False) + buf = io.BytesIO() + static.save(buf) + return buf.getvalue() + + +@lru_cache(maxsize=8) +def face(family: str, bold: bool, italic: bool): + from fontTools.ttLib import TTFont + return TTFont(io.BytesIO(face_bytes(bundled(family), bold, italic)), lazy=False) + + +def subset_woff(family: str, bold: bool, italic: bool, text: str) -> bytes: + from fontTools import subset + from fontTools.ttLib import TTFont + font = TTFont(io.BytesIO(face_bytes(bundled(family), bold, italic))) + opts = subset.Options() + opts.flavor = "woff" + opts.layout_features = ["kern", "liga", "clig", "calt", "locl", "mark", "mkmk"] + opts.name_IDs = ["*"] + opts.name_languages = ["*"] + opts.notdef_outline = True + opts.drop_tables += ["DSIG"] + sub = subset.Subsetter(opts) + sub.populate(text=text or " ") + sub.subset(font) + buf = io.BytesIO() + font.flavor = "woff" + font.save(buf) + return buf.getvalue() + + +class _Recorder: + def __init__(self, glyphset, matrix): + from fontTools.pens.basePen import BasePen + from fontTools.pens.transformPen import TransformPen + + out = self.out = [] + + class Pen(BasePen): + def _moveTo(self, p): + out.append(("M", p[0], p[1])) + + def _lineTo(self, p): + out.append(("L", p[0], p[1])) + + def _curveToOne(self, p1, p2, p3): + out.append(("C", p1[0], p1[1], p2[0], p2[1], p3[0], p3[1])) + + def _closePath(self): + out.append(("Z",)) + + def _endPath(self): + pass + + self.pen = TransformPen(Pen(glyphset), matrix) + + +def outline(family: str, bold: bool, italic: bool, text: str, size: float, x: float, y: float, matrix=(1, 0, 0, 1, 0, 0)) -> tuple[list[tuple], float]: + font = face(family, bold, italic) + upm = font["head"].unitsPerEm + cmap = font.getBestCmap() or {} + glyphs = font.getGlyphSet() + hmtx = font["hmtx"] + k = size / upm + a, b, c, d, e, f = matrix + segs: list[tuple] = [] + pen_x = x + for ch in text: + name = cmap.get(ord(ch)) or ".notdef" + if name not in glyphs: + name = ".notdef" + gx = (k, 0, 0, -k, pen_x, y) + full = (a * gx[0] + c * gx[1], b * gx[0] + d * gx[1], a * gx[2] + c * gx[3], b * gx[2] + d * gx[3], + a * gx[4] + c * gx[5] + e, b * gx[4] + d * gx[5] + f) + rec = _Recorder(glyphs, full) + glyphs[name].draw(rec.pen) + segs.extend(rec.out) + pen_x += hmtx[name][0] * k + return segs, pen_x - x + + +def advance(family: str, bold: bool, italic: bool, text: str, size: float) -> float: + font = face(family, bold, italic) + upm = font["head"].unitsPerEm + cmap = font.getBestCmap() or {} + hmtx = font["hmtx"] + return sum(hmtx[cmap.get(ord(ch)) or ".notdef"][0] for ch in text) * size / upm From 6b39b247fa8272899096996f315e5970daeb6580 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:14:34 -0500 Subject: [PATCH 062/357] feat(pictures): read the export SVG into a display list for the vector writers (0.7.0) PDF and EPS are written from the same SVG the window exports, so this reads its shapes, paths with arcs, transforms, clips, pictures and positioned text into page coordinates. --- backend/app/services/pictures/svgdraw.py | 573 +++++++++++++++++++++++ 1 file changed, 573 insertions(+) create mode 100644 backend/app/services/pictures/svgdraw.py diff --git a/backend/app/services/pictures/svgdraw.py b/backend/app/services/pictures/svgdraw.py new file mode 100644 index 00000000..06358c27 --- /dev/null +++ b/backend/app/services/pictures/svgdraw.py @@ -0,0 +1,573 @@ +import base64 +import math +import re +import xml.etree.ElementTree as ET +from dataclasses import dataclass, field + +from app.services.pictures import fonts + +SVG = "{http://www.w3.org/2000/svg}" +XLINK = "{http://www.w3.org/1999/xlink}" +KAPPA = 0.5522847498307936 +SKIP = {"metadata", "style", "title", "desc", "defs", "clipPath", "linearGradient", "radialGradient", "mask", "pattern", "symbol", "marker", "filter"} +INHERITED = ("fill", "fill-opacity", "fill-rule", "stroke", "stroke-width", "stroke-opacity", "stroke-linecap", "stroke-linejoin", + "stroke-miterlimit", "stroke-dasharray", "stroke-dashoffset", "font-family", "font-size", "font-weight", "font-style", + "text-anchor", "visibility", "clip-rule") +NAMED = { + "black": (0, 0, 0), "white": (255, 255, 255), "red": (255, 0, 0), "green": (0, 128, 0), "blue": (0, 0, 255), + "gray": (128, 128, 128), "grey": (128, 128, 128), "silver": (192, 192, 192), "maroon": (128, 0, 0), "purple": (128, 0, 128), + "fuchsia": (255, 0, 255), "magenta": (255, 0, 255), "lime": (0, 255, 0), "olive": (128, 128, 0), "yellow": (255, 255, 0), + "navy": (0, 0, 128), "teal": (0, 128, 128), "aqua": (0, 255, 255), "cyan": (0, 255, 255), "orange": (255, 165, 0), + "darkgray": (169, 169, 169), "lightgray": (211, 211, 211), "brown": (165, 42, 42), "pink": (255, 192, 203), +} +_NUM = re.compile(r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?") +_PATH_TOKEN = re.compile(r"[MmZzLlHhVvCcSsQqTtAa]|[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?") +_TRANSFORM = re.compile(r"(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)") +_URL = re.compile(r"url\(\s*['\"]?#([^)'\"]+)['\"]?\s*\)") + +Matrix = tuple[float, float, float, float, float, float] +IDENTITY: Matrix = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0) + + +def mul(m: Matrix, n: Matrix) -> Matrix: + a, b, c, d, e, f = m + p, q, r, s, t, u = n + return (a * p + c * q, b * p + d * q, a * r + c * s, b * r + d * s, a * t + c * u + e, b * t + d * u + f) + + +def apply(m: Matrix, x: float, y: float) -> tuple[float, float]: + return (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]) + + +def scale_of(m: Matrix) -> float: + return math.sqrt(abs(m[0] * m[3] - m[1] * m[2])) or 1.0 + + +@dataclass +class Item: + kind: str + segs: list = field(default_factory=list) + fill: tuple | None = None + fill_alpha: float = 1.0 + even_odd: bool = False + stroke: tuple | None = None + stroke_alpha: float = 1.0 + width: float = 1.0 + cap: int = 0 + join: int = 0 + miter: float = 4.0 + dash: list = field(default_factory=list) + dash_offset: float = 0.0 + clip: list | None = None + text: str = "" + font: str = "Helvetica" + text_matrix: Matrix = IDENTITY + image: bytes = b"" + image_mime: str = "" + image_matrix: Matrix = IDENTITY + + +@dataclass +class Drawing: + width: float + height: float + items: list[Item] + warnings: list[str] + + +def _floats(text: str | None) -> list[float]: + return [float(v) for v in _NUM.findall(text or "")] + + +def _length(text: str | None, default: float = 0.0, font_size: float = 10.0) -> float: + if text is None: + return default + s = text.strip() + m = _NUM.match(s) + if not m: + return default + v = float(m.group(0)) + unit = s[m.end():].strip().lower() + return {"pt": 1.0, "px": 0.75, "in": 72.0, "mm": 72 / 25.4, "cm": 72 / 2.54, "pc": 12.0, "em": font_size}.get(unit, 1.0) * v if unit else v + + +def colour(text: str | None, current: tuple = (0, 0, 0)) -> tuple | None: + if text is None: + return None + s = text.strip().lower() + if not s or s in ("none", "transparent"): + return None + if s == "currentcolor": + return current + if s.startswith("#"): + h = s[1:] + if len(h) in (3, 4): + return tuple(int(ch * 2, 16) / 255 for ch in h[:3]) + if len(h) in (6, 8): + return tuple(int(h[i:i + 2], 16) / 255 for i in (0, 2, 4)) + return None + if s.startswith("rgb"): + parts = re.findall(r"[-+]?\d*\.?\d+%?", s)[:3] + out = [] + for p in parts: + out.append(float(p[:-1]) / 100 if p.endswith("%") else float(p) / 255) + return tuple(max(0.0, min(1.0, v)) for v in out) if len(out) == 3 else None + found = NAMED.get(s) + return tuple(v / 255 for v in found) if found else (0, 0, 0) + + +def _alpha_of(text: str | None) -> float: + if not text: + return 1.0 + s = text.strip().lower() + if s.startswith("rgba") or s.startswith("#") and len(s) in (5, 9): + if s.startswith("#"): + h = s[1:] + return int(h[-1] * 2, 16) / 255 if len(h) == 4 else int(h[-2:], 16) / 255 + parts = re.findall(r"[-+]?\d*\.?\d+%?", s) + if len(parts) >= 4: + p = parts[3] + return float(p[:-1]) / 100 if p.endswith("%") else float(p) + return 1.0 + + +def parse_transform(text: str | None) -> Matrix: + m = IDENTITY + for name, raw in _TRANSFORM.findall(text or ""): + v = _floats(raw) + if name == "matrix" and len(v) == 6: + n = tuple(v) + elif name == "translate": + n = (1, 0, 0, 1, v[0] if v else 0, v[1] if len(v) > 1 else 0) + elif name == "scale": + sx = v[0] if v else 1 + n = (sx, 0, 0, v[1] if len(v) > 1 else sx, 0, 0) + elif name == "rotate": + a = math.radians(v[0] if v else 0) + r = (math.cos(a), math.sin(a), -math.sin(a), math.cos(a), 0, 0) + if len(v) >= 3: + n = mul(mul((1, 0, 0, 1, v[1], v[2]), r), (1, 0, 0, 1, -v[1], -v[2])) + else: + n = r + elif name == "skewX": + n = (1, 0, math.tan(math.radians(v[0] if v else 0)), 1, 0, 0) + else: + n = (1, math.tan(math.radians(v[0] if v else 0)), 0, 1, 0, 0) + m = mul(m, n) + return m + + +def _arc(x1, y1, rx, ry, phi, large, sweep, x2, y2) -> list[tuple]: + if rx == 0 or ry == 0 or (x1 == x2 and y1 == y2): + return [("L", x2, y2)] + rx, ry = abs(rx), abs(ry) + cp, sp = math.cos(math.radians(phi)), math.sin(math.radians(phi)) + dx, dy = (x1 - x2) / 2, (y1 - y2) / 2 + x1p, y1p = cp * dx + sp * dy, -sp * dx + cp * dy + lam = (x1p / rx) ** 2 + (y1p / ry) ** 2 + if lam > 1: + rx, ry = rx * math.sqrt(lam), ry * math.sqrt(lam) + num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p + den = rx * rx * y1p * y1p + ry * ry * x1p * x1p + co = math.sqrt(max(0.0, num / den)) if den else 0.0 + if large == sweep: + co = -co + cxp, cyp = co * rx * y1p / ry, -co * ry * x1p / rx + cx, cy = cp * cxp - sp * cyp + (x1 + x2) / 2, sp * cxp + cp * cyp + (y1 + y2) / 2 + + def ang(ux, uy, vx, vy): + a = math.atan2(ux * vy - uy * vx, ux * vx + uy * vy) + return a + + t1 = ang(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry) + dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry) + if not sweep and dt > 0: + dt -= 2 * math.pi + elif sweep and dt < 0: + dt += 2 * math.pi + n = max(1, int(math.ceil(abs(dt) / (math.pi / 2) - 1e-9))) + step = dt / n + k = 4 / 3 * math.tan(step / 4) + out = [] + + def rot(qx: float, qy: float) -> tuple[float, float]: + return cx + cp * qx - sp * qy, cy + sp * qx + cp * qy + + for i in range(n): + a0, a1 = t1 + i * step, t1 + (i + 1) * step + p0x, p0y = rx * math.cos(a0), ry * math.sin(a0) + p1x, p1y = rx * math.cos(a1), ry * math.sin(a1) + a = rot(p0x - k * rx * math.sin(a0), p0y + k * ry * math.cos(a0)) + b = rot(p1x + k * rx * math.sin(a1), p1y - k * ry * math.cos(a1)) + e = rot(p1x, p1y) + out.append(("C", a[0], a[1], b[0], b[1], e[0], e[1])) + return out + + +def path_segments(d: str) -> list[tuple]: + tokens = _PATH_TOKEN.findall(d or "") + out: list[tuple] = [] + i = 0 + cmd = "" + x = y = sx = sy = 0.0 + last_c = last_q = None + + def nums(n): + nonlocal i + vals = [] + for _ in range(n): + if i >= len(tokens) or tokens[i].isalpha(): + raise ValueError("short path") + vals.append(float(tokens[i])) + i += 1 + return vals + + while i < len(tokens): + if tokens[i].isalpha(): + cmd = tokens[i] + i += 1 + if cmd in "Zz": + out.append(("Z",)) + x, y = sx, sy + last_c = last_q = None + continue + elif not cmd: + break + rel = cmd.islower() + c = cmd.upper() + try: + if c == "M": + px, py = nums(2) + x, y = (x + px, y + py) if rel else (px, py) + sx, sy = x, y + out.append(("M", x, y)) + cmd = "l" if rel else "L" + last_c = last_q = None + elif c == "L": + px, py = nums(2) + x, y = (x + px, y + py) if rel else (px, py) + out.append(("L", x, y)) + last_c = last_q = None + elif c == "H": + (px,) = nums(1) + x = x + px if rel else px + out.append(("L", x, y)) + last_c = last_q = None + elif c == "V": + (py,) = nums(1) + y = y + py if rel else py + out.append(("L", x, y)) + last_c = last_q = None + elif c in "CS": + if c == "C": + x1, y1, x2, y2, px, py = nums(6) + if rel: + x1, y1, x2, y2 = x1 + x, y1 + y, x2 + x, y2 + y + else: + x2, y2, px, py = nums(4) + if rel: + x2, y2 = x2 + x, y2 + y + x1, y1 = (2 * x - last_c[0], 2 * y - last_c[1]) if last_c else (x, y) + ex, ey = (x + px, y + py) if rel else (px, py) + out.append(("C", x1, y1, x2, y2, ex, ey)) + last_c, last_q = (x2, y2), None + x, y = ex, ey + elif c in "QT": + if c == "Q": + qx, qy, px, py = nums(4) + if rel: + qx, qy = qx + x, qy + y + else: + px, py = nums(2) + qx, qy = (2 * x - last_q[0], 2 * y - last_q[1]) if last_q else (x, y) + ex, ey = (x + px, y + py) if rel else (px, py) + out.append(("C", x + 2 / 3 * (qx - x), y + 2 / 3 * (qy - y), ex + 2 / 3 * (qx - ex), ey + 2 / 3 * (qy - ey), ex, ey)) + last_q, last_c = (qx, qy), None + x, y = ex, ey + elif c == "A": + rx, ry, phi, large, sweep, px, py = nums(7) + ex, ey = (x + px, y + py) if rel else (px, py) + out.extend(_arc(x, y, rx, ry, phi, int(large), int(sweep), ex, ey)) + x, y = ex, ey + last_c = last_q = None + else: + break + except ValueError: + break + return out + + +def _ellipse(cx, cy, rx, ry) -> list[tuple]: + kx, ky = rx * KAPPA, ry * KAPPA + return [("M", cx + rx, cy), ("C", cx + rx, cy + ky, cx + kx, cy + ry, cx, cy + ry), ("C", cx - kx, cy + ry, cx - rx, cy + ky, cx - rx, cy), + ("C", cx - rx, cy - ky, cx - kx, cy - ry, cx, cy - ry), ("C", cx + kx, cy - ry, cx + rx, cy - ky, cx + rx, cy), ("Z",)] + + +def _rect(x, y, w, h, rx=0.0, ry=0.0) -> list[tuple]: + if w <= 0 or h <= 0: + return [] + rx, ry = min(rx, w / 2), min(ry, h / 2) + if rx <= 0 or ry <= 0: + return [("M", x, y), ("L", x + w, y), ("L", x + w, y + h), ("L", x, y + h), ("Z",)] + kx, ky = rx * KAPPA, ry * KAPPA + return [("M", x + rx, y), ("L", x + w - rx, y), ("C", x + w - rx + kx, y, x + w, y + ry - ky, x + w, y + ry), + ("L", x + w, y + h - ry), ("C", x + w, y + h - ry + ky, x + w - rx + kx, y + h, x + w - rx, y + h), + ("L", x + rx, y + h), ("C", x + rx - kx, y + h, x, y + h - ry + ky, x, y + h - ry), + ("L", x, y + ry), ("C", x, y + ry - ky, x + rx - kx, y, x + rx, y), ("Z",)] + + +def _points(text: str | None) -> list[tuple[float, float]]: + v = _floats(text) + return [(v[i], v[i + 1]) for i in range(0, len(v) - 1, 2)] + + +def transform_segs(segs: list[tuple], m: Matrix) -> list[tuple]: + out = [] + for s in segs: + if s[0] == "Z": + out.append(s) + elif s[0] == "C": + a, b, c = apply(m, s[1], s[2]), apply(m, s[3], s[4]), apply(m, s[5], s[6]) + out.append(("C", *a, *b, *c)) + else: + out.append((s[0], *apply(m, s[1], s[2]))) + return out + + +def _local(tag: str) -> str: + return tag.split("}", 1)[1] if tag.startswith("{") else tag + + +def _style_attrs(el: ET.Element) -> dict: + out = dict(el.attrib) + for part in (el.get("style") or "").split(";"): + if ":" in part: + k, v = part.split(":", 1) + k = k.strip() + if k and not k.startswith("--"): + out[k] = v.strip() + return out + + +class Reader: + def __init__(self, root: ET.Element): + self.root = root + self.items: list[Item] = [] + self.warnings: list[str] = [] + self.ids = {el.get("id"): el for el in root.iter() if el.get("id")} + self.fonts_ok = fonts.available() + self._warned: set[str] = set() + + def warn(self, text: str) -> None: + if text not in self._warned: + self._warned.add(text) + self.warnings.append(text) + + def paint(self, value: str | None, current: tuple) -> tuple[tuple | None, float]: + if value is None: + return None, 1.0 + found = _URL.search(value) + if found: + grad = self.ids.get(found.group(1)) + stops = [s for s in (grad.iter() if grad is not None else []) if _local(s.tag) == "stop"] + cols = [colour(_style_attrs(s).get("stop-color", "black")) for s in stops] + cols = [c for c in cols if c] + if not cols: + return None, 1.0 + self.warn("Gradient fills are drawn as one flat colour in PDF and EPS.") + return tuple(sum(c[i] for c in cols) / len(cols) for i in range(3)), 1.0 + return colour(value, current), _alpha_of(value) + + def clip_for(self, attrs: dict, m: Matrix) -> list | None: + found = _URL.search(attrs.get("clip-path") or "") + if not found: + return None + clip = self.ids.get(found.group(1)) + if clip is None: + return None + segs: list[tuple] = [] + for kid in clip: + ka = _style_attrs(kid) + km = mul(m, parse_transform(ka.get("transform"))) + segs.extend(transform_segs(self.shape(_local(kid.tag), ka), km)) + return segs or None + + def shape(self, tag: str, a: dict) -> list[tuple]: + num = lambda k, d=0.0: _length(a.get(k), d) + if tag == "path": + return path_segments(a.get("d", "")) + if tag == "line": + return [("M", num("x1"), num("y1")), ("L", num("x2"), num("y2"))] + if tag in ("polyline", "polygon"): + pts = _points(a.get("points")) + if not pts: + return [] + segs = [("M", *pts[0])] + [("L", *p) for p in pts[1:]] + return segs + [("Z",)] if tag == "polygon" else segs + if tag == "rect": + rx, ry = a.get("rx"), a.get("ry") + rxv = _length(rx if rx is not None else ry, 0.0) + ryv = _length(ry if ry is not None else rx, 0.0) + return _rect(num("x"), num("y"), num("width"), num("height"), rxv, ryv) + if tag == "circle": + r = num("r") + return _ellipse(num("cx"), num("cy"), r, r) if r > 0 else [] + if tag == "ellipse": + rx, ry = num("rx"), num("ry") + return _ellipse(num("cx"), num("cy"), rx, ry) if rx > 0 and ry > 0 else [] + return [] + + def walk(self, el: ET.Element, m: Matrix, inherited: dict, opacity: float, clip: list | None) -> None: + tag = _local(el.tag) + if tag in SKIP: + return + own = _style_attrs(el) + if own.get("display") == "none": + return + style = dict(inherited) + for k in INHERITED: + if k in own: + style[k] = own[k] + if style.get("visibility") in ("hidden", "collapse") and tag != "g": + return + m = mul(m, parse_transform(own.get("transform"))) + try: + opacity *= float(own.get("opacity", 1)) + except ValueError: + pass + clip = self.clip_for(own, m) or clip + if tag in ("g", "svg", "a", "switch"): + for kid in el: + self.walk(kid, m, style, opacity, clip) + elif tag == "text": + self.text(el, m, style, opacity, clip) + elif tag == "image": + self.image(own, m, opacity, clip) + else: + segs = self.shape(tag, own) + if segs: + self.add_path(transform_segs(segs, m), style, m, opacity, clip, tag in ("line", "polyline")) + + def add_path(self, segs: list[tuple], style: dict, m: Matrix, opacity: float, clip: list | None, open_shape: bool) -> None: + fill, fill_a = self.paint(style.get("fill", "black"), (0, 0, 0)) + if open_shape: + fill = None + stroke, stroke_a = self.paint(style.get("stroke"), (0, 0, 0)) + try: + fill_a *= float(style.get("fill-opacity", 1)) * opacity + stroke_a *= float(style.get("stroke-opacity", 1)) * opacity + except ValueError: + pass + s = scale_of(m) + width = _length(style.get("stroke-width"), 1.0) * s + if stroke is not None and width <= 0: + stroke = None + if fill is None and stroke is None: + return + dash_raw = style.get("stroke-dasharray") + dash = [] if not dash_raw or dash_raw.strip() == "none" else [max(0.0, v) * s for v in _floats(dash_raw)] + if dash and len(dash) % 2: + dash = dash * 2 + if dash and sum(dash) <= 0: + dash = [] + self.items.append(Item( + kind="path", segs=segs, fill=fill, fill_alpha=max(0.0, min(1.0, fill_a)), even_odd=style.get("fill-rule") == "evenodd", + stroke=stroke, stroke_alpha=max(0.0, min(1.0, stroke_a)), width=width, + cap={"butt": 0, "round": 1, "square": 2}.get(style.get("stroke-linecap", "butt"), 0), + join={"miter": 0, "round": 1, "bevel": 2}.get(style.get("stroke-linejoin", "miter"), 0), + miter=_length(style.get("stroke-miterlimit"), 4.0), dash=dash, dash_offset=_length(style.get("stroke-dashoffset"), 0.0) * s, clip=clip, + )) + + def image(self, a: dict, m: Matrix, opacity: float, clip: list | None) -> None: + href = a.get("href") or a.get(f"{XLINK}href") or "" + found = re.match(r"data:(image/(?:png|jpeg|jpg));base64,(.*)$", href.strip(), re.S) + if not found: + self.warn("Pictures that are not embedded PNG or JPEG data were left out.") + return + try: + data = base64.b64decode(re.sub(r"\s+", "", found.group(2))) + except ValueError: + return + x, y = _length(a.get("x")), _length(a.get("y")) + w, h = _length(a.get("width")), _length(a.get("height")) + if w <= 0 or h <= 0: + return + place = mul(m, (w, 0, 0, h, x, y)) + self.items.append(Item(kind="image", image=data, image_mime=found.group(1).replace("jpg", "jpeg"), image_matrix=place, fill_alpha=opacity, clip=clip)) + + def text(self, el: ET.Element, m: Matrix, style: dict, opacity: float, clip: list | None) -> None: + if not self.fonts_ok: + self.warn("Text was left out because the engine has no font tools; install fontTools to draw labels in PDF and EPS.") + return + pieces: list[tuple[str, dict, dict]] = [] + if el.text: + pieces.append((el.text, style, {})) + for kid in el: + if _local(kid.tag) != "tspan": + continue + ka = _style_attrs(kid) + ks = dict(style) + for k in INHERITED: + if k in ka: + ks[k] = ka[k] + pieces.append((kid.text or "", ks, ka)) + if kid.tail: + pieces.append((kid.tail, style, {})) + pen_x, pen_y = _length(el.get("x"), 0.0), _length(el.get("y"), 0.0) + chunks: list[list[tuple[str, dict, float, float]]] = [[]] + for text, st, attrs in pieces: + if "x" in attrs: + if chunks[-1]: + chunks.append([]) + pen_x = _length(attrs.get("x"), pen_x) + if "y" in attrs: + pen_y = _length(attrs.get("y"), pen_y) + if not text: + continue + size = _length(st.get("font-size"), 10.0) + fam, bold, italic = st.get("font-family", "Arimo"), fonts.is_bold(st.get("font-weight")), (st.get("font-style") or "").lower() in ("italic", "oblique") + width = fonts.advance(fam, bold, italic, text, size) + chunks[-1].append((text, st, pen_x, pen_y)) + pen_x += width + for chunk in chunks: + if not chunk: + continue + anchor = chunk[0][1].get("text-anchor", "start") + first = chunk[0][2] + last_text, last_st, last_x, _ = chunk[-1] + size = _length(last_st.get("font-size"), 10.0) + end = last_x + fonts.advance(last_st.get("font-family", "Arimo"), fonts.is_bold(last_st.get("font-weight")), + (last_st.get("font-style") or "").lower() in ("italic", "oblique"), last_text, size) + shift = -(end - first) / 2 if anchor == "middle" else -(end - first) if anchor == "end" else 0.0 + for text, st, x, y in chunk: + size = _length(st.get("font-size"), 10.0) + fam, bold = st.get("font-family", "Arimo"), fonts.is_bold(st.get("font-weight")) + italic = (st.get("font-style") or "").lower() in ("italic", "oblique") + segs, _ = fonts.outline(fam, bold, italic, text, size, x + shift, y, m) + fill, fill_a = self.paint(st.get("fill", "black"), (0, 0, 0)) + try: + fill_a *= float(st.get("fill-opacity", 1)) * opacity + except ValueError: + pass + if fill is None: + continue + self.items.append(Item(kind="text", segs=segs, fill=fill, fill_alpha=max(0.0, min(1.0, fill_a)), clip=clip, text=text, + font=fonts.pdf_base(fam, bold, italic), text_matrix=mul(m, (size, 0, 0, -size, x + shift, y)))) + + +def read(svg: str | bytes) -> Drawing: + root = ET.fromstring(svg.encode("utf-8") if isinstance(svg, str) else svg) + if _local(root.tag) != "svg": + raise ValueError("The picture is not an SVG document.") + vb = _floats(root.get("viewBox")) + width = _length(root.get("width"), vb[2] if len(vb) == 4 else 0.0) + height = _length(root.get("height"), vb[3] if len(vb) == 4 else 0.0) + if len(vb) != 4: + vb = [0.0, 0.0, width, height] + if width <= 0 or height <= 0 or vb[2] <= 0 or vb[3] <= 0: + raise ValueError("The picture has no size.") + sx, sy = width / vb[2], height / vb[3] + page: Matrix = (sx, 0.0, 0.0, -sy, -vb[0] * sx, height + vb[1] * sy) + reader = Reader(root) + reader.walk(root, page, {"fill": "black"}, 1.0, None) + return Drawing(width, height, reader.items, reader.warnings) From f000a2c7567fe091e2055947705db3275eab012b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:14:34 -0500 Subject: [PATCH 063/357] feat(pictures): write PDF pictures with the drawing attached (0.7.0) A small own writer keeps the dependency list short: labels are glyph outlines with an invisible text layer for search and copy, and the document.json rides along as an embedded file. --- backend/app/services/pictures/pdf.py | 195 +++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 backend/app/services/pictures/pdf.py diff --git a/backend/app/services/pictures/pdf.py b/backend/app/services/pictures/pdf.py new file mode 100644 index 00000000..846e11a2 --- /dev/null +++ b/backend/app/services/pictures/pdf.py @@ -0,0 +1,195 @@ +import io +import time +import zlib + +from app import __version__ +from app.services.pictures.svgdraw import Drawing, Item + +SOURCE_MIME = "application/x-formchem+json" +SOURCE_NAME = "drawing.fchem.json" + + +def _n(v: float) -> str: + s = f"{v:.3f}".rstrip("0").rstrip(".") + return "0" if s in ("-0", "") else s + + +def _pdf_string(text: str) -> bytes: + try: + raw = text.encode("latin-1") + return b"(" + raw.replace(b"\\", b"\\\\").replace(b"(", b"\\(").replace(b")", b"\\)").replace(b"\r", b"\\r").replace(b"\n", b"\\n") + b")" + except UnicodeEncodeError: + return b"" + + +def _win_ansi(text: str) -> bytes: + text = text.replace("\u2212", "-").replace("\u2013", "-").replace("\u2022", "\x95").replace("\u00b7", "\xb7") + raw = text.encode("cp1252", errors="replace") + return b"(" + raw.replace(b"\\", b"\\\\").replace(b"(", b"\\(").replace(b")", b"\\)") + b")" + + +def path_ops(segs: list[tuple]) -> list[str]: + out = [] + for s in segs: + if s[0] == "M": + out.append(f"{_n(s[1])} {_n(s[2])} m") + elif s[0] == "L": + out.append(f"{_n(s[1])} {_n(s[2])} l") + elif s[0] == "C": + out.append(" ".join(_n(v) for v in s[1:]) + " c") + else: + out.append("h") + return out + + +class _Images: + def __init__(self): + self.list: list[tuple[str, dict, bytes, bytes | None, dict | None]] = [] + + def add(self, item: Item) -> str | None: + name = f"Im{len(self.list) + 1}" + if item.image_mime == "image/jpeg": + try: + from PIL import Image + with Image.open(io.BytesIO(item.image)) as im: + w, h, mode = im.width, im.height, im.mode + except Exception: + return None + space = "/DeviceGray" if mode == "L" else "/DeviceCMYK" if mode == "CMYK" else "/DeviceRGB" + self.list.append((name, {"Width": w, "Height": h, "ColorSpace": space, "BitsPerComponent": 8, "Filter": "/DCTDecode"}, item.image, None, None)) + return name + try: + from PIL import Image + with Image.open(io.BytesIO(item.image)) as im: + im = im.convert("RGBA") + w, h = im.size + rgb = im.convert("RGB").tobytes() + alpha = im.getchannel("A").tobytes() + except Exception: + return None + smask = None if alpha.count(b"\xff") == len(alpha) else zlib.compress(alpha) + mask_dict = {"Width": w, "Height": h, "ColorSpace": "/DeviceGray", "BitsPerComponent": 8, "Filter": "/FlateDecode"} if smask else None + self.list.append((name, {"Width": w, "Height": h, "ColorSpace": "/DeviceRGB", "BitsPerComponent": 8, "Filter": "/FlateDecode"}, zlib.compress(rgb), smask, mask_dict)) + return name + + +def _content(drawing: Drawing, background: tuple | None) -> tuple[bytes, dict, dict, _Images, list[str]]: + ops: list[str] = [] + states: dict[tuple[float, float], str] = {} + fonts: dict[str, str] = {} + images = _Images() + warnings: list[str] = [] + + def gs(fill_a: float, stroke_a: float) -> None: + if fill_a >= 0.999 and stroke_a >= 0.999: + return + key = (round(fill_a, 3), round(stroke_a, 3)) + if key not in states: + states[key] = f"GS{len(states) + 1}" + ops.append(f"/{states[key]} gs") + + if background is not None: + ops.append(f"{_n(background[0])} {_n(background[1])} {_n(background[2])} rg 0 0 {_n(drawing.width)} {_n(drawing.height)} re f") + for item in drawing.items: + ops.append("q") + if item.clip: + ops.extend(path_ops(item.clip)) + ops.append("W n") + if item.kind == "image": + name = images.add(item) + if name is None: + if "A picture inside the drawing could not be read and was left out." not in warnings: + warnings.append("A picture inside the drawing could not be read and was left out.") + ops.append("Q") + continue + gs(item.fill_alpha, 1.0) + a, b, c, d, e, f = item.image_matrix + ops.append(f"{_n(a)} {_n(b)} {_n(-c)} {_n(-d)} {_n(c + e)} {_n(d + f)} cm") + ops.append(f"/{name} Do") + ops.append("Q") + continue + if item.kind == "text": + gs(item.fill_alpha, 1.0) + ops.extend(path_ops(item.segs)) + ops.append(f"{_n(item.fill[0])} {_n(item.fill[1])} {_n(item.fill[2])} rg f") + if item.font not in fonts: + fonts[item.font] = f"F{len(fonts) + 1}" + a, b, c, d, e, f = item.text_matrix + ops.append(f"BT 3 Tr /{fonts[item.font]} 1 Tf {_n(a)} {_n(b)} {_n(c)} {_n(d)} {_n(e)} {_n(f)} Tm " + _win_ansi(item.text).decode("latin-1") + " Tj ET") + ops.append("Q") + continue + gs(item.fill_alpha if item.fill else 1.0, item.stroke_alpha if item.stroke else 1.0) + ops.extend(path_ops(item.segs)) + if item.fill: + ops.append(f"{_n(item.fill[0])} {_n(item.fill[1])} {_n(item.fill[2])} rg") + if item.stroke: + ops.append(f"{_n(item.stroke[0])} {_n(item.stroke[1])} {_n(item.stroke[2])} RG {_n(item.width)} w {item.cap} J {item.join} j {_n(max(1.0, item.miter))} M") + ops.append(f"[{' '.join(_n(v) for v in item.dash)}] {_n(item.dash_offset)} d") + if item.fill and item.stroke: + ops.append("B*" if item.even_odd else "B") + elif item.fill: + ops.append("f*" if item.even_odd else "f") + else: + ops.append("S") + ops.append("Q") + return "\n".join(ops).encode("latin-1"), states, fonts, images, warnings + + +def _date() -> bytes: + return time.strftime("D:%Y%m%d%H%M%SZ", time.gmtime()).encode("ascii") + + +def write(drawing: Drawing, title: str = "", source: str | None = None, background: tuple | None = None) -> tuple[bytes, list[str]]: + content, states, fonts, images, warnings = _content(drawing, background) + objects: list[bytes] = [] + + def add(body: bytes) -> int: + objects.append(body) + return len(objects) + + def stream(head: dict, data: bytes) -> bytes: + parts = [f"/{k} {v}" for k, v in head.items()] + return b"<< " + " ".join(parts).encode("latin-1") + f" /Length {len(data)} >>\nstream\n".encode("latin-1") + data + b"\nendstream" + + catalog = add(b"") + pages = add(b"") + packed = zlib.compress(content) + contents = add(stream({"Filter": "/FlateDecode"}, packed)) + font_refs = {} + for base, name in fonts.items(): + font_refs[name] = add(f"<< /Type /Font /Subtype /Type1 /BaseFont /{base} /Encoding /WinAnsiEncoding >>".encode("latin-1")) + image_refs = {} + for name, head, data, smask, mask_head in images.list: + extra = {} + if smask is not None and mask_head is not None: + extra["SMask"] = f"{add(stream({'Type': '/XObject', 'Subtype': '/Image', **mask_head}, smask))} 0 R" + image_refs[name] = add(stream({"Type": "/XObject", "Subtype": "/Image", **head, **extra}, data)) + res = [] + if font_refs: + res.append("/Font << " + " ".join(f"/{n} {r} 0 R" for n, r in font_refs.items()) + " >>") + if states: + res.append("/ExtGState << " + " ".join(f"/{n} << /ca {_n(k[0])} /CA {_n(k[1])} >>" for k, n in states.items()) + " >>") + if image_refs: + res.append("/XObject << " + " ".join(f"/{n} {r} 0 R" for n, r in image_refs.items()) + " >>") + page = add(f"<< /Type /Page /Parent {pages} 0 R /MediaBox [0 0 {_n(drawing.width)} {_n(drawing.height)}] /Resources << {' '.join(res)} >> /Contents {contents} 0 R >>".encode("latin-1")) + objects[pages - 1] = f"<< /Type /Pages /Kids [{page} 0 R] /Count 1 >>".encode("latin-1") + names = b"" + if source: + data = source.encode("utf-8") + embedded = add(b"<< /Type /EmbeddedFile /Subtype /application#2Fx-formchem+json " + f"/Params << /Size {len(data)} /ModDate ".encode("latin-1") + _pdf_string(_date().decode()) + f" >> /Length {len(data)} >>\nstream\n".encode("latin-1") + data + b"\nendstream") + spec = add(b"<< /Type /Filespec /F " + _pdf_string(SOURCE_NAME) + b" /UF " + _pdf_string(SOURCE_NAME) + f" /EF << /F {embedded} 0 R /UF {embedded} 0 R >> /AFRelationship /Source /Desc ".encode("latin-1") + _pdf_string("FormChem drawing: open this PDF in FormChem to edit it") + b" >>") + names = f" /Names << /EmbeddedFiles << /Names [".encode("latin-1") + _pdf_string(SOURCE_NAME) + f" {spec} 0 R] >> >> /AF [{spec} 0 R]".encode("latin-1") + objects[catalog - 1] = f"<< /Type /Catalog /Pages {pages} 0 R".encode("latin-1") + names + b" >>" + info = add(b"<< /Title " + _pdf_string(title or "FormChem drawing") + b" /Creator " + _pdf_string(f"FormChem {__version__}") + b" /Producer " + _pdf_string(f"FormChem {__version__}") + b" /CreationDate " + _pdf_string(_date().decode()) + b" >>") + out = io.BytesIO() + out.write(b"%PDF-1.7\n%\xe2\xe3\xcf\xd3\n") + offsets = [] + for i, body in enumerate(objects, start=1): + offsets.append(out.tell()) + out.write(f"{i} 0 obj\n".encode("latin-1") + body + b"\nendobj\n") + xref = out.tell() + out.write(f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode("latin-1")) + for off in offsets: + out.write(f"{off:010d} 00000 n \n".encode("latin-1")) + out.write(f"trailer\n<< /Size {len(objects) + 1} /Root {catalog} 0 R /Info {info} 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode("latin-1")) + return out.getvalue(), drawing.warnings + warnings From d85438bdf47b7209b843e35f7cc8beec581b3d5c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:14:34 -0500 Subject: [PATCH 064/357] feat(pictures): write EPS pictures for journals that still ask for them (0.7.0) Level 2 EPS with outlined labels, a tight bounding box and the drawing kept in comment lines so FormChem can open the file again. --- backend/app/services/pictures/eps.py | 120 +++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 backend/app/services/pictures/eps.py diff --git a/backend/app/services/pictures/eps.py b/backend/app/services/pictures/eps.py new file mode 100644 index 00000000..2ca8887a --- /dev/null +++ b/backend/app/services/pictures/eps.py @@ -0,0 +1,120 @@ +import base64 +import io +import math +import time + +from app import __version__ +from app.services.pictures.svgdraw import Drawing, Item + +SOURCE_LINE = "%FormChemSource:" +LINE = 76 + +PROLOG = """/fcdict 16 dict def fcdict begin +/m {moveto} bind def /l {lineto} bind def /c {curveto} bind def /h {closepath} bind def +end""" + + +def _n(v: float) -> str: + s = f"{v:.3f}".rstrip("0").rstrip(".") + return "0" if s in ("-0", "") else s + + +def _ps_text(text: str) -> str: + return text.replace("−", "-").encode("latin-1", errors="replace").decode("latin-1").replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)").replace("\n", " ") + + +def path_ops(segs: list[tuple]) -> list[str]: + out = [] + for s in segs: + if s[0] == "M": + out.append(f"{_n(s[1])} {_n(s[2])} m") + elif s[0] == "L": + out.append(f"{_n(s[1])} {_n(s[2])} l") + elif s[0] == "C": + out.append(" ".join(_n(v) for v in s[1:]) + " c") + else: + out.append("h") + return out + + +def _image(item: Item, background: tuple | None) -> list[str] | None: + try: + from PIL import Image + with Image.open(io.BytesIO(item.image)) as im: + im = im.convert("RGBA") + base = Image.new("RGBA", im.size, tuple(int(v * 255) for v in (background or (1, 1, 1))) + (255,)) + base.alpha_composite(im) + rgb = base.convert("RGB") + w, h = rgb.size + data = base64.a85encode(rgb.tobytes(), wrapcol=LINE, adobe=True).decode("ascii") + except Exception: + return None + a, b, c, d, e, f = item.image_matrix + return [ + "gsave", + f"[{_n(a)} {_n(b)} {_n(-c)} {_n(-d)} {_n(c + e)} {_n(d + f)}] concat", + "/DeviceRGB setcolorspace", + f"<< /ImageType 1 /Width {w} /Height {h} /BitsPerComponent 8 /Decode [0 1 0 1 0 1] /ImageMatrix [{w} 0 0 {-h} 0 {h}] /DataSource currentfile /ASCII85Decode filter >> image", + data, + "grestore", + ] + + +def write(drawing: Drawing, title: str = "", source: str | None = None, background: tuple | None = None) -> tuple[bytes, list[str]]: + warnings = list(drawing.warnings) + body: list[str] = [] + if background is not None: + body.append(f"{_n(background[0])} {_n(background[1])} {_n(background[2])} setrgbcolor 0 0 {_n(drawing.width)} {_n(drawing.height)} rectfill") + seen_alpha = False + for item in drawing.items: + alpha = item.fill_alpha if item.kind != "path" or item.fill else item.stroke_alpha + if alpha < 0.999: + seen_alpha = True + if alpha <= 0.001: + continue + body.append("gsave") + if item.clip: + body.extend(path_ops(item.clip)) + body.append("clip newpath") + if item.kind == "image": + ops = _image(item, background) + if ops is None: + warnings.append("A picture inside the drawing could not be read and was left out.") + else: + body.extend(ops) + body.append("grestore") + continue + if item.kind == "text": + body.extend(path_ops(item.segs)) + body.append(f"{_n(item.fill[0])} {_n(item.fill[1])} {_n(item.fill[2])} setrgbcolor fill") + body.append(f"% text: ({_ps_text(item.text)})") + body.append("grestore") + continue + if item.fill: + body.extend(path_ops(item.segs)) + body.append(f"{_n(item.fill[0])} {_n(item.fill[1])} {_n(item.fill[2])} setrgbcolor {'eofill' if item.even_odd else 'fill'}") + if item.stroke: + body.extend(path_ops(item.segs)) + body.append(f"{_n(item.stroke[0])} {_n(item.stroke[1])} {_n(item.stroke[2])} setrgbcolor {_n(item.width)} setlinewidth {item.cap} setlinecap {item.join} setlinejoin {_n(max(1.0, item.miter))} setmiterlimit") + body.append(f"[{' '.join(_n(v) for v in item.dash)}] {_n(item.dash_offset)} setdash stroke") + body.append("grestore") + if seen_alpha: + warnings.append("EPS has no transparency, so see-through parts are drawn solid.") + head = [ + "%!PS-Adobe-3.0 EPSF-3.0", + f"%%BoundingBox: 0 0 {math.ceil(drawing.width)} {math.ceil(drawing.height)}", + f"%%HiResBoundingBox: 0 0 {_n(drawing.width)} {_n(drawing.height)}", + f"%%Title: {_ps_text(title or 'FormChem drawing')}", + f"%%Creator: FormChem {__version__}", + f"%%CreationDate: {time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())}", + "%%LanguageLevel: 2", + "%%Pages: 1", + "%%EndComments", + ] + if source: + packed = base64.b64encode(source.encode("utf-8")).decode("ascii") + head.append("% FormChem drawing: open this file in FormChem to edit it") + head.extend(f"{SOURCE_LINE}{packed[i:i + LINE]}" for i in range(0, len(packed), LINE)) + head += ["%%BeginProlog", PROLOG, "%%EndProlog", "%%Page: 1 1", "fcdict begin", "gsave"] + tail = ["grestore", "end", "showpage", "%%Trailer", "%%EOF", ""] + return "\n".join(head + body + tail).encode("latin-1"), warnings From 671c53df3ce118481e979aa27e18f584e04f90d0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:14:34 -0500 Subject: [PATCH 065/357] feat(pictures): add the font subset and PDF and EPS conversion routes (0.7.0) The window builds SVG from the document model and asks the engine for font subsets and for PDF or EPS, both behind the window key. --- backend/app/main.py | 2 + backend/app/routers/pictures.py | 85 +++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 backend/app/routers/pictures.py diff --git a/backend/app/main.py b/backend/app/main.py index 9b4bf5c2..3f484358 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -18,6 +18,7 @@ from app.services import terminal as terminals from app.services.chat import engine as chat_engine from app.routers import files as file_writes +from app.routers import pictures mimetypes.add_type("text/javascript", ".js") mimetypes.add_type("text/javascript", ".mjs") @@ -73,6 +74,7 @@ async def lifespan(this: FastAPI): app.include_router(live.router) app.include_router(mcp.router) app.include_router(file_writes.router) +app.include_router(pictures.router) _dist = config.dist_dir() if _dist is not None: diff --git a/backend/app/routers/pictures.py b/backend/app/routers/pictures.py new file mode 100644 index 00000000..472599cf --- /dev/null +++ b/backend/app/routers/pictures.py @@ -0,0 +1,85 @@ +import asyncio +import base64 +import xml.etree.ElementTree as ET + +from fastapi import APIRouter, Body, Depends, HTTPException, Request + +from app.core import window_key +from app.services.pictures import eps, fonts, pdf, svgdraw + +router = APIRouter() + +SVG_LIMIT = 80 * 1024 * 1024 +FACE_LIMIT = 16 +TEXT_LIMIT = 20000 +WRITERS = {"pdf": (pdf.write, "application/pdf"), "eps": (eps.write, "application/postscript")} + + +def _guard(request: Request) -> None: + window_key.require(request) + + +GUARD = [Depends(_guard)] + + +@router.get("/api/pictures/capabilities") +def capabilities() -> dict: + return {"formats": sorted(WRITERS), "fonts": fonts.available()} + + +def _subset_all(faces: list) -> dict: + out, missing = [], [] + for raw in faces[:FACE_LIMIT]: + if not isinstance(raw, dict): + continue + family = raw.get("family") if isinstance(raw.get("family"), str) else "Arimo" + bold, italic = raw.get("bold") is True, raw.get("italic") is True + text = raw.get("text") if isinstance(raw.get("text"), str) else "" + try: + data = fonts.subset_woff(family, bold, italic, text[:TEXT_LIMIT]) + except Exception as exc: + missing.append({"family": family, "bold": bold, "italic": italic, "reason": str(exc)}) + continue + out.append({"family": fonts.bundled(family), "bold": bold, "italic": italic, "woff": base64.b64encode(data).decode("ascii")}) + return {"faces": out, "missing": missing} + + +@router.post("/api/pictures/fonts", dependencies=GUARD) +async def subset_fonts(body: dict = Body(...)) -> dict: + faces = body.get("faces") + if not isinstance(faces, list): + raise HTTPException(400, "List the faces to embed.") + if not fonts.available(): + return {"faces": [], "missing": [{"reason": "fontTools is not installed in the engine"}]} + return await asyncio.to_thread(_subset_all, faces) + + +def _background(raw: object) -> tuple | None: + if not isinstance(raw, str) or raw in ("", "transparent", "none"): + return None + return svgdraw.colour(raw) + + +def _convert(fmt: str, svg: str, title: str, source: str | None, background: tuple | None) -> tuple[bytes, list[str]]: + drawing = svgdraw.read(svg) + writer, _ = WRITERS[fmt] + return writer(drawing, title, source, background) + + +@router.post("/api/pictures/convert", dependencies=GUARD) +async def convert(body: dict = Body(...)) -> dict: + fmt = body.get("format") + if fmt not in WRITERS: + raise HTTPException(400, f"FormChem converts pictures to {' and '.join(f.upper() for f in sorted(WRITERS))}.") + svg = body.get("svg") + if not isinstance(svg, str) or not svg.strip(): + raise HTTPException(400, "Send the picture as SVG text.") + if len(svg) > SVG_LIMIT: + raise HTTPException(413, "The picture is too large to convert.") + source = body.get("source") if isinstance(body.get("source"), str) and body.get("source") else None + title = body.get("title") if isinstance(body.get("title"), str) else "" + try: + data, warnings = await asyncio.to_thread(_convert, fmt, svg, title, source, _background(body.get("background"))) + except (ET.ParseError, ValueError) as exc: + raise HTTPException(400, f"Could not read the picture: {exc}") + return {"base64": base64.b64encode(data).decode("ascii"), "mime": WRITERS[fmt][1], "bytes": len(data), "warnings": warnings} From 0d9a6510bfa48db6238d8af84eb95182858b0035 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:14:49 -0500 Subject: [PATCH 066/357] build(deps): pin fontTools 4.69.1 for picture export and freeze its table modules (0.7.0) fontTools (MIT) subsets and outlines the label fonts; it loads its table modules by name, so the frozen engine collects them explicitly. --- backend/requirements.txt | 1 + backend/requirements_macos.txt | 1 + setup/freeze_backend | 2 +- setup/freeze_backend.bat | 2 +- 4 files changed, 4 insertions(+), 2 deletions(-) diff --git a/backend/requirements.txt b/backend/requirements.txt index 4f93a99d..0e7b766c 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -7,3 +7,4 @@ pywinpty==3.0.5; sys_platform == "win32" keyring==25.7.0 rdkit==2025.9.3 epam.indigo==1.49.0 +fonttools==4.69.1 diff --git a/backend/requirements_macos.txt b/backend/requirements_macos.txt index 79838e93..78b7accb 100644 --- a/backend/requirements_macos.txt +++ b/backend/requirements_macos.txt @@ -7,3 +7,4 @@ pywinpty==3.0.5; sys_platform == "win32" keyring==25.7.0 rdkit==2025.9.3 epam.indigo==1.49.0 +fonttools==4.69.1 diff --git a/setup/freeze_backend b/setup/freeze_backend index aaba705b..dad8981f 100755 --- a/setup/freeze_backend +++ b/setup/freeze_backend @@ -25,7 +25,7 @@ pyinstaller --noconfirm --clean "$mode" --name formchem-engine \ --add-data "$FORMCHEM_ROOT/THIRD-PARTY-NOTICES.txt${sep}." \ --add-data "$FORMCHEM_ROOT/backend/app/data/templates${sep}templates" \ --collect-submodules app --collect-submodules uvicorn \ - --collect-all rdkit --collect-all indigo \ + --collect-all rdkit --collect-all indigo --collect-submodules fontTools \ ${extra[@]+"${extra[@]}"} \ "$FORMCHEM_ROOT/backend/formchem_engine.py" if [ "$mode" = --onedir ]; then diff --git a/setup/freeze_backend.bat b/setup/freeze_backend.bat index 156ab61e..e04fec57 100644 --- a/setup/freeze_backend.bat +++ b/setup/freeze_backend.bat @@ -17,7 +17,7 @@ if "%FORMCHEM_ENGINE_WINDOWED%"=="0" set "WINDOWED=" cd backend if exist build\pyinstaller rmdir /s /q build\pyinstaller if exist dist-engine rmdir /s /q dist-engine -pyinstaller --noconfirm --clean --onefile %WINDOWED% --name formchem-engine --distpath dist-engine --workpath build\pyinstaller --specpath build\pyinstaller --add-data "%ROOT%\frontend\dist;frontend_dist" --add-data "%ROOT%\THIRD-PARTY-NOTICES.txt;." --add-data "%ROOT%\backend\app\data\templates;templates" --collect-submodules app --collect-submodules uvicorn --collect-all rdkit --collect-all indigo %FONTS% "%ROOT%\backend\formchem_engine.py" || exit /b 1 +pyinstaller --noconfirm --clean --onefile %WINDOWED% --name formchem-engine --distpath dist-engine --workpath build\pyinstaller --specpath build\pyinstaller --add-data "%ROOT%\frontend\dist;frontend_dist" --add-data "%ROOT%\THIRD-PARTY-NOTICES.txt;." --add-data "%ROOT%\backend\app\data\templates;templates" --collect-submodules app --collect-submodules uvicorn --collect-all rdkit --collect-all indigo --collect-submodules fontTools %FONTS% "%ROOT%\backend\formchem_engine.py" || exit /b 1 if not exist "%ROOT%\src-tauri\binaries" mkdir "%ROOT%\src-tauri\binaries" copy /y dist-engine\formchem-engine.exe "%ROOT%\src-tauri\binaries\formchem-engine-%TRIPLE%.exe" >nul || exit /b 1 "%ROOT%\src-tauri\binaries\formchem-engine-%TRIPLE%.exe" --selfcheck || exit /b 1 From 45c6ef8ad915a3644d59fca10f5f7557f5dbef4b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:15:36 -0500 Subject: [PATCH 067/357] fix(embed): keep pictures in the exported page and leave only their bytes out of the source (0.7.0) The subset drives the rendering too, so placed pictures must stay in it; the embedded document.json drops them because their media bytes are not carried. --- frontend/src/app/embedded-source.ts | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/frontend/src/app/embedded-source.ts b/frontend/src/app/embedded-source.ts index a986ead8..1fc740b7 100644 --- a/frontend/src/app/embedded-source.ts +++ b/frontend/src/app/embedded-source.ts @@ -94,7 +94,6 @@ export function subsetDocument(doc: FormChemDocument, page: Id, pick: Selection const p = doc.pages.find((x) => x.id === page) ?? doc.pages[0]; if (!p) return { ...doc, pages: [], objects: {}, media: undefined }; const { ids, trimmed } = pickObjects(doc, p, pick); - for (const id of [...ids]) if (doc.objects[id]?.kind === 'image') ids.delete(id); const objects: Record = {}; for (const id of ids) { const o = trimmed.get(id) ?? doc.objects[id]; @@ -108,12 +107,24 @@ export function subsetDocument(doc: FormChemDocument, page: Id, pick: Selection const pageOut: Page = { ...p, order }; if (reactions.length) pageOut.reactions = reactions; else delete pageOut.reactions; - const out: FormChemDocument = { ...doc, pages: [pageOut], objects, meta: { ...doc.meta, embedded: { scope, from: doc.id } } }; + return { ...doc, pages: [pageOut], objects, meta: { ...doc.meta, embedded: { scope, from: doc.id } } }; +} + +function portable(doc: FormChemDocument): FormChemDocument { + const images = new Set(Object.keys(doc.objects).filter((id) => doc.objects[id].kind === 'image')); + if (!images.size && !doc.media) return doc; + const objects: Record = {}; + for (const [id, o] of Object.entries(doc.objects)) { + if (images.has(id)) continue; + objects[id] = o.kind === 'group' ? { ...o, children: o.children.filter((k) => !images.has(k)) } : o; + } + const pages = doc.pages.map((p) => ({ ...p, order: p.order.filter((id) => !images.has(id)) })); + const out: FormChemDocument = { ...doc, pages, objects }; delete out.media; return out; } -export const sourceText = (doc: FormChemDocument): string => JSON.stringify(doc); +export const sourceText = (doc: FormChemDocument): string => JSON.stringify(portable(doc)); export function readSourceText(text: string): EmbeddedSource | null { let raw: unknown; From c39728bfbb8b9f0cdefa3927f69cc21dd46b67e6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:29:23 -0500 Subject: [PATCH 068/357] feat(export): build SVG and PNG pictures from the document model offscreen (0.7.0) Exports render the drawing with the renderer's own functions on a hidden stage, never the live canvas or its dark page filter, embed WOFF subsets of the label fonts and rasterise PNG at the chosen dpi with pHYs and the source kept inside. --- frontend/src/app/picture.ts | 308 ++++++++++++++++++++++++++++++++++++ 1 file changed, 308 insertions(+) create mode 100644 frontend/src/app/picture.ts diff --git a/frontend/src/app/picture.ts b/frontend/src/app/picture.ts new file mode 100644 index 00000000..269fd0cd --- /dev/null +++ b/frontend/src/app/picture.ts @@ -0,0 +1,308 @@ +import { mediaCache } from '../canvas/render/image'; +import { createRenderer } from '../canvas/render'; +import { union, type Box } from '../canvas/render/geom'; +import { EMPTY_SELECTION } from '../canvas/selection'; +import type { RenderDisplay } from '../canvas/types'; +import type { Derived, FormChemDocument, Id } from '../engine/model'; +import { post } from '../io/api'; +import { embedInPng, embedInSvg } from './embedded-source'; +import { toBase64 } from './save-file'; + +export type PictureBackground = 'transparent' | 'white'; + +export interface PictureOptions { + scale: number; + margin: number; + background: PictureBackground; + embedSource: boolean; + fonts: 'subset' | 'full' | 'none'; + crop?: boolean; + display?: RenderDisplay; +} + +export interface Picture { svg: string; width: number; height: number; box: Box; warnings: string[] } + +const SVG_NS = 'http://www.w3.org/2000/svg'; +const XLINK_NS = 'http://www.w3.org/1999/xlink'; +const CONTENT_LAYERS = ['objects', 'bonds', 'atoms', 'text', 'stereo']; +const MAX_SIDE = 16384; +const MAX_AREA = 120_000_000; +const MEDIA_WAIT = 6000; +const FONT_FILES: Record = { + 'Arimo|0|0': 'Arimo-VariableFont_wght.ttf', + 'Arimo|1|0': 'Arimo-VariableFont_wght.ttf', + 'Arimo|0|1': 'Arimo-Italic-VariableFont_wght.ttf', + 'Arimo|1|1': 'Arimo-Italic-VariableFont_wght.ttf', + 'Tinos|0|0': 'Tinos-Regular.ttf', + 'Tinos|1|0': 'Tinos-Bold.ttf', + 'Tinos|0|1': 'Tinos-Italic.ttf', + 'Tinos|1|1': 'Tinos-BoldItalic.ttf', +}; +const CLASS_ATTRS: Record> = { + 'fc-mk-group': { 'font-weight': '600' }, + 'fc-mk-flag': { 'font-weight': '600' }, + 'fc-mk-query': { 'font-weight': '500' }, + 'fc-mk-qbond': { 'font-weight': '500' }, + 'fc-mk-rgdef': { 'font-weight': '500' }, + 'fc-mk-rglabel': { 'font-weight': '500' }, + 'fc-map': { 'fill-opacity': '0.85' }, +}; +const NO_WARNINGS = { valenceWarnings: false }; + +const fmt = (v: number): string => String(Math.round(v * 1000) / 1000); +const esc = (s: string): string => s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); + +function bundled(familyList: string | null): string | null { + for (const raw of (familyList ?? '').split(',')) { + const name = raw.trim().replace(/^['"]|['"]$/g, '').toLowerCase(); + if (['arimo', 'arial', 'helvetica', 'helvetica neue', 'sans-serif'].includes(name)) return 'Arimo'; + if (['tinos', 'times', 'times new roman', 'serif'].includes(name)) return 'Tinos'; + if (name) return null; + } + return null; +} + +const isBold = (w: string | null): boolean => !!w && (w === 'bold' || w === 'bolder' || Number(w) >= 600); + +async function fontsReady(): Promise { + const set = (document as Document & { fonts?: FontFaceSet }).fonts; + if (!set) return; + await Promise.all(['10px "Arimo"', 'bold 10px "Arimo"', 'italic 10px "Arimo"', 'bold italic 10px "Arimo"', '10px "Tinos"', 'bold 10px "Tinos"', 'italic 10px "Tinos"', 'bold italic 10px "Tinos"'] + .map((f) => set.load(f).catch(() => []))); + await set.ready; +} + +async function mediaReady(doc: FormChemDocument): Promise { + const media = Object.values(doc.objects).filter((o) => o.kind === 'image').map((o) => (o as { media: Id }).media); + const pending = (): boolean => media.some((m) => { const r = mediaCache.ref(doc, m); return !r.href && !r.failed; }); + if (!pending()) return; + await new Promise((resolve) => { + const timer = window.setTimeout(done, MEDIA_WAIT); + const off = mediaCache.subscribe(() => { if (!pending()) done(); }); + function done(): void { window.clearTimeout(timer); off(); resolve(); } + }); +} + +function hiddenHost(): HTMLDivElement { + const host = document.createElement('div'); + host.setAttribute('aria-hidden', 'true'); + host.style.cssText = 'position:fixed;left:-100000px;top:0;width:10px;height:10px;overflow:hidden;visibility:hidden;pointer-events:none;contain:strict;'; + document.body.appendChild(host); + return host; +} + +function flatten(doc: FormChemDocument, ids: readonly Id[], out: Id[] = []): Id[] { + for (const id of ids) { + const o = doc.objects[id]; + if (!o || o.hidden) continue; + if (o.kind === 'group') flatten(doc, o.children, out); + else out.push(id); + } + return out; +} + +function inlineClasses(root: Element): void { + for (const node of [root, ...Array.from(root.querySelectorAll('*'))]) { + const cls = node.getAttribute('class'); + if (cls) { + for (const name of cls.split(/\s+/)) { + const extra = CLASS_ATTRS[name]; + if (extra) for (const [k, v] of Object.entries(extra)) if (!node.hasAttribute(k)) node.setAttribute(k, v); + } + node.removeAttribute('class'); + } + for (const a of Array.from(node.attributes)) if (a.name.startsWith('data-')) node.removeAttribute(a.name); + const style = node.getAttribute('style'); + if (style !== null) { + const kept = style.split(';').map((s) => s.trim()).filter((s) => s && !s.startsWith('--')); + if (kept.length) node.setAttribute('style', kept.join(';')); + else node.removeAttribute('style'); + } + } +} + +async function inlineMedia(root: Element, warnings: string[]): Promise { + const cache = new Map(); + for (const img of Array.from(root.querySelectorAll('image'))) { + const href = img.getAttribute('href') ?? img.getAttributeNS(XLINK_NS, 'href') ?? ''; + if (!href || href.startsWith('data:')) continue; + if (!cache.has(href)) { + try { + const res = await fetch(href); + if (!res.ok) throw new Error(String(res.status)); + const mime = res.headers.get('content-type')?.split(';')[0] || 'image/png'; + cache.set(href, `data:${mime};base64,${toBase64(new Uint8Array(await res.arrayBuffer()))}`); + } catch { + cache.set(href, null); + } + } + const data = cache.get(href); + if (data) img.setAttribute('href', data); + else { img.remove(); warnings.push('A picture inside the drawing could not be read and was left out.'); } + } +} + +interface FaceUse { family: string; bold: boolean; italic: boolean; chars: Set } + +function usedFaces(root: Element): FaceUse[] { + const out = new Map(); + const walk = (node: Element, fam: string | null, weight: string | null, style: string | null): void => { + const f = node.getAttribute('font-family') ?? fam; + const w = node.getAttribute('font-weight') ?? weight; + const s = node.getAttribute('font-style') ?? style; + const tag = node.localName; + if (tag === 'text' || tag === 'tspan') { + let own = ''; + for (const c of Array.from(node.childNodes)) if (c.nodeType === Node.TEXT_NODE) own += c.textContent ?? ''; + const family = bundled(f); + if (own && family) { + const key = `${family}|${isBold(w) ? 1 : 0}|${s === 'italic' || s === 'oblique' ? 1 : 0}`; + let use = out.get(key); + if (!use) out.set(key, (use = { family, bold: isBold(w), italic: s === 'italic' || s === 'oblique', chars: new Set() })); + for (const ch of own) use.chars.add(ch); + } + } + for (const kid of Array.from(node.children)) walk(kid, f, w, s); + }; + walk(root, null, null, null); + return [...out.values()]; +} + +const faceRule = (u: { family: string; bold: boolean; italic: boolean }, src: string): string => + `@font-face{font-family:'${u.family}';font-weight:${u.bold ? 700 : 400};font-style:${u.italic ? 'italic' : 'normal'};src:url(${src});}`; + +async function fullFace(u: FaceUse): Promise { + const file = FONT_FILES[`${u.family}|${u.bold ? 1 : 0}|${u.italic ? 1 : 0}`]; + try { + const res = await fetch(`/fonts/${file}`); + if (!res.ok) return null; + const rule = faceRule(u, `data:font/ttf;base64,${toBase64(new Uint8Array(await res.arrayBuffer()))}`); + return u.family === 'Arimo' ? rule.replace(`font-weight:${u.bold ? 700 : 400}`, 'font-weight:400 700') : rule; + } catch { + return null; + } +} + +async function fontRules(faces: FaceUse[], mode: PictureOptions['fonts'], warnings: string[]): Promise { + if (mode === 'none' || !faces.length) return ''; + const rules: string[] = []; + let left = faces; + if (mode === 'subset') { + try { + const out = await post<{ faces: { family: string; bold: boolean; italic: boolean; woff: string }[] }>('/api/pictures/fonts', { + faces: faces.map((f) => ({ family: f.family, bold: f.bold, italic: f.italic, text: [...f.chars].join('') })), + }); + for (const f of out.faces) rules.push(faceRule(f, `data:font/woff;base64,${f.woff}`)); + left = faces.filter((f) => !out.faces.some((g) => g.family === f.family && g.bold === f.bold && g.italic === f.italic)); + } catch { + left = faces; + } + } + for (const f of left) { + const rule = await fullFace(f); + if (rule) rules.push(rule); + else warnings.push(`The ${f.family} font could not be embedded; viewers fall back to a matching system font.`); + } + return rules.join(''); +} + +function contentBox(renderer: ReturnType, layers: SVGGElement[], ids: Id[]): Box | null { + const boxes: Box[] = []; + for (const id of ids) { + const b = renderer.objectBox(id); + if (b) boxes.push(b); + } + for (const g of layers) { + try { + const b = g.getBBox(); + if (b.width > 0 || b.height > 0) boxes.push({ x: b.x, y: b.y, w: b.width, h: b.height }); + } catch { continue; } + } + return union(boxes); +} + +export async function pictureSvg(doc: FormChemDocument, derived: Derived | null, opts: PictureOptions): Promise { + const warnings: string[] = []; + await fontsReady(); + await mediaReady(doc); + const page = doc.pages[0]; + const host = hiddenHost(); + const stage = document.createElementNS(SVG_NS, 'svg'); + host.appendChild(stage); + const renderer = createRenderer(); + try { + renderer.mount(stage); + renderer.update({ doc, rev: derived?.rev ?? 0, display: opts.display ? { ...opts.display, ...NO_WARNINGS } : undefined, derived, selection: EMPTY_SELECTION, hover: { kind: 'none' }, preview: null }); + const root = stage.querySelector('.fc-root') as SVGGElement | null; + if (!root || !page) throw new Error('nothing to draw'); + const layers = CONTENT_LAYERS.map((n) => root.querySelector(`.fc-layer-${n}`) as SVGGElement | null).filter((g): g is SVGGElement => !!g); + const ids = flatten(doc, page.order); + let box: Box | null; + if (opts.crop === false && page.size !== 'auto') box = { x: 0, y: 0, w: page.size.w, h: page.size.h }; + else { + const c = contentBox(renderer, layers, ids); + const m = Math.max(0, opts.margin); + box = c ? { x: c.x - m, y: c.y - m, w: c.w + 2 * m, h: c.h + 2 * m } : null; + } + if (!box || box.w <= 0 || box.h <= 0) throw new Error('there is nothing to export'); + const body = document.createElementNS(SVG_NS, 'g'); + for (const g of layers) if (g.childNodes.length) body.appendChild(g.cloneNode(true)); + inlineClasses(body); + await inlineMedia(body, warnings); + const faces = usedFaces(body); + const style = await fontRules(faces, opts.fonts, warnings); + const scale = opts.scale > 0 ? opts.scale : 1; + const width = box.w * scale, height = box.h * scale; + const title = doc.title ? `${esc(doc.title)}` : ''; + const bg = opts.background === 'white' ? `` : ''; + const inner = new XMLSerializer().serializeToString(body).replace(/^/, ''); + let svg = `` + + `${title}${bg}${inner}`; + if (opts.embedSource) svg = embedInSvg(svg, doc); + return { svg, width, height, box, warnings }; + } finally { + renderer.destroy(); + host.remove(); + } +} + +const frame = (): Promise => new Promise((r) => requestAnimationFrame(() => r())); + +export function pngSize(pic: Picture, dpi: number): { w: number; h: number; clamped: boolean } { + let w = Math.max(1, Math.round((pic.width / 72) * dpi)); + let h = Math.max(1, Math.round((pic.height / 72) * dpi)); + const k = Math.min(1, MAX_SIDE / w, MAX_SIDE / h, Math.sqrt(MAX_AREA / (w * h))); + if (k < 1) { w = Math.max(1, Math.floor(w * k)); h = Math.max(1, Math.floor(h * k)); } + return { w, h, clamped: k < 1 }; +} + +export async function picturePng(pic: Picture, dpi: number, background: PictureBackground, source: FormChemDocument | null): Promise { + const { w, h, clamped } = pngSize(pic, dpi); + if (clamped) pic.warnings.push('The picture was made smaller to fit the largest image the window can draw.'); + const url = URL.createObjectURL(new Blob([pic.svg], { type: 'image/svg+xml' })); + try { + const img = new Image(); + img.decoding = 'sync'; + img.src = url; + await img.decode(); + const canvas = document.createElement('canvas'); + canvas.width = w; + canvas.height = h; + const ctx = canvas.getContext('2d'); + if (!ctx) throw new Error('the window cannot draw pictures'); + const paint = (): void => { + ctx.clearRect(0, 0, w, h); + if (background === 'white') { ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, w, h); } + ctx.drawImage(img, 0, 0, w, h); + }; + paint(); + await frame(); + await frame(); + paint(); + const blob = await new Promise((r) => canvas.toBlob(r, 'image/png')); + if (!blob) throw new Error('the window could not encode the PNG'); + return embedInPng(new Uint8Array(await blob.arrayBuffer()), source, dpi); + } finally { + URL.revokeObjectURL(url); + } +} From e8d3a2dac3a7e09c6d2e1ddb6a5cb15cf77f3ddf Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:29:23 -0500 Subject: [PATCH 069/357] feat(export): add the Export Picture dialog and the File > Export commands (0.7.0) Format, scope (page, selection, each structure), dpi, background, scale, margin and embedded source in one small dialog reached from the title bar split button and File > Export; EPS joins the menus, and CDXML, Molfile and SMILES save through the engine's export route. --- frontend/src/app.ts | 2 +- frontend/src/app/canvas.ts | 2 + frontend/src/app/commands-shell.ts | 7 - frontend/src/app/export-commands.ts | 191 ++++++++++++++++++++++++++++ frontend/src/app/menus.ts | 2 +- frontend/src/ui/export-dialog.ts | 181 ++++++++++++++++++++++++++ 6 files changed, 376 insertions(+), 9 deletions(-) create mode 100644 frontend/src/app/export-commands.ts create mode 100644 frontend/src/ui/export-dialog.ts diff --git a/frontend/src/app.ts b/frontend/src/app.ts index 8dfedcbe..b541f52f 100644 --- a/frontend/src/app.ts +++ b/frontend/src/app.ts @@ -91,7 +91,7 @@ function isTyping(t: EventTarget | null): boolean { const GRID_KEY = 'formchem.showGrid'; const RECENT_IN_MENU = 10; -const EXPORT_ITEMS = ['export-png', 'export-svg', 'export-pdf', '-', 'export-cdxml', 'export-mol', 'export-smiles']; +const EXPORT_ITEMS = ['export-png', 'export-svg', 'export-pdf', 'export-eps', '-', 'export-cdxml', 'export-mol', 'export-smiles']; const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e)); const tauriCore = (): Promise => import('@tauri-apps/api/core'); diff --git a/frontend/src/app/canvas.ts b/frontend/src/app/canvas.ts index 4ec0b451..6836e8ef 100644 --- a/frontend/src/app/canvas.ts +++ b/frontend/src/app/canvas.ts @@ -17,6 +17,7 @@ import { mountToolRail, type ToolRail } from '../ui/tool-rail'; import { registerCanvasCommands } from './canvas-commands'; import { registerChemCommands } from './chem-commands'; import { commandStateChanged } from './commands-shell'; +import { registerExportCommands } from './export-commands'; import { objectCommandDefs } from './object-commands'; import { registerReactionCommands } from './reaction-commands'; @@ -58,6 +59,7 @@ export function mountCanvas(h: CanvasHosts, homeOpen: () => boolean): MountedCan commands.register(...objectCommandDefs(view, () => open() && !isEmpty(view.selection()))); registerReactionCommands({ view, homeOpen }); registerChemCommands({ host: view, homeOpen }); + registerExportCommands({ view, homeOpen, display }); onMarksView(() => view.setDisplay(display())); view.setDisplay(display()); diff --git a/frontend/src/app/commands-shell.ts b/frontend/src/app/commands-shell.ts index e7e8477c..c444b889 100644 --- a/frontend/src/app/commands-shell.ts +++ b/frontend/src/app/commands-shell.ts @@ -150,13 +150,6 @@ export function registerShellCommands(deps: ShellCommandDeps): () => void { { id: 'save-as', label: () => t('Save As...'), group: 'File', keys: ['Shift+Mod+S'], when: NO_DRAWING, enabled: () => deps.hasDocument(), run: () => deps.saveAs() }, { id: 'save-copy', label: () => t('Save a Copy...'), group: 'File', when: NO_DRAWING, enabled: () => deps.hasDocument(), run: () => deps.saveCopy() }, later('import', 'Import...', 'File', '0.7.0', 'upload'), - later('export-png', 'Export as PNG...', 'File', '0.7.0', 'fileImage'), - later('export-svg', 'Export as SVG...', 'File', '0.7.0'), - later('export-pdf', 'Export as PDF...', 'File', '0.7.0', 'filePdf'), - later('export-cdxml', 'Export as CDXML...', 'File', '0.7.0'), - later('export-mol', 'Export as Molfile...', 'File', '0.7.0'), - later('export-smiles', 'Export as SMILES...', 'File', '0.7.0'), - later('print', 'Print...', 'File', '0.7.0'), { id: 'preferences', label: preferencesLabel, group: 'File', keys: ['Mod+,'], icon: 'settings', run: () => deps.preferences() }, { id: 'close-document', label: () => t('Close Drawing'), group: 'File', when: NO_DRAWING, enabled: () => deps.hasDocument(), run: () => deps.closeDocument() }, diff --git a/frontend/src/app/export-commands.ts b/frontend/src/app/export-commands.ts new file mode 100644 index 00000000..7e62c6a7 --- /dev/null +++ b/frontend/src/app/export-commands.ts @@ -0,0 +1,191 @@ +import { fragmentsTouched, isEmpty } from '../canvas/selection'; +import type { RenderDisplay } from '../canvas/types'; +import type { CanvasView } from '../canvas/view'; +import { commands, type CommandDef } from '../commands/registry'; +import { isFragment, type FormChemDocument, type Id, type Page } from '../engine/model'; +import { t } from '../i18n'; +import { get, post } from '../io/api'; +import { askExport, type ExportChoice, type ExportScope, type PictureFormat } from '../ui/export-dialog'; +import { toast } from '../ui/toast'; +import { sourceText, subsetDocument, type SourceScope } from './embedded-source'; +import { pictureSvg, picturePng, type Picture } from './picture'; +import { printPicture } from './print'; +import { safeFileName, saveFiles, type SaveFileRequest } from './save-file'; + +export interface ExportCommandDeps { + view: CanvasView; + homeOpen(): boolean; + display(): RenderDisplay; +} + +type ChemFormat = 'cdxml' | 'molfile' | 'smiles'; + +interface Job { doc: FormChemDocument; name: string; scope: SourceScope } +interface ChemAnswer { format: string; filename: string; mime: string; binary: boolean; text: string | null; base64: string | null; report?: { severity?: string; text?: string }[] } + +const NEED_DRAWING = 'Open or create a drawing with something on the page first'; +const PICTURE_MIME: Record = { svg: 'image/svg+xml', png: 'image/png', pdf: 'application/pdf', eps: 'application/postscript' }; +const pictureKind = (f: PictureFormat): string => (f === 'svg' ? t('SVG picture') : f === 'png' ? t('PNG picture') : f === 'pdf' ? t('PDF document') : t('EPS picture')); +const CHEM_KIND: Record = { cdxml: 'CDXML', molfile: 'MDL molfile', smiles: 'SMILES' }; + +const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e)); + +function bytesOf(b64: string): Uint8Array { + const bin = atob(b64); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} + +function topLevel(doc: FormChemDocument, page: Page): Id[] { + return page.order.filter((id) => doc.objects[id] && !doc.objects[id].hidden); +} + +function structures(doc: FormChemDocument, page: Page): Id[] { + const out: Id[] = []; + const walk = (ids: readonly Id[]): void => { + for (const id of ids) { + const o = doc.objects[id]; + if (!o || o.hidden) continue; + if (o.kind === 'group') walk(o.children); + else if (isFragment(o) && Object.keys(o.atoms).length) out.push(id); + } + }; + walk(page.order); + return out; +} + +function noteOf(warnings: string[]): string { + const first = warnings.find((w) => w); + return first ? ` (${first})` : ''; +} + +export function registerExportCommands(deps: ExportCommandDeps): () => void { + const { view } = deps; + const ready = (): boolean => !!view.client && !deps.homeOpen() && !!view.page() && topLevel(view.doc, view.page()!).length > 0; + const hasSelection = (): boolean => !isEmpty(view.selection()); + const baseName = (): string => safeFileName(view.doc.title || t('Untitled')); + + const jobsFor = (scope: ExportScope): Job[] => { + const doc = view.doc, page = view.page(); + if (!page) return []; + if (scope === 'selection' && hasSelection()) return [{ doc: subsetDocument(doc, page.id, view.selection(), 'selection'), name: baseName(), scope: 'selection' }]; + if (scope === 'each') { + const ids = structures(doc, page); + const used = new Set(); + return ids.map((id, i) => { + const f = doc.objects[id]; + let name = safeFileName(isFragment(f) && f.name ? f.name : `${baseName()} ${i + 1}`); + while (used.has(name.toLowerCase())) name = `${name} ${i + 1}`; + used.add(name.toLowerCase()); + return { doc: subsetDocument(doc, page.id, [id], 'structure'), name, scope: 'structure' as const }; + }); + } + return [{ doc: subsetDocument(doc, page.id, null, 'page'), name: baseName(), scope: 'page' }]; + }; + + const sizeOf = (scope: ExportScope): { w: number; h: number } | null => { + const r = view.renderer as unknown as { objectBox?: (id: Id) => { x: number; y: number; w: number; h: number } | null }; + const page = view.page(); + if (!r.objectBox || !page) return null; + const box = (ids: Id[]): { w: number; h: number } | null => { + const boxes = ids.map((id) => r.objectBox!(id)).filter((b): b is NonNullable => !!b); + if (!boxes.length) return null; + const x0 = Math.min(...boxes.map((b) => b.x)), y0 = Math.min(...boxes.map((b) => b.y)); + return { w: Math.max(...boxes.map((b) => b.x + b.w)) - x0, h: Math.max(...boxes.map((b) => b.y + b.h)) - y0 }; + }; + if (scope === 'each') { + const all = structures(view.doc, page).map((id) => box([id])).filter((b): b is NonNullable => !!b); + return all.length ? all.reduce((p, q) => (q.w * q.h > p.w * p.h ? q : p)) : null; + } + if (scope === 'selection') { + const s = view.selection(); + return box([...new Set([...fragmentsTouched(s), ...s.objects])]); + } + return box(topLevel(view.doc, page)); + }; + + async function render(job: Job, choice: ExportChoice): Promise { + const vector = choice.format === 'pdf' || choice.format === 'eps'; + const pic: Picture = await pictureSvg(job.doc, view.client?.derived ?? null, { + scale: choice.scale / 100, margin: choice.margin, background: choice.background, + embedSource: choice.embed && !vector, fonts: vector ? 'none' : 'subset', display: deps.display(), + }); + const name = `${job.name}.${choice.format}`; + const base = { name, mime: PICTURE_MIME[choice.format], kind: pictureKind(choice.format) }; + if (choice.format === 'svg') return { ...base, data: pic.svg, warnings: pic.warnings }; + if (choice.format === 'png') { + const data = await picturePng(pic, choice.dpi, choice.background, choice.embed ? job.doc : null); + return { ...base, data, warnings: pic.warnings }; + } + const out = await post<{ base64: string; warnings?: string[] }>('/api/pictures/convert', { + format: choice.format, svg: pic.svg, title: job.doc.title, source: choice.embed ? sourceText(job.doc) : null, + }); + return { ...base, data: bytesOf(out.base64), warnings: [...pic.warnings, ...(out.warnings ?? [])] }; + } + + async function exportPicture(format?: PictureFormat): Promise { + const page = view.page(); + if (!ready() || !page) { toast(t('There is nothing on the page to export.')); return; } + const choice = await askExport({ format, hasSelection: hasSelection(), structures: structures(view.doc, page).length, sizeOf }); + if (!choice) return; + const jobs = jobsFor(choice.scope); + if (!jobs.length) { toast(t('There is nothing on the page to export.')); return; } + const files: SaveFileRequest[] = []; + const warnings: string[] = []; + for (const job of jobs) { + const made = await render(job, choice); + warnings.push(...made.warnings); + files.push(made); + } + const saved = (await saveFiles(files)).filter((r) => r.saved); + if (!saved.length) return; + toast(`${saved.length === 1 ? `${t('Exported')} ${saved[0].name}` : `${t('Exported')} ${saved.length} ${t('files')}`}${noteOf(warnings)}`); + } + + async function exportChem(format: ChemFormat, ext: string): Promise { + const c = view.client, page = view.page(); + if (!c || !page || !ready()) { toast(t('There is nothing on the page to export.')); return; } + const s = view.selection(); + const ids = isEmpty(s) ? [] : [...new Set([...fragmentsTouched(s), ...s.objects])]; + const query = new URLSearchParams({ format, scope: ids.length ? 'selection' : 'page', page: page.id, as: 'json' }); + if (ids.length) query.set('ids', ids.join(',')); + const out = await get(`/api/documents/${encodeURIComponent(c.id)}/export?${query.toString()}`); + const data = out.binary && out.base64 ? bytesOf(out.base64) : out.text ?? ''; + const name = safeFileName(out.filename || `${baseName()}.${ext}`); + const done = (await saveFiles([{ name, mime: out.mime || 'text/plain', data, kind: CHEM_KIND[format] }]))[0]; + if (!done?.saved) return; + const lost = (out.report ?? []).filter((r) => r.severity === 'warn' || r.severity === 'error').map((r) => r.text ?? ''); + toast(`${t('Exported')} ${done.name}${noteOf(lost)}`); + } + + async function print(): Promise { + const page = view.page(); + if (!ready() || !page) { toast(t('There is nothing on the page to print.')); return; } + const sel = hasSelection(); + const doc = subsetDocument(view.doc, page.id, sel ? view.selection() : null, sel ? 'selection' : 'page'); + const fixed = page.size !== 'auto'; + const pic = await pictureSvg(doc, view.client?.derived ?? null, { + scale: 1, margin: fixed ? 0 : page.margins ?? 36, background: 'white', embedSource: false, fonts: 'subset', crop: !fixed, display: deps.display(), + }); + await printPicture(pic); + } + + const failed = (what: () => string) => (e: unknown): void => toast(`${what()}: ${errText(e)}`, 'error'); + const picture = (format?: PictureFormat) => (): void => { void exportPicture(format).catch(failed(() => t('Could not export the picture'))); }; + const chem = (format: ChemFormat, ext: string) => (): void => { void exportChem(format, ext).catch(failed(() => t('Could not export the drawing'))); }; + const describe = (what: string): string => `Opens the Export Picture dialog set to ${what}: the whole page, the selection or each structure, at a chosen scale, margin, resolution (PNG) and background, with the editable drawing kept inside the file; the desktop app asks where to save, a browser downloads.`; + + const defs: CommandDef[] = [ + { id: 'export-picture', label: () => t('Export Picture...'), group: 'File', icon: 'fileImage', description: describe('the last used format'), when: NEED_DRAWING, enabled: ready, run: picture() }, + { id: 'export-png', label: () => t('Export as PNG...'), group: 'File', icon: 'fileImage', description: describe('PNG (300 dpi by default, transparent or white)'), when: NEED_DRAWING, enabled: ready, run: picture('png') }, + { id: 'export-svg', label: () => t('Export as SVG...'), group: 'File', description: describe('SVG with the label fonts embedded'), when: NEED_DRAWING, enabled: ready, run: picture('svg') }, + { id: 'export-pdf', label: () => t('Export as PDF...'), group: 'File', icon: 'filePdf', description: describe('PDF'), when: NEED_DRAWING, enabled: ready, run: picture('pdf') }, + { id: 'export-eps', label: () => t('Export as EPS...'), group: 'File', description: describe('EPS'), when: NEED_DRAWING, enabled: ready, run: picture('eps') }, + { id: 'export-cdxml', label: () => t('Export as CDXML...'), group: 'File', description: 'Saves the selection, or the whole page, as a CDXML file and reports what the format cannot keep.', when: NEED_DRAWING, enabled: ready, run: chem('cdxml', 'cdxml') }, + { id: 'export-mol', label: () => t('Export as Molfile...'), group: 'File', description: 'Saves the selected structures, or every structure on the page, as an MDL molfile (V3000 when V2000 cannot hold them) and reports what the format cannot keep.', when: NEED_DRAWING, enabled: ready, run: chem('molfile', 'mol') }, + { id: 'export-smiles', label: () => t('Export as SMILES...'), group: 'File', description: 'Saves the selected structures, or every structure on the page, as a SMILES file.', when: NEED_DRAWING, enabled: ready, run: chem('smiles', 'smi') }, + { id: 'print', label: () => t('Print...'), group: 'File', keys: ['Mod+P'], description: 'Prints the page, or only the selection in its place on the page, at real size on paper the size of the page; the dark page view never prints.', when: NEED_DRAWING, enabled: ready, run: () => { void print().catch(failed(() => t('Could not print'))); } }, + ]; + return commands.register(...defs); +} diff --git a/frontend/src/app/menus.ts b/frontend/src/app/menus.ts index 98bbc6e5..ce7e08de 100644 --- a/frontend/src/app/menus.ts +++ b/frontend/src/app/menus.ts @@ -6,7 +6,7 @@ export type MenuSource = () => MenuItem[] | null | undefined; const EXTENSIONS_FALLBACK: MenuItem[] = ['ext-panel', 'ext-reload', 'ext-manage']; -const EXPORT: MenuItem = { label: 'Export', items: ['export-png', 'export-svg', 'export-pdf', '-', 'export-cdxml', 'export-mol', 'export-smiles'] }; +const EXPORT: MenuItem = { label: 'Export', items: ['export-png', 'export-svg', 'export-pdf', 'export-eps', '-', 'export-cdxml', 'export-mol', 'export-smiles'] }; const COPY_AS: MenuItem = { label: 'Copy As', items: ['copy-smiles', 'copy-molfile', 'copy-inchi', 'copy-svg'] }; const REACTION_COPY: MenuItem = { label: 'Copy Reaction As', items: ['copy-reaction-smiles', 'copy-reaction-rxn'] }; const REACTION_EXPORT: MenuItem = { label: 'Export Reaction', items: ['export-reaction-smiles', 'export-reaction-rxn'] }; diff --git a/frontend/src/ui/export-dialog.ts b/frontend/src/ui/export-dialog.ts new file mode 100644 index 00000000..5ff3bf51 --- /dev/null +++ b/frontend/src/ui/export-dialog.ts @@ -0,0 +1,181 @@ +import { t } from '../i18n'; +import { Dialog, segOn, segSet } from './dialogs'; +import { el, q, setChecked, setDisabled, setHidden, setText } from './dom'; + +export type PictureFormat = 'svg' | 'png' | 'pdf' | 'eps'; +export type ExportScope = 'page' | 'selection' | 'each'; + +export interface ExportChoice { + format: PictureFormat; + scope: ExportScope; + dpi: number; + background: 'transparent' | 'white'; + scale: number; + margin: number; + embed: boolean; +} + +export interface ExportRequest { + format?: PictureFormat; + hasSelection: boolean; + structures: number; + sizeOf(scope: ExportScope): { w: number; h: number } | null; +} + +const KEY = 'formchem.exportPicture'; +const DPIS = [72, 150, 300, 600]; +const DEFAULTS: ExportChoice = { format: 'png', scope: 'page', dpi: 300, background: 'transparent', scale: 100, margin: 6, embed: true }; +const SCALE_MIN = 5; +const SCALE_MAX = 2000; +const MARGIN_MAX = 288; + +function remembered(): ExportChoice { + try { + const raw = JSON.parse(localStorage.getItem(KEY) ?? '{}') as Partial; + return { + format: (['svg', 'png', 'pdf', 'eps'] as const).find((f) => f === raw.format) ?? DEFAULTS.format, + scope: raw.scope === 'each' ? 'each' : 'page', + dpi: DPIS.includes(Number(raw.dpi)) ? Number(raw.dpi) : DEFAULTS.dpi, + background: raw.background === 'white' ? 'white' : 'transparent', + scale: Number.isFinite(raw.scale) && raw.scale! >= SCALE_MIN && raw.scale! <= SCALE_MAX ? raw.scale! : DEFAULTS.scale, + margin: Number.isFinite(raw.margin) && raw.margin! >= 0 && raw.margin! <= MARGIN_MAX ? raw.margin! : DEFAULTS.margin, + embed: raw.embed !== false, + }; + } catch { + return { ...DEFAULTS }; + } +} + +function remember(c: ExportChoice): void { + try { localStorage.setItem(KEY, JSON.stringify({ ...c, scope: c.scope === 'selection' ? 'page' : c.scope })); } catch { return; } +} + +const fmt = (v: number, digits = 2): string => String(Math.round(v * 10 ** digits) / 10 ** digits); + +class ExportDialog extends Dialog { + private readonly format: HTMLElement; + private readonly scope: HTMLElement; + private readonly dpi: HTMLElement; + private readonly dpiRow: HTMLElement; + private readonly background: HTMLElement; + private readonly scale: HTMLInputElement; + private readonly margin: HTMLInputElement; + private readonly embed: HTMLInputElement; + private readonly size: HTMLElement; + private readonly ok: HTMLButtonElement; + private choice: ExportChoice = { ...DEFAULTS }; + private req: ExportRequest | null = null; + private resolve: ((v: ExportChoice | null) => void) | null = null; + + constructor() { + super(t('Export Picture'), 460); + const seg = (items: [string, string][]): HTMLElement => { + const s = el('
'); + for (const [v, label] of items) { + const b = el(``); + b.textContent = label; + s.appendChild(b); + } + return s; + }; + this.format = seg([['svg', 'SVG'], ['png', 'PNG'], ['pdf', 'PDF'], ['eps', 'EPS']]); + this.field(t('Format'), this.format); + this.scope = seg([['page', t('Whole page')], ['selection', t('Selection')], ['each', t('Each structure')]]); + this.field(t('Export'), this.scope); + this.dpi = seg(DPIS.map((d) => [String(d), `${d} dpi`])); + this.dpiRow = this.field(t('Resolution'), this.dpi); + this.background = seg([['transparent', t('Transparent')], ['white', t('White')]]); + this.field(t('Background'), this.background); + const num = (unit: string, max: number): HTMLElement => + el(`${unit}`); + const sc = num('%', SCALE_MAX); + this.scale = q(sc, 'input'); + this.field(t('Scale'), sc); + const mg = num('pt', MARGIN_MAX); + this.margin = q(mg, 'input'); + this.field(t('Margin'), mg); + this.embed = el(''); + const check = el(''); + check.appendChild(this.embed); + check.appendChild(document.createTextNode(t('Keep the editable drawing inside the file'))); + this.body.appendChild(check); + this.size = el('

'); + this.body.appendChild(this.size); + + segOn(this.format, (v) => { this.choice.format = v as PictureFormat; this.sync(); }); + segOn(this.scope, (v) => { this.choice.scope = v as ExportScope; this.sync(); }); + segOn(this.dpi, (v) => { this.choice.dpi = Number(v); this.sync(); }); + segOn(this.background, (v) => { this.choice.background = v === 'white' ? 'white' : 'transparent'; this.sync(); }); + this.scale.addEventListener('input', () => this.sync()); + this.margin.addEventListener('input', () => this.sync()); + this.embed.addEventListener('change', () => { this.choice.embed = this.embed.checked; }); + for (const input of [this.scale, this.margin]) { + input.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.isComposing) { e.preventDefault(); if (!this.ok.disabled) this.ok.click(); } }); + } + this.button(t('Cancel'), 'ghost', () => this.finish(null)); + this.ok = this.button(t('Export'), 'primary', () => this.finish(this.answer())); + this.onClose = () => this.finish(null); + } + + ask(req: ExportRequest): Promise { + this.resolve?.(null); + this.req = req; + this.choice = remembered(); + if (req.format) this.choice.format = req.format; + this.choice.scope = req.hasSelection ? 'selection' : this.choice.scope === 'each' && req.structures > 1 ? 'each' : 'page'; + segSet(this.format, this.choice.format); + segSet(this.dpi, String(this.choice.dpi)); + segSet(this.background, this.choice.background); + this.scale.value = fmt(this.choice.scale, 1); + this.margin.value = fmt(this.choice.margin, 1); + setChecked(this.embed, this.choice.embed); + setDisabled(q(this.scope, 'button[data-v="selection"]'), !req.hasSelection); + setDisabled(q(this.scope, 'button[data-v="each"]'), req.structures < 2); + this.sync(); + this.open(this.ok); + return new Promise((r) => { this.resolve = r; }); + } + + private number(input: HTMLInputElement, lo: number, hi: number): number | null { + const n = Number.parseFloat(input.value); + return Number.isFinite(n) && n >= lo && n <= hi ? n : null; + } + + private sync(): void { + segSet(this.scope, this.choice.scope); + setHidden(this.dpiRow, this.choice.format !== 'png'); + const scale = this.number(this.scale, SCALE_MIN, SCALE_MAX); + const margin = this.number(this.margin, 0, MARGIN_MAX); + setDisabled(this.ok, scale === null || margin === null); + const box = this.req?.sizeOf(this.choice.scope); + if (!box || scale === null || margin === null) { setText(this.size, ''); return; } + const w = ((box.w + 2 * margin) * scale) / 100, h = ((box.h + 2 * margin) * scale) / 100; + const inches = `${fmt(w / 72)} x ${fmt(h / 72)} in (${fmt((w / 72) * 25.4, 1)} x ${fmt((h / 72) * 25.4, 1)} mm)`; + const px = this.choice.format === 'png' ? `, ${Math.round((w / 72) * this.choice.dpi)} x ${Math.round((h / 72) * this.choice.dpi)} px` : ''; + const each = this.choice.scope === 'each' ? `${t('Largest structure')}: ` : ''; + setText(this.size, `${each}${inches}${px}`); + } + + private answer(): ExportChoice | null { + const scale = this.number(this.scale, SCALE_MIN, SCALE_MAX); + const margin = this.number(this.margin, 0, MARGIN_MAX); + if (scale === null || margin === null) return null; + const out = { ...this.choice, scale, margin, embed: this.embed.checked }; + remember(out); + return out; + } + + private finish(v: ExportChoice | null): void { + const r = this.resolve; + this.resolve = null; + if (this.isOpen) this.close(); + r?.(v); + } +} + +let dialog: ExportDialog | null = null; + +export function askExport(req: ExportRequest): Promise { + dialog ??= new ExportDialog(); + return dialog.ask(req); +} From e2556f1aa41ac27a5383f496b4fdfefea86a3b1a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:29:30 -0500 Subject: [PATCH 070/357] feat(print): print the page or the selection at real size (0.7.0) File > Print hands the webview a picture built from the document model on paper the size of the page, and a print stylesheet hides everything else, so the dark page and the app chrome never print. --- frontend/index.html | 1 + frontend/src/app/print.ts | 49 +++++++++++++++++++++++++++++++++++ frontend/src/styles/print.css | 17 ++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 frontend/src/app/print.ts create mode 100644 frontend/src/styles/print.css diff --git a/frontend/index.html b/frontend/index.html index 7a2710d0..82f3b364 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -118,6 +118,7 @@ +
diff --git a/frontend/src/app/print.ts b/frontend/src/app/print.ts new file mode 100644 index 00000000..bb75f190 --- /dev/null +++ b/frontend/src/app/print.ts @@ -0,0 +1,49 @@ +import { inTauri } from '../ui/dom'; +import type { Picture } from './picture'; + +const HOST_CLASS = 'fc-print-host'; +const PAGE_STYLE_ID = 'fc-print-page'; + +let host: HTMLDivElement | null = null; +let img: HTMLImageElement | null = null; +let pageStyle: HTMLStyleElement | null = null; +let url = ''; + +const pt = (v: number): string => `${Math.round(v * 1000) / 1000}pt`; + +function ensureHost(): { host: HTMLDivElement; img: HTMLImageElement; style: HTMLStyleElement } { + if (!host || !host.isConnected) { + host = document.createElement('div'); + host.className = HOST_CLASS; + host.setAttribute('aria-hidden', 'true'); + img = document.createElement('img'); + img.alt = ''; + host.appendChild(img); + document.body.appendChild(host); + } + if (!pageStyle || !pageStyle.isConnected) { + pageStyle = document.createElement('style'); + pageStyle.id = PAGE_STYLE_ID; + pageStyle.media = 'print'; + document.head.appendChild(pageStyle); + } + return { host, img: img!, style: pageStyle }; +} + +export async function printPicture(pic: Picture): Promise { + const parts = ensureHost(); + const next = URL.createObjectURL(new Blob([pic.svg], { type: 'image/svg+xml' })); + parts.img.style.width = pt(pic.width); + parts.img.style.height = pt(pic.height); + parts.img.src = next; + if (url) URL.revokeObjectURL(url); + url = next; + await parts.img.decode(); + parts.style.textContent = `@page { size: ${pt(pic.width)} ${pt(pic.height)}; margin: 0; }`; + if (inTauri()) { + const [{ invoke }, { getCurrentWindow }] = await Promise.all([import('@tauri-apps/api/core'), import('@tauri-apps/api/window')]); + await invoke('print_window', { label: getCurrentWindow().label }); + return; + } + window.print(); +} diff --git a/frontend/src/styles/print.css b/frontend/src/styles/print.css new file mode 100644 index 00000000..127d6067 --- /dev/null +++ b/frontend/src/styles/print.css @@ -0,0 +1,17 @@ +.fc-print-host { display: none; } + +@media print { + html, body { + width: auto !important; + height: auto !important; + min-height: 0 !important; + margin: 0 !important; + padding: 0 !important; + overflow: visible !important; + background: #ffffff !important; + color: #000000 !important; + } + body > *:not(.fc-print-host) { display: none !important; } + .fc-print-host { display: block !important; position: static !important; margin: 0; padding: 0; background: #ffffff; } + .fc-print-host img { display: block; max-width: none; filter: none !important; break-inside: avoid; } +} From 25cc37d926708c61ef980c888e887e1433dccbfb Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:29:30 -0500 Subject: [PATCH 071/357] feat(documents): offer exported pictures in the Open dialogs (0.7.0) SVG, PNG, PDF and EPS files made by FormChem open as drawings from File > Open and Home, using the source kept inside them. --- frontend/src/app/documents.ts | 2 +- frontend/src/ui/home.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/frontend/src/app/documents.ts b/frontend/src/app/documents.ts index c2334fe3..95381271 100644 --- a/frontend/src/app/documents.ts +++ b/frontend/src/app/documents.ts @@ -26,7 +26,7 @@ export interface DocumentHooks { interface ParseAnswer { fragments?: Fragment[]; warnings?: { text?: string }[] } -const OPEN_EXTENSIONS = ['fchem', 'mol', 'mdl', 'sdf', 'sd', 'rxn', 'smi', 'smiles', 'cxsmi', 'cxsmiles', 'inchi', 'cml', 'cdxml', 'cdx']; +const OPEN_EXTENSIONS = ['fchem', 'mol', 'mdl', 'sdf', 'sd', 'rxn', 'smi', 'smiles', 'cxsmi', 'cxsmiles', 'inchi', 'cml', 'cdxml', 'cdx', 'svg', 'png', 'pdf', 'eps']; const UPLOAD_URL = '/api/documents/upload'; const PARSE_URL = '/api/chem/parse'; diff --git a/frontend/src/ui/home.ts b/frontend/src/ui/home.ts index 11b19ec2..bd2b651d 100644 --- a/frontend/src/ui/home.ts +++ b/frontend/src/ui/home.ts @@ -35,7 +35,7 @@ const RECENT_ON_START = 8; const FORMATS = ['FCHEM', 'MOL', 'SDF', 'RXN', 'SMILES', 'CDXML', 'CDX', 'CML', 'CIF', 'PDB', 'JDX']; const KINDS: ListKind[] = ['recent', 'templates', 'databases', 'trash']; -export const STRUCTURE_ACCEPT = '.fchem,.mol,.sdf,.sd,.rxn,.rdf,.smi,.smiles,.cdxml,.cdx,.cml,.cif,.pdb,.jdx,.dx'; +export const STRUCTURE_ACCEPT = '.fchem,.mol,.sdf,.sd,.rxn,.rdf,.smi,.smiles,.cdxml,.cdx,.cml,.cif,.pdb,.jdx,.dx,.svg,.png,.pdf,.eps'; export function chooseStructureFiles(multiple = true): Promise { return new Promise((resolve) => { From f6d449d57633ccef6cde5e3d606a9176f8717c43 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:29:30 -0500 Subject: [PATCH 072/357] fix(embed): find the PDF source length past the nested Params dictionary (0.7.0) The embedded file's /Params holds its own dictionary, so the readers stopped at its end and missed /Length; FormChem PDFs did not open as drawings. --- backend/app/services/embedded_source.py | 8 ++++---- frontend/src/app/embedded-source.ts | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/backend/app/services/embedded_source.py b/backend/app/services/embedded_source.py index e1716ae4..b33bdfb2 100644 --- a/backend/app/services/embedded_source.py +++ b/backend/app/services/embedded_source.py @@ -82,11 +82,11 @@ def from_pdf(data: bytes) -> dict | None: if mark < 0: return None start = data.rfind(b"<<", 0, mark) - end = data.find(b">>", mark) - length = _PDF_LENGTH.search(data, start, end) - stream = data.find(b"stream", end) - if not length or stream < 0: + stream = data.find(b"stream", mark) + found = list(_PDF_LENGTH.finditer(data, start, stream)) if stream > 0 else [] + if not found: return None + length = found[-1] at = stream + 6 if data[at:at + 1] == b"\r": at += 1 diff --git a/frontend/src/app/embedded-source.ts b/frontend/src/app/embedded-source.ts index 1fc740b7..46bcb6b5 100644 --- a/frontend/src/app/embedded-source.ts +++ b/frontend/src/app/embedded-source.ts @@ -275,10 +275,10 @@ export function extractFromPdf(pdf: Uint8Array): EmbeddedSource | null { const mark = text.indexOf(PDF_MARK); if (mark < 0) return null; const open = text.lastIndexOf('<<', mark); - const close = text.indexOf('>>', mark); - const len = /\/Length\s+(\d+)/.exec(text.slice(open, close)); - const stream = text.indexOf('stream', close); - if (!len || stream < 0) return null; + const stream = text.indexOf('stream', mark); + const lens = stream > 0 ? [...text.slice(open, stream).matchAll(/\/Length\s+(\d+)/g)] : []; + const len = lens[lens.length - 1]; + if (!len) return null; let start = stream + 6; if (text[start] === '\r') start++; if (text[start] === '\n') start++; From 659a77ad37aff54316eb0e587d30bddd4cf827a3 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:29:30 -0500 Subject: [PATCH 073/357] fix(pictures): keep font subsets byte for byte the same between exports (0.7.0) fontTools stamped the save time into each subset, so the same drawing exported twice gave different SVG files; exports are now deterministic. --- backend/app/services/pictures/fonts.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backend/app/services/pictures/fonts.py b/backend/app/services/pictures/fonts.py index 0fb949d5..d3aa5b92 100644 --- a/backend/app/services/pictures/fonts.py +++ b/backend/app/services/pictures/fonts.py @@ -105,6 +105,7 @@ def face_bytes(family: str, bold: bool, italic: bool) -> bytes: with _LOCK: font = TTFont(str(folder / name)) static = instancer.instantiateVariableFont(font, {"wght": 700 if bold else 400}, inplace=False, updateFontNames=False) + static.recalcTimestamp = False buf = io.BytesIO() static.save(buf) return buf.getvalue() @@ -119,7 +120,7 @@ def face(family: str, bold: bool, italic: bool): def subset_woff(family: str, bold: bool, italic: bool, text: str) -> bytes: from fontTools import subset from fontTools.ttLib import TTFont - font = TTFont(io.BytesIO(face_bytes(bundled(family), bold, italic))) + font = TTFont(io.BytesIO(face_bytes(bundled(family), bold, italic)), recalcTimestamp=False) opts = subset.Options() opts.flavor = "woff" opts.layout_features = ["kern", "liga", "clig", "calt", "locl", "mark", "mkmk"] From f305069f4669193844162003dd278464005026a1 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:13:06 -0500 Subject: [PATCH 074/357] fix(layout): fall back to the first candidate when every layout score is not a number (0.7.0) A two-atom hydrogen molecule scores NaN, so reading H2 from a reaction SMILES crashed the layout instead of drawing it. --- backend/app/services/chem/layout.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/app/services/chem/layout.py b/backend/app/services/chem/layout.py index 0191c8bc..7b1c9204 100644 --- a/backend/app/services/chem/layout.py +++ b/backend/app/services/chem/layout.py @@ -91,7 +91,7 @@ def depict(mol: Chem.Mol, fixed: dict[int, Point] | None = None, near = sorted((f for f in found if f[0].hard <= least), key=lambda f: _distance(f[1], reference)) else: floor = min(f[0].total for f in found) + SWITCH_MARGIN - near = [f for f in found if f[0].total <= floor] + near = [f for f in found if f[0].total <= floor] or found[:1] score, chosen, name = near[0] conf = Chem.Conformer(chosen.GetConformer()) if mol.GetNumAtoms() <= CANDIDATE_LIMIT and shape is not None and (score.hard > 0 or not keep): From 9a7c7068db6e9650aca3c9869e5b15b62d381f6f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:13:06 -0500 Subject: [PATCH 075/357] feat(chem): add import and export report items with a code, a count and a short text (0.7.0) Readers and writers collect warnings; the report merges them by code so the window and agents can show what was lost or changed. --- backend/app/services/chem/report.py | 89 +++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 backend/app/services/chem/report.py diff --git a/backend/app/services/chem/report.py b/backend/app/services/chem/report.py new file mode 100644 index 00000000..190f83e0 --- /dev/null +++ b/backend/app/services/chem/report.py @@ -0,0 +1,89 @@ +from typing import Iterable + +INFO, WARN, ERROR = "info", "warn", "error" + +SEVERITY = { + "coordinates_generated": INFO, "coordinates_flattened": INFO, "rescaled": INFO, "abbreviations_expanded": INFO, + "inchi_normalised": INFO, "reaction_arrow": INFO, "v3000": INFO, "molfile_merged": INFO, "styles_dropped": INFO, + "conditions_comment": INFO, "bond_length_changed": INFO, "names_dropped": INFO, "reaction_layout": INFO, + "parse_failed": ERROR, "record_failed": ERROR, "inchi_failed": ERROR, "engine_error": ERROR, +} + +TEXTS = { + "record_failed": "{n} records could not be read and were skipped.", + "parse_failed": "{n} parts of the file could not be read.", + "structure_problem": "{n} valence or aromaticity problems were found and kept as drawn.", + "valence_fixed": "{n} atoms had their valence or hydrogen count adjusted.", + "stereo_unknown": "{n} stereocentres or double bonds have unknown configuration.", + "coordinates_generated": "{n} structures had no 2D coordinates; a layout was generated.", + "coordinates_flattened": "{n} structures had 3D coordinates and were flattened to 2D.", + "unsupported_object": "{n} drawing objects of kinds FormChem does not read were left out.", + "text_dropped": "{n} text objects are not stored in this format.", + "graphics_dropped": "{n} arrows, plus signs and other drawing objects are not stored in this format.", + "enhanced_stereo_lost": "{n} enhanced stereo groups are not stored in this format.", + "query_lost": "{n} query features are not stored in this format.", + "rgroups_lost": "{n} R-group definitions are not stored in this format.", + "sgroups_dropped": "{n} Sgroups (brackets, data or superatoms) were not read.", + "data_dropped": "{n} data fields are not stored in this format.", + "cannot_kekulise": "{n} aromatic systems could not be kekulised.", + "unknown_label": "{n} labels are not elements or known abbreviations.", +} + + +def item(code: str, count: int = 1, text: str = "", severity: str | None = None, atoms: Iterable[str] = (), + bonds: Iterable[str] = (), objects: Iterable[str] = ()) -> dict: + out: dict = {"code": code, "count": max(1, int(count)), "text": text or TEXTS.get(code, code).format(n=count), + "severity": severity or SEVERITY.get(code, "warn")} + for key, values in (("atoms", atoms), ("bonds", bonds), ("objects", objects)): + found = sorted({v for v in values if v}) + if found: + out[key] = found + return out + + +def _count(w: dict) -> int: + if isinstance(w.get("count"), int) and not isinstance(w.get("count"), bool) and w["count"] > 0: + return w["count"] + return max(1, len(w.get("atoms") or []) or len(w.get("objects") or []) or 1) + + +def collect(warnings: Iterable[dict | str], limit: int = 200) -> list[dict]: + merged: dict[str, dict] = {} + texts: dict[str, list[str]] = {} + for w in warnings: + if isinstance(w, str): + w = {"code": "note", "text": w} + if not isinstance(w, dict): + continue + code = str(w.get("code") or "note") + n = _count(w) + cur = merged.get(code) + if cur is None: + cur = merged[code] = {"code": code, "count": 0, "text": "", "severity": w.get("severity") or SEVERITY.get(code, "warn")} + texts[code] = [] + cur["count"] += n + text = str(w.get("text") or "") + if text and text not in texts[code]: + texts[code].append(text) + for key in ("atoms", "bonds", "objects"): + if w.get(key): + cur[key] = sorted({*cur.get(key, []), *w[key]}) + out = [] + for code, cur in merged.items(): + found = texts[code] + if len(found) == 1: + cur["text"] = found[0] + elif code in TEXTS: + cur["text"] = TEXTS[code].format(n=cur["count"]) + elif found: + cur["text"] = found[0] + (f" (and {len(found) - 1} more)" if len(found) > 1 else "") + else: + cur["text"] = code + out.append(cur) + order = {ERROR: 0, WARN: 1, INFO: 2} + out.sort(key=lambda r: (order.get(r["severity"], 1), r["code"])) + return out[:limit] + + +def lines(report: Iterable[dict]) -> list[str]: + return [r["text"] for r in report if r.get("text")] From f603a4124638efb7fb731cde87b6acb7ddab5088 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:13:06 -0500 Subject: [PATCH 076/357] feat(chem): read and write RD files with reaction and molecule records and data fields (0.7.0) RD files carry reactions with their conditions and data fields; long data values wrap with a plus at column 80. --- backend/app/services/chem/rdfio.py | 111 +++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 backend/app/services/chem/rdfio.py diff --git a/backend/app/services/chem/rdfio.py b/backend/app/services/chem/rdfio.py new file mode 100644 index 00000000..6542a9c3 --- /dev/null +++ b/backend/app/services/chem/rdfio.py @@ -0,0 +1,111 @@ +from dataclasses import dataclass, field +from datetime import datetime, timezone + +CONDITIONS_FIELD = "RXN:CONDITIONS" +NAME_FIELD = "NAME" +LINE = 80 +STARTS = ("$RFMT", "$MFMT") + + +@dataclass +class RdRecord: + kind: str + block: str + data: dict = field(default_factory=dict) + conditions: str = "" + registry: str = "" + + +def _finish(rec: RdRecord | None, lines: list[str], out: list[RdRecord]) -> None: + if rec is None: + return + rec.block = "\n".join(lines).rstrip("\n") + "\n" + for key in list(rec.data): + if key.upper().endswith("CONDITIONS"): + rec.conditions = str(rec.data.pop(key)) + out.append(rec) + + +def parse(text: str) -> list[RdRecord]: + out: list[RdRecord] = [] + rec: RdRecord | None = None + block: list[str] = [] + key: str | None = None + value: list[str] = [] + + def flush_datum() -> None: + nonlocal key, value + if rec is not None and key is not None: + joined = "" + for raw, line in value: + joined += line[:-1] if line.endswith("+") and len(raw) >= LINE else line + "\n" + rec.data[key] = joined.rstrip("\n") + key, value = None, [] + + in_data = False + for line in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"): + head = line[:5] + if head in STARTS or line.startswith("$RIREG") or line.startswith("$MIREG") or line.startswith("$MEREG") or line.startswith("$REREG"): + if line.startswith(STARTS) or rec is None or in_data: + flush_datum() + _finish(rec, block, out) + kind = "rxn" if line.startswith(("$RFMT", "$RIREG", "$REREG")) else "mol" + rec, block, in_data = RdRecord(kind, ""), [], False + parts = line.split() + if len(parts) >= 3 and parts[1].endswith("REG"): + rec.registry = parts[2] + elif len(parts) >= 2 and parts[0].endswith("REG"): + rec.registry = parts[1] + continue + if line.startswith("$DTYPE"): + flush_datum() + in_data = True + key = line[6:].strip() + continue + if line.startswith("$DATUM"): + value = [(line, line[6:].lstrip(" "))] + continue + if line.startswith("$RDFILE") or line.startswith("$DATM"): + continue + if rec is None: + continue + if in_data: + if key is not None and value: + value.append((line, line)) + continue + block.append(line) + flush_datum() + _finish(rec, block, out) + return [r for r in out if r.block.strip()] + + +def _datum(name: str, value: object) -> list[str]: + lines = [f"$DTYPE {name}"] + text = str(value) + first = True + for part in text.split("\n"): + while True: + prefix = "$DATUM " if first else "" + room = LINE - len(prefix) + if len(part) > room: + lines.append(prefix + part[: room - 1] + "+") + part = part[room - 1:] + first = False + continue + lines.append(prefix + part) + first = False + break + return lines + + +def write(records: list[dict], when: datetime | None = None) -> str: + stamp = (when or datetime.now(timezone.utc)).strftime("%m/%d/%y %H:%M") + lines = ["$RDFILE 1", f"$DATM {stamp}"] + for rec in records: + lines.append("$RFMT" if rec.get("kind") == "rxn" else "$MFMT") + lines.extend(str(rec.get("block") or "").rstrip("\n").split("\n")) + if rec.get("conditions"): + lines.extend(_datum(CONDITIONS_FIELD, rec["conditions"])) + for key, value in (rec.get("data") or {}).items(): + lines.extend(_datum(str(key), value)) + return "\n".join(lines) + "\n" From caab060dc7a205e63573963f48d8c38641630e6c Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:13:06 -0500 Subject: [PATCH 077/357] feat(chem): bridge the reference suite's XML and binary drawing formats through Indigo's document JSON (0.7.0) Indigo 1.49 writes and reads CDXML and CDX from its KET document, which carries structures, arrows, plus signs and text, so annotations survive both ways. --- backend/app/services/chem/cdxio.py | 411 +++++++++++++++++++++++++++++ 1 file changed, 411 insertions(+) create mode 100644 backend/app/services/chem/cdxio.py diff --git a/backend/app/services/chem/cdxio.py b/backend/app/services/chem/cdxio.py new file mode 100644 index 00000000..cb0f0593 --- /dev/null +++ b/backend/app/services/chem/cdxio.py @@ -0,0 +1,411 @@ +import base64 +import json +import os +import statistics +import tempfile + +from rdkit import Chem + +from app.services.chem import DEFAULT_BOND_LENGTH, convert, geometry, query, report, warning +from app.services.chem.reactions import fresh_id + +CDXML_UNIT = 30.0 +PX_PER_PT = 1.5 +ASCENT = 0.8 +ARROW_TO_KET = { + "forward": "filled-triangle", "dashed": "dashed-open-angle", "equilibrium": "equilibrium-filled-half-bow", + "equilibrium_unbalanced": "unbalanced-equilibrium-filled-half-bow", "reversible": "equilibrium-filled-triangle", + "resonance": "both-ends-filled-triangle", "retro": "retrosynthetic", "nogo_cross": "failed", "nogo_slash": "failed", + "curved": "elliptical-arc-arrow-filled-triangle", "arc": "elliptical-arc-arrow-filled-triangle", + "fishhook": "elliptical-arc-arrow-open-half-angle", +} +KET_TO_ARROW = { + "open-angle": ("forward", "open"), "filled-triangle": ("forward", "full"), "filled-bow": ("forward", "full"), + "dashed-open-angle": ("dashed", "open"), "failed": ("nogo_cross", "full"), "retrosynthetic": ("retro", "open"), + "both-ends-filled-triangle": ("resonance", "full"), "equilibrium-filled-half-bow": ("equilibrium", "half_left"), + "equilibrium-filled-triangle": ("reversible", "full"), "equilibrium-open-angle": ("equilibrium", "half_left"), + "unbalanced-equilibrium-filled-half-bow": ("equilibrium_unbalanced", "half_left"), + "unbalanced-equilibrium-open-half-angle": ("equilibrium_unbalanced", "half_left"), + "unbalanced-equilibrium-large-filled-half-bow": ("equilibrium_unbalanced", "half_left"), + "unbalanced-equilibrium-filled-half-triangle": ("equilibrium_unbalanced", "half_left"), + "elliptical-arc-arrow-filled-bow": ("curved", "full"), "elliptical-arc-arrow-filled-triangle": ("curved", "full"), + "elliptical-arc-arrow-open-angle": ("curved", "open"), "elliptical-arc-arrow-open-half-angle": ("fishhook", "half_left"), +} +TEXT_KINDS = ("text", "caption") +STYLE_FLAGS = (("b", "BOLD"), ("i", "ITALIC"), ("u", "UNDERLINE"), ("sub", "SUBSCRIPT"), ("sup", "SUPERSCRIPT")) +FONT_SIZE = "CUSTOM_FONT_SIZE_" + + +def indigo(): + from indigo import Indigo + ind = Indigo() + ind.setOption("ignore-stereochemistry-errors", True) + ind.setOption("ignore-noncritical-query-features", True) + ind.setOption("molfile-saving-mode", "3000") + return ind + + +def available() -> bool: + try: + indigo() + return True + except Exception: + return False + + +def _load(ind, source: str | bytes, is_path: bool): + tmp = None + if isinstance(source, bytes) and not is_path: + fd, tmp = tempfile.mkstemp(suffix=".cdx") + with os.fdopen(fd, "wb") as fh: + fh.write(source) + source, is_path = tmp, True + try: + last = None + for name in ("loadReaction", "loadMolecule", "loadQueryReaction", "loadQueryMolecule"): + fn = getattr(ind, name + ("FromFile" if is_path else "")) + try: + return fn(source) + except Exception as exc: + last = exc + raise ValueError(str(last)) + finally: + if tmp: + os.unlink(tmp) + + +def _xy(p) -> tuple[float, float]: + if isinstance(p, dict): + return float(p.get("x", 0.0)), float(p.get("y", 0.0)) + return float(p[0]), float(p[1]) + + +def _runs(content: str) -> list[dict]: + try: + doc = json.loads(content) + except (TypeError, ValueError): + return [{"t": str(content or "")}] + runs: list[dict] = [] + for n, block in enumerate(doc.get("blocks") or []): + text = str(block.get("text") or "") + if n: + runs.append({"t": "\n"}) + marks: list[dict] = [{} for _ in text] + for r in block.get("inlineStyleRanges") or []: + style, start, length = str(r.get("style") or ""), int(r.get("offset") or 0), int(r.get("length") or 0) + for i in range(max(0, start), min(len(text), start + length)): + if style.startswith(FONT_SIZE): + digits = style[len(FONT_SIZE):].rstrip("px") + try: + marks[i]["size"] = round(float(digits) / PX_PER_PT, 2) + except ValueError: + pass + else: + for key, name in STYLE_FLAGS: + if style == name: + marks[i][key] = True + for ch, mark in zip(text, marks): + if runs and runs[-1]["t"] != "\n" and {k: v for k, v in runs[-1].items() if k != "t"} == mark: + runs[-1]["t"] += ch + else: + runs.append({"t": ch, **mark}) + return [r for r in runs if r["t"]] or [{"t": ""}] + + +def _content(runs: list[dict], base: float) -> str: + blocks: list[dict] = [{"text": "", "inlineStyleRanges": [], "entityRanges": []}] + for run in runs: + if not isinstance(run, dict): + continue + for n, part in enumerate(str(run.get("t") or "").split("\n")): + if n: + blocks.append({"text": "", "inlineStyleRanges": [], "entityRanges": []}) + if not part: + continue + block = blocks[-1] + start = len(block["text"]) + block["text"] += part + for key, name in STYLE_FLAGS: + if run.get(key): + block["inlineStyleRanges"].append({"offset": start, "length": len(part), "style": name}) + size = run.get("size") if isinstance(run.get("size"), (int, float)) else base + block["inlineStyleRanges"].append({"offset": start, "length": len(part), "style": f"{FONT_SIZE}{round(size * PX_PER_PT)}px"}) + return json.dumps({"blocks": blocks, "entityMap": {}}) + + +def _plain(runs: list[dict]) -> str: + return "".join(str(r.get("t") or "") for r in runs if isinstance(r, dict)) + + +class _Frame: + def __init__(self, points: list[tuple[float, float]], bond_lengths: list[float], bond_length: float, origin: tuple[float, float]): + median = statistics.median(bond_lengths) if bond_lengths else bond_length / CDXML_UNIT + self.k = bond_length / median if median > 1e-6 else CDXML_UNIT + self.min_x = min((p[0] for p in points), default=0.0) + self.max_y = max((p[1] for p in points), default=0.0) + self.origin = origin + + def page(self, x: float, y: float) -> tuple[float, float]: + return (round((x - self.min_x) * self.k + self.origin[0], 3), round((self.max_y - y) * self.k + self.origin[1], 3)) + + +def _ket_bonds(mol: dict) -> list[float]: + atoms = mol.get("atoms") or [] + out = [] + for b in mol.get("bonds") or []: + i, j = (b.get("atoms") or [0, 0])[:2] + if i < len(atoms) and j < len(atoms): + (x1, y1), (x2, y2) = _xy(atoms[i]["location"]), _xy(atoms[j]["location"]) + d = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 + if d > 1e-6: + out.append(d) + return out + + +def read(source: str | bytes, is_path: bool, fmt: str, bond_length: float = DEFAULT_BOND_LENGTH, + origin: tuple[float, float] = (72.0, 72.0), used: set[str] | None = None) -> tuple[list[dict], list[dict], list[dict]]: + from app.services.chem import io + used = used if used is not None else set() + ind = indigo() + try: + obj = _load(ind, source, is_path) + ket = json.loads(obj.json()) + except Exception as exc: + return [], [], [warning("parse_failed", f"{fmt.upper()}: {exc}")] + notes: list[dict] = [] + nodes = (ket.get("root") or {}).get("nodes") or [] + mols: list[dict] = [] + skipped: dict[str, int] = {} + for node in nodes: + ref = node.get("$ref") + if ref: + body = ket.get(ref) or {} + if body.get("type") == "molecule": + mols.append(body) + elif str(ref).startswith("rg"): + skipped["R-group definition"] = skipped.get("R-group definition", 0) + 1 + else: + skipped[str(body.get("type") or ref)] = skipped.get(str(body.get("type") or ref), 0) + 1 + points: list[tuple[float, float]] = [] + lengths: list[float] = [] + for m in mols: + points.extend(_xy(a["location"]) for a in m.get("atoms") or [] if "location" in a) + lengths.extend(_ket_bonds(m)) + for node in nodes: + if node.get("type") == "plus": + points.append(_xy(node.get("location") or [0, 0])) + elif node.get("type") in ("arrow", "text"): + points.extend(_xy(p) for p in (node.get("data") or {}).get("pos") or [] if p) + if (node.get("data") or {}).get("position"): + points.append(_xy(node["data"]["position"])) + frame = _Frame(points, lengths, bond_length, origin) + fragments: list[dict] = [] + for m in mols: + part = json.dumps({"root": {"nodes": [{"$ref": "mol0"}]}, "mol0": m}) + is_query = False + try: + single = ind.loadMolecule(part) + except Exception: + try: + single = ind.loadQueryMolecule(part) + is_query = True + except Exception as exc: + notes.append(warning("parse_failed", f"{fmt.upper()}: a structure could not be read ({exc}).")) + continue + block = single.molfile() + if is_query: + from app.services.chem import v3000 + try: + frags, more = v3000.read(block, bond_length, (0.0, 0.0)) + except ValueError as exc: + notes.append(warning("parse_failed", f"{fmt.upper()}: a query structure could not be read ({exc}).")) + continue + frag = frags[0] + notes.extend(more) + else: + found: list[dict] = [] + mol = io._molblock_mol(block, fmt.upper(), found) + notes.extend(found) + if mol is None: + continue + frag = convert.from_mol(mol, bond_length, (0.0, 0.0), used=used) + xs = [_xy(a["location"]) for a in m.get("atoms") or [] if "location" in a] + if xs: + left, top = frame.page(min(p[0] for p in xs), max(p[1] for p in xs)) + ax = min(a["x"] for a in frag["atoms"].values()) + ay = min(a["y"] for a in frag["atoms"].values()) + for a in frag["atoms"].values(): + a["x"] = round(a["x"] - ax + left, 3) + a["y"] = round(a["y"] - ay + top, 3) + fragments.append(frag) + objects: list[dict] = [] + for node in nodes: + kind = node.get("type") + data = node.get("data") or {} + if kind == "plus": + x, y = frame.page(*_xy(node.get("location") or [0, 0])) + objects.append({"id": fresh_id(used, "o"), "kind": "plus", "x": x, "y": y, "symbol": "plus"}) + elif kind == "arrow": + pos = data.get("pos") or [] + if len(pos) < 2: + continue + (x1, y1), (x2, y2) = frame.page(*_xy(pos[0])), frame.page(*_xy(pos[1])) + arrow_type, head = KET_TO_ARROW.get(str(data.get("mode") or ""), ("forward", "full")) + rec = {"id": fresh_id(used, "o"), "kind": "arrow", "type": arrow_type, "x1": x1, "y1": y1, "x2": x2, "y2": y2, + "head": head, "tail": "full" if arrow_type == "resonance" else "none"} + if arrow_type in ("curved", "fishhook"): + rec["bend"] = 60 + objects.append(rec) + elif kind == "text": + runs = _runs(data.get("content") or "") + size = next((r["size"] for r in runs if isinstance(r.get("size"), (int, float))), geometry.DEFAULT_FONT) + px, py = frame.page(*_xy(data.get("position") or (data.get("pos") or [{"x": 0, "y": 0}])[0])) + objects.append({"id": fresh_id(used, "o"), "kind": "text", "x": px, "y": round(py - ASCENT * size, 3), "align": "l", "runs": runs}) + elif kind and not node.get("$ref"): + name = {"simpleObject": "shape", "image": "picture", "multi-tailed-arrow": "multi-tailed arrow"}.get(kind, kind) + skipped[name] = skipped.get(name, 0) + 1 + for name, n in sorted(skipped.items()): + notes.append(report.item("unsupported_object", n, f"{n} {name}{'s' if n > 1 else ''} could not be read and {'were' if n > 1 else 'was'} left out.")) + if objects and any(o["kind"] == "text" for o in objects): + notes.append(report.item("styles_dropped", 1, "Fonts, colours and line breaks of text are approximated.")) + if abs(frame.k - CDXML_UNIT) > 0.5 and lengths: + notes.append(report.item("rescaled", 1, "The drawing was scaled to the document bond length.")) + return fragments, objects, notes + + +def _mol_node(ind, frag: dict, expansions: dict | None, members: dict | None, bl: float, notes: list[dict]) -> list[dict]: + from app.services.chem import io, v3000 + asks_query = query.has_query(frag) or bool(frag.get("rgroups")) + if asks_query: + block, more = v3000.write(frag, expansions, members) + notes.extend(more) + loaders = ("loadQueryMolecule",) + else: + mol, more = io._writable(frag, expansions) + notes.extend(more) + block = Chem.MolToV3KMolBlock(mol, includeStereo=True, kekulize=True) + loaders = ("loadMolecule", "loadQueryMolecule") + block = _rescale(block, frag) + last = None + for name in loaders: + try: + ket = json.loads(getattr(ind, name)(block).json()) + return [ket[n["$ref"]] for n in ket["root"]["nodes"] if n.get("$ref") in ket] + [ + {"$rg": ket[k]} for k in ket if k.startswith("rg")] + except Exception as exc: + last = exc + notes.append(warning("structure_dropped", f"A structure could not be converted ({last}).")) + return [] + + +def _rescale(block: str, frag: dict) -> str: + from app.services.chem import v3000 + f = convert.median_bond_length(frag) / (convert.MOL_BOND_LENGTH * CDXML_UNIT) + out = [] + section = False + for line in v3000._unwrap(block): + body = line[len(v3000.PREFIX):].split() if line.startswith(v3000.PREFIX) else [] + if body[:2] == ["BEGIN", "ATOM"]: + section = True + elif body[:2] == ["END", "ATOM"]: + section = False + elif section and len(body) >= 5: + try: + body[2], body[3] = f"{float(body[2]) * f:.4f}", f"{float(body[3]) * f:.4f}" + line = v3000.PREFIX + " ".join(body) + except ValueError: + pass + out.append(line) + return "\n".join(out) + + +def _ket_point(x: float, y: float) -> dict: + return {"x": round(x / CDXML_UNIT, 4), "y": round(-y / CDXML_UNIT, 4), "z": 0.0} + + +def write(fragments: list[dict], objects: list[dict], style: dict, expansions: dict | None = None, + members: dict | None = None, binary: bool = False) -> tuple[str | bytes, list[dict]]: + ind = indigo() + bl = float(style.get("bond_length") or DEFAULT_BOND_LENGTH) + notes: list[dict] = [] + ket: dict = {"root": {"nodes": []}} + n = 0 + rgroups: dict[str, dict] = {} + for frag in fragments: + for node in _mol_node(ind, frag, expansions, members, bl, notes): + if "$rg" in node: + body = node["$rg"] + key = f"rg{(body.get('rlogic') or {}).get('number', len(rgroups) + 1)}" + rgroups[key] = body + continue + key = f"mol{n}" + n += 1 + ket[key] = node + ket["root"]["nodes"].append({"$ref": key}) + for key, body in rgroups.items(): + ket[key] = body + ket["root"]["nodes"].append({"$ref": key}) + has_arrow = False + lost: dict[str, list[str]] = {} + base = float((style.get("caption_font") or {}).get("size") or geometry.DEFAULT_FONT) + for obj in objects: + kind = obj.get("kind") + if kind == "plus": + ket["root"]["nodes"].append({"type": "plus", "location": [round(obj["x"] / CDXML_UNIT, 4), round(-obj["y"] / CDXML_UNIT, 4), 0.0]}) + elif kind == "arrow": + pts = geometry.arrow_points(obj) + if pts is None: + continue + mode = ARROW_TO_KET.get(obj.get("type") or "forward") + if mode is None: + mode = "open-angle" + lost.setdefault("arrow style", []).append(obj["id"]) + elif obj.get("type") == "forward" and obj.get("head") == "open": + mode = "open-angle" + ket["root"]["nodes"].append({"type": "arrow", "data": {"mode": mode, "pos": [_ket_point(*pts[0]), _ket_point(*pts[1])]}}) + has_arrow = True + elif kind in TEXT_KINDS: + runs = [r for r in obj.get("runs") or [] if isinstance(r, dict)] + if not _plain(runs).strip(): + continue + box = geometry.text_box(obj, style) or (obj.get("x", 0.0), obj.get("y", 0.0), 0, 0) + size = next((float(r["size"]) for r in runs if isinstance(r.get("size"), (int, float))), base) + pos = _ket_point(box[0], box[1] + ASCENT * size) + ket["root"]["nodes"].append({"type": "text", "data": {"content": _content(runs, base), "position": pos, "pos": [pos, pos, pos, pos]}}) + if "\n" in _plain(runs): + lost.setdefault("line break", []).append(obj["id"]) + if any(r.get("font") or r.get("color") for r in runs): + lost.setdefault("text font or colour", []).append(obj["id"]) + elif kind not in ("fragment", "group"): + lost.setdefault(str(kind), []).append(obj["id"]) + for name, ids_ in sorted(lost.items()): + notes.append(report.item("graphics_dropped", len(ids_), f"{len(ids_)} {name}{'s' if len(ids_) > 1 else ''} not written: the format bridge cannot store {'it' if len(ids_) == 1 else 'them'}.", objects=ids_)) + if any(f.get("data") for f in fragments): + notes.append(report.item("data_dropped", sum(1 for f in fragments if f.get("data")), "Structure data fields are not written to this format.")) + if not ket["root"]["nodes"]: + raise ValueError("there is nothing to write") + text = json.dumps(ket) + if has_arrow: + doc = None + for name in ("loadReaction", "loadQueryReaction"): + try: + doc = getattr(ind, name)(text) + break + except Exception: + continue + if doc is None: + raise ValueError("the reaction could not be converted") + else: + doc = None + for name in ("loadMolecule", "loadQueryMolecule"): + try: + doc = getattr(ind, name)(text) + break + except Exception: + continue + if doc is None: + raise ValueError("the drawing could not be converted") + notes.append(report.item("styles_dropped", 1, "Colours, fonts, bond styles and the page setup are not written; Indigo writes its own defaults.")) + if binary: + return base64.b64decode(doc.b64cdx()), notes + return doc.cdxml(), notes From 2b2d705382f4338182d69d7cc06b8a95ee8d93c7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:13:07 -0500 Subject: [PATCH 078/357] feat(chem): extend the readers with RD files, SMARTS files, InChI names, reaction lines and annotation objects (0.7.0) Every reader now records what it changed or could not keep (valence fixes, generated coordinates, unknown stereo, Sgroups, failed records) for the import report. --- backend/app/services/chem/io.py | 487 +++++++++++++++++++++++++------- 1 file changed, 382 insertions(+), 105 deletions(-) diff --git a/backend/app/services/chem/io.py b/backend/app/services/chem/io.py index a0d35a17..517808c2 100644 --- a/backend/app/services/chem/io.py +++ b/backend/app/services/chem/io.py @@ -7,13 +7,13 @@ from rdkit.Chem import rdChemReactions from rdkit.Geometry import Point3D -from app.services.chem import DEFAULT_BOND_LENGTH, convert, ids, perceive, warning +from app.services.chem import DEFAULT_BOND_LENGTH, convert, ids, perceive, report, warning -FORMATS = ("smiles", "cxsmiles", "rsmiles", "molfile", "sdf", "rxn", "cml", "cdxml", "cdx", "inchi") +FORMATS = ("smiles", "cxsmiles", "rsmiles", "smarts", "molfile", "sdf", "rxn", "rdf", "cml", "cdxml", "cdx", "inchi") EXTENSIONS = { ".smi": "smiles", ".smiles": "smiles", ".cxsmi": "cxsmiles", ".cxsmiles": "cxsmiles", ".txt": None, - ".mol": "molfile", ".mdl": "molfile", ".sdf": "sdf", ".sd": "sdf", ".rxn": "rxn", ".cml": "cml", - ".cdxml": "cdxml", ".cdx": "cdx", ".inchi": "inchi", + ".mol": "molfile", ".mdl": "molfile", ".sdf": "sdf", ".sd": "sdf", ".rxn": "rxn", ".rdf": "rdf", ".rd": "rdf", + ".cml": "cml", ".cdxml": "cdxml", ".cdx": "cdx", ".inchi": "inchi", ".sma": "smarts", ".smarts": "smarts", } MAX_RECORDS = 1000 ROLE_TAGS = {"reactant": "reactants", "product": "products", "spectator": "agents", "substance": "agents", "agent": "agents"} @@ -25,11 +25,26 @@ class ParseResult: fragments: list[dict] = field(default_factory=list) warnings: list[dict] = field(default_factory=list) reaction: dict | None = None + reactions: list[dict] = field(default_factory=list) + objects: list[dict] = field(default_factory=list) + + @property + def report(self) -> list[dict]: + return report.collect(self.warnings) + + def add_reaction(self, roles: dict) -> None: + self.reactions.append(roles) + if self.reaction is None: + self.reaction = roles def as_dict(self) -> dict: - out = {"format": self.format, "fragments": self.fragments, "warnings": self.warnings} + out = {"format": self.format, "fragments": self.fragments, "warnings": self.warnings, "report": self.report} if self.reaction: out["reaction"] = self.reaction + if len(self.reactions) > 1: + out["reactions"] = self.reactions + if self.objects: + out["objects"] = self.objects return out @@ -37,14 +52,34 @@ class _Row: def __init__(self, bond_length: float, origin: tuple[float, float]): self.bond_length = bond_length self.x, self.y = origin + self.x0 = origin[0] self.used: set[str] = set() def place(self, mol: Chem.Mol, name: str | None = None) -> dict: frag = convert.from_mol(mol, self.bond_length, (self.x, self.y), name=name, used=self.used) + return self.advance(frag) + + def advance(self, frag: dict) -> dict: xs = [a["x"] for a in frag["atoms"].values()] or [self.x] self.x = max(xs) + 2 * self.bond_length return frag + def take(self, frags: list[dict]) -> list[dict]: + dx = self.x - min((a["x"] for f in frags for a in f["atoms"].values()), default=self.x) + dy = self.y - min((a["y"] for f in frags[:1] for a in f["atoms"].values()), default=self.y) + for f in frags: + for a in f["atoms"].values(): + a["x"], a["y"] = round(a["x"] + dx, 3), round(a["y"] + dy, 3) + self.used.update([f["id"], *f["atoms"], *f["bonds"]]) + if frags: + self.advance(frags[0]) + return frags + + def newline(self, frags: list[dict]) -> None: + bottom = max((a["y"] for f in frags for a in f["atoms"].values()), default=self.y) + self.x = self.x0 + self.y = round(bottom + 4 * self.bond_length, 3) + def gap(self, width: float) -> tuple[float, float]: start = self.x self.x += width @@ -53,6 +88,8 @@ def gap(self, width: float) -> tuple[float, float]: def detect(text: str) -> str: head = text.lstrip()[:4096] + if head.startswith("$RDFILE") or head.startswith("$RFMT") or head.startswith("$MFMT") or head.startswith("$DATM"): + return "rdf" if head.startswith("$RXN"): return "rxn" if "$$$$" in text or text.count("M END") > 1: @@ -98,26 +135,74 @@ def _smiles_params(sanitize: bool) -> Chem.SmilesParserParams: return params +def counted(code: str, text: str, n: int, atoms: list[str] | tuple = ()) -> dict: + out = warning(code, text, atoms) + out["count"] = max(1, n) + return out + + +def _fixed(mol: Chem.Mol, raw: Chem.Mol | None, where: str, warnings: list[dict]) -> Chem.Mol: + if raw is None or raw.GetNumAtoms() != mol.GetNumAtoms(): + return mol + changed = sum(1 for a in mol.GetAtoms() if a.GetFormalCharge() != raw.GetAtomWithIdx(a.GetIdx()).GetFormalCharge()) + if changed: + warnings.append(counted("valence_fixed", f"{where}: {changed} atom{'s' if changed > 1 else ''} had charges rearranged to fit valence rules (for example a nitro group).", changed)) + return mol + + +def mol_notes(mol: Chem.Mol, where: str, warnings: list[dict], coords_expected: bool = True) -> None: + if mol.GetNumAtoms() > 1: + if not mol.GetNumConformers(): + if coords_expected: + warnings.append(counted("coordinates_generated", f"{where}: no coordinates; a 2D layout was generated.", 1)) + else: + conf = mol.GetConformer() + if conf.Is3D() and any(abs(conf.GetAtomPosition(i).z) > 1e-4 for i in range(mol.GetNumAtoms())): + warnings.append(counted("coordinates_flattened", f"{where}: 3D coordinates were flattened to a 2D layout.", 1)) + elif all(abs(conf.GetAtomPosition(i).x) + abs(conf.GetAtomPosition(i).y) < 1e-4 for i in range(mol.GetNumAtoms())): + warnings.append(counted("coordinates_generated", f"{where}: all coordinates were zero; a 2D layout was generated.", 1)) + unknown = sum(1 for b in mol.GetBonds() if b.GetBondDir() == Chem.BondDir.UNKNOWN or b.GetStereo() == Chem.BondStereo.STEREOANY) + unknown += sum(1 for a in mol.GetAtoms() if a.HasProp("_UnknownStereo") and a.GetIntProp("_UnknownStereo")) + if unknown: + warnings.append(counted("stereo_unknown", f"{where}: {unknown} stereo element{'s are' if unknown > 1 else ' is'} marked unknown (wavy or crossed bonds).", unknown)) + try: + groups = Chem.GetMolSubstanceGroups(mol) + except Exception: + groups = [] + kinds: dict[str, int] = {} + for g in groups: + kind = g.GetProp("TYPE") if g.HasProp("TYPE") else "?" + kinds[kind] = kinds.get(kind, 0) + 1 + if kinds: + names = {"SUP": "abbreviation", "DAT": "data", "SRU": "polymer repeat", "MUL": "multiple group", "GEN": "bracket", "COP": "copolymer", "MON": "monomer", "MIX": "mixture", "FOR": "formulation", "COM": "component"} + listed = ", ".join(f"{n} {names.get(k, k)}" for k, n in sorted(kinds.items())) + warnings.append(counted("sgroups_dropped", f"{where}: Sgroups not kept ({listed}); their atoms are kept as drawn.", sum(kinds.values()))) + + def _smiles_mol(text: str, where: str, warnings: list[dict]) -> Chem.Mol | None: mol = Chem.MolFromSmiles(text, _smiles_params(True)) + raw = Chem.MolFromSmiles(text, _smiles_params(False)) if mol is not None: - return mol - mol = Chem.MolFromSmiles(text, _smiles_params(False)) - if mol is None: + return _fixed(mol, raw, where, warnings) + if raw is None: warnings.append(warning("parse_failed", f"{where}: not a valid SMILES.")) return None - return _soft(mol, where, warnings) + return _soft(raw, where, warnings) + + +def is_query_mol(mol: Chem.Mol) -> bool: + return any(a.HasQuery() for a in mol.GetAtoms()) or any(b.HasQuery() for b in mol.GetBonds()) def _molblock_mol(block: str, where: str, warnings: list[dict]) -> Chem.Mol | None: mol = Chem.MolFromMolBlock(block, sanitize=True, removeHs=False, strictParsing=False) + raw = Chem.MolFromMolBlock(block, sanitize=False, removeHs=False, strictParsing=False) if mol is not None: - return mol - mol = Chem.MolFromMolBlock(block, sanitize=False, removeHs=False, strictParsing=False) - if mol is None: + return _fixed(mol, raw, where, warnings) + if raw is None: warnings.append(warning("parse_failed", f"{where}: not a readable molfile.")) return None - return _soft(mol, where, warnings) + return _soft(raw, where, warnings) def _name(mol: Chem.Mol) -> str | None: @@ -132,30 +217,127 @@ def _data(mol: Chem.Mol) -> dict: return {k: v if isinstance(v, (int, float, str, bool)) else str(v) for k, v in props.items()} +def _is_reaction_line(line: str) -> bool: + first = line.split()[0] if line.split() else "" + return first.count(">") == 2 + + def _read_smiles(text: str, res: ParseResult, row: _Row) -> None: + generated = 0 for n, line in enumerate(l.strip() for l in text.splitlines() if l.strip()): + if _is_reaction_line(line): + _read_rsmiles(line, res, row) + continue mol = _smiles_mol(line, f"line {n + 1}", res.warnings) - if mol is not None: - res.fragments.append(row.place(mol, _name(mol))) + if mol is None: + continue + if mol.GetNumAtoms() > 1 and not mol.GetNumConformers(): + generated += 1 + res.fragments.append(row.place(mol, _name(mol))) + if generated: + res.warnings.append(counted("coordinates_generated", f"{generated} structure{'s' if generated > 1 else ''} got a generated 2D layout (SMILES has no coordinates).", generated)) + + +def _query_frags(block: str, where: str, res: ParseResult, row: _Row) -> list[dict] | None: + from app.services.chem import v3000 + raw = Chem.MolFromMolBlock(block, sanitize=False, removeHs=False, strictParsing=False) + rgroups = "BEGIN RGROUP" in block + if raw is None and not rgroups: + return None + if not rgroups and not is_query_mol(raw): + return None + text = block if "V3000" in block[:2000] else Chem.MolToV3KMolBlock(raw) + try: + frags, notes = v3000.read(text, row.bond_length, (row.x, row.y)) + except ValueError as exc: + res.warnings.append(warning("parse_failed", f"{where}: {exc}")) + return [] + res.warnings.extend(notes) + name = _name(raw) if raw is not None else None + if name and frags: + frags[0]["name"] = name + return row.take(frags) def _read_molfile(text: str, res: ParseResult, row: _Row) -> None: + found = _query_frags(text, "molfile", res, row) + if found is not None: + res.fragments.extend(found) + return mol = _molblock_mol(text, "molfile", res.warnings) if mol is not None: - frag = row.place(mol, _name(mol)) - res.fragments.append(frag) + mol_notes(mol, "molfile", res.warnings) + res.fragments.append(row.place(mol, _name(mol))) + + +def sd_records(text: str): + start = 0 + lines = text.split("\n") + for i, line in enumerate(lines): + if line.rstrip() == "$$$$": + block = "\n".join(lines[start:i]) + start = i + 1 + if block.strip(): + yield block + rest = "\n".join(lines[start:]) + if rest.strip(): + yield rest + + +def sd_fields(block: str) -> tuple[str, dict]: + end = block.find("M END") + if end < 0: + return block, {} + cut = block.find("\n", end) + ctab, tail = (block, "") if cut < 0 else (block[:cut + 1], block[cut + 1:]) + data: dict = {} + name = None + value: list[str] = [] + for line in tail.split("\n"): + if line.startswith(">"): + if name is not None: + data[name] = "\n".join(value).strip("\n") + m = re.search(r"<([^>]*)>", line) + name = m.group(1) if m else line[1:].strip() + value = [] + elif name is not None: + if line.strip() == "" and value and value[-1].strip() == "": + continue + value.append(line) + if name is not None: + data[name] = "\n".join(value).strip("\n") + return ctab, data -def _sdf_records(supplier: Chem.SDMolSupplier, res: ParseResult, row: _Row, max_records: int) -> None: - total = len(supplier) - for i in range(min(total, max_records)): - mol = supplier[i] +def _record_mol(block: str, where: str, res: ParseResult) -> Chem.Mol | None: + found: list[dict] = [] + mol = _molblock_mol(block, where, found) + if mol is None: + res.warnings.append(counted("record_failed", f"{where} could not be read and was skipped.", 1)) + return None + res.warnings.extend(found) + return mol + + +def _sdf_records(text: str, res: ParseResult, row: _Row, max_records: int) -> None: + total = 0 + for i, block in enumerate(sd_records(text)): + total += 1 + if i >= max_records: + continue + where = f"record {i + 1}" + ctab, data = sd_fields(block) + found = _query_frags(ctab, where, res, row) + if found is not None: + if found and data: + found[0]["data"] = data + res.fragments.extend(found) + continue + mol = _record_mol(ctab, where, res) if mol is None: - mol = _molblock_mol(supplier.GetItemText(i), f"record {i + 1}", res.warnings) - if mol is None: - continue + continue + mol_notes(mol, where, res.warnings) frag = row.place(mol, _name(mol)) - data = _data(mol) if data: frag["data"] = data res.fragments.append(frag) @@ -164,14 +346,14 @@ def _sdf_records(supplier: Chem.SDMolSupplier, res: ParseResult, row: _Row, max_ def _read_sdf(text: str, res: ParseResult, row: _Row, max_records: int) -> None: - supplier = Chem.SDMolSupplier() - supplier.SetData(text, sanitize=True, removeHs=False, strictParsing=False) - _sdf_records(supplier, res, row, max_records) + _sdf_records(text, res, row, max_records) def _reaction(rxn: rdChemReactions.ChemicalReaction, res: ParseResult, row: _Row) -> None: roles = {"reactants": [], "products": [], "agents": []} centres: list[float] = [] + if res.reactions: + row.newline(res.fragments) def add(role: str, template: Chem.Mol, n: int) -> None: mol = _soft(Chem.Mol(template), f"{role} {n + 1}", res.warnings) @@ -201,9 +383,10 @@ def add(role: str, template: Chem.Mol, n: int) -> None: frag = next(f for f in res.fragments if f["id"] == fid) for a in frag["atoms"].values(): a["y"] = round(a["y"] - lift, 3) - res.reaction = {"reactants": roles["reactants"], "products": roles["products"], "agents": roles["agents"], - "arrow": {"x1": round(tail - row.bond_length, 3), "y1": round(y, 3), "x2": round(arrow_left - row.bond_length, 3), "y2": round(y, 3)}} - res.warnings.append(warning("reaction_arrow", "The reaction arrow and plus signs are left for the window to draw.")) + res.add_reaction({"reactants": roles["reactants"], "products": roles["products"], "agents": roles["agents"], + "arrow": {"x1": round(tail - row.bond_length, 3), "y1": round(y, 3), "x2": round(arrow_left - row.bond_length, 3), "y2": round(y, 3)}}) + if not any(w.get("code") == "reaction_arrow" for w in res.warnings): + res.warnings.append(warning("reaction_arrow", "The reaction arrow and plus signs are left for the window to draw.")) def _read_rxn(text: str, res: ParseResult, row: _Row) -> None: @@ -213,26 +396,91 @@ def _read_rxn(text: str, res: ParseResult, row: _Row) -> None: res.warnings.append(warning("parse_failed", f"RXN: {exc}")) return _reaction(rxn, res, row) + lines = text.lstrip("\n").split("\n") + comment = lines[3].strip() if len(lines) > 3 and lines[0].startswith("$RXN") else "" + if comment and res.reactions: + res.reactions[-1]["conditions"] = comment + name = lines[1].strip() if len(lines) > 1 and lines[0].startswith("$RXN") else "" + if name and res.reactions: + res.reactions[-1]["name"] = name def _read_rsmiles(text: str, res: ParseResult, row: _Row) -> None: - try: - rxn = rdChemReactions.ReactionFromSmarts(text.split()[0], useSmiles=True) - except Exception as exc: - res.warnings.append(warning("parse_failed", f"reaction SMILES: {exc}")) - return - _reaction(rxn, res, row) + for line in (l.strip() for l in text.splitlines() if l.strip()): + try: + rxn = rdChemReactions.ReactionFromSmarts(line.split()[0], useSmiles=True) + except Exception as exc: + res.warnings.append(warning("parse_failed", f"reaction SMILES: {exc}")) + continue + _reaction(rxn, res, row) + res.warnings.append(counted("coordinates_generated", "Reaction SMILES has no coordinates; a 2D layout was generated.", 1)) def _read_inchi(text: str, res: ParseResult, row: _Row) -> None: + n_read = 0 for n, line in enumerate(l.strip() for l in text.splitlines() if l.strip()): - mol = Chem.MolFromInchi(line, sanitize=True, removeHs=True) + token = line.split()[0] + if not token.startswith("InChI="): + continue + mol = Chem.MolFromInchi(token, sanitize=True, removeHs=True) if mol is None: res.warnings.append(warning("parse_failed", f"line {n + 1}: not a readable InChI.")) continue - res.fragments.append(row.place(mol)) - if res.fragments: - res.warnings.append(warning("inchi_normalised", "InChI may normalise tautomers and charges; the structure can differ from the original drawing.")) + name = line[len(token):].strip() or None + res.fragments.append(row.place(mol, name)) + n_read += 1 + if n_read: + res.warnings.append(counted("inchi_normalised", "InChI may normalise tautomers and charges; the structure can differ from the original drawing.", n_read)) + res.warnings.append(counted("coordinates_generated", f"{n_read} structure{'s' if n_read > 1 else ''} got a generated 2D layout (InChI has no coordinates).", n_read)) + + +def _read_smarts(text: str, res: ParseResult, row: _Row) -> None: + from app.services.chem import query + for n, line in enumerate(l.strip() for l in text.splitlines() if l.strip()): + token, _, name = line.partition(" ") + if line.startswith("#"): + continue + try: + frag, notes = query.from_smarts(token, row.bond_length, (row.x, row.y)) + except ValueError: + res.warnings.append(counted("record_failed", f"line {n + 1}: not valid SMARTS.", 1)) + continue + if name.strip(): + frag["name"] = name.strip() + res.warnings.extend(notes) + res.fragments.extend(row.take([frag])) + + +def _read_rdf(text: str, res: ParseResult, row: _Row, max_records: int) -> None: + from app.services.chem import rdfio + for i, rec in enumerate(rdfio.parse(text)): + if i >= max_records: + res.warnings.append(warning("truncated", f"Read the first {max_records} records.")) + break + where = f"record {i + 1}" + if rec.kind == "rxn": + before = len(res.reactions) + _read_rxn(rec.block, res, row) + if len(res.reactions) > before: + if rec.conditions: + res.reactions[-1]["conditions"] = rec.conditions + if rec.data: + res.reactions[-1]["data"] = rec.data + else: + res.warnings.append(counted("record_failed", f"{where}: the reaction could not be read.", 1)) + continue + if res.reactions and res.fragments and row.x > row.x0: + row.newline(res.fragments) + found = _query_frags(rec.block, where, res, row) + if found is None: + mol = _record_mol(rec.block, where, res) + if mol is None: + continue + mol_notes(mol, where, res.warnings) + found = [row.place(mol, _name(mol))] + if found and rec.data: + found[0]["data"] = rec.data + res.fragments.extend(found) def _local(tag: str) -> str: @@ -254,6 +502,8 @@ def _cml_atoms(el: ET.Element) -> list[dict]: for child in a: if _local(child.tag) in ("scalar", "string", "integer", "float") and child.get("builtin"): rec[child.get("builtin")] = (child.text or "").strip() + elif _local(child.tag) == "label" and (child.get("value") or child.text): + rec["label"] = (child.get("value") or child.text or "").strip() out.append(rec) else: idl = _cml_list(arr, "atomID") or [] @@ -317,6 +567,12 @@ def _cml_mol(el: ET.Element, warnings: list[dict]) -> Chem.Mol | None: spin = int(_num(a.get("spinMultiplicity"), 1)) if spin > 1: atom.SetNumRadicalElectrons(spin - 1) + if a.get("label"): + found = re.fullmatch(r"R(\d+)", a["label"]) + if z == 0: + atom.SetProp("atomLabel", f"_R{found.group(1)}" if found else a["label"]) + else: + atom.SetProp("molFileAlias", a["label"]) idx = rw.AddAtom(atom) index[a.get("id", f"a{idx}")] = idx if a.get("hydrogenCount") is not None: @@ -379,59 +635,97 @@ def _read_cml(text: str, res: ParseResult, row: _Row) -> None: res.warnings.append(warning("parse_failed", f"CML: {exc}")) return parent = {c: p for p in root.iter() for c in p} - roles = {"reactants": [], "products": [], "agents": []} - found_reaction = any(_local(e.tag) == "reaction" for e in root.iter()) + by_id: dict[str, str] = {} + reaction_of: dict[int, dict] = {} + order: list[dict] = [] + for el in root.iter(): + if _local(el.tag) == "reaction": + rec = {"reactants": [], "products": [], "agents": []} + texts = [(c.get("value") or c.text or "").strip() for cl in el if _local(cl.tag) == "conditionList" for c in cl.iter() + if _local(c.tag) in ("scalar", "label", "string", "condition") and (c.get("value") or (c.text or "").strip())] + if texts: + rec["conditions"] = "; ".join(t for t in texts if t) + if el.get("title") or el.get("name"): + rec["name"] = el.get("title") or el.get("name") + reaction_of[id(el)] = rec + order.append(rec) for el in root.iter(): if _local(el.tag) != "molecule": continue - up, role, nested = parent.get(el), None, False + up, role, nested, owner = parent.get(el), None, False, None while up is not None: name = _local(up.tag) if name == "molecule": nested = True break role = role or ROLE_TAGS.get(name) + if name == "reaction" and owner is None: + owner = reaction_of.get(id(up)) up = parent.get(up) if nested: continue + ref = el.get("ref") + if ref and not any(_local(c.tag) == "atomArray" for c in el): + fid = by_id.get(ref) + if fid and owner is not None and role: + owner[role].append(fid) + elif not fid: + res.warnings.append(warning("cml_bond_skipped", f"CML molecule reference {ref} names no molecule.")) + continue mol = _cml_mol(el, res.warnings) if mol is None: continue + mol_notes(mol, f"CML molecule {el.get('id') or len(res.fragments) + 1}", res.warnings) frag = row.place(mol, _name(mol)) + data = _cml_properties(el) + if data: + frag["data"] = data res.fragments.append(frag) - if role: - roles[role].append(frag["id"]) - if found_reaction: - res.reaction = {k: v for k, v in roles.items()} + if el.get("id"): + by_id[el.get("id")] = frag["id"] + if role and owner is not None: + owner[role].append(frag["id"]) + for rec in order: + if rec["reactants"] or rec["products"]: + res.add_reaction(rec) + if res.reactions: res.warnings.append(warning("reaction_arrow", "The reaction arrow and plus signs are left for the window to draw.")) - dropped = sorted({_local(e.tag) for e in root.iter()} & {"spectrum", "peakList", "crystal", "propertyList"}) + dropped = sorted({_local(e.tag) for e in root.iter()} & {"spectrum", "peakList", "crystal"}) if dropped: - res.warnings.append(warning("cml_dropped", f"Not read: {', '.join(dropped)}.")) + res.warnings.append(counted("unsupported_object", f"Not read: {', '.join(dropped)}.", len(dropped))) + + +def _cml_properties(el: ET.Element) -> dict: + out: dict = {} + for plist in (c for c in el if _local(c.tag) == "propertyList"): + for prop in (c for c in plist if _local(c.tag) == "property"): + key = prop.get("title") or prop.get("dictRef") + values = [(c.text or "").strip() for c in prop if _local(c.tag) in ("scalar", "string", "integer", "float")] + if key and values: + out[key] = values[0] + return out -CDXML_DROPPED = {"t": "text", "graphic": "graphic", "arrow": "arrow", "curve": "curve", "bracketedgroup": "bracket", - "table": "table", "embeddedobject": "embedded object", "spectrum": "spectrum", "tlcplate": "TLC plate", - "step": "reaction step", "scheme": "reaction scheme", "altgroup": "R-group definition", "geometry": "geometry"} +CDXML_UNREAD = {"curve": "curve", "bracketedgroup": "bracket", "table": "table", "embeddedobject": "embedded object", + "spectrum": "spectrum", "tlcplate": "TLC plate", "geometry": "geometry", "constraint": "constraint", + "chemicalproperty": "chemical property", "annotation": "annotation"} -def _cdxml_report(text: str) -> list[dict]: +def _cdxml_unread(text: str) -> list[dict]: try: - root = ET.fromstring(text) + root = ET.fromstring(text.encode("utf-8") if isinstance(text, str) else text) except ET.ParseError: - return [warning("cdxml_dropped", "Only structures were read; text, graphics and styles are dropped.")] - parent = {c: p for p in root.iter() for c in p} + return [] counts: dict[str, int] = {} for el in root.iter(): - tag = _local(el.tag) - if tag not in CDXML_DROPPED: - continue - if tag == "t" and parent.get(el) is not None and _local(parent[el].tag) == "n": - continue - counts[CDXML_DROPPED[tag]] = counts.get(CDXML_DROPPED[tag], 0) + 1 - if not counts: - return [warning("cdxml_dropped", "Fonts, colours and label styles are not read.")] - lost = ", ".join(f"{n} {k}{'s' if n > 1 else ''}" for k, n in sorted(counts.items())) - return [warning("cdxml_dropped", f"Only structures were read. Dropped: {lost}; fonts, colours and label styles are not read.")] + tag = _local(el.tag).lower() + name = CDXML_UNREAD.get(tag) + if tag == "graphic" and el.get("SymbolType") != "Plus" and not el.get("ArrowType"): + name = f"{(el.get('GraphicType') or 'graphic').lower()} graphic" + if name: + counts[name] = counts.get(name, 0) + 1 + return [counted("unsupported_object", f"{n} {k}{'s' if n > 1 else ''} could not be read and {'were' if n > 1 else 'was'} left out.", n) + for k, n in sorted(counts.items())] def split_components(frag: dict) -> list[dict]: @@ -466,46 +760,20 @@ def split_components(frag: dict) -> list[dict]: return out -def _indigo(): - from indigo import Indigo - ind = Indigo() - ind.setOption("ignore-stereochemistry-errors", True) - ind.setOption("ignore-noncritical-query-features", True) - ind.setOption("molfile-saving-mode", "3000") - return ind - - def _read_indigo(source: str | bytes, is_path: bool, fmt: str, res: ParseResult, row: _Row) -> None: + from app.services.chem import cdxio try: - ind = _indigo() + cdxio.indigo() except Exception as exc: res.warnings.append(warning("indigo_missing", f"Indigo is not available: {exc}")) return - text = "" + frags, objects, notes = cdxio.read(source, is_path, fmt, row.bond_length, (row.x, row.y), row.used) + res.fragments.extend(frags) + res.objects.extend(objects) + res.warnings.extend(notes) if fmt == "cdxml": text = Path(source).read_text(encoding="utf-8", errors="replace") if is_path else str(source) - reaction_like = fmt == "cdxml" and re.search(r" ParseResult: + if fmt == "cdx" or (fmt is None and data[:8] == b"VjCD0100"): + res = ParseResult("cdx") + _read_indigo(data, False, "cdx", res, _Row(bond_length, origin)) + return res + text = data.decode("utf-16") if data[:2] in (b"\xff\xfe", b"\xfe\xff") else _decode(data) + return read_text(text, fmt, bond_length, origin, max_records) + + def parse_text(text: str, fmt: str | None = None, bond_length: float = DEFAULT_BOND_LENGTH) -> list[dict]: return read_text(text, fmt, bond_length).fragments @@ -553,11 +835,6 @@ def read_file(path: str | Path, bond_length: float = DEFAULT_BOND_LENGTH, origin res = ParseResult("cdxml") _read_indigo(str(p), True, "cdxml", res, _Row(bond_length, origin)) return res - if kind == "sdf": - res = ParseResult("sdf") - supplier = Chem.SDMolSupplier(str(p), sanitize=True, removeHs=False, strictParsing=False) - _sdf_records(supplier, res, _Row(bond_length, origin), max_records) - return res raw = p.read_bytes() text = raw.decode("utf-16") if raw[:2] in (b"\xff\xfe", b"\xfe\xff") else _decode(raw) return read_text(text, kind, bond_length, origin, max_records) From 46b1128fb501372ca5304c584a7402e3d80ea69f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:19:09 -0500 Subject: [PATCH 079/357] fix(chem): leave internal notes out of the import and export report (0.7.0) The reaction arrow hint and ignored query notes are for the engine, not for the person reading the report. --- backend/app/services/chem/report.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/backend/app/services/chem/report.py b/backend/app/services/chem/report.py index 190f83e0..59d9c405 100644 --- a/backend/app/services/chem/report.py +++ b/backend/app/services/chem/report.py @@ -1,6 +1,7 @@ from typing import Iterable INFO, WARN, ERROR = "info", "warn", "error" +INTERNAL = frozenset({"reaction_arrow", "query_ignored", "conditions_comment"}) SEVERITY = { "coordinates_generated": INFO, "coordinates_flattened": INFO, "rescaled": INFO, "abbreviations_expanded": INFO, @@ -56,6 +57,8 @@ def collect(warnings: Iterable[dict | str], limit: int = 200) -> list[dict]: if not isinstance(w, dict): continue code = str(w.get("code") or "note") + if code in INTERNAL: + continue n = _count(w) cur = merged.get(code) if cur is None: From eb0e4935df5da97301f3a89ed1154a36335e674f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:19:09 -0500 Subject: [PATCH 080/357] feat(chem): declare every chemistry format with its extensions, mime type and what it loses on write (0.7.0) One capability table drives GET /api/formats, the export report and the window's save menu, so the warning before saving and the report after it agree. --- backend/app/services/chem/formats.py | 99 ++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 backend/app/services/chem/formats.py diff --git a/backend/app/services/chem/formats.py b/backend/app/services/chem/formats.py new file mode 100644 index 00000000..501b5ea5 --- /dev/null +++ b/backend/app/services/chem/formats.py @@ -0,0 +1,99 @@ +FEATURES = { + "text": "Text and captions", + "graphics": "Arrows, plus signs, shapes and other drawing objects", + "layout": "Positions of structures on the page", + "coordinates": "2D coordinates (a layout is generated on reading)", + "enhanced_stereo": "Enhanced stereo groups (AND, OR, ABS)", + "query": "Query features (atom lists, generic atoms, bond queries)", + "rgroups": "R-group definitions", + "abbreviations": "Abbreviations (written as their full structures)", + "data": "Structure data fields", + "names": "Structure names", + "maps": "Atom-atom map numbers", + "conditions": "Reaction conditions text", + "reactions": "Reaction roles", + "steps": "More than one reaction step", + "styles": "Colours, fonts, bond display and label styles", + "tautomer": "The drawn tautomer and charge placement (InChI normalises them)", +} + +TABLE: list[dict] = [ + {"id": "molfile", "name": "MDL molfile", "extensions": [".mol", ".mdl"], "mime": "chemical/x-mdl-molfile", "read": True, "write": True, + "multi": False, "reactions": False, "options": {"version": ["auto", "v2000", "v3000"]}, + "loses": ["text", "graphics", "layout", "abbreviations", "data", "reactions", "styles"], + "loses_v2000": ["enhanced_stereo", "query", "rgroups"]}, + {"id": "molfile3000", "name": "MDL molfile V3000", "extensions": [".mol"], "mime": "chemical/x-mdl-molfile", "read": True, "write": True, + "multi": False, "reactions": False, "options": {}, + "loses": ["text", "graphics", "layout", "abbreviations", "data", "reactions", "styles"]}, + {"id": "sdf", "name": "SD file", "extensions": [".sdf", ".sd"], "mime": "chemical/x-mdl-sdfile", "read": True, "write": True, + "multi": True, "reactions": False, "options": {"version": ["auto", "v2000", "v3000"]}, + "loses": ["text", "graphics", "layout", "abbreviations", "reactions", "styles"], "loses_v2000": ["enhanced_stereo", "query", "rgroups"]}, + {"id": "rxn", "name": "MDL reaction file", "extensions": [".rxn"], "mime": "chemical/x-mdl-rxnfile", "read": True, "write": True, + "multi": False, "reactions": True, "options": {"version": ["auto", "v2000", "v3000"]}, + "loses": ["text", "graphics", "layout", "abbreviations", "data", "steps", "styles"], "loses_v2000": ["enhanced_stereo", "query", "rgroups"]}, + {"id": "rdf", "name": "RD file", "extensions": [".rdf", ".rd"], "mime": "chemical/x-mdl-rdfile", "read": True, "write": True, + "multi": True, "reactions": True, "options": {"version": ["auto", "v2000", "v3000"]}, + "loses": ["text", "graphics", "layout", "abbreviations", "styles"], "loses_v2000": ["enhanced_stereo", "query", "rgroups"]}, + {"id": "smiles", "name": "SMILES", "extensions": [".smi", ".smiles"], "mime": "chemical/x-daylight-smiles", "read": True, "write": True, + "multi": True, "reactions": True, "options": {}, + "loses": ["text", "graphics", "layout", "coordinates", "enhanced_stereo", "query", "rgroups", "abbreviations", "data", "conditions", "styles"]}, + {"id": "cxsmiles", "name": "CXSMILES", "extensions": [".cxsmi", ".cxsmiles"], "mime": "chemical/x-daylight-smiles", "read": True, "write": True, + "multi": True, "reactions": True, "options": {"coords": [False, True]}, + "loses": ["text", "graphics", "layout", "query", "rgroups", "abbreviations", "data", "conditions", "styles"]}, + {"id": "rsmiles", "name": "Reaction SMILES", "extensions": [".smi", ".rsmi"], "mime": "chemical/x-daylight-smiles", "read": True, "write": True, + "multi": True, "reactions": True, "options": {}, + "loses": ["text", "graphics", "layout", "coordinates", "enhanced_stereo", "query", "rgroups", "abbreviations", "data", "conditions", "styles"]}, + {"id": "smarts", "name": "SMARTS", "extensions": [".sma", ".smarts"], "mime": "text/plain", "read": True, "write": True, + "multi": True, "reactions": False, "options": {}, + "loses": ["text", "graphics", "layout", "coordinates", "enhanced_stereo", "rgroups", "abbreviations", "data", "reactions", "styles"]}, + {"id": "inchi", "name": "InChI", "extensions": [".inchi"], "mime": "chemical/x-inchi", "read": True, "write": True, + "multi": True, "reactions": False, "options": {}, + "loses": ["text", "graphics", "layout", "coordinates", "enhanced_stereo", "query", "rgroups", "abbreviations", "data", "names", "maps", + "reactions", "styles", "tautomer"]}, + {"id": "inchikey", "name": "InChIKey", "extensions": [".txt"], "mime": "text/plain", "read": False, "write": True, + "multi": True, "reactions": False, "options": {}, "loses": ["everything except a hashed identity"]}, + {"id": "cml", "name": "Chemical Markup Language", "extensions": [".cml"], "mime": "chemical/x-cml", "read": True, "write": True, + "multi": True, "reactions": True, "options": {}, + "loses": ["text", "graphics", "layout", "enhanced_stereo", "query", "rgroups", "abbreviations", "maps", "styles"]}, + {"id": "cdxml", "name": "CDXML drawing", "extensions": [".cdxml"], "mime": "chemical/x-cdxml", "read": True, "write": True, + "multi": True, "reactions": True, "options": {}, + "loses": ["abbreviations", "data", "styles"]}, + {"id": "cdx", "name": "CDX drawing", "extensions": [".cdx"], "mime": "chemical/x-cdx", "read": True, "write": True, "binary": True, + "multi": True, "reactions": True, "options": {}, + "loses": ["abbreviations", "data", "styles"]}, +] +BY_ID = {f["id"]: f for f in TABLE} +ALIASES = {"mol": "molfile", "mdl": "molfile", "v3000": "molfile3000", "sd": "sdf", "rd": "rdf", "smi": "smiles", "cxsmi": "cxsmiles", + "sma": "smarts", "rxnv3000": "rxn", "reaction_smiles": "rsmiles"} + + +def get(fmt: str) -> dict | None: + return BY_ID.get(ALIASES.get(fmt, fmt)) + + +def by_extension(ext: str) -> dict | None: + ext = ext.lower() if ext.startswith(".") else "." + ext.lower() + return next((f for f in TABLE if ext in f["extensions"] and f["read"]), None) + + +def loses(fmt: str, version: str = "auto") -> list[str]: + found = get(fmt) + if found is None: + return [] + out = list(found["loses"]) + if version == "v2000": + out.extend(found.get("loses_v2000", [])) + return out + + +def describe() -> dict: + out = [] + for f in TABLE: + rec = {"id": f["id"], "name": f["name"], "extensions": f["extensions"], "mime": f["mime"], "read": f["read"], "write": f["write"], + "binary": bool(f.get("binary")), "multi": f["multi"], "reactions": f["reactions"], + "scopes": ["document", "page", "selection", "fragments"], "options": f["options"], + "loses": [{"code": c, "text": FEATURES.get(c, c)} for c in f["loses"]]} + if f.get("loses_v2000"): + rec["loses_v2000"] = [{"code": c, "text": FEATURES.get(c, c)} for c in f["loses_v2000"]] + out.append(rec) + return {"formats": out, "features": FEATURES} From 08e1a40a3c4c0c1b43ab9490be428c2a860fdf60 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:19:09 -0500 Subject: [PATCH 081/357] feat(chem): write CML molecules and reaction schemes in the dialect the reader accepts (0.7.0) Molecules carry coordinates, charges, isotopes, hydrogen counts, wedges, labels and data; reactions refer to molecules by id so a two-step scheme keeps its shared intermediate. --- backend/app/services/chem/cml.py | 106 +++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 backend/app/services/chem/cml.py diff --git a/backend/app/services/chem/cml.py b/backend/app/services/chem/cml.py new file mode 100644 index 00000000..69a10714 --- /dev/null +++ b/backend/app/services/chem/cml.py @@ -0,0 +1,106 @@ +from xml.sax.saxutils import escape, quoteattr + +from rdkit import Chem + +from app.services.chem import io + +NAMESPACE = "http://www.xml-cml.org/schema" +ROLE_LISTS = (("reactants", "reactantList", "reactant"), ("agents", "spectatorList", "spectator"), ("products", "productList", "product")) +WEDGE_CODES = {Chem.BondDir.BEGINWEDGE: "W", Chem.BondDir.BEGINDASH: "H"} +ORDERS = {Chem.BondType.SINGLE: "1", Chem.BondType.DOUBLE: "2", Chem.BondType.TRIPLE: "3", Chem.BondType.AROMATIC: "A", + Chem.BondType.QUADRUPLE: "4"} + + +def _label(atom: Chem.Atom) -> str | None: + if atom.HasProp("_MolFileRLabel") and atom.GetIntProp("_MolFileRLabel") > 0: + return f"R{atom.GetIntProp('_MolFileRLabel')}" + for prop in ("dummyLabel", "atomLabel", "molFileAlias"): + if atom.HasProp(prop) and atom.GetProp(prop) not in ("", "*"): + return atom.GetProp(prop) + return None + + +def molecule(frag: dict, mid: str, expansions: dict | None, indent: str = " ") -> tuple[list[str], list[dict]]: + mol, notes = io._writable(frag, expansions) + kek = Chem.Mol(mol) + try: + Chem.Kekulize(kek, clearAromaticFlags=True) + except Exception: + kek = mol + conf = kek.GetConformer() if kek.GetNumConformers() else None + title = str(frag.get("name") or "") + head = f'{indent}" + out = [head] + if title: + out.append(f"{indent} {escape(title)}") + out.append(f"{indent} ") + for a in kek.GetAtoms(): + attrs = [f'id="{mid}_a{a.GetIdx() + 1}"'] + z = a.GetAtomicNum() + attrs.append(f'elementType="{a.GetSymbol() if z else "R"}"') + if conf is not None: + p = conf.GetAtomPosition(a.GetIdx()) + attrs.append(f'x2="{p.x:.4f}" y2="{p.y:.4f}"') + if a.GetFormalCharge(): + attrs.append(f'formalCharge="{a.GetFormalCharge()}"') + if a.GetIsotope() and z: + attrs.append(f'isotopeNumber="{a.GetIsotope()}"') + if z: + attrs.append(f'hydrogenCount="{a.GetTotalNumHs(includeNeighbors=True)}"') + if a.GetNumRadicalElectrons(): + attrs.append(f'spinMultiplicity="{a.GetNumRadicalElectrons() + 1}"') + label = _label(a) if not z else None + if label: + out.append(f"{indent} ") + else: + out.append(f"{indent} ") + out.append(f"{indent} ") + if kek.GetNumBonds(): + out.append(f"{indent} ") + for b in kek.GetBonds(): + order = ORDERS.get(b.GetBondType(), "1") + refs = f"{mid}_a{b.GetBeginAtomIdx() + 1} {mid}_a{b.GetEndAtomIdx() + 1}" + stereo = WEDGE_CODES.get(b.GetBondDir()) if b.GetBondType() == Chem.BondType.SINGLE else None + if stereo: + out.append(f'{indent} {stereo}') + else: + out.append(f'{indent} ') + out.append(f"{indent} ") + data = frag.get("data") if isinstance(frag.get("data"), dict) else {} + if data: + out.append(f"{indent} ") + for key, value in data.items(): + out.append(f"{indent} {escape(str(value))}") + out.append(f"{indent} ") + out.append(f"{indent}") + return out, notes + + +def write(structures: list[dict], steps: list[dict], conditions: dict[str, str], expansions: dict | None = None) -> tuple[str, list[dict]]: + notes: list[dict] = [] + lines = ['', f''] + ids: dict[str, str] = {} + for n, frag in enumerate(structures): + mid = f"m{n + 1}" + ids[frag["id"]] = mid + found, more = molecule(frag, mid, expansions) + lines.extend(found) + notes.extend(more) + if steps: + lines.append(' ' if len(steps) > 1 else " ") + for n, step in enumerate(steps): + lines.append(f' ') + for key, list_tag, item_tag in ROLE_LISTS: + refs = [ids[i] for i in step.get(key) or [] if i in ids] + if not refs: + continue + lines.append(f" <{list_tag}>") + lines.extend(f' <{item_tag}>' for r in refs) + lines.append(f" ") + text = conditions.get(step.get("id") or "", "") + if text: + lines.append(f" {escape(text)}") + lines.append(" ") + lines.append(" " if len(steps) > 1 else " ") + lines.append("") + return "\n".join(lines) + "\n", notes From 51380d03374f8912f7f384939f45fb29ba6bf8f7 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:19:09 -0500 Subject: [PATCH 082/357] feat(reactions): lay out several reaction steps in chains, continuing a row when a step starts from the last products (0.7.0) RD files, CML schemes and SMILES files with several reactions now open as one scheme instead of piled structures. --- backend/app/services/chem/scheme.py | 93 +++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/backend/app/services/chem/scheme.py b/backend/app/services/chem/scheme.py index 9b2b400a..cb5253da 100644 --- a/backend/app/services/chem/scheme.py +++ b/backend/app/services/chem/scheme.py @@ -138,6 +138,99 @@ def side(items: list[dict], x: float) -> float: return {"objects": objects, "reaction": {"id": fresh_id(used, "r"), "steps": [step]}, "warnings": notes} +def layout_steps(parsed: io.ParseResult, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (72.0, 72.0), + used: set[str] | None = None) -> dict: + used = used if used is not None else set() + frags = {f["id"]: f for f in parsed.fragments} + for f in parsed.fragments: + _repair(f, bond_length) + p = _Placer(bond_length) + bl = bond_length + objects: list[dict] = [] + steps: list[dict] = [] + placed: set[str] = set() + x0, top = origin + x, cy, row_bottom = x0, 0.0, top + previous: list[str] = [] + for roles in parsed.reactions: + reactants = [frags[i] for i in roles.get("reactants") or [] if i in frags] + products = [frags[i] for i in roles.get("products") or [] if i in frags] + agents = [frags[i] for i in roles.get("agents") or [] if i in frags] + if not reactants and not products: + continue + chained = bool(previous) and {f["id"] for f in reactants} <= set(previous) and all(f["id"] in placed for f in reactants) + if not chained: + row = [f for f in reactants + products if f["id"] not in placed] + height = max((p.box(f)[3] - p.box(f)[1] for f in row), default=bl) + agent_h = max((p.box(f)[3] - p.box(f)[1] for f in agents), default=0.0) + cy = row_bottom + max(height / 2, agent_h + END_BONDS * bl if agents else 0.0) + x = x0 + for n, f in enumerate(reactants): + if n: + x += GAP_BONDS * bl + objects.append({"id": fresh_id(used, "o"), "kind": "plus", "x": round(x + PLUS_BONDS * bl / 2, 3), "y": round(cy, 3), "symbol": "plus"}) + x += PLUS_BONDS * bl + GAP_BONDS * bl + if f["id"] not in placed: + x = p.put(f, x, cy) + objects.append(f) + placed.add(f["id"]) + tail = x + END_BONDS * bl + widths = [p.box(f)[2] - p.box(f)[0] for f in agents] + span = sum(widths) + GAP_BONDS * bl * max(0, len(agents) - 1) + text = str(roles.get("conditions") or "") + note = {"id": fresh_id(used, "o"), "kind": "text", "x": 0.0, "y": round(cy + END_BONDS * bl, 3), "align": "c", "runs": [{"t": text}]} if text else None + note_w = (geometry.text_box(note, p.style)[2] - geometry.text_box(note, p.style)[0]) if note else 0.0 + length = max(ARROW_BONDS * bl, span + 2 * CONDITION_PAD, note_w + 2 * CONDITION_PAD) + ax = tail + (length - span) / 2 + for f, w in zip(agents, widths): + if f["id"] in placed: + continue + b = p.box(f) + _move(f, ax - b[0], cy - END_BONDS * bl - b[3]) + objects.append(f) + placed.add(f["id"]) + ax += w + GAP_BONDS * bl + head = tail + length + arrow = {"id": fresh_id(used, "o"), "kind": "arrow", "type": "forward", "x1": round(tail, 3), "y1": round(cy, 3), + "x2": round(head, 3), "y2": round(cy, 3), "head": "full", "tail": "none"} + objects.append(arrow) + if note: + note["x"] = round((tail + head) / 2, 3) + objects.append(note) + x = head + END_BONDS * bl + for n, f in enumerate(products): + if n: + x += GAP_BONDS * bl + objects.append({"id": fresh_id(used, "o"), "kind": "plus", "x": round(x + PLUS_BONDS * bl / 2, 3), "y": round(cy, 3), "symbol": "plus"}) + x += PLUS_BONDS * bl + GAP_BONDS * bl + if f["id"] not in placed: + x = p.put(f, x, cy) + objects.append(f) + placed.add(f["id"]) + row_bottom = max([row_bottom] + [p.box(f)[3] for f in reactants + products + agents] + ([geometry.text_box(note, p.style)[3]] if note else [])) + ROW_GAP_BONDS * bl + steps.append({"id": fresh_id(used, "r"), "arrow": arrow["id"], "reactants": [f["id"] for f in reactants], "products": [f["id"] for f in products], + "agents": [f["id"] for f in agents], "conditions": [note["id"]] if note else [], "explicit": True}) + previous = [f["id"] for f in products] + x = x0 + for f in parsed.fragments: + if f["id"] in placed: + continue + b = p.box(f) + _move(f, x - b[0], row_bottom - b[1]) + x += b[2] - b[0] + ROW_GAP_BONDS * bl + objects.append(f) + renamed = {} + for f in parsed.fragments: + old = f["id"] + _claim(f, used) + renamed[old] = f["id"] + for s in steps: + for key in ("reactants", "products", "agents"): + s[key] = [renamed.get(i, i) for i in s[key]] + notes = [w for w in parsed.warnings if w.get("code") != "reaction_arrow"] + return {"objects": objects, "steps": steps, "warnings": notes} + + def parse(text: str, fmt: str | None = None, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (72.0, 72.0), used: set[str] | None = None) -> dict: kind = ALIASES.get(fmt) if fmt else None From 940d3bbb4b10e4b2fd38e7d60ed27df0f90448c8 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:19:09 -0500 Subject: [PATCH 083/357] feat(chem): export a page, a selection or a set of fragments to every chemistry format with a report of what is lost (0.7.0) Molfiles switch to V3000 by themselves for large structures, enhanced stereo, queries and R-groups; SD records carry fragment data; reactions go to RXN, RD file, reaction SMILES, CML and the drawing formats. --- backend/app/services/chem/writers.py | 545 +++++++++++++++++++++++++++ 1 file changed, 545 insertions(+) create mode 100644 backend/app/services/chem/writers.py diff --git a/backend/app/services/chem/writers.py b/backend/app/services/chem/writers.py new file mode 100644 index 00000000..3eb14a57 --- /dev/null +++ b/backend/app/services/chem/writers.py @@ -0,0 +1,545 @@ +import base64 +import copy +import re +from dataclasses import dataclass, field + +from rdkit import Chem + +from app.services import model +from app.services.chem import cdxio, cml, formats, ids, io, perceive, query, rdfio, report, rxnio, v3000, warning +from app.services.chem.reactions import ReactionError + +SCOPES = ("page", "selection", "document") +RGROUP_FORMATS = ("molfile", "molfile3000", "sdf", "cdxml", "cdx") +CONDITION_FORMATS = ("rxn", "rdf", "cml", "cdxml", "cdx") +STYLE_KEYS = ("color", "bold", "dashed", "hashed", "label_side", "lone_pairs", "charge_angle", "note") +UNSAFE = re.compile(r'[\\/:*?"<>|\x00-\x1f]+') + + +class ExportError(ValueError): + def __init__(self, message: str, items: list[dict] | None = None): + super().__init__(message) + self.report = items or [] + + +@dataclass +class Exported: + format: str + mime: str + filename: str + binary: bool = False + text: str | None = None + data: bytes | None = None + report: list[dict] = field(default_factory=list) + + @property + def body(self) -> bytes: + return self.data if self.binary and self.data is not None else (self.text or "").encode("utf-8") + + def as_json(self) -> dict: + return {"format": self.format, "filename": self.filename, "mime": self.mime, "binary": self.binary, + "text": None if self.binary else self.text, "base64": base64.b64encode(self.data).decode("ascii") if self.binary and self.data else None, + "report": self.report} + + +@dataclass +class Scope: + doc: dict + fragments: list[dict] + annotations: list[dict] + steps: list[dict] + members: dict[str, dict] + title: str + + @property + def expansions(self) -> dict | None: + return self.doc.get("expansions") or None + + @property + def style(self) -> dict: + return model.resolve_style(self.doc) + + def member_ids(self) -> set[str]: + out: set[str] = set() + for f in self.fragments: + for g in (f.get("rgroups") or {}).values(): + if isinstance(g, dict): + out.update(m for m in g.get("members") or [] if isinstance(m, str)) + return out + + +def _flatten(doc: dict, ids_: list[str], depth: int = 0) -> list[str]: + out: list[str] = [] + for oid in ids_: + obj = (doc.get("objects") or {}).get(oid) + if not isinstance(obj, dict) or depth > 32: + continue + if obj.get("kind") == "group": + out.extend(_flatten(doc, [c for c in obj.get("children") or [] if isinstance(c, str)], depth + 1)) + else: + out.append(oid) + return out + + +def collect(doc: dict, scope: str = "page", page: str | None = None, ids_: list[str] | None = None) -> Scope: + pages = [p for p in doc.get("pages") or [] if isinstance(p, dict)] + if scope not in SCOPES: + raise ExportError(f"scope must be one of {', '.join(SCOPES)}") + if scope == "document": + chosen = pages + tops = [oid for p in pages for oid in p.get("order") or [] if isinstance(oid, str)] + elif scope == "page": + found = next((p for p in pages if p.get("id") == page), None) if page else (pages[0] if pages else None) + if found is None: + raise ExportError(f"The drawing has no page {page}.") + chosen = [found] + tops = [oid for oid in found.get("order") or [] if isinstance(oid, str)] + else: + if not ids_: + raise ExportError("Name the objects to export with ids.") + missing = [i for i in ids_ if i not in (doc.get("objects") or {})] + if missing: + raise ExportError(f"{missing[0]} is not an object of this drawing; give fragment or object ids, not atom ids.") + tops = list(ids_) + homes = {model.page_of(doc, i)["id"] for i in ids_ if model.page_of(doc, i)} + chosen = [p for p in pages if p.get("id") in homes] + flat = _flatten(doc, tops) + objects = doc.get("objects") or {} + fragments = [objects[i] for i in flat if objects[i].get("kind") == "fragment" and objects[i].get("atoms")] + annotations = [objects[i] for i in flat if objects[i].get("kind") != "fragment"] + inside = set(flat) + steps = [] + for p in chosen: + for r in p.get("reactions") or []: + for s in (r.get("steps") or []) if isinstance(r, dict) else []: + if isinstance(s, dict) and (scope != "selection" or s.get("arrow") in inside): + steps.append(s) + members = {k: o for k, o in objects.items() if isinstance(o, dict) and o.get("kind") == "fragment"} + title = str(doc.get("title") or "Untitled") + if len(fragments) == 1 and fragments[0].get("name"): + title = str(fragments[0]["name"]) + return Scope(doc, fragments, annotations, steps, members, title) + + +def features(frag: dict) -> dict[str, int]: + atoms = [a for a in (frag.get("atoms") or {}).values() if isinstance(a, dict)] + bonds = [b for b in (frag.get("bonds") or {}).values() if isinstance(b, dict)] + groups = [g for g in frag.get("stereo_groups") or [] if isinstance(g, dict) and g.get("kind") in ("and", "or")] + return { + "enhanced_stereo": len(groups) + (1 if frag.get("chiral") in ("relative", "racemic") else 0), + "query": sum(1 for a in atoms if query.is_query_atom(a)) + sum(1 for b in bonds if query.is_query_bond(b)), + "rgroups": len(frag.get("rgroups") or {}), + "data": len(frag.get("data") or {}) if isinstance(frag.get("data"), dict) else 0, + "names": 1 if frag.get("name") else 0, + "maps": sum(1 for a in atoms if a.get("map")), + "styles": sum(1 for a in atoms + bonds if any(a.get(k) for k in STYLE_KEYS)), + } + + +def needs_v3000(frag: dict) -> list[str]: + f = features(frag) + why = [] + if len(frag.get("atoms") or {}) > 999 or len(frag.get("bonds") or {}) > 999: + why.append("more than 999 atoms or bonds") + if f["enhanced_stereo"]: + why.append("enhanced stereo") + if f["query"]: + why.append("query features") + if f["rgroups"]: + why.append("R-groups") + if any(b.get("order") in ("dative", "hydrogen") for b in (frag.get("bonds") or {}).values() if isinstance(b, dict)): + why.append("dative or hydrogen bonds") + return why + + +LOSS_CODES = {"enhanced_stereo": "enhanced_stereo_lost", "query": "query_lost", "rgroups": "rgroups_lost", "data": "data_dropped", + "names": "names_dropped", "maps": "maps_dropped", "styles": "styles_dropped"} +LOSS_TEXTS = { + "enhanced_stereo": "{n} enhanced stereo group{s} (AND, OR) {are} not stored in {fmt}; the centres are written as plain stereo.", + "query": "{n} query feature{s} {are} not stored in {fmt}.", + "rgroups": "{n} R-group definition{s} {are} not stored in {fmt}; R-group atoms are written as any-atoms.", + "data": "{n} structure data field{s} {are} not stored in {fmt}.", + "names": "{n} structure name{s} {are} not stored in {fmt}.", + "maps": "{n} atom map number{s} {are} not stored in {fmt}.", + "styles": "Colours, bond display and label styles of {n} atom{s} and bond{s} are not stored in {fmt}.", +} + + +def _plural(text: str, n: int, fmt: str) -> str: + return text.format(n=n, s="s" if n != 1 else "", are="are" if n != 1 else "is", fmt=fmt) + + +class _Writer: + def __init__(self, sc: Scope, fmt: str, options: dict): + self.sc = sc + self.fmt = fmt + self.options = options + self.notes: list[dict] = [] + self.version = str(options.get("version") or "auto") + self.conditions_written = fmt in CONDITION_FORMATS + self.steps_written: list[dict] = [] + self.name = formats.get(fmt)["name"] + + def note_losses(self, frags: list[dict], lost: list[str]) -> None: + totals: dict[str, int] = {} + for f in frags: + for key, n in features(f).items(): + if n and key in lost: + totals[key] = totals.get(key, 0) + n + for key, n in totals.items(): + self.notes.append(report.item(LOSS_CODES[key], n, _plural(LOSS_TEXTS[key], n, self.name), + severity="info" if key in ("styles", "names") else None)) + + def note_annotations(self) -> None: + written_arrows = {s.get("arrow") for s in self.steps_written} + conditions = {c for s in self.steps_written for c in s.get("conditions") or []} if self.conditions_written else set() + roles = {i for s in self.steps_written for k in ("reactants", "products", "agents") for i in s.get(k) or []} + text, other = [], [] + for obj in self.sc.annotations: + kind = obj.get("kind") + if obj["id"] in written_arrows or obj["id"] in conditions or obj["id"] in roles: + continue + if kind == "plus" and self.steps_written: + continue + (text if kind in ("text", "caption") else other).append(obj["id"]) + if text: + self.notes.append(report.item("text_dropped", len(text), f"{len(text)} text object{'s are' if len(text) > 1 else ' is'} not stored in {self.name}.", objects=text)) + if other: + self.notes.append(report.item("graphics_dropped", len(other), f"{len(other)} arrow{'s' if len(other) > 1 else ''}, plus sign{'s' if len(other) > 1 else ''} or other drawing object{'s are' if len(other) > 1 else ' is'} not stored in {self.name}.", objects=other)) + + def structures(self, embed_members: bool) -> list[dict]: + skip = self.sc.member_ids() if embed_members else set() + return [f for f in self.sc.fragments if f["id"] not in skip] + + def need(self, frags: list[dict]) -> str: + if self.fmt == "molfile3000" or self.version == "v3000": + return "v3000" + if self.version == "v2000": + return "v2000" + why = sorted({w for f in frags for w in needs_v3000(f)}) + if why: + self.notes.append(report.item("v3000", 1, f"Written as V3000 because the drawing has {', '.join(why)}.", severity="info")) + return "v3000" + return "v2000" + + def molblock(self, frag: dict, version: str) -> str: + if version == "v3000": + text, more = v3000.write(frag, self.sc.expansions, self.sc.members) + self.notes.extend(more) + return text + mol, more = io._writable(frag, self.sc.expansions) + self.notes.extend(more) + mol.SetStereoGroups([]) + try: + return Chem.MolToMolBlock(mol, includeStereo=True, kekulize=True) + except Exception: + self.notes.append(warning("cannot_kekulise", "Aromatic bonds were written as type 4 because the system cannot be kekulised.")) + return Chem.MolToMolBlock(mol, includeStereo=True, kekulize=False) + + def lost_for(self, version: str) -> list[str]: + return formats.loses(self.fmt, version) + + def require(self, frags: list[dict], what: str = "structures") -> None: + if not frags: + raise ExportError(f"There are no {what} to write as {self.name}.") + + +def _merge(frags: list[dict]) -> dict: + if len(frags) == 1: + return frags[0] + out: dict = {"id": frags[0]["id"], "kind": "fragment", "atoms": {}, "bonds": {}} + groups: list = [] + rgroups: dict = {} + for f in frags: + out["atoms"].update(f.get("atoms") or {}) + out["bonds"].update(f.get("bonds") or {}) + groups.extend(f.get("stereo_groups") or []) + rgroups.update(f.get("rgroups") or {}) + if groups: + out["stereo_groups"] = groups + if rgroups: + out["rgroups"] = rgroups + return out + + +def _write_molfile(w: _Writer) -> str: + version = "v3000" if w.fmt == "molfile3000" else None + frags = w.structures(True) + w.require(frags) + whole = _merge(frags) + if len(frags) > 1: + whole["name"] = w.sc.title + w.notes.append(report.item("molfile_merged", len(frags), f"{len(frags)} structures are written as one molfile; use an SD file to keep them as separate records.", severity="info")) + version = version or w.need([whole]) + w.note_losses(frags, w.lost_for(version)) + return w.molblock(whole, version) + + +def _sd_value(value: object) -> str: + lines = [l for l in str(value).replace("\r\n", "\n").split("\n")] + return "\n".join(l if l.strip() else " " for l in lines) if any(lines) else "" + + +def _write_sdf(w: _Writer) -> str: + frags = w.structures(True) + w.require(frags) + out: list[str] = [] + versions = set() + for f in frags: + version = "v3000" if w.version == "v3000" else "v2000" if w.version == "v2000" else ("v3000" if needs_v3000(f) else "v2000") + versions.add(version) + block = w.molblock(f, version).rstrip("\n") + out.append(block) + for key, value in (f.get("data") or {}).items() if isinstance(f.get("data"), dict) else []: + out.append(f"> <{key}>") + out.append(_sd_value(value)) + out.append("") + out.append("$$$$") + if "v3000" in versions and w.version == "auto": + w.notes.append(report.item("v3000", sum(1 for f in frags if needs_v3000(f)), "Records with enhanced stereo, queries, R-groups or more than 999 atoms are written as V3000.", severity="info")) + w.note_losses(frags, w.lost_for("v2000" if w.version == "v2000" else "auto")) + return "\n".join(out) + "\n" + + +def _rxn_version(w: _Writer, step: dict) -> str: + if w.version in ("v2000", "v3000"): + return w.version + frags = [f for oid, _ in rxnio.roles_of(step) for f in rxnio.fragments_in(w.sc.doc, oid)] + return "v3000" if any(needs_v3000(f) for f in frags) else "v2000" + + +def _step_frags(w: _Writer, step: dict) -> list[dict]: + return [f for oid, _ in rxnio.roles_of(step) for f in rxnio.fragments_in(w.sc.doc, oid)] + + +def _conditions(doc: dict, step: dict) -> str: + return "; ".join(t for t in (rxnio.plain_text((doc.get("objects") or {}).get(c)) for c in step.get("conditions") or []) if t) + + +def _write_rxn(w: _Writer) -> str: + if not w.sc.steps: + raise ExportError("There is no reaction to write: draw a reaction arrow with structures on both sides, or export as a molfile or SD file.") + step = w.sc.steps[0] + if len(w.sc.steps) > 1: + w.notes.append(report.item("steps_dropped", len(w.sc.steps) - 1, f"An RXN file holds one step; {len(w.sc.steps) - 1} more step{'s are' if len(w.sc.steps) > 2 else ' is'} not written. Use an RD file or CML to keep every step.")) + version = _rxn_version(w, step) + try: + text, more = rxnio.export_step(w.sc.doc, step, "rxnv3000" if version == "v3000" else "rxn", w.sc.title) + except ReactionError as exc: + raise ExportError(str(exc)) + w.notes.extend(m for m in more if m.get("code") != "conditions_comment") + w.steps_written = [step] + w.note_losses(_step_frags(w, step), w.lost_for(version)) + others = [f for f in w.sc.fragments if f["id"] not in {i for k in ("reactants", "products", "agents") for i in step.get(k) or []}] + if others: + w.notes.append(report.item("structures_dropped", len(others), f"{len(others)} structure{'s are' if len(others) > 1 else ' is'} not part of the reaction and {'are' if len(others) > 1 else 'is'} not written.")) + return text + + +def _write_rdf(w: _Writer) -> str: + records = [] + in_steps: set[str] = set() + frags_all: list[dict] = [] + for step in w.sc.steps: + version = _rxn_version(w, step) + try: + text, more = rxnio.export_step(w.sc.doc, step, "rxnv3000" if version == "v3000" else "rxn", "") + except ReactionError as exc: + w.notes.append(report.item("record_failed", 1, f"A reaction step was not written: {exc}", severity="error")) + continue + w.notes.extend(m for m in more if m.get("code") != "conditions_comment") + w.steps_written.append(step) + sf = _step_frags(w, step) + frags_all.extend(sf) + in_steps.update(f["id"] for f in sf) + records.append({"kind": "rxn", "block": text, "conditions": _conditions(w.sc.doc, step)}) + for f in w.structures(False): + if f["id"] in in_steps: + continue + version = "v3000" if w.version == "v3000" or (w.version == "auto" and needs_v3000(f)) else "v2000" + records.append({"kind": "mol", "block": w.molblock(f, version), "data": f.get("data") if isinstance(f.get("data"), dict) else {}}) + frags_all.append(f) + if not records: + raise ExportError("There are no structures or reactions to write as an RD file.") + w.note_losses(frags_all, w.lost_for("v2000" if w.version == "v2000" else "v3000")) + return rdfio.write(records) + + +def _smiles_of(frag: dict, expansions: dict | None, cx: bool, coords: bool) -> tuple[str, list[dict]]: + conv = perceive.prepare(frag, expansions) + mol = ids.identifier_mol(conv.mol) + notes = list(conv.warnings) + if conv.expanded: + notes.append(warning("abbreviations_expanded", "Abbreviations are written as their full structures.")) + if not cx: + return ids.smiles(mol), notes + flags = int(Chem.CXSmilesFields.CX_ALL) ^ int(Chem.CXSmilesFields.CX_ATOM_PROPS) + if not coords: + flags = ids.CX_FLAGS + try: + return Chem.MolToCXSmiles(mol, Chem.SmilesWriteParams(), flags), notes + except Exception: + return ids.cxsmiles(mol), notes + + +def _write_smiles(w: _Writer) -> str: + cx = w.fmt == "cxsmiles" + coords = bool(w.options.get("coords")) and cx + lines: list[str] = [] + in_steps: set[str] = set() + for step in w.sc.steps: + try: + text, more = rxnio.export_step(w.sc.doc, step, "smiles") + except ReactionError as exc: + w.notes.append(report.item("record_failed", 1, f"A reaction step was not written: {exc}", severity="error")) + continue + w.notes.extend(more) + w.steps_written.append(step) + in_steps.update(f["id"] for f in _step_frags(w, step)) + lines.append(text) + if w.fmt == "rsmiles": + if not lines: + raise ExportError("There is no reaction to write as reaction SMILES.") + else: + refused = [] + written: list[dict] = [] + for f in w.structures(False): + if f["id"] in in_steps: + continue + if query.has_query(f): + refused.append(f["id"]) + continue + text, more = _smiles_of(f, w.sc.expansions, cx, coords) + w.notes.extend(more) + if not text: + w.notes.append(report.item("record_failed", 1, "A structure could not be written as SMILES.", severity="error", objects=[f["id"]])) + continue + written.append(f) + lines.append(f"{text} {f['name']}" if f.get("name") else text) + if refused: + w.notes.append(report.item("query_refused", len(refused), f"{len(refused)} query structure{'s' if len(refused) > 1 else ''} cannot be written as SMILES and {'were' if len(refused) > 1 else 'was'} left out; export as SMARTS or a V3000 molfile.", + severity="error", objects=refused)) + w.note_losses(written, [k for k in w.lost_for("auto") if k != "names"]) + if not lines: + raise ExportError(f"There are no structures to write as {w.name}.") + if not coords and len(lines) > 0: + w.notes.append(report.item("coordinates_dropped", 1, f"{w.name} keeps no coordinates; a layout is generated when it is read.", severity="info")) + return "\n".join(lines) + "\n" + + +def _write_smarts(w: _Writer) -> str: + frags = w.structures(False) + w.require(frags) + lines = [] + for f in frags: + text, more = query.to_smarts(f, w.sc.expansions) + w.notes.extend(more) + lines.append(f"{text} {f['name']}" if f.get("name") else text) + w.note_losses(frags, [k for k in w.lost_for("auto") if k not in ("enhanced_stereo", "rgroups")]) + return "\n".join(lines) + "\n" + + +def _write_inchi(w: _Writer) -> str: + frags = w.structures(False) + w.require(frags) + lines = [] + for f in frags: + conv = perceive.prepare(f, w.sc.expansions) + text, key, more = ids.inchi(ids.identifier_mol(conv.mol)) + w.notes.extend(more) + if not text: + w.notes.append(report.item("record_failed", 1, "A structure has no InChI (labels, R-groups or any-atoms).", severity="error", objects=[f["id"]])) + continue + lines.append(key if w.fmt == "inchikey" else text) + if not lines: + raise ExportError(f"None of the structures can be written as {w.name}.") + w.note_losses(frags, w.lost_for("auto")) + if w.fmt == "inchi": + w.notes.append(report.item("tautomer_normalised", 1, "InChI normalises tautomers and charge placement; reading it back can draw a different tautomer.", severity="info")) + return "\n".join(lines) + "\n" + + +def _write_cml(w: _Writer) -> str: + frags = w.structures(False) + w.require(frags) + w.steps_written = list(w.sc.steps) + conditions = {s.get("id") or "": _conditions(w.sc.doc, s) for s in w.sc.steps} + text, more = cml.write(frags, w.sc.steps, conditions, w.sc.expansions) + w.notes.extend(more) + w.note_losses(frags, w.lost_for("auto")) + return text + + +def _write_cdx(w: _Writer) -> str | bytes: + frags = w.structures(True) + w.require(frags) + try: + out, more = cdxio.write(frags, w.sc.annotations, w.sc.style, w.sc.expansions, w.sc.members, binary=w.fmt == "cdx") + except ValueError as exc: + raise ExportError(f"{w.name}: {exc}") + w.notes.extend(more) + w.steps_written = list(w.sc.steps) + w.note_losses(frags, w.lost_for("auto")) + return out + + +WRITERS = {"molfile": _write_molfile, "molfile3000": _write_molfile, "sdf": _write_sdf, "rxn": _write_rxn, "rdf": _write_rdf, + "smiles": _write_smiles, "cxsmiles": _write_smiles, "rsmiles": _write_smiles, "smarts": _write_smarts, + "inchi": _write_inchi, "inchikey": _write_inchi, "cml": _write_cml, "cdxml": _write_cdx, "cdx": _write_cdx} + + +def filename(title: str, fmt: str) -> str: + stem = UNSAFE.sub(" ", title or "").strip(" .") or "Untitled" + stem = re.sub(r"\s+", " ", stem)[:120] + return stem + formats.get(fmt)["extensions"][0] + + +def write_scope(sc: Scope, fmt: str, options: dict | None = None) -> Exported: + spec = formats.get(fmt) + if spec is None or not spec["write"]: + raise ExportError(f"FormChem cannot write the format {fmt}.") + fmt = spec["id"] + w = _Writer(sc, fmt, options or {}) + try: + out = WRITERS[fmt](w) + except ExportError as exc: + exc.report = exc.report or report.collect(w.notes) + raise + if fmt not in ("cdxml", "cdx"): + w.note_annotations() + if w.sc.steps and not w.steps_written and not spec["reactions"]: + n = len(w.sc.steps) + w.notes.append(report.item("reactions_dropped", n, f"{n} reaction step{'s are' if n > 1 else ' is'} written as separate structures; {w.name} has no reaction roles.")) + if w.steps_written and fmt in ("smiles", "cxsmiles", "rsmiles") and any(_conditions(sc.doc, s) for s in w.steps_written): + w.notes.append(report.item("conditions_dropped", sum(1 for s in w.steps_written if _conditions(sc.doc, s)), "Reaction SMILES has no place for the conditions text.")) + items = report.collect([n for n in w.notes if n.get("code") not in ("query_ignored", "conditions_comment")]) + final = "molfile3000" if fmt == "molfile" and isinstance(out, str) and "V3000" in out[:400] else fmt + binary = isinstance(out, bytes) + mime = spec["mime"] + return Exported(final, mime, filename(sc.title, fmt), binary, None if binary else out, out if binary else None, items) + + +def export_document(doc: dict, fmt: str, scope: str = "page", page: str | None = None, ids_: list[str] | None = None, + options: dict | None = None) -> Exported: + return write_scope(collect(doc, scope, page, ids_), fmt, options) + + +def export_fragments(fragments: list[dict], fmt: str, options: dict | None = None, objects: dict | list | None = None, + reactions: list[dict] | None = None, expansions: dict | None = None, name: str | None = None) -> Exported: + doc = model.empty_document(name or "Untitled") + page = doc["pages"][0] + extra = list(objects.values()) if isinstance(objects, dict) else list(objects or []) + for obj in [*fragments, *extra]: + if not isinstance(obj, dict) or not isinstance(obj.get("id"), str): + continue + obj = copy.deepcopy(obj) + obj.setdefault("kind", "fragment") + doc["objects"][obj["id"]] = obj + page["order"].append(obj["id"]) + if reactions: + page["reactions"] = copy.deepcopy(reactions) + if expansions: + doc["expansions"] = expansions + if not name and len(fragments) == 1 and isinstance(fragments[0], dict) and fragments[0].get("name"): + doc["title"] = str(fragments[0]["name"]) + return write_scope(collect(doc, "page"), fmt, options) From 3f61e63b624252f55d08d55a3e2e0e2556d05164 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:19:09 -0500 Subject: [PATCH 084/357] feat(import): keep annotation objects and every reaction step on import and return the import report (0.7.0) Opening a foreign file now answers with report items and keeps them on meta.imported.report, so the window can show what was lost or changed. --- backend/app/services/importers.py | 78 ++++++++++++++++++++++++------- backend/app/services/store.py | 2 +- 2 files changed, 61 insertions(+), 19 deletions(-) diff --git a/backend/app/services/importers.py b/backend/app/services/importers.py index f40d0335..29c24f0a 100644 --- a/backend/app/services/importers.py +++ b/backend/app/services/importers.py @@ -12,6 +12,10 @@ ".sdf": "SD file", ".sd": "SD file", ".rxn": "MDL reaction file", + ".rdf": "RD file", + ".rd": "RD file", + ".sma": "SMARTS", + ".smarts": "SMARTS", ".smi": "SMILES", ".smiles": "SMILES", ".cxsmi": "CXSMILES", @@ -42,12 +46,6 @@ def _parser(): return read_file -def _warning_text(w: object) -> str: - if isinstance(w, dict): - return str(w.get("text") or w.get("code") or "") - return str(w) - - def _locale() -> str | None: found = config.read_settings().get("locale") return found if isinstance(found, str) and found else None @@ -170,20 +168,57 @@ def place(frags: list[dict], page: dict, bond_length: float) -> None: top += height + gap -def _reaction(doc: dict, page: dict, result: object, bond_length: float, ids: _Ids, warnings: list[str], source: Path) -> bool: +def _reaction(doc: dict, page: dict, result: object, bond_length: float, ids: _Ids, warnings: list, source: Path) -> bool: margin = float(page.get("margins", 36)) + reactions = getattr(result, "reactions", None) or [result.reaction] try: - from app.services.chem import scheme - comment = scheme.rxn_comment(source.read_text(encoding="utf-8", errors="replace")) if source.suffix.lower() == ".rxn" else "" - found = scheme.layout(result, bond_length, (margin, margin), ids.used, comment) + from app.services.chem import reactions as rx, scheme + if len(reactions) > 1: + found = scheme.layout_steps(result, bond_length, (margin, margin), ids.used) + steps = found["steps"] + else: + comment = str(reactions[0].get("conditions") or "") + if not comment and source.suffix.lower() == ".rxn": + comment = scheme.rxn_comment(source.read_text(encoding="utf-8", errors="replace")) + found = scheme.layout(result, bond_length, (margin, margin), ids.used, comment) + steps = found["reaction"]["steps"] except Exception as exc: - warnings.append(f"the reaction could not be laid out, so its structures are placed in rows ({exc})") + warnings.append({"code": "reaction_layout", "text": f"The reaction could not be laid out, so its structures are placed in rows ({exc})."}) return False for obj in found["objects"]: doc["objects"][obj["id"]] = obj page["order"].append(obj["id"]) - page["reactions"] = [found["reaction"]] - warnings[:] = [t for t in (_warning_text(w) for w in found["warnings"]) if t] + page["reactions"] = [{"id": rx.fresh_id(ids.used, "r"), "steps": steps}] + grouped, _ = rx.perceive_page(doc, page, ids.used) + if grouped: + page["reactions"] = grouped + warnings[:] = list(found["warnings"]) + return True + + +def _drawing(doc: dict, page: dict, result: object, ids: _Ids, warnings: list) -> bool: + texts: list[str] = [] + frags = [f for f in (normalise_fragment(raw, ids, texts) for raw in result.fragments if isinstance(raw, dict)) if f is not None] + warnings.extend({"code": "bad_bond", "text": t} for t in texts) + for f in frags: + doc["objects"][f["id"]] = f + page["order"].append(f["id"]) + for obj in getattr(result, "objects", None) or []: + if not isinstance(obj, dict): + continue + rec = copy.deepcopy(obj) + rec["id"] = ids.claim(obj.get("id"), "o") + doc["objects"][rec["id"]] = rec + page["order"].append(rec["id"]) + if not page["order"]: + return False + try: + from app.services.chem import reactions as rx + found, _ = rx.perceive_page(doc, page, ids.used) + except Exception: + found = [] + if found: + page["reactions"] = found return True @@ -205,17 +240,24 @@ def import_file(path: str | Path) -> tuple[dict, list[str]]: raise ImportFailed(f"Could not read {p.name}: the chemistry service returned no structures.") page = doc["pages"][0] ids = _Ids({doc["id"], page["id"]}) - warnings: list[str] = [t for t in (_warning_text(w) for w in getattr(result, "warnings", None) or []) if t] - if not (getattr(result, "reaction", None) and _reaction(doc, page, result, bond_length, ids, warnings, p)): - frags = [f for f in (normalise_fragment(raw, ids, warnings) for raw in parsed if isinstance(raw, dict)) if f is not None] + warnings: list = list(getattr(result, "warnings", None) or []) + if getattr(result, "objects", None): + if not _drawing(doc, page, result, ids, warnings): + raise ImportFailed(f"{p.name} holds nothing FormChem can draw.") + elif not (getattr(result, "reaction", None) and _reaction(doc, page, result, bond_length, ids, warnings, p)): + texts: list[str] = [] + frags = [f for f in (normalise_fragment(raw, ids, texts) for raw in parsed if isinstance(raw, dict)) if f is not None] + warnings.extend({"code": "bad_bond", "text": t} for t in texts) if not frags: raise ImportFailed(f"{p.name} holds no structures FormChem can draw.") place(frags, page, bond_length) for f in frags: doc["objects"][f["id"]] = f page["order"].append(f["id"]) - doc["meta"]["imported"] = {"name": p.name, "format": FORMATS[p.suffix.lower()]} + from app.services.chem import report + items = report.collect(w if isinstance(w, dict) else {"code": "note", "text": str(w)} for w in warnings) + doc["meta"]["imported"] = {"name": p.name, "format": FORMATS[p.suffix.lower()], "report": items} errors = model.validate(doc) if errors: raise ImportFailed(f"{p.name} could not be turned into a FormChem drawing: {errors[0]}.") - return doc, warnings + return doc, report.lines(items) diff --git a/backend/app/services/store.py b/backend/app/services/store.py index a9a57ab2..6bb8aeac 100644 --- a/backend/app/services/store.py +++ b/backend/app/services/store.py @@ -211,7 +211,7 @@ async def open(self, path: str | Path) -> dict: s = self.add(doc, dirty=True) _remember(p) await self._announce("opened", s) - return {**self.info(s), "imported": str(p), "warnings": warnings} + return {**self.info(s), "imported": str(p), "warnings": warnings, "report": doc["meta"]["imported"].get("report", [])} if embedded_source.can_open(p): try: doc, warnings = await asyncio.to_thread(embedded_source.open_picture, p) From 4f62ba0dd0ec0f197887e452a0e3aad12c8cbbb4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:19:09 -0500 Subject: [PATCH 085/357] feat(api): list formats, export fragments and parse binary drawings over the chemistry routes (0.7.0) GET /api/formats, POST /api/chem/export and base64 input for /api/chem/parse are what the save path, the clipboard and batch conversion call. --- backend/app/routers/chem.py | 84 +++++++++++++++++++++++++++++++++---- 1 file changed, 76 insertions(+), 8 deletions(-) diff --git a/backend/app/routers/chem.py b/backend/app/routers/chem.py index d9667eef..c294f66e 100644 --- a/backend/app/routers/chem.py +++ b/backend/app/routers/chem.py @@ -1,8 +1,12 @@ +import asyncio +import base64 +import binascii +import json import math from fastapi import APIRouter, HTTPException -from app.services.chem import DEFAULT_BOND_LENGTH, ENGINE, derive, io, layout, mass, perceive +from app.services.chem import DEFAULT_BOND_LENGTH, ENGINE, derive, formats, io, layout, mass, perceive, writers router = APIRouter() @@ -57,25 +61,89 @@ def _ids(body: dict, key: str) -> list[str] | None: @router.post("/api/chem/parse") def parse(body: dict) -> dict: text = body.get("text") - if not isinstance(text, str) or not text.strip(): - raise HTTPException(422, "text is required") - if len(text) > MAX_TEXT: - raise HTTPException(413, "text is too large") + packed = body.get("base64") fmt = body.get("format") if fmt is not None and fmt not in io.FORMATS and fmt != "mol": raise HTTPException(422, f"format must be one of {', '.join(io.FORMATS)}") - if fmt == "cdx": - raise HTTPException(422, "cdx is binary; open it as a file") origin = body.get("origin") if not (isinstance(origin, list) and len(origin) == 2 and all(_num(v) for v in origin)): origin = [72.0, 72.0] + at = (float(origin[0]), float(origin[1])) + if isinstance(packed, str) and packed: + if len(packed) > MAX_TEXT: + raise HTTPException(413, "the data is too large") + try: + data = base64.b64decode(packed, validate=True) + except (ValueError, binascii.Error): + raise HTTPException(422, "base64 is not valid base64") + try: + return io.read_bytes(data, fmt, _bond_length(body), at).as_dict() + except ValueError as exc: + raise HTTPException(422, str(exc)) + if not isinstance(text, str) or not text.strip(): + raise HTTPException(422, "text is required (or base64 for binary data)") + if len(text) > MAX_TEXT: + raise HTTPException(413, "text is too large") + if fmt == "cdx": + raise HTTPException(422, "cdx is binary; send it as base64 or open it as a file") try: - res = io.read_text(text, fmt, _bond_length(body), (float(origin[0]), float(origin[1]))) + res = io.read_text(text, fmt, _bond_length(body), at) except ValueError as exc: raise HTTPException(422, str(exc)) return res.as_dict() +@router.get("/api/formats") +def list_formats() -> dict: + out = formats.describe() + out["engine"] = ENGINE + return out + + +def export_options(value: object) -> dict: + if value is None: + return {} + if isinstance(value, str): + try: + value = json.loads(value) if value.strip() else {} + except ValueError: + raise HTTPException(422, "options must be a JSON object") + if not isinstance(value, dict): + raise HTTPException(422, "options must be a JSON object") + return value + + +def export_failed(exc: writers.ExportError) -> HTTPException: + return HTTPException(422, {"message": str(exc), "report": exc.report}) + + +@router.post("/api/chem/export") +async def export_fragments(body: dict) -> dict: + fmt = body.get("format") + spec = formats.get(fmt) if isinstance(fmt, str) else None + if spec is None or not spec["write"]: + raise HTTPException(422, f"format must be one of {', '.join(f['id'] for f in formats.TABLE if f['write'])}") + given = body.get("fragments") + if isinstance(given, dict): + given = list(given.values()) + if not isinstance(given, list): + raise HTTPException(422, "fragments must be a list of fragment objects") + frags = [_fragment({"fragment": f}) for f in given] + objects = body.get("objects") + if objects is not None and not isinstance(objects, (dict, list)): + raise HTTPException(422, "objects must be a map or a list of document objects") + reactions = body.get("reactions") + if reactions is not None and not isinstance(reactions, list): + raise HTTPException(422, "reactions must be a list of page reaction records") + name = body.get("name") if isinstance(body.get("name"), str) else None + try: + out = await asyncio.to_thread(writers.export_fragments, frags, spec["id"], export_options(body.get("options")), objects, reactions, + _expansions(body), name) + except writers.ExportError as exc: + raise export_failed(exc) + return out.as_json() + + @router.post("/api/chem/derive") def derive_fragment(body: dict) -> dict: frag = _fragment(body) From 17508c93db64e08e2201b640e338372865b59af6 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:19:10 -0500 Subject: [PATCH 086/357] feat(api): export an open drawing's page, selection or whole document with a suggested filename and report headers (0.7.0) GET /api/documents/{id}/export answers the file bytes with its mime type, or JSON with as=json, as agreed with the export agent. --- backend/app/routers/documents.py | 49 +++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/backend/app/routers/documents.py b/backend/app/routers/documents.py index 692e284d..d6ab84bd 100644 --- a/backend/app/routers/documents.py +++ b/backend/app/routers/documents.py @@ -1,13 +1,19 @@ import asyncio +import copy +import json from pathlib import Path +from urllib.parse import quote -from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response +from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request, Response +from fastapi.responses import JSONResponse from starlette.datastructures import UploadFile as StarletteUpload from app.core import config, files, window_key +from app.routers import chem as chem_router from app.routers.live import HANDLERS from app.services import importers, package from app.services import embedded_source +from app.services.chem import writers from app.services import ops as opsmod from app.services.hub import Client from app.services.store import STORE, StoreError @@ -193,6 +199,47 @@ def get_media(doc_id: str, media_id: str) -> Response: "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'"}) +REPORT_HEADER_LIMIT = 8192 + + +def _report_header(items: list[dict]) -> str: + keep = list(items) + while keep: + text = quote(json.dumps(keep, separators=(",", ":"))) + if len(text) <= REPORT_HEADER_LIMIT: + return text + keep = keep[: max(0, len(keep) // 2)] + more = {"code": "report_truncated", "count": len(items), "text": f"{len(items)} report items; ask with as=json for all of them.", "severity": "info"} + return quote(json.dumps([more], separators=(",", ":"))) + + +@router.get("/api/documents/{doc_id}/export") +async def export_document(doc_id: str, format: str, scope: str = "page", page: str | None = None, ids: str | None = None, + options: str | None = None, as_: str = Query("bytes", alias="as")) -> Response: + s = _session(doc_id) + with s.lock: + doc = copy.deepcopy(s.doc) + chosen = [i for i in (ids or "").split(",") if i.strip()] or None + try: + out = await asyncio.to_thread(writers.export_document, doc, format, scope, page, [i.strip() for i in chosen] if chosen else None, + chem_router.export_options(options)) + except writers.ExportError as exc: + raise chem_router.export_failed(exc) + if as_ == "json": + return JSONResponse(out.as_json()) + mime = out.mime if out.binary else f"{out.mime}; charset=utf-8" + plain = out.filename.encode("ascii", "replace").decode("ascii").replace('"', "") + headers = { + "content-disposition": f"attachment; filename=\"{plain}\"; filename*=UTF-8''{quote(out.filename)}", + "x-formchem-filename": quote(out.filename), + "x-formchem-format": out.format, + "x-formchem-report": _report_header(out.report), + "access-control-expose-headers": "x-formchem-filename, x-formchem-format, x-formchem-report, content-disposition", + "x-content-type-options": "nosniff", + } + return Response(out.body, media_type=mime, headers=headers) + + @router.get("/api/documents/{doc_id}/versions") def versions(doc_id: str) -> dict: _session(doc_id) From 9c7f9670c466a06c36f2bc62c9c63c6071f860d3 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:20:10 -0500 Subject: [PATCH 087/357] feat(ui): show an import report toast with a non-modal details panel of what was lost or changed (0.7.0) The panel reuses the structure check layout, lists each report item with its severity, code and count, and closes with Escape. --- frontend/src/ui/import-report.ts | 129 +++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 frontend/src/ui/import-report.ts diff --git a/frontend/src/ui/import-report.ts b/frontend/src/ui/import-report.ts new file mode 100644 index 00000000..7a40e634 --- /dev/null +++ b/frontend/src/ui/import-report.ts @@ -0,0 +1,129 @@ +import { t } from '../i18n'; +import { el, overlayRoot, patchList, q, setClass, setHidden, setText, setTitle } from './dom'; +import { icon } from './icons'; +import { toast } from './toast'; + +export type ReportSeverity = 'info' | 'warn' | 'error'; + +export interface ReportItem { + code: string; + count: number; + text: string; + severity: ReportSeverity; + atoms?: string[]; + bonds?: string[]; + objects?: string[]; +} + +export interface ImportedMeta { name?: string; format?: string; report?: unknown } + +const ORDER: Record = { error: 0, warn: 1, info: 2 }; +const ICONS: Record = { error: 'error', warn: 'warning', info: 'info' }; + +function clean(raw: unknown): ReportItem[] { + if (!Array.isArray(raw)) return []; + const out: ReportItem[] = []; + for (const r of raw) { + if (!r || typeof r !== 'object') continue; + const o = r as Record; + if (typeof o.code !== 'string' || typeof o.text !== 'string') continue; + const sev = o.severity === 'error' || o.severity === 'info' ? o.severity : 'warn'; + out.push({ code: o.code, text: o.text, count: typeof o.count === 'number' ? o.count : 1, severity: sev }); + } + return out.sort((a, b) => ORDER[a.severity] - ORDER[b.severity]); +} + +class ReportPanel { + readonly root: HTMLElement; + private readonly title: HTMLElement; + private readonly note: HTMLElement; + private readonly list: HTMLElement; + private readonly counts: Record; + + constructor() { + this.root = el(``); + this.title = q(this.root, '.fc-check-title'); + this.note = q(this.root, '.fc-check-scope'); + this.list = q(this.root, '.fc-check-items'); + setText(q(this.root, '.fc-check-status'), t('Nothing was changed in the file on disk. Save the drawing to keep it as a FormChem file.')); + const close = q(this.root, '[data-act="close"]'); + setTitle(close, t('Close')); + close.setAttribute('aria-label', t('Close')); + close.addEventListener('click', () => this.close()); + this.counts = { + error: q(this.root, '.fc-check-count.is-error b'), + warn: q(this.root, '.fc-check-count.is-warning b'), + info: q(this.root, '.fc-check-count.is-info b'), + }; + this.root.addEventListener('keydown', (e) => { + if (e.key !== 'Escape') return; + e.preventDefault(); + e.stopPropagation(); + this.close(); + }); + overlayRoot().appendChild(this.root); + } + + show(name: string, format: string, items: ReportItem[]): void { + setText(this.title, `${t('Import report')}: ${name}`); + this.root.setAttribute('aria-label', t('Import report')); + setText(this.note, format ? `${t('Read as')} ${format}` : ''); + setHidden(this.note, !format); + const n: Record = { error: 0, warn: 0, info: 0 }; + for (const r of items) n[r.severity]++; + for (const s of Object.keys(n) as ReportSeverity[]) { + setText(this.counts[s], String(n[s])); + setClass(this.counts[s].parentElement, 'is-zero', n[s] === 0); + } + patchList(this.list, items, { + key: (r) => r.code, + create: (r) => { + const item = el(`
`); + this.paint(item, r); + return item; + }, + update: (item, r) => this.paint(item, r), + }); + setHidden(this.root, false); + } + + close(): void { setHidden(this.root, true); } + + private paint(item: HTMLElement, r: ReportItem): void { + const host = q(item, '.fc-check-icon'); + if (host.dataset.sev !== r.severity) { + host.dataset.sev = r.severity; + host.innerHTML = icon(ICONS[r.severity], 14); + } + setClass(item, 'is-error', r.severity === 'error'); + setClass(item, 'is-warning', r.severity === 'warn'); + setClass(item, 'is-info', r.severity === 'info'); + setText(q(item, '.fc-check-msg'), r.text); + setText(q(item, '.fc-check-code'), r.count > 1 ? `${r.code} x${r.count}` : r.code); + } +} + +let panel: ReportPanel | null = null; + +export function showImportReport(name: string, format: string, raw: unknown): void { + const items = clean(raw); + if (!items.length) return; + const open = (): void => { panel ??= new ReportPanel(); panel.show(name, format, items); }; + const lost = items.filter((r) => r.severity !== 'info').length; + const text = lost ? `${name}: ${lost === 1 ? t('1 thing was lost or changed on import') : `${lost} ${t('things were lost or changed on import')}`}` : `${name}: ${t('opened with notes')}`; + toast(text, items.some((r) => r.severity === 'error') ? 'error' : 'info', { label: t('Details'), run: open }); +} + +export function showImportReportOf(name: string, meta: ImportedMeta | undefined | null): void { + if (!meta || /\.fchem$/i.test(name)) return; + showImportReport(meta.name || name, meta.format || '', meta.report); +} + +export function closeImportReport(): void { panel?.close(); } From 30cbe3294d9e968dc855c87f4ac2b3382d5837db Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:20:10 -0500 Subject: [PATCH 088/357] feat(app): show the import report after opening a foreign file and accept RD, SMARTS and CXSMILES files (0.7.0) The report comes from meta.imported on the opened drawing, so it shows for both the desktop open dialog and browser uploads, never for .fchem files. --- frontend/src/app/documents.ts | 9 ++++++--- frontend/src/ui/home.ts | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/frontend/src/app/documents.ts b/frontend/src/app/documents.ts index 95381271..e5932637 100644 --- a/frontend/src/app/documents.ts +++ b/frontend/src/app/documents.ts @@ -9,6 +9,7 @@ import { askSaveChanges, promptName } from '../ui/dialogs'; import { inTauri } from '../ui/dom'; import { chooseStructureFiles } from '../ui/home'; import { setStoichSource } from '../ui/stoich-panel'; +import { showImportReportOf, type ImportedMeta } from '../ui/import-report'; import { setDocTitle } from '../ui/titlebar'; import { toast } from '../ui/toast'; import { commandStateChanged } from './commands-shell'; @@ -26,7 +27,7 @@ export interface DocumentHooks { interface ParseAnswer { fragments?: Fragment[]; warnings?: { text?: string }[] } -const OPEN_EXTENSIONS = ['fchem', 'mol', 'mdl', 'sdf', 'sd', 'rxn', 'smi', 'smiles', 'cxsmi', 'cxsmiles', 'inchi', 'cml', 'cdxml', 'cdx', 'svg', 'png', 'pdf', 'eps']; +const OPEN_EXTENSIONS = ['fchem', 'mol', 'mdl', 'sdf', 'sd', 'rxn', 'rdf', 'rd', 'smi', 'smiles', 'cxsmi', 'cxsmiles', 'sma', 'smarts', 'inchi', 'cml', 'cdxml', 'cdx', 'svg', 'png', 'pdf', 'eps']; const UPLOAD_URL = '/api/documents/upload'; const PARSE_URL = '/api/chem/parse'; @@ -78,7 +79,9 @@ export class DocumentActions { async openPath(path: string): Promise { try { - return await session.open(path); + const client = await session.open(path); + showImportReportOf(path.split(/[\\/]/).pop() ?? path, client.doc.meta.imported as ImportedMeta | undefined); + return client; } catch (e) { toast(`${t('Could not open')} ${stem(path)}: ${errText(e)}`, 'error'); return null; @@ -91,7 +94,7 @@ export class DocumentActions { const info = await upload<{ id: string; warnings?: unknown[] }>(UPLOAD_URL, [file], 'file'); const client = await session.attach(info.id); session.activate(client.id); - if (Array.isArray(info.warnings) && info.warnings.length) toast(`${file.name}: ${String(info.warnings[0])}`); + showImportReportOf(file.name, client.doc.meta.imported as ImportedMeta | undefined); } catch (e) { toast(`${t('Could not open')} ${file.name}: ${errText(e)}`, 'error'); } diff --git a/frontend/src/ui/home.ts b/frontend/src/ui/home.ts index bd2b651d..c5296b70 100644 --- a/frontend/src/ui/home.ts +++ b/frontend/src/ui/home.ts @@ -35,7 +35,7 @@ const RECENT_ON_START = 8; const FORMATS = ['FCHEM', 'MOL', 'SDF', 'RXN', 'SMILES', 'CDXML', 'CDX', 'CML', 'CIF', 'PDB', 'JDX']; const KINDS: ListKind[] = ['recent', 'templates', 'databases', 'trash']; -export const STRUCTURE_ACCEPT = '.fchem,.mol,.sdf,.sd,.rxn,.rdf,.smi,.smiles,.cdxml,.cdx,.cml,.cif,.pdb,.jdx,.dx,.svg,.png,.pdf,.eps'; +export const STRUCTURE_ACCEPT = '.fchem,.mol,.mdl,.sdf,.sd,.rxn,.rdf,.rd,.smi,.smiles,.cxsmi,.cxsmiles,.sma,.smarts,.inchi,.cdxml,.cdx,.cml,.cif,.pdb,.jdx,.dx,.svg,.png,.pdf,.eps'; export function chooseStructureFiles(multiple = true): Promise { return new Promise((resolve) => { From ec713b125da24d74c418cf97d1bc03cdb5853239 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:27:56 -0500 Subject: [PATCH 089/357] fix(chem): keep absolute stereo, salts, atom lists and arrow heads through the drawing formats (0.7.0) The round-trip corpus showed Indigo reading molecules as reactions, adding racemic groups without a chiral flag and dropping element lists; names, R-groups and curved arrows now show in the export report. --- backend/app/services/chem/cdxio.py | 57 ++++++++++++++++++++++++---- backend/app/services/chem/formats.py | 4 +- 2 files changed, 51 insertions(+), 10 deletions(-) diff --git a/backend/app/services/chem/cdxio.py b/backend/app/services/chem/cdxio.py index cb0f0593..024da170 100644 --- a/backend/app/services/chem/cdxio.py +++ b/backend/app/services/chem/cdxio.py @@ -8,6 +8,7 @@ from app.services.chem import DEFAULT_BOND_LENGTH, convert, geometry, query, report, warning from app.services.chem.reactions import fresh_id +from app.services.model import ELEMENTS CDXML_UNIT = 30.0 PX_PER_PT = 1.5 @@ -20,7 +21,7 @@ "fishhook": "elliptical-arc-arrow-open-half-angle", } KET_TO_ARROW = { - "open-angle": ("forward", "open"), "filled-triangle": ("forward", "full"), "filled-bow": ("forward", "full"), + "open-angle": ("forward", "full"), "filled-triangle": ("forward", "full"), "filled-bow": ("forward", "full"), "dashed-open-angle": ("dashed", "open"), "failed": ("nogo_cross", "full"), "retrosynthetic": ("retro", "open"), "both-ends-filled-triangle": ("resonance", "full"), "equilibrium-filled-half-bow": ("equilibrium", "half_left"), "equilibrium-filled-triangle": ("reversible", "full"), "equilibrium-open-angle": ("equilibrium", "half_left"), @@ -62,7 +63,7 @@ def _load(ind, source: str | bytes, is_path: bool): source, is_path = tmp, True try: last = None - for name in ("loadReaction", "loadMolecule", "loadQueryReaction", "loadQueryMolecule"): + for name in ("loadMolecule", "loadReaction", "loadQueryMolecule", "loadQueryReaction"): fn = getattr(ind, name + ("FromFile" if is_path else "")) try: return fn(source) @@ -97,7 +98,9 @@ def _runs(content: str) -> list[dict]: if style.startswith(FONT_SIZE): digits = style[len(FONT_SIZE):].rstrip("px") try: - marks[i]["size"] = round(float(digits) / PX_PER_PT, 2) + size = round(float(digits) / PX_PER_PT, 2) + if abs(size - geometry.DEFAULT_FONT) > 0.05: + marks[i]["size"] = size except ValueError: pass else: @@ -229,6 +232,16 @@ def read(source: str | bytes, is_path: bool, fmt: str, bond_length: float = DEFA if mol is None: continue frag = convert.from_mol(mol, bond_length, (0.0, 0.0), used=used) + for a in frag["atoms"].values(): + listed = str(a.get("label") or "").split(",") + if a.get("element") == "*" and len(listed) > 1 and all(s in ELEMENTS for s in listed): + a.pop("label") + a.pop("hydrogens", None) + a["query"] = {"list": listed} + groups = frag.get("stereo_groups") or [] + if groups and all(g.get("kind") == "abs" for g in groups): + frag.pop("stereo_groups") + frag["chiral"] = "absolute" xs = [_xy(a["location"]) for a in m.get("atoms") or [] if "location" in a] if xs: left, top = frame.page(min(p[0] for p in xs), max(p[1] for p in xs)) @@ -283,6 +296,8 @@ def _mol_node(ind, frag: dict, expansions: dict | None, members: dict | None, bl else: mol, more = io._writable(frag, expansions) notes.extend(more) + if frag.get("chiral") not in ("relative", "racemic"): + mol.SetIntProp("_MolFileChiralFlag", 1) block = Chem.MolToV3KMolBlock(mol, includeStereo=True, kekulize=True) loaders = ("loadMolecule", "loadQueryMolecule") block = _rescale(block, frag) @@ -290,14 +305,29 @@ def _mol_node(ind, frag: dict, expansions: dict | None, members: dict | None, bl for name in loaders: try: ket = json.loads(getattr(ind, name)(block).json()) - return [ket[n["$ref"]] for n in ket["root"]["nodes"] if n.get("$ref") in ket] + [ - {"$rg": ket[k]} for k in ket if k.startswith("rg")] except Exception as exc: last = exc + continue + mols = [ket[n["$ref"]] for n in ket["root"]["nodes"] if (ket.get(n.get("$ref")) or {}).get("type") == "molecule"] + return _joined(mols) + [{"$rg": ket[k]} for k in ket if k.startswith("rg")] notes.append(warning("structure_dropped", f"A structure could not be converted ({last}).")) return [] +def _joined(mols: list[dict]) -> list[dict]: + if len(mols) < 2 or any(set(m) - {"type", "atoms", "bonds", "stereoFlagPosition"} for m in mols): + return mols + out: dict = {"type": "molecule", "atoms": [], "bonds": []} + for m in mols: + base = len(out["atoms"]) + out["atoms"].extend(m.get("atoms") or []) + for b in m.get("bonds") or []: + out["bonds"].append({**b, "atoms": [i + base for i in b.get("atoms") or []]}) + if mols[0].get("stereoFlagPosition"): + out["stereoFlagPosition"] = mols[0]["stereoFlagPosition"] + return [out] + + def _rescale(block: str, frag: dict) -> str: from app.services.chem import v3000 f = convert.median_bond_length(frag) / (convert.MOL_BOND_LENGTH * CDXML_UNIT) @@ -345,8 +375,13 @@ def write(fragments: list[dict], objects: list[dict], style: dict, expansions: d for key, body in rgroups.items(): ket[key] = body ket["root"]["nodes"].append({"$ref": key}) + from app.services.chem import io + split = sum(1 for f in fragments if len(io.split_components(dict(f))) > 1) + if split: + notes.append(report.item("components_split", split, f"{split} structure{'s have' if split > 1 else ' has'} disconnected parts (a salt or a mixture); reading the file back gives one structure per part.", severity="info")) has_arrow = False lost: dict[str, list[str]] = {} + bent: list[str] = [] base = float((style.get("caption_font") or {}).get("size") or geometry.DEFAULT_FONT) for obj in objects: kind = obj.get("kind") @@ -364,6 +399,8 @@ def write(fragments: list[dict], objects: list[dict], style: dict, expansions: d mode = "open-angle" ket["root"]["nodes"].append({"type": "arrow", "data": {"mode": mode, "pos": [_ket_point(*pts[0]), _ket_point(*pts[1])]}}) has_arrow = True + if obj.get("bend") or obj.get("type") in ("curved", "arc", "fishhook"): + bent.append(obj["id"]) elif kind in TEXT_KINDS: runs = [r for r in obj.get("runs") or [] if isinstance(r, dict)] if not _plain(runs).strip(): @@ -378,6 +415,8 @@ def write(fragments: list[dict], objects: list[dict], style: dict, expansions: d lost.setdefault("text font or colour", []).append(obj["id"]) elif kind not in ("fragment", "group"): lost.setdefault(str(kind), []).append(obj["id"]) + if bent: + notes.append(report.item("arrow_straightened", len(bent), f"{len(bent)} curved arrow{'s are' if len(bent) > 1 else ' is'} written straight; reading the file back can see {'them' if len(bent) > 1 else 'it'} as a reaction arrow.", objects=bent)) for name, ids_ in sorted(lost.items()): notes.append(report.item("graphics_dropped", len(ids_), f"{len(ids_)} {name}{'s' if len(ids_) > 1 else ''} not written: the format bridge cannot store {'it' if len(ids_) == 1 else 'them'}.", objects=ids_)) if any(f.get("data") for f in fragments): @@ -406,6 +445,8 @@ def write(fragments: list[dict], objects: list[dict], style: dict, expansions: d if doc is None: raise ValueError("the drawing could not be converted") notes.append(report.item("styles_dropped", 1, "Colours, fonts, bond styles and the page setup are not written; Indigo writes its own defaults.")) - if binary: - return base64.b64decode(doc.b64cdx()), notes - return doc.cdxml(), notes + try: + out = base64.b64decode(doc.b64cdx()) if binary else doc.cdxml() + except Exception as exc: + raise ValueError(f"Indigo cannot write this drawing ({exc})") from exc + return out, notes diff --git a/backend/app/services/chem/formats.py b/backend/app/services/chem/formats.py index 501b5ea5..e0fce8ba 100644 --- a/backend/app/services/chem/formats.py +++ b/backend/app/services/chem/formats.py @@ -57,10 +57,10 @@ "loses": ["text", "graphics", "layout", "enhanced_stereo", "query", "rgroups", "abbreviations", "maps", "styles"]}, {"id": "cdxml", "name": "CDXML drawing", "extensions": [".cdxml"], "mime": "chemical/x-cdxml", "read": True, "write": True, "multi": True, "reactions": True, "options": {}, - "loses": ["abbreviations", "data", "styles"]}, + "loses": ["rgroups", "abbreviations", "data", "names", "styles"]}, {"id": "cdx", "name": "CDX drawing", "extensions": [".cdx"], "mime": "chemical/x-cdx", "read": True, "write": True, "binary": True, "multi": True, "reactions": True, "options": {}, - "loses": ["abbreviations", "data", "styles"]}, + "loses": ["rgroups", "abbreviations", "data", "names", "styles"]}, ] BY_ID = {f["id"]: f for f in TABLE} ALIASES = {"mol": "molfile", "mdl": "molfile", "v3000": "molfile3000", "sd": "sdf", "rd": "rdf", "smi": "smiles", "cxsmi": "cxsmiles", From ed925e6dd2ee95d40fff78a5aab753dbcabfe15f Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:27:57 -0500 Subject: [PATCH 090/357] fix(query): write SMARTS chirality that reads back the same and draw SMARTS chirality as wedges (0.7.0) RDKit writes some three-coordinate centres of a query with the opposite parity; the writer checks the text against the query and inverts those centres, and the reader wedges the centres it reads. --- backend/app/services/chem/query.py | 59 ++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 4 deletions(-) diff --git a/backend/app/services/chem/query.py b/backend/app/services/chem/query.py index 97ebecf1..5da9744b 100644 --- a/backend/app/services/chem/query.py +++ b/backend/app/services/chem/query.py @@ -156,7 +156,49 @@ def to_smarts(frag: dict, expansions: dict | None = None, atoms: list[str] | Non notes.append(warning("smarts_rgroups", "SMARTS cannot hold R-group definitions or their logic; R-groups are written as any atom.")) if frag.get("stereo_groups"): notes.append(warning("smarts_stereo_groups", "SMARTS cannot hold enhanced stereo groups.")) - return Chem.MolToSmarts(qm), notes + return smarts_text(qm), notes + + +TETRA = (Chem.ChiralType.CHI_TETRAHEDRAL_CW, Chem.ChiralType.CHI_TETRAHEDRAL_CCW) + + +def _odd(seq: list[int]) -> bool: + return sum(1 for i in range(len(seq)) for j in range(i + 1, len(seq)) if seq[i] > seq[j]) % 2 == 1 + + +def _wrong_centres(qm: Chem.Mol, written: Chem.Mol, text: str) -> list[int] | None: + try: + order = [int(x) for x in written.GetProp("_smilesAtomOutputOrder").strip("[]").split(",") if x.strip()] + back = Chem.MolFromSmarts(text) + except Exception: + return None + if back is None or back.GetNumAtoms() != len(order): + return None + wrong = [] + for i, qi in enumerate(order): + a, b = qm.GetAtomWithIdx(qi), back.GetAtomWithIdx(i) + if a.GetChiralTag() not in TETRA or b.GetChiralTag() not in TETRA: + continue + pos = {n.GetIdx(): k for k, n in enumerate(a.GetNeighbors())} + seq = [pos.get(order[n.GetIdx()], -1) for n in b.GetNeighbors()] + if -1 not in seq and _odd(seq) == (a.GetChiralTag() == b.GetChiralTag()): + wrong.append(qi) + return wrong + + +def smarts_text(qm: Chem.Mol) -> str: + first = Chem.RWMol(qm) + text = Chem.MolToSmarts(first) + if not any(a.GetChiralTag() in TETRA for a in qm.GetAtoms()): + return text + wrong = _wrong_centres(qm, first, text) + if not wrong: + return text + fixed = Chem.RWMol(qm) + for i in wrong: + fixed.GetAtomWithIdx(i).InvertChirality() + again = Chem.MolToSmarts(fixed) + return again if _wrong_centres(qm, fixed, again) == [] else text PRIMITIVE_LETTERS = {"A", "D", "H", "R", "X"} @@ -305,9 +347,12 @@ def fresh(prefix: str) -> str: rec = {"id": aid, "x": x, "y": y, **found} if not rec["query"]: del rec["query"] - if a.GetChiralTag() != Chem.ChiralType.CHI_UNSPECIFIED: - notes.append(warning("smarts_chirality", "Chirality in the SMARTS is not drawn; set it with wedges.", [aid])) frag["atoms"][aid] = rec + wedges = convert._wedges_from_mol(mol) if any(a.GetChiralTag() != Chem.ChiralType.CHI_UNSPECIFIED for a in mol.GetAtoms()) else {} + wedged = {w[1] for w in wedges.values() if w[0] in ("wedge", "hash")} + for a in mol.GetAtoms(): + if a.GetChiralTag() != Chem.ChiralType.CHI_UNSPECIFIED and a.GetIdx() not in wedged: + notes.append(warning("smarts_chirality", "Chirality in the SMARTS is not drawn; set it with wedges.", [ids[a.GetIdx()]])) if opaque: notes.append(warning("smarts_opaque", "These atoms keep their SMARTS text as an opaque query.", opaque)) for b in mol.GetBonds(): @@ -325,7 +370,13 @@ def fresh(prefix: str) -> str: order, q = BOND_FROM_SMARTS.get(base, (1, None)) if base not in BOND_FROM_SMARTS: notes.append(warning("smarts_bond_simplified", f"The bond query {text_b} is read as a single bond.", bonds=[bid])) - rec = {"id": bid, "a": ids[b.GetBeginAtomIdx()], "b": ids[b.GetEndAtomIdx()], "order": order} + i, j = b.GetBeginAtomIdx(), b.GetEndAtomIdx() + wedge = wedges.get(b.GetIdx()) + if wedge and wedge[0] in ("wedge", "hash") and wedge[1] == j: + i, j = j, i + rec = {"id": bid, "a": ids[i], "b": ids[j], "order": order} + if wedge and wedge[0] in ("wedge", "hash") and order == 1: + rec["stereo"] = wedge[0] if q: rec["query"] = q if topo: From e98c63fbab2a77dfb2e9a2f6093022bcaeb3365e Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:27:57 -0500 Subject: [PATCH 091/357] fix(chem): draw amides read from InChI as amides and stop counting stereo flag symbols as unread (0.7.0) InChI to structure gives iminol tautomers for amides, which changed Taxol on a round trip; the reader turns them back into amides. --- backend/app/services/chem/io.py | 36 ++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/backend/app/services/chem/io.py b/backend/app/services/chem/io.py index 517808c2..d1c9c157 100644 --- a/backend/app/services/chem/io.py +++ b/backend/app/services/chem/io.py @@ -416,6 +416,39 @@ def _read_rsmiles(text: str, res: ParseResult, row: _Row) -> None: res.warnings.append(counted("coordinates_generated", "Reaction SMILES has no coordinates; a 2D layout was generated.", 1)) +IMINOL = Chem.MolFromSmarts("[OX2H1]-[CX3;!R]=[NX2;!R]") + + +def amide_form(mol: Chem.Mol) -> Chem.Mol: + matches = mol.GetSubstructMatches(IMINOL) + if not matches: + return mol + rw = Chem.RWMol(mol) + seen: set[int] = set() + for o, c, n in matches: + if {o, c, n} & seen: + continue + seen.update((o, c, n)) + rw.GetBondBetweenAtoms(o, c).SetBondType(Chem.BondType.DOUBLE) + cn = rw.GetBondBetweenAtoms(c, n) + cn.SetBondType(Chem.BondType.SINGLE) + cn.SetStereo(Chem.BondStereo.STEREONONE) + for i in (o, n): + atom = rw.GetAtomWithIdx(i) + atom.SetNumExplicitHs(0) + atom.SetNoImplicit(False) + for b in rw.GetBonds(): + if b.GetBondDir() in (Chem.BondDir.ENDUPRIGHT, Chem.BondDir.ENDDOWNRIGHT) and (b.GetBeginAtomIdx() in seen or b.GetEndAtomIdx() in seen): + b.SetBondDir(Chem.BondDir.NONE) + out = rw.GetMol() + try: + Chem.SanitizeMol(out) + Chem.AssignStereochemistry(out, cleanIt=True, force=True) + except Exception: + return mol + return out + + def _read_inchi(text: str, res: ParseResult, row: _Row) -> None: n_read = 0 for n, line in enumerate(l.strip() for l in text.splitlines() if l.strip()): @@ -426,6 +459,7 @@ def _read_inchi(text: str, res: ParseResult, row: _Row) -> None: if mol is None: res.warnings.append(warning("parse_failed", f"line {n + 1}: not a readable InChI.")) continue + mol = amide_form(mol) name = line[len(token):].strip() or None res.fragments.append(row.place(mol, name)) n_read += 1 @@ -720,7 +754,7 @@ def _cdxml_unread(text: str) -> list[dict]: for el in root.iter(): tag = _local(el.tag).lower() name = CDXML_UNREAD.get(tag) - if tag == "graphic" and el.get("SymbolType") != "Plus" and not el.get("ArrowType"): + if tag == "graphic" and el.get("SymbolType") not in ("Plus", "Absolute", "Relative", "Racemic") and not el.get("ArrowType"): name = f"{(el.get('GraphicType') or 'graphic').lower()} graphic" if name: counts[name] = counts.get(name, 0) + 1 From 703dd24f3cc46a852d43d48c53bf69d6077fa2a2 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:27:58 -0500 Subject: [PATCH 092/357] fix(reactions): join a step's starting material to the same product of the previous step when a scheme is read (0.7.0) RD files and SMILES write each step on its own, so a two-step scheme came back with its intermediate drawn twice. --- backend/app/services/chem/scheme.py | 37 ++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/backend/app/services/chem/scheme.py b/backend/app/services/chem/scheme.py index cb5253da..4aa1567f 100644 --- a/backend/app/services/chem/scheme.py +++ b/backend/app/services/chem/scheme.py @@ -1,7 +1,7 @@ import math from app.services import model -from app.services.chem import DEFAULT_BOND_LENGTH, geometry, io, warning +from app.services.chem import DEFAULT_BOND_LENGTH, geometry, ids, io, perceive, warning from app.services.chem.reactions import ReactionError, fresh_id, used_ids GAP_BONDS = 1.0 @@ -138,6 +138,34 @@ def side(items: list[dict], x: float) -> float: return {"objects": objects, "reaction": {"id": fresh_id(used, "r"), "steps": [step]}, "warnings": notes} +def _same_key(frag: dict) -> str | None: + try: + return ids.smiles(ids.identifier_mol(perceive.prepare(frag).mol)) or None + except Exception: + return None + + +def _joined_steps(steps: list[dict], frags: dict[str, dict]) -> tuple[list[dict], set[str]]: + out = [dict(s) for s in steps] + dropped: set[str] = set() + for k in range(1, len(out)): + made = {} + for i in out[k - 1].get("products") or []: + key = _same_key(frags[i]) if i in frags else None + if key: + made.setdefault(key, i) + joined = [] + for i in out[k].get("reactants") or []: + key = _same_key(frags[i]) if i in frags and made else None + if key in made and made[key] != i: + dropped.add(i) + joined.append(made.pop(key)) + else: + joined.append(i) + out[k]["reactants"] = joined + return out, dropped + + def layout_steps(parsed: io.ParseResult, bond_length: float = DEFAULT_BOND_LENGTH, origin: tuple[float, float] = (72.0, 72.0), used: set[str] | None = None) -> dict: used = used if used is not None else set() @@ -152,7 +180,8 @@ def layout_steps(parsed: io.ParseResult, bond_length: float = DEFAULT_BOND_LENGT x0, top = origin x, cy, row_bottom = x0, 0.0, top previous: list[str] = [] - for roles in parsed.reactions: + reactions, dropped = _joined_steps(parsed.reactions, frags) + for roles in reactions: reactants = [frags[i] for i in roles.get("reactants") or [] if i in frags] products = [frags[i] for i in roles.get("products") or [] if i in frags] agents = [frags[i] for i in roles.get("agents") or [] if i in frags] @@ -213,7 +242,7 @@ def layout_steps(parsed: io.ParseResult, bond_length: float = DEFAULT_BOND_LENGT previous = [f["id"] for f in products] x = x0 for f in parsed.fragments: - if f["id"] in placed: + if f["id"] in placed or f["id"] in dropped: continue b = p.box(f) _move(f, x - b[0], row_bottom - b[1]) @@ -221,6 +250,8 @@ def layout_steps(parsed: io.ParseResult, bond_length: float = DEFAULT_BOND_LENGT objects.append(f) renamed = {} for f in parsed.fragments: + if f["id"] in dropped: + continue old = f["id"] _claim(f, used) renamed[old] = f["id"] From 24117ff534c0d4dcb96f4f0660490ac1ea30a5c2 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:27:58 -0500 Subject: [PATCH 093/357] fix(chem): embed R-group members in RD file records and report a dropped conditions text once (0.7.0) Markush members were written both inside the V3000 record and as records of their own, so reading the file back doubled them. --- backend/app/services/chem/writers.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/app/services/chem/writers.py b/backend/app/services/chem/writers.py index 3eb14a57..aa42d000 100644 --- a/backend/app/services/chem/writers.py +++ b/backend/app/services/chem/writers.py @@ -192,7 +192,7 @@ def note_losses(self, frags: list[dict], lost: list[str]) -> None: def note_annotations(self) -> None: written_arrows = {s.get("arrow") for s in self.steps_written} - conditions = {c for s in self.steps_written for c in s.get("conditions") or []} if self.conditions_written else set() + conditions = {c for s in self.steps_written for c in s.get("conditions") or []} roles = {i for s in self.steps_written for k in ("reactants", "products", "agents") for i in s.get(k) or []} text, other = [], [] for obj in self.sc.annotations: @@ -353,7 +353,7 @@ def _write_rdf(w: _Writer) -> str: frags_all.extend(sf) in_steps.update(f["id"] for f in sf) records.append({"kind": "rxn", "block": text, "conditions": _conditions(w.sc.doc, step)}) - for f in w.structures(False): + for f in w.structures(w.version != "v2000"): if f["id"] in in_steps: continue version = "v3000" if w.version == "v3000" or (w.version == "auto" and needs_v3000(f)) else "v2000" From 8a6c1f74d69849f4313da134db671fbc023618da Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:29:18 -0500 Subject: [PATCH 094/357] perf(chem): stream SD, SMILES, InChI and RD files record by record for batch conversion with per-record failures (0.7.0) Converting 10,000 SD records to SMILES takes under a second this way, because batch conversion does not build drawable fragments; each failed record keeps its number, name and the reason. --- backend/app/services/chem/stream.py | 184 ++++++++++++++++++++++++++++ 1 file changed, 184 insertions(+) create mode 100644 backend/app/services/chem/stream.py diff --git a/backend/app/services/chem/stream.py b/backend/app/services/chem/stream.py new file mode 100644 index 00000000..16772b0d --- /dev/null +++ b/backend/app/services/chem/stream.py @@ -0,0 +1,184 @@ +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import IO, Iterator + +from rdkit import Chem + +from app.services.chem import ids, io + +STREAMED = ("sdf", "smiles", "cxsmiles", "inchi", "rdf", "molfile") +TARGETS = ("smiles", "cxsmiles", "inchi", "inchikey", "sdf", "molfile") + + +@dataclass +class Record: + index: int + mol: Chem.Mol | None + name: str = "" + block: str = "" + error: str = "" + extra: dict = field(default_factory=dict) + + @property + def data(self) -> dict: + if "data" not in self.extra: + self.extra["data"] = io.sd_fields(self.block)[1] if self.block else {} + return self.extra["data"] + + +def _sd_blocks(lines: Iterator[str]) -> Iterator[str]: + buf: list[str] = [] + for line in lines: + if line.rstrip("\r\n") == "$$$$": + if any(l.strip() for l in buf): + yield "".join(buf) + buf = [] + else: + buf.append(line) + if any(l.strip() for l in buf): + yield "".join(buf) + + +def _why(block: str) -> str: + raw = Chem.MolFromMolBlock(block, sanitize=False, removeHs=False, strictParsing=False) + if raw is None: + return "not a readable connection table" + try: + Chem.SanitizeMol(raw) + except Exception as exc: + return str(exc).strip().splitlines()[0] if str(exc).strip() else exc.__class__.__name__ + return "could not be read" + + +def _molblock(i: int, block: str) -> Record: + text = block.replace("\r\n", "\n") + mol = Chem.MolFromMolBlock(text, strictParsing=False) + name = text.split("\n", 1)[0].strip() + if mol is None: + return Record(i, None, name, text, _why(text)) + return Record(i, mol, name, text) + + +def _is_file(source: object) -> bool: + if isinstance(source, Path): + return source.is_file() + if not isinstance(source, str) or "\n" in source or len(source) > 4096: + return False + try: + return Path(source).is_file() + except OSError: + return False + + +def _lines_of(source: str | Path | IO[str]) -> Iterator[str]: + if _is_file(source): + with open(source, "r", encoding="utf-8-sig", errors="replace", newline="") as fh: + yield from fh + return + if hasattr(source, "read"): + yield from source + return + yield from str(source).splitlines(keepends=True) + + +def kind_of(path: str | Path) -> str | None: + return io.EXTENSIONS.get(Path(str(path)).suffix.lower()) + + +def iter_records(source: str | Path | IO[str], fmt: str | None = None) -> Iterator[Record]: + kind = fmt or (kind_of(source) if _is_file(source) else None) + lines = _lines_of(source) + if kind is None: + head = [] + for line in lines: + head.append(line) + if len(head) > 200: + break + kind = io.detect("".join(head)) + lines = iter(head + list(lines)) + if kind in ("sdf", "molfile"): + for i, block in enumerate(_sd_blocks(lines)): + yield _molblock(i, block) + elif kind in ("smiles", "cxsmiles"): + params = io._smiles_params(True) + for i, line in enumerate(l for l in lines if l.strip()): + text = line.strip() + mol = Chem.MolFromSmiles(text, params) + name = mol.GetProp("_Name").strip() if mol is not None and mol.HasProp("_Name") else "" + if mol is None: + raw = Chem.MolFromSmiles(text, io._smiles_params(False)) + yield Record(i, None, "", text, "not a valid SMILES" if raw is None else _sanitize_error(raw)) + else: + yield Record(i, mol, name, "") + elif kind == "inchi": + for i, line in enumerate(l for l in lines if l.strip()): + token = line.split()[0] + mol = Chem.MolFromInchi(token) if token.startswith("InChI=") else None + yield Record(i, io.amide_form(mol) if mol is not None else None, line[len(token):].strip(), "", "" if mol is not None else "not a readable InChI") + elif kind == "rdf": + from app.services.chem import rdfio + for i, rec in enumerate(rdfio.parse("".join(lines))): + if rec.kind == "rxn": + yield Record(i, None, "", rec.block, "a reaction record (convert reactions with the reaction formats)", {"data": rec.data}) + else: + r = _molblock(i, rec.block) + r.extra["data"] = rec.data + yield r + else: + raise ValueError(f"{kind} files cannot be streamed record by record") + + +def _sanitize_error(mol: Chem.Mol) -> str: + try: + Chem.SanitizeMol(mol) + except Exception as exc: + return str(exc).strip().splitlines()[0] if str(exc).strip() else exc.__class__.__name__ + return "could not be read" + + +def write_record(rec: Record, to: str) -> str: + mol = rec.mol + if to == "smiles": + text = Chem.MolToSmiles(mol) + return f"{text} {rec.name}" if rec.name else text + if to == "cxsmiles": + text = Chem.MolToCXSmiles(mol, Chem.SmilesWriteParams(), ids.CX_FLAGS) + return f"{text} {rec.name}" if rec.name else text + if to in ("inchi", "inchikey"): + inchi, key, notes = ids.inchi(mol) + if not inchi: + raise ValueError(notes[0]["text"] if notes else "no InChI") + return key if to == "inchikey" else inchi + if to in ("sdf", "molfile"): + block = Chem.MolToMolBlock(mol) + if to == "sdf": + fields = "".join(f"> <{k}>\n{v}\n\n" for k, v in rec.data.items()) + return block + fields + "$$$$" + return block + raise ValueError(f"cannot write {to} record by record") + + +def convert(source: str | Path | IO[str], to: str, out: IO[str] | None = None, fmt: str | None = None, + limit: int | None = None) -> dict: + if to not in TARGETS: + raise ValueError(f"to must be one of {', '.join(TARGETS)}") + start = time.perf_counter() + read = written = 0 + failed: list[dict] = [] + for rec in iter_records(source, fmt): + if limit is not None and read >= limit: + break + read += 1 + if rec.mol is None: + failed.append({"index": rec.index, "record": rec.index + 1, "name": rec.name, "error": rec.error}) + continue + try: + line = write_record(rec, to) + except Exception as exc: + failed.append({"index": rec.index, "record": rec.index + 1, "name": rec.name, "error": str(exc) or exc.__class__.__name__}) + continue + written += 1 + if out is not None: + out.write(line + "\n") + return {"records": read, "written": written, "failed": failed, "seconds": round(time.perf_counter() - start, 3), "to": to} From acfdf89e3bccc6571d8195b09644fee7690a0a26 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 23:05:49 -0500 Subject: [PATCH 095/357] feat(format): add the optional style.grid field for a drawing's page grid (0.7.0) A drawing now keeps its grid type, spacing, major lines and strength so it reopens with the same grid; the field is optional, documents without it load unchanged and follow the window default. --- backend/app/services/model.py | 8 ++++++++ docs/FORMAT.md | 18 ++++++++++++++++++ frontend/src/engine/model.ts | 4 ++++ 3 files changed, 30 insertions(+) diff --git a/backend/app/services/model.py b/backend/app/services/model.py index 71aa9551..943e7925 100644 --- a/backend/app/services/model.py +++ b/backend/app/services/model.py @@ -25,6 +25,13 @@ class Font(TypedDict): italic: NotRequired[bool] +class Grid(TypedDict, total=False): + type: Literal["lines", "dots", "crosses", "isometric", "isometric-dots", "hex", "hex-dots"] + spacing: float | Literal["bond"] + major: int + strength: Literal["faint", "normal", "strong"] + + class Style(TypedDict, total=False): preset: str chain_angle: float @@ -47,6 +54,7 @@ class Style(TypedDict, total=False): lone_pair: Literal["dots", "bar"] color_by_element: bool stereo_labels: Literal["none", "cip", "cip_enhanced"] + grid: Grid class Atom(TypedDict): diff --git a/docs/FORMAT.md b/docs/FORMAT.md index ed99b9ee..207f0428 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -107,9 +107,27 @@ The document has exactly one active style. Every field is optional in the file; | `lone_pair` | enum | `"dots"` | `"dots"` or `"bar"` | | `color_by_element` | boolean | false | CPK-like colours for labels | | `stereo_labels` | enum | `"none"` | `"none"`, `"cip"` (R, S, E, Z) or `"cip_enhanced"` (also abs, and, or groups). Built from 0.6.0 | +| `grid` | grid | absent | the drawing's page grid (see Grid below). Absent: the window shows its own default grid. Built from 0.7.0 | A font is `{ "family": "Arimo", "size": 10, "bold": false, "italic": false }` (size in points). Arimo stands in for Arial and Helvetica and Tinos for Times; a reader that meets `Arial`, `Helvetica`, `Times` or `Times New Roman` in an imported file maps them to these families when the originals are missing, so output measures the same on every system. Both families ship with FormChem under the SIL Open Font License 1.1 (not Apache-2.0); their licence files sit beside the font files in `frontend/public/fonts`. +### Grid + +Built from 0.7.0. `style.grid` is optional and only ever read from the document's own style (an object's `style` never sets a grid, and presets carry none). It changes how the page looks on screen and where snapping puts things; it never changes export, printing or the chemistry. A document without it opens unchanged and shows the window's default grid (Preferences > Drawing > Grid). Setting it is one `set` op on `["style", "grid"]`, so changing the grid is one undo step. + +```json +"style": { "preset": "journal-1996", "grid": { "type": "isometric", "spacing": "bond", "major": 5, "strength": "normal" } } +``` + +| Field | Unit | Default | Meaning | +| --- | --- | --- | --- | +| `type` | enum | `"lines"` | `"lines"` (square lines), `"dots"` (square dots), `"crosses"` (small plus marks at square intersections), `"isometric"` (triangular lines at 30, 90 and 150 degrees), `"isometric-dots"`, `"hex"` (hexagon edges) or `"hex-dots"` (hexagon corners) | +| `spacing` | pt or `"bond"` | 7.2 for the square types, `"bond"` for the others | distance between neighbouring grid points: a number of points (1 to 288), or `"bond"` for the style's `bond_length`. For the isometric and hex types it is the side of a triangle or hexagon, so a chain or a six-membered ring drawn at the bond length lands on grid points | +| `major` | count | 5 | a stronger line or point every this many cells; 0 or 1 for none. The hex types have no major lines | +| `strength` | enum | `"normal"` | `"faint"`, `"normal"` or `"strong"` | + +Grid points are measured from the page origin (its top-left corner). For the square types they are `(i s, j s)`. For the isometric types, with `w = s * sqrt(3) / 2`, they are `(a w, a s / 2 + b s)` for integers `a` and `b`; the hex types use the same points except those where `(a - b) mod 3` is 2, which are the hexagon centres. Lengths are shown to the person in `units`; storage is always points. A reader that meets an unknown `type` or `strength` uses the default. + Values derived from the style and never stored: the wedge wide end (1.5 x `bold_width`), sub- and superscript size (75 percent of the font size, baseline shift down 25 percent or up 40 percent), default arrow length (4 x `bond_length`), plus sign size (0.6 x `bond_length`), charge and radical distance from an unlabelled atom (0.4 x `bond_length`), lone pair distance (0.33 x `bond_length`), atom and map number text (70 percent of the label size). ### Built-in presets diff --git a/frontend/src/engine/model.ts b/frontend/src/engine/model.ts index 3201b2ec..711d71a1 100644 --- a/frontend/src/engine/model.ts +++ b/frontend/src/engine/model.ts @@ -11,6 +11,9 @@ export type Units = 'pt' | 'mm' | 'cm' | 'in'; export type TerminalCarbon = 'line' | 'ch3' | 'me'; export type LonePairStyle = 'dots' | 'bar'; export type StereoLabels = 'none' | 'cip' | 'cip_enhanced'; +export type GridType = 'lines' | 'dots' | 'crosses' | 'isometric' | 'isometric-dots' | 'hex' | 'hex-dots'; +export type GridStrength = 'faint' | 'normal' | 'strong'; +export interface GridSpec { type?: GridType; spacing?: number | 'bond'; major?: number; strength?: GridStrength } export interface Style { preset: string; @@ -34,6 +37,7 @@ export interface Style { lone_pair: LonePairStyle; color_by_element: boolean; stereo_labels: StereoLabels; + grid?: GridSpec; } export type StyleOverride = Partial