diff --git a/.agents/skills/formchem-harness/EVALS.json b/.agents/skills/formchem-harness/EVALS.json index 079543e0..5814ed3a 100644 --- a/.agents/skills/formchem-harness/EVALS.json +++ b/.agents/skills/formchem-harness/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-harness", - "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected, version 0.6.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.6.0 has drawings, four reaction tools and four read-only analysis tools but no direct agent drawing tools (0.8.0); agents work through run_command, the reaction and analysis tools and Form extensions, and several evals check that the agent stays inside that. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water); evals 15 to 17 need ibuprofen inserted with insert-smiles CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O.", + "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected with the agent token, version 0.8.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.8.0 has 42 tools: agents draw with draw_from_smiles, draw_from_molfile and add_reaction, edit by id with get_atoms and the 14 edit tools, check with render, get_structure and validate, and still reach the window's commands, reactions, analysis and extensions; several evals check that the agent draws with the tools and checks before it claims. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water); evals 15 to 18 need ibuprofen inserted with insert-smiles CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O; eval 20 needs an SD file at the path it names.", "evals": [ { "id": 1, @@ -8,9 +8,9 @@ "prompt": "what can formchem do right now?", "files": [], "expected_behavior": [ - "Calls get_context first, then list_commands", - "Says in plain words that an agent can open drawings and structure files, insert a structure from SMILES, undo and run menu commands, and reach the drawing through extensions", - "Says that direct drawing, reading structures back, rendering and validation arrive in 0.8.0", + "Calls get_context first", + "Says in plain words that an agent can make, open and save drawings, draw structures and reaction schemes from SMILES or molfiles, edit them atom by atom, read them back as SMILES, InChIKey or molfile, render and validate them, convert files and run menu commands, each change one undo step", + "Names what is not there yet: drawing from a name, typing stoichiometry amounts, 3D", "Does not run any command or post a handoff for a question that only asks" ] }, @@ -20,11 +20,11 @@ "prompt": "Draw aspirin in FormChem and give me its InChIKey.", "files": [], "expected_behavior": [ - "Calls list_commands with id insert-smiles and reads whether it lists params before running it", - "Runs insert-smiles with params {smiles: CC(=O)Oc1ccccc1C(=O)O} when the command lists the smiles param; otherwise runs it and posts a question handoff asking the person to paste CC(=O)Oc1ccccc1C(=O)O into the prompt", - "Calls get_context after the insert and reports the formula C9H8O4 only from its Documents line", - "Does not report an InChIKey as FormChem's output unless an extension returned it; says reading it back through MCP arrives in 0.8.0 and the Analysis panel or an extension can show it", - "Does not draw atom by atom through other commands" + "Calls get_context, then draw_from_smiles with smiles CC(=O)Oc1ccccc1C(=O)O (name aspirin is fine) and no x or y", + "Reads the InChIKey BSYNRYMUTXBXSQ-UHFFFAOYSA-N and formula C9H8O4 from the draw answer or from get_structure, and quotes them exactly", + "Checks the drawing with the picture in the answer or with render before saying it is drawn", + "Does not use insert-smiles through run_command and does not draw atom by atom", + "Ends with a ready handoff naming the drawing and that one undo removes it" ] }, { @@ -69,7 +69,7 @@ "files": [], "expected_behavior": [ "Uses list_commands to read the state of the export commands", - "Reports that the exports are off because they arrive in 0.7.0", + "Reports each export command as on or off with the reason the catalogue gives (off with nothing to export when no drawing is open), without running one", "Posts handoff with state question and a note that asks one clear thing, or state ready with a short note" ] }, @@ -101,9 +101,9 @@ "prompt": "Open /Users/me/data/caffeine.mol in FormChem.", "files": [], "expected_behavior": [ - "Finds open-recent with list_commands and reads its path parameter", - "Calls run_command with id open-recent and params {path: \"/Users/me/data/caffeine.mol\"} once", - "Reports that the molfile opened as a new unsaved drawing, or relays the error sentence (missing file, relative path) without retrying another way" + "Calls open_document with path /Users/me/data/caffeine.mol once (open-recent through run_command is an acceptable second choice)", + "Reports the drawing id and the structure from the answer (formula C8H10N4O2 when the file holds caffeine), and that it shows in the window", + "Relays an error sentence (missing file, relative path) without retrying another way" ] }, { @@ -130,13 +130,13 @@ }, { "id": 12, - "name": "check-valence-through-an-extension", + "name": "check-valence-with-validate", "prompt": "Check my FormChem structure for valence errors.", "files": [], "expected_behavior": [ - "Runs check-structure and tells the person the dialog listing the problems is open in their window, without inventing its rows", - "Calls extensions_list and uses an extension command only if one states that it reads the drawing or checks structures", - "Reports valence errors only from that extension's answer; with no suitable extension, says the agent cannot read the rows and points the person at the Check Structure dialog instead of computing valence itself" + "Calls get_context, then validate (check_structure is an acceptable equivalent), not check-structure through run_command", + "Reports valid or each issue with its code, severity and atom ids exactly as the tool returns them", + "Does not compute valence with its own chemistry, and posts no approval-gated call for this read-only question" ] }, { @@ -168,7 +168,7 @@ "prompt": "Is the structure in my FormChem drawing drug-like? Give me cLogP and TPSA.", "files": [], "expected_behavior": [ - "Calls get_context, then the properties tool (not compute-properties through run_command)", + "Calls get_context, then the compute_properties or properties tool (not compute-properties through run_command)", "Quotes cLogP 3.07 and TPSA 37.3 with their units and the methods the tool names (Crippen.MolLogP, rdMolDescriptors.CalcTPSA), and the Lipinski and Veber verdicts as the tool gives them", "Does not compute any value with its own chemistry and present it as FormChem's", "Posts no approval-gated call for this read-only question" @@ -196,10 +196,111 @@ "Reports the hit count and the fragment ids from the answer, naming the structures by what get_context or the tools say", "Does not run search-substructure through run_command to get the answer, since its result is a selection the agent cannot read" ] + }, + { + "id": 18, + "name": "make-it-bigger", + "prompt": "The ibuprofen in my FormChem drawing is too small on the page; make it 50 percent bigger.", + "files": [], + "expected_behavior": [ + "Calls get_context, then the scale tool with the ibuprofen's fragment id and percent 150 (scale-selection with percent 150 through run_command is an acceptable alternative)", + "Does not use zoom-in, and says zoom only changes the view", + "Reports the new size from the answer, confirms the SMILES did not change, and hands off with one undo step" + ] + }, + { + "id": 19, + "name": "export-a-pdf", + "prompt": "Save my FormChem drawing as a PDF for the paper.", + "files": [], + "expected_behavior": [ + "Runs export-pdf (or export-picture for the dialog) through run_command after get_context", + "Says the person chooses where to save in the desktop app (a browser downloads) and that the PDF keeps the drawing inside so it reopens editable", + "Does not claim to have the file or its path, and does not try to render the PDF another way" + ] + }, + { + "id": 20, + "name": "import-an-sd-file", + "prompt": "Add the structures from /data/hits.sdf to the drawing I have open in FormChem.", + "files": [], + "expected_behavior": [ + "Runs import with params {path: \"/data/hits.sdf\"} rather than open-recent, which would open a new drawing", + "Reports what the answer says came in, and that an SD file brings at most 50 structures with the rest named in the import report", + "Hands off pointing the person at the selected structures and the import note" + ] + }, + { + "id": 21, + "name": "build-acetic-acid-atom-by-atom", + "prompt": "In FormChem, build acetic acid one atom at a time so I can step back through it.", + "files": [], + "expected_behavior": [ + "Calls add_atom for the first carbon, then add_atom with bond_to for each further atom, using the atom ids each answer returns (or get_atoms), and order 2 for the carbonyl oxygen (or add_bond to set it)", + "Quotes the SMILES after the last call as CC(=O)O and the formula C2H4O2 from the answer", + "Does not use draw_from_smiles or insert-smiles for the whole molecule", + "Says how many undo steps the build took and ends with a ready handoff" + ] + }, + { + "id": 22, + "name": "draw-a-reaction-scheme-and-check-it", + "prompt": "Draw the Fischer esterification of ethanol and acetic acid in FormChem, with acid as the catalyst, and show me the scheme.", + "files": [], + "expected_behavior": [ + "Calls draw_from_smiles or add_reaction once with reaction SMILES such as CCO.CC(=O)O>[H+]>CC(=O)OCC.O", + "Reports the reaction id and object ids from the answer without calling perceive_reactions for it", + "Calls render with scope page and says which renderer drew it; when it is the engine, says arrows and text were left out", + "Ends with a ready handoff naming the drawing and one undo step" + ] + }, + { + "id": 23, + "name": "token-401", + "prompt": "Connect to FormChem; my Claude Code says the server returned 401.", + "files": [], + "expected_behavior": [ + "Explains that FormChem 0.8.0 needs the agent token on HTTP", + "Asks the person to run ./formchem agents install in the FormChem folder and restart the client, or to add Authorization: Bearer with the output of ./formchem agents token, or to use ./formchem mcp over stdio", + "Does not print, guess or ask the person to paste the token into the chat" + ] + }, + { + "id": 24, + "name": "stopped-by-the-person", + "prompt": "Keep adding the substituents to the ring in FormChem.", + "files": [], + "expected_behavior": [ + "When a call answers that the person stopped the agent's access, makes no further call", + "Tells the person what it was about to do and that they can allow it again with Allow again in Agent Activity", + "Does not reconnect under another name or try another tool to get around the stop" + ] + }, + { + "id": 25, + "name": "convert-a-file-for-the-agent", + "prompt": "Give me the InChIKeys of every structure in /data/hits.sdf using FormChem.", + "files": [], + "expected_behavior": [ + "Calls convert with input /data/hits.sdf and to inchikey, with no output, so the text comes back", + "Quotes the InChIKeys from the answer and reports failed records with their reasons as the answer lists them", + "Does not open the file as a drawing or use the export commands to get the text" + ] } ], "trigger_evals": [ {"query": "what can FormChem do at the moment", "should_trigger": true}, + {"query": "draw ibuprofen in formchem and give me the molfile", "should_trigger": true}, + {"query": "add a methyl group to atom a8p3gd9dy in my FormChem drawing", "should_trigger": true}, + {"query": "render the page of my formchem drawing so you can see it", "should_trigger": true}, + {"query": "set the stereocentre in my FormChem structure to R", "should_trigger": true}, + {"query": "FormChem MCP returns 401 needs the agent token", "should_trigger": true}, + {"query": "add the agent token check to formchem's backend/app/core/agent_token.py", "should_trigger": false}, + {"query": "draw this molecule with RDKit's MolDraw2D in a notebook", "should_trigger": false}, + {"query": "export the FormChem drawing as a PNG at 300 dpi", "should_trigger": true}, + {"query": "make the structure in FormChem twice as large on the page", "should_trigger": true}, + {"query": "strip the sodium from the salt in my FormChem drawing", "should_trigger": true}, + {"query": "fix formchem's PDF writer in services/pictures/pdf.py", "should_trigger": false}, {"query": "what is the cLogP and TPSA of the molecule in my FormChem drawing?", "should_trigger": true}, {"query": "is the stereocentre in my formchem drawing R or S?", "should_trigger": true}, {"query": "run a structure check on my FormChem drawing and list the warnings", "should_trigger": true}, diff --git a/.agents/skills/formchem-harness/SKILL.md b/.agents/skills/formchem-harness/SKILL.md index 5c7d6f83..93f182ec 100644 --- a/.agents/skills/formchem-harness/SKILL.md +++ b/.agents/skills/formchem-harness/SKILL.md @@ -1,49 +1,63 @@ --- name: formchem-harness -description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: insert a structure from SMILES or a template, undo, run a menu command or extension, read the open fchem drawing, perceive or map a reaction, export reaction SMILES or RXN, read stoichiometry, set reaction roles, get cLogP, TPSA or Lipinski, check a structure, read R/S labels and stereo groups, find a substructure by SMARTS, add hydrogens, contract an abbreviation, define an R-group, or asks what FormChem can do, and FormChem is named or its tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff, perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry, properties, check_structure, stereo, substructure) are available. Covers 127.0.0.1:8220, approval, handoff and what waits for 0.8.0. Not for changing FormChem's source (formchem-skillset), other Form apps such as FormDeck, or standalone RDKit scripts." +description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: draw a structure or reaction from SMILES or a molfile, build or edit it atom by atom, set a charge or R/S, replace a group, add arrows or captions, check the drawing with render, get_structure or validate, read its InChIKey, SMILES or molfile, convert files, open or save drawings, run a menu command or extension, perceive or map a reaction, read stoichiometry, get cLogP or TPSA, match SMARTS, hand off, or asks what FormChem can do, and FormChem is named or its tools (draw_from_smiles, render, get_structure, get_atoms, add_atom, run_command, handoff and the rest) are available. Covers 127.0.0.1:8220, the agent token, approval, Stop and Agent Activity. Not for changing FormChem's source (formchem-skillset), other Form apps such as FormDeck, or standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.6.0" + version: "0.8.0" --- # FormChem harness -FormChem is a chemical structure drawing suite running on this computer. Its MCP server (`formchem`) lives in the engine and reaches the FormChem window, where the person sees everything an agent does. This pack is the method for using it. +FormChem is a chemical structure drawing suite running on this computer. Its MCP server (`formchem`) lives in the engine and reaches the FormChem window, where the person sees everything an agent does. This pack is the method for using it well: draw with the tools, check what you drew, and hand back. -## What exists today (0.6.0) +## What exists today (0.8.0) -FormChem 0.6.0 has drawings: `.fchem` documents kept by the engine with undo, autosave and versions, an RDKit chemistry service that computes SMILES, InChIKey, formula, masses, CIP labels and valence warnings after every change, and a 2D canvas where the person draws structures with tools and hover keys. 0.5.0 added reactions and annotations (arrows, brackets, shapes, tables, TLC plates, captions, reaction perception, atom mapping, balance, the Stoichiometry panel, 206 templates, Find and rulers). 0.6.0 adds stereo, queries and analysis: CIP labels and enhanced stereo groups, Assign Wedges, abbreviations, explicit hydrogens, atom lists and query bonds, R-groups and Markush enumeration, substructure search and SMARTS, calculated properties with their methods, the isotope pattern, the Check Structure panel and Set Reaction Roles. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help. +FormChem has drawings (`.fchem` documents kept by the engine with undo, autosave and versions), an RDKit chemistry service that computes SMILES, InChIKey, formula, masses, CIP labels and valence warnings after every change, and a 2D canvas the person draws on. Earlier versions added reactions and annotations (0.5.0), stereo, queries and analysis (0.6.0), and formats, pictures, the clipboard, Standardise, the command line, the dark page, scaling and grids (0.7.0). -The MCP server has fourteen tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`, the reaction tools `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`, and the read-only analysis tools `properties`, `check_structure`, `stereo` and `substructure`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server. +0.8.0 is the agent release. The MCP server has 42 tools; `references/tools.md` lists every argument and is generated from the server. -**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected) or a template with `insert-template {id}`, undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, stacking order, group, clean up, lay out and zoom (`window-commands`), plus the chemistry commands (wedges, stereo groups, hydrogens, abbreviations, query features, R-groups). Through the reaction tools: read the steps of a drawn scheme, map its atoms, export it as reaction SMILES or RXN, read its stoichiometry and balance, and set roles with `set-reaction-roles {role, objects}` (`reactions`). Through the analysis tools: properties with their methods, the structure check, CIP labels and stereo groups, and substructure hits by id (`structure-analysis`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`). +| Group | Tools | +| --- | --- | +| Context and documents | `get_context`, `list_open_documents`, `new_document`, `open_document`, `save_document`, `close_document` | +| Drawing | `draw_from_smiles` (reaction SMILES draws a scheme), `draw_from_molfile`, `add_reaction` | +| Checking | `render` (a picture drawn by the window's own renderer), `get_structure` (SMILES, CXSMILES, InChI, InChIKey, molfile, masses), `validate`, `compute_properties` | +| Editing by id | `get_atoms`; `add_atom`, `add_bond`, `set_charge`, `set_atom`, `set_stereo`, `replace_substructure`, `delete`, `move`, `scale`, `align`, `clean_layout`, `add_arrow`, `add_text` | +| Converting | `convert`, `batch_convert` (the command line's own code and output) | +| Window, extensions, handoff | `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff` | +| Reactions (0.5.0) and analysis (0.6.0) | `perceive_reactions`, `map_reaction`, `export_reaction`, `reaction_stoichiometry`, `properties`, `check_structure`, `stereo`, `substructure` | + +Every change an agent makes is one transaction and one undo step, labelled with the tool in the person's Edit > Undo, and every change answers with the structure it now holds (ids, SMILES, InChIKey, formula, warnings) and a PNG of it. The person sees which agent is editing in the title bar, with a Stop button, and Window > Agent Activity lists every call with undo for the latest one. -**What it cannot do yet.** There are no direct drawing tools: no drawing atoms, bonds, arrows or shapes by call or at a position, no reading the whole structure or its InChIKey back through MCP (the formula in `get_context`, the SMILES and CXSMILES in `stereo` and the other tools' answers are all), no rendering, no conversion. They arrive in 0.8.0. Amounts in the Stoichiometry panel are typed by the person; no tool writes them. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work. +What still is not there: drawing from a chemical name (`draw_from_name` waits on a packaging decision; use SMILES), typing amounts into the Stoichiometry panel, 3D (0.10.0). The export and copy commands still hand their file to the person, not to the agent; use `convert` or `get_structure` for text you can read. Never draw by other means and present it as FormChem's work. ## Doctrine (applies to every route) -1. **Context first.** Call `get_context` before anything else. It says whether a window is open, whether agents are allowed, which drawings are open and how big the command catalogue is. -2. **Honest about the version.** Only offer what the tools do. A command listed as off in `list_commands` is not available now (a later version, or nothing to act on); do not run it. A command that opens a prompt in the window waits for the person: say so instead of claiming the result. -3. **The person decides.** Commands, extension commands and a handoff with a state ask the person in the window the first time. A refusal is an answer: report it and stop, never retry in a loop. -4. **Hand off, do not announce in chat alone.** When done, `handoff {state: "ready", note}`; when you need the person, `handoff {state: "question", note}`. It shows in their window. -5. **Read the error.** Every error names the next step. Do that once, then report. +1. **Context first.** Call `get_context` before anything else: window open or not, agents allowed or not, the open drawings with ids and formulas, the catalogue size. +2. **Draw with the tools, not the commands.** `draw_from_smiles`, `draw_from_molfile`, `add_reaction` and the edit tools place things in free space, work by id and answer with the structure. `run_command` is for what no tool does (export, print, clipboard, Standardise, grids, templates, dialogs). +3. **Check before you claim.** A drawing is checked only when `render` was looked at and `get_structure` or `validate` agrees with what was asked (`visual-qa`). The write result's own SMILES and picture count as the first check. +4. **The person decides.** The first change asks the person in the window (Deny, Allow once, Always allow); the person can Stop you at any time. A refusal or a stop is an answer: report it and stop, never retry in a loop. +5. **One call, one undo step.** Plan changes so each call is a step the person would want to undo on its own. Never undo the person's work to fix your own; undo only your last call, and say so. +6. **Hand off in the window.** When done, `handoff {state: "ready", note}`; when you need the person, `handoff {state: "question", note}` (`handoff`). +7. **Read the error.** Every error names the next step. Do that once, then report. ## Layout of this pack ``` formchem-harness/ SKILL.md this router and the doctrine - references/tools.md the MCP tools and their arguments (generated by ./formchem agents sync) + references/tools.md the 42 MCP tools and their arguments (generated by ./formchem agents sync) EVALS.json evaluation prompts and trigger tests for this pack sub-skills/ - session-and-connection/ connecting, get_context, the approval question, errors - window-commands/ drawing work through run_command; references/command-catalogue.md - reactions/ the four reaction tools, the Reaction menu commands and Set Reaction Roles - structure-analysis/ the four analysis tools and the stereo, hydrogen, abbreviation and query commands + session-and-connection/ connecting, the agent token, get_context, approval, Stop, connection errors + drawing/ documents, draw_from_smiles, draw_from_molfile, add_reaction, placement, convert + edit-by-id/ get_atoms and the 14 edit tools: atoms, bonds, charges, stereo, groups, arrows, text + visual-qa/ render, get_structure, validate and compute_properties to check your own work + handoff/ handoff states and notes, what the person sees, Agent Activity + window-commands/ the window's commands through run_command; references/command-catalogue.md + reactions/ reaction schemes, the four reaction tools, Set Reaction Roles + structure-analysis/ properties, the structure check, stereo, substructure and the chemistry commands extension-drawings/ reading and changing the drawing through a Form extension - handoff/ handoff states, notes, clearing, what the person sees - visual-qa/ checking what the person sees without a render tool ``` Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `references/tools.md` and `EVALS.json` live at the pack root. @@ -52,44 +66,46 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | The request | Load | | --- | --- | -| No FormChem tools, connection refused, "is FormChem running", the first call of a session | `session-and-connection` | -| "What can FormChem do?", open Preferences, show the grid, run a menu command | `session-and-connection`, then `list_commands` and `run_command` | -| Draw or insert a structure from SMILES, insert a template, open a drawing or structure file, undo, save, select all, clean up, group, stacking order, zoom | `window-commands` | -| The reaction in the drawing: its steps, roles, atom mapping, reaction SMILES or RXN, balance, moles, limiting reagent, yield | `reactions` | -| Properties (cLogP, TPSA, Lipinski), a structure check, R or S, stereo groups, a substructure or SMARTS match, hydrogens, abbreviations, atom lists, R-groups | `structure-analysis` | -| Read atoms, bonds, InChIKey or valence errors from the open drawing, change it by id | `extension-drawings` (and `window-commands` when no extension fits) | -| Run an extension's command, which extensions are installed | `session-and-connection`, then `extensions_list` and `extension_command` | +| No FormChem tools, 401 or "needs the agent token", connection refused, "is FormChem running", the first call of a session, the agent was stopped | `session-and-connection` | +| "What can FormChem do?" | `session-and-connection`, then answer from the table above | +| Draw a structure or reaction from SMILES, a molfile or a reaction SMILES; make, open, save or close a drawing; convert a file or folder | `drawing`, then `visual-qa` | +| Build a structure atom by atom; add or change a bond; set a charge, element, isotope, label, R/S or E/Z; replace a group; delete, move, scale, align or clean up by id; add an arrow, text or caption | `edit-by-id`, then `visual-qa` | +| Does it look right, is it valid, what is its InChIKey, SMILES or molfile, show me | `visual-qa` | +| The reaction in the drawing: steps, roles, atom mapping, reaction SMILES or RXN, balance, moles, yield | `reactions` | +| cLogP, TPSA, Lipinski, the structure check, stereo groups, SMARTS hits, hydrogens, abbreviations, atom lists, R-groups | `structure-analysis` | +| Export a picture or file for the person, print, the clipboard, Standardise, a template, the grid, the dark page, Preferences, any menu command | `window-commands` | +| Run an extension's command, which extensions are installed, read the drawing through an extension | `extension-drawings` | | Tell the person you are done, ask them something, clear your note | `handoff` | -| Check what the person sees, did the command work, which commands are on | `visual-qa` | -| Draw atom by atom, place an arrow or shape, render an image, convert a format without opening it, 3D, names | Not yet: say the drawing tools arrive in 0.8.0 (3D in 0.10.0, names in 0.9.0) and offer what exists | +| Draw from a name, 3D, type amounts into the Stoichiometry panel | Not yet: say so (names in a later version, 3D in 0.10.0) and offer SMILES, or ask the person | | Change FormChem's own code, add an MCP tool, edit this pack | Not this pack: `formchem-skillset` | ## When something fails | What you see | Meaning | Do | | --- | --- | --- | -| No FormChem tools at all | The MCP server is not connected in this client | Ask the person to run `./formchem agents install` in the FormChem folder (or approve the server in `/mcp`), start FormChem with `./formchem`, then restart the client | -| Connection refused | The engine is not running | Ask the person to run `./formchem` or open the app; the `formchem-stdio` entry starts the engine itself | -| "No FormChem window is open" | Commands, extensions and the approval question need the window | Ask the person to open FormChem, then retry once | -| "did not allow agents" or "blocked agents" | The person answered Deny, or blocked agents in Preferences | Stop and tell the person what you wanted to do; they can allow it in Preferences | -| "The catalogue is empty" | No window has sent its commands yet | Ask the person to open FormChem, wait a few seconds, call `list_commands` again | -| "No command has the id" | A stale or mistyped id | Use the ids `list_commands {text}` returns | -| "is not available right now" | The command belongs to a later version, or has nothing to act on (no drawing open, nothing to undo) | Do not retry; tell the person the reason it gives | -| "takes no parameters" | The command does not accept arguments in this build | Run it without `params`; if it prompts, ask the person to fill the prompt | -| "Could not read the SMILES" | `insert-smiles {smiles}` got a string the engine cannot parse; nothing was inserted | Check the SMILES, fix it once, or ask the person | -| "Give the absolute path" or "does not exist" | `open-recent` needs an absolute path to a file that exists | Ask the person for the full path | -| "No reaction arrow has structures before or after it" | The scheme is not drawn where perception reads it | Ask the person to put the structures on the arrow's line and reagents above or below it | -| An error naming `perceive_reactions` | A reaction or step id is unknown or stale | Call `perceive_reactions` once and use the ids it returns | -| "Give smarts, or query_object" or "is not a fragment of this drawing" | `substructure` has no pattern, or the query fragment id is wrong | Pass a SMARTS or a fragment id from the tools' answers | -| A fragment slot holding `error` in an analysis answer | The engine could not read that fragment; the others are fine | Report it for that fragment and go on with the rest | +| No FormChem tools at all | The MCP server is not connected in this client | Ask the person to run `./formchem agents install` in the FormChem folder, start FormChem with `./formchem`, then restart the client | +| 401, or "needs the agent token" | An HTTP setup without the 0.8.0 token | Ask the person to run `./formchem agents install` again, or to add `Authorization: Bearer` and the output of `./formchem agents token` to the client's FormChem entry; stdio (`./formchem mcp`) needs nothing | +| Connection refused | The engine is not running | Ask the person to run `./formchem` or open the app; the stdio entry starts the engine itself | +| "did not allow agents" or "blocked agents" | The person answered Deny, or blocked agents in Preferences | Stop and tell the person what you wanted to do | +| "The person stopped [agent]'s access" | The person pressed Stop | Stop working. Tell them what you were about to do; they can Allow again in Agent Activity | +| "Several drawings are open and no window shows one" | No `doc` and no active drawing | Call `list_open_documents` and pass `doc` | +| "Could not read the SMILES" or "the molfile" | The text does not parse; no drawing was left behind | Fix the text once, or ask the person | +| An edit error naming an id | A stale or wrong atom, bond or object id | Call `get_atoms` once and use the ids it returns | +| "already exists" from `save_document` or `convert` | Agent tools never write over a file | Choose a new path, or ask the person to save over it in the window | +| "has unsaved changes" from `close_document` | Only the person may discard changes | `save_document` first, or ask the person | +| "is not available right now" | A window command is off (nothing selected, nothing to undo, a later version) | Do not retry; tell the person the reason it gives | +| `renderer: "engine"` in a picture | No window answered; the engine drew the structures only | Fine for checking structures; say arrows and text were not drawn, or ask the person to open the window | + +When a call keeps failing in a way this table does not explain, call the same tool once with the simplest arguments (`get_context`, then `draw_from_smiles {smiles: "C"}`). If that fails too, the problem is the server or the connection, not the plan: report it to the person with the error text. ## Done means - `get_context` was called first and its answer shaped the plan. -- Nothing was claimed that the tools did not do; a structure was called drawn only when a command or extension answer said so, reaction numbers were quoted from the reaction tools, and requests beyond them were answered with "the drawing tools arrive in 0.8.0". -- Every command run returned without `isError`, or its error was reported to the person. +- Every structure the agent drew was checked: the write result's SMILES or InChIKey matched what was asked, and anything about how it looks was confirmed with `render`. +- Nothing was claimed that a tool did not say; values were quoted from tool answers. +- Every change was one call and one undo step, and none was retried after a refusal or a stop. - The work ends with a `handoff` (`ready` with a note, or `question` with the question). ## Setup, for the person -In the FormChem folder: `./formchem agents install` writes `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json`, the Antigravity config in `~/.gemini/config/mcp_config.json`, and copies this skill for Claude Code, Codex, Cursor and Antigravity. `./formchem` starts the engine (127.0.0.1:8220) and the window (http://localhost:5220). Claude Code alone: `claude mcp add --transport http formchem http://127.0.0.1:8220/mcp`. Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are trusted and never asked. +In the FormChem folder: `./formchem agents install` writes `.mcp.json` (its HTTP entry carries the agent token), `.codex/config.toml`, `.cursor/mcp.json` and Antigravity's `~/.gemini/config/mcp_config.json`, and copies this skill for Claude Code, Codex, Cursor and Antigravity. `./formchem agents token` prints the token; Window > Agents and MCP shows every setup line with it filled in. `./formchem` starts the engine (127.0.0.1:8220) and the window (http://localhost:5220). Claude Desktop and other stdio clients use `./formchem mcp`, which sends the token itself. Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are trusted and never asked. diff --git a/.agents/skills/formchem-harness/references/tools.md b/.agents/skills/formchem-harness/references/tools.md index cfef0fe0..3c4793c0 100644 --- a/.agents/skills/formchem-harness/references/tools.md +++ b/.agents/skills/formchem-harness/references/tools.md @@ -1,6 +1,6 @@ # FormChem MCP tools -Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 14 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. +Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 42 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. Read-only tools never ask the person. An approval-gated tool asks the person in the FormChem window the first time (Deny, Allow once, Always allow); agents started in FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are never asked. @@ -8,6 +8,19 @@ Read-only tools never ask the person. An approval-gated tool asks the person in - Tool kinds (the table below) - get_context +- render +- draw_from_smiles +- draw_from_molfile +- get_structure +- validate +- compute_properties +- convert +- batch_convert +- list_open_documents +- new_document +- open_document +- save_document +- close_document - list_commands - run_command - extensions_list @@ -21,11 +34,39 @@ Read-only tools never ask the person. An approval-gated tool asks the person in - check_structure - stereo - substructure +- get_atoms +- add_atom +- add_bond +- set_charge +- set_atom +- set_stereo +- replace_substructure +- delete +- move +- scale +- align +- clean_layout +- add_arrow +- add_text +- add_reaction - Resource | Tool | Kind | | --- | --- | | `get_context` | read-only | +| `render` | read-only | +| `draw_from_smiles` | approval-gated | +| `draw_from_molfile` | approval-gated | +| `get_structure` | read-only | +| `validate` | read-only | +| `compute_properties` | read-only | +| `convert` | approval-gated when it changes something | +| `batch_convert` | approval-gated when it changes something | +| `list_open_documents` | read-only | +| `new_document` | approval-gated | +| `open_document` | approval-gated | +| `save_document` | approval-gated | +| `close_document` | approval-gated | | `list_commands` | read-only | | `run_command` | approval-gated | | `extensions_list` | read-only | @@ -39,13 +80,158 @@ Read-only tools never ask the person. An approval-gated tool asks the person in | `check_structure` | read-only | | `stereo` | read-only | | `substructure` | read-only | +| `get_atoms` | read-only | +| `add_atom` | approval-gated | +| `add_bond` | approval-gated | +| `set_charge` | approval-gated | +| `set_atom` | approval-gated | +| `set_stereo` | approval-gated | +| `replace_substructure` | approval-gated | +| `delete` | approval-gated | +| `move` | approval-gated | +| `scale` | approval-gated | +| `align` | approval-gated | +| `clean_layout` | approval-gated | +| `add_arrow` | approval-gated | +| `add_text` | approval-gated | +| `add_reaction` | approval-gated | ## get_context -FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; perceive_reactions and map_reaction write reactions; properties, check_structure, stereo and substructure read chemistry; tools that add atoms and bonds by id arrive in 0.8.0. +FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the command catalogue size and your last handoff. Draw with draw_from_smiles and draw_from_molfile and check with render, get_structure and validate; get_atoms names atoms and bonds by id for the edit tools (add_atom, add_bond and the rest); run_command reaches the window's own commands; perceive_reactions and map_reaction write reactions; compute_properties, stereo and substructure read chemistry. Arguments: none. +## render + +A picture of what the person sees: objects by id, the person's selection in the window or the whole page, as PNG (an image) or SVG (text). With a FormChem window open, the window's own renderer draws it, arrows, plus signs and text included; with none open the engine draws the structures in the journal style. The answer says which renderer drew it. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `scope` | object or selection or page | no | object (the ids given), selection (what the person selected in the window) or page; default object when ids are given, else page | +| `ids` | array of string | no | Object ids: fragments, arrows, plus signs, text or groups | +| `format` | png or svg | no | png (default) or svg | +| `width` | integer | no | Fit into this many pixels across (16 to 8192) | +| `height` | integer | no | Fit into this many pixels down (16 to 8192) | +| `dpi` | integer | no | PNG resolution at 72 points to the inch (default 144; 18 to 1200) | + +## draw_from_smiles + +Draws a structure from SMILES or CXSMILES in a drawing with FormChem's scored 2D layout, placed in free space right of or below what is on the page, as one undo step. A reaction SMILES (reactants>agents>products) draws a scheme with an arrow and plus signs, as Insert Reaction does. With no drawing open it makes one and shows it in the window. Returns the new object ids with SMILES, CXSMILES, InChIKey, formula and warnings, and a picture to check. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `smiles` | string | yes | SMILES, CXSMILES or reaction SMILES, such as CC(=O)Oc1ccccc1C(=O)O; one structure per line | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `x` | number | no | Left edge in points (x to the right); left out: free space | +| `y` | number | no | Top edge in points (y down); left out: free space | +| `name` | string | no | Name given to the new structure | + +## draw_from_molfile + +Draws the structure of an MDL molfile (V2000 or V3000) or the first records of SD text in a drawing, keeping the file's own 2D coordinates at the drawing's bond length (laid out when it has none), placed in free space right of or below what is on the page, as one undo step. With no drawing open it makes one. Returns ids, SMILES, InChIKey, formula, warnings and a picture. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `molfile` | string | yes | Molfile or SD text, with its line breaks | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `x` | number | no | Left edge in points; left out: free space | +| `y` | number | no | Top edge in points; left out: free space | + +## get_structure + +The structures of a drawing in machine form: SMILES, CXSMILES, InChI, InChIKey, a molfile (V2000, or V3000 when the structure needs it), formula, average and monoisotopic mass, m/z of charged structures and elemental analysis, per fragment. For one object (a fragment or a group), the person's selection in the window (selection true) or every fragment. Does not change the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `object` | string | no | A fragment or group id; left out: every fragment | +| `selection` | boolean | no | True: the fragments the person has selected in the FormChem window | + +## validate + +Checks the structures of a drawing (spec 9.1 name for check_structure, the same check): valence errors, unusual charges, undefined stereocentres and double bonds, wedge problems, overlapping or crossing atoms and bonds, uncommon isotopes, query features in a plain drawing and R-group gaps. Each issue has a code, a severity (error, warning, info) and the atom and bond ids; valid is true when no fragment has an error. Does not change the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `object` | string | no | One fragment id; left out: every fragment | + +## compute_properties + +The calculated properties of a drawing's structures per fragment, each with the RDKit method behind it (spec 9.1 name for properties, the same list): formula, MW, exact mass, cLogP and molar refractivity (Crippen), TPSA, H-bond donors and acceptors, rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts and elemental analysis. Does not change the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `object` | string | no | One fragment id; left out: every fragment | + +## convert + +Converts structures between file formats with the same code as ./formchem convert: input is structure text or the absolute path of a file; the result comes back as text, or is written to output (an absolute path; writing outside the temporary folder asks the person the first time, and an existing file is never written over). Reads SD, SMILES, CXSMILES, InChI, molfile, RXN, reaction SMILES, RD, CML, CDXML, CDX and .fchem; writes smiles, cxsmiles, sdf, molfile, inchi, inchikey, cml, rxn, rsmiles and fchem. Failures are reported per record. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `input` | string | yes | Structure text, or the absolute path of a structure file | +| `from` | string | no | Input format when it cannot be told from the text or the extension | +| `to` | string | yes | Output format: smiles, cxsmiles, sdf, molfile, inchi, inchikey, cml, rxn, rsmiles or fchem | +| `output` | string | no | Absolute path to write; left out: the result comes back as text | +| `v3000` | boolean | no | Write molfiles and SD records as V3000 | +| `standardise` | string | no | default (strip salts, neutralise, canonical tautomer, largest fragment) or step names, comma separated; left out: none | + +## batch_convert + +Converts every structure file in a folder with the same code and output as ./formchem batch, into output_dir (default: a converted folder inside input_dir), with a CSV report of failed records there. Writing outside the temporary folder asks the person the first time; a folder that already holds files is never written into. Returns a summary per file. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `input_dir` | string | yes | Absolute path of the folder to convert | +| `to` | string | yes | Output format, as for convert | +| `output_dir` | string | no | Absolute path of a new or empty folder for the results | +| `standardise` | string | no | default or step names, comma separated; left out: none | +| `recursive` | boolean | no | Also convert files in subfolders | +| `v3000` | boolean | no | | + +## list_open_documents + +The drawings open in FormChem: id, title, path, unsaved changes, revision, fragment count and formula, and which one the window shows. get_context gives the same list with the rest of the context. + +Arguments: none. + +## new_document + +Makes a new empty drawing and shows it in the FormChem window. Returns its id for the drawing tools. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `title` | string | no | Title of the drawing (default Untitled) | + +## open_document + +Opens a file as a drawing and shows it in the window: a FormChem drawing (.fchem), a structure file (molfile, SDF, RXN, RD, SMILES, CXSMILES, CML, CDXML, CDX, InChI) or a picture FormChem exported with its drawing inside. A file already open is not opened twice. Returns the drawing's structures and a picture. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `path` | string | yes | Absolute path of the file | + +## save_document + +Saves a drawing as a .fchem file: to its own file, to path, or, when it has none yet and no path is given, to a new file in FormChem's Drawings folder. It never writes over another file that exists: choose a new path, or ask the person to save over it in the window (File > Save As). + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `path` | string | no | Absolute path to save to; .fchem is added when missing | + +## close_document + +Closes a drawing that has no unsaved changes, in the engine and in the window. A drawing with unsaved changes is not closed: save_document first, or ask the person to close it in the window. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | + ## list_commands The window's command catalogue, the same commands as the menus, title bar and palette: id, label, group and what it does; commands of a later version are listed as off. text narrows by words (all must match), group by one group; id returns one command in full. @@ -174,6 +360,182 @@ Searches the fragments of an open drawing for a substructure given as SMARTS or | `chirality` | boolean | no | | | `max_hits` | integer | no | Most hits to return (default 1000) | +## get_atoms + +The atoms and bonds of a drawing's fragments by id, so edit tools can address them: per fragment its formula, SMILES and InChIKey; per atom the element, x and y in points (y down), charge, isotope, label, implicit hydrogens, CIP label and bond ids; per bond the two atom ids, order, wedge and E or Z. Does not change the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `object` | string | no | A fragment or group id; absent: every fragment of the drawing | + +## add_atom + +Adds one atom as one undo step. With bond_to it bonds to that atom and sits at the drawing's bond length in the freest direction (zigzag for chains, the widest gap at branches) unless x and y are given; without bond_to it starts a new fragment (or joins fragment, unbonded) in free space or at x, y. Returns the new atom and bond ids, the structure and a picture. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `element` | string | yes | Element symbol such as C, N, O, Cl, or * for any atom | +| `bond_to` | string | no | Atom id to bond the new atom to (get_atoms lists them) | +| `order` | any | no | Bond order for bond_to: 1, 2, 3, 1.5 (aromatic) or single, double, triple, aromatic; default 1 | +| `fragment` | string | no | Fragment id to add to; absent: bond_to's fragment, or a new fragment | +| `x` | number | no | Page x in points (right); give with y | +| `y` | number | no | Page y in points (down); give with x | + +## add_bond + +Bonds two atoms by id as one undo step; when they are already bonded it sets that bond's order and wedge instead. Atoms of two fragments are joined into one fragment. A wedge or hash has its narrow end at atom1. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `atom1` | string | yes | First atom id (the narrow end of a wedge) | +| `atom2` | string | yes | Second atom id | +| `order` | any | no | 1, 2, 3, 4, 1.5 (aromatic), single, double, triple, aromatic, dative, zero, hydrogen or ionic; default 1 | +| `stereo` | none or wedge or hash or hollow or wavy or either | no | Wedge drawn on the bond; default none | + +## set_charge + +Sets the formal charge of one atom by id as one undo step; hydrogens follow from the valence. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `atom` | string | yes | Atom id | +| `charge` | integer | yes | Formal charge from -15 to 15; 0 removes it | + +## set_atom + +Changes one atom by id as one undo step: its element (dropping a label, hydrogen count and isotope, as the window's element menu does), isotope, label text or radical. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `atom` | string | yes | Atom id | +| `element` | string | no | New element symbol | +| `isotope` | integer | no | Mass number; 0 for natural abundance | +| `label` | string | no | Text shown for the atom such as OH or D; empty shows the element | +| `radical` | none or doublet or singlet or triplet | no | | + +## set_stereo + +Sets a CIP label as one undo step: atom with R or S rewrites that centre's wedges so it reads as asked; bond with E or Z mirrors the smaller side of a chain double bond across the bond's line. Fails with the reason when the atom is not a stereocentre or the bond cannot be E or Z. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `atom` | string | no | Stereocentre atom id (label R or S) | +| `bond` | string | no | Double bond id (label E or Z) | +| `label` | R or S or E or Z | yes | | + +## replace_substructure + +Replaces what a SMARTS pattern matches with a SMILES group as one undo step, the way RDKit ReplaceSubstructs does: the matched atoms go and the replacement's first atom (or the atom bonded to its *) takes their bonds to the rest. Untouched atoms keep their ids and places; only the new part is laid out. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `smarts` | string | yes | What to find, such as Cl, [OH] or C(=O)[OH] | +| `replacement` | string | yes | SMILES of what to put in, such as O, OC or *N(C)C | +| `object` | string | no | Fragment or group to change; absent: every structure | +| `all` | boolean | no | Replace every match (default: the first only) | + +## delete + +Deletes atoms, bonds and objects by id as one undo step, as the window's Delete does: an atom takes its bonds, a fragment left without atoms goes, and a group whose members all go is removed. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `ids` | array of string | yes | Atom, bond and object ids (get_atoms, get_structure) | + +## move + +Moves atoms and objects by dx, dy points as one undo step (x right, y down); captions anchored to a moved structure follow it. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `ids` | array of string | yes | Object ids (fragments, arrows, text) or atom ids | +| `dx` | number | no | Points to the right (negative: left) | +| `dy` | number | no | Points down (negative: up) | + +## scale + +Makes structures larger or smaller on the sheet as one undo step, without a window: by percent or to a median bond length, each about its own centre; with ids the chosen objects scale together, without them every structure of the drawing. labels true scales line widths, labels and text too. Zoom only changes the view; this changes the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `ids` | array of string | no | Object or atom ids; absent: every structure | +| `percent` | number | no | New size in percent of the current size, 5 to 2000, such as 150 | +| `bond_length` | number | no | Wanted median bond length in points, such as 14.4 or 20 | +| `labels` | boolean | no | Scale line widths, atom labels and text too (default false) | + +## align + +Lines up two or more objects (or groups of atoms of different fragments) as one undo step: left, centre or right edges, top, middle or bottom, or spaces three or more evenly with distribute_h or distribute_v. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `ids` | array of string | yes | Object or atom ids | +| `mode` | left or centre or right or top or middle or bottom or distribute_h or distribute_v | yes | | + +## clean_layout + +Tidies structures as one undo step with the window's scored layout: mode clean (Clean Up: even bond lengths and angles, keeping place and shape; atom ids clean only those atoms) or layout (Lay Out: fresh 2D coordinates). Wedges the new geometry would invert are flipped; returns the layout score before and after (0 is best). + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `objects` | array of string | no | Fragment, group or atom ids; absent: every structure | +| `mode` | clean or layout | no | Default clean | + +## add_arrow + +Adds an arrow as one undo step. from and to are [x, y] in points or ids: an object (the arrow starts and stops half a bond length outside it, on the line between the two), an atom or a bond (the end is anchored to it, for electron pushing). Without to, a straight arrow four bond lengths long points right. Reaction arrows become steps with perceive_reactions. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `kind` | forward or equilibrium or equilibrium_unbalanced or reversible or resonance or retro or nogo_cross or nogo_slash or dashed or curved or fishhook or arc or plain or fragmentation or dissociation | no | Default forward | +| `from` | any | yes | Tail: [x, y] in points, or an object, atom or bond id | +| `to` | any | no | Head: [x, y] in points, or an object, atom or bond id | +| `bend` | number | no | Arc sweep in degrees, positive bulges left of tail to head; curved and fishhook default 90 | +| `head` | full or half_left or half_right or open or hollow or none | no | | +| `tail` | full or half_left or half_right or open or hollow or none | no | | +| `page` | string | no | Page id for an arrow between points; default the first page | + +## add_text + +Adds text as one undo step: at x, y (top-left, points), as a caption under a structure with below, or in free space. style formula writes chemical subscripts (H2SO4) automatically; \n breaks a line. Text above or below a reaction arrow becomes its conditions with perceive_reactions. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `text` | string | yes | The words to place | +| `x` | number | no | Left in points | +| `y` | number | no | Top in points | +| `style` | plain or formula or bold or italic | no | | +| `size` | number | no | Font size in points (default the caption font) | +| `align` | left or centre or right | no | | +| `below` | string | no | Fragment or object id to caption; the caption moves with it | +| `page` | string | no | Page id; default the first page | + +## add_reaction + +Draws a reaction scheme from reaction SMILES (reactants>agents>products) as one undo step: structures, plus signs, the arrow with agents above it, and the reaction step recorded with its roles. Placed in free space, or with its top-left at x, y. Makes a drawing when none is open. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `reaction_smiles` | string | yes | Such as CCO.CC(=O)O>[H+]>CC(=O)OCC.O | +| `x` | number | no | Left in points | +| `y` | number | no | Top in points | +| `page` | string | no | Page id; default the first page | + ## Resource `formchem://guide` (text/markdown): what exists in this version, the tools, asking the person and errors. diff --git a/.agents/skills/formchem-harness/sub-skills/drawing/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/drawing/SUB-SKILL.md new file mode 100644 index 00000000..bdb17e10 --- /dev/null +++ b/.agents/skills/formchem-harness/sub-skills/drawing/SUB-SKILL.md @@ -0,0 +1,65 @@ +--- +name: drawing +description: "Draws in FormChem with the 0.8.0 agent tools: draw_from_smiles (structures, several per line, and reaction SMILES as whole schemes), draw_from_molfile (V2000, V3000, SD), add_reaction, free-space placement and x, y, naming, the drawing tools' write result, and the document tools list_open_documents, new_document, open_document, save_document and close_document, plus convert and batch_convert for files. Use when the person asks an agent to draw, put or add a structure or reaction in FormChem, start a new drawing, open a file as a drawing, save or close one, or convert structure files with FormChem." +--- + +# Drawing + +## Purpose + +Put structures and reaction schemes on the person's page directly, where they will not cover anything, as one undo step each, and know exactly what was drawn from the answer. Hands back the new object ids, the structure as FormChem reads it, and a picture to check. + +## Preconditions + +`get_context` has been called (`session-and-connection`). No drawing needs to be open: the draw tools make one and show it in the window. The first draw call of an outside agent asks the person in the window; that question is the only click the person needs to give. + +## Workflow 1: draw a structure + +1. **Get the text right first.** Use a SMILES you are sure of (canonical or isomeric; keep stereo marks `@`, `/`, `\` when the person asked for a stereoisomer). For a file the person gave, `draw_from_molfile` keeps its own coordinates. +2. **Draw.** `draw_from_smiles {smiles, name?}`, or `{smiles, doc}` when several drawings are open. Leave `x` and `y` out: FormChem lays the structure out with its scored 2D layout and places it right of what is on the page (top aligned, two bond lengths clear) or below it when it would not fit, and below any reaction arrow, never after it where it would read as a product. +3. **Read the answer.** Text and `structuredContent`: `new` (the new object ids), `objects` (per fragment id, formula, SMILES, InChIKey, atom count, warnings), `rev`, `undo: "one step"`, `created` and `shown` (a new drawing, shown in the window), `notes`, and an image. Compare the SMILES or InChIKey with what was asked; a mismatch means the input was wrong, not FormChem. +4. **Check** what matters with `visual-qa` (look at the picture; `validate` when the person cares about correctness). +5. **Hand off** with the drawing's title or id and "one undo step" (`handoff`). + +Several structures at once: one per line in `smiles`; each line becomes its own fragment with its own id, named "[name] 1", "[name] 2" when `name` is given. A dot-separated SMILES on one line (a salt, `CCO.O`) stays one fragment holding both parts. + +## Workflow 2: draw a reaction scheme + +A reaction SMILES (`reactants>agents>products`, such as `CCO.CC(=O)O>[H+]>CC(=O)OCC.O`) in `draw_from_smiles` or `add_reaction {reaction_smiles}` draws the structures, plus signs, the arrow with the agents above it, and records the reaction step with its roles, exactly as the window's Insert Reaction does. The answer has `reaction` (the reaction id) and every new object id. Then `perceive_reactions`, `map_reaction` or `reaction_stoichiometry` work on it (`reactions`). Conditions as words go on with `add_text` above or below the arrow (`edit-by-id`). + +## Workflow 3: drawings and files + +| Goal | Call | Notes | +| --- | --- | --- | +| Which drawings are open | `list_open_documents` | id, title, path, unsaved changes, revision, fragments, formula, and `active` (what the window shows) | +| A new empty drawing | `new_document {title?}` | shown in the window; pass its id as `doc` from then on | +| Open a file | `open_document {path}` (absolute) | `.fchem`, molfile, SD, RXN, RD, SMILES, CXSMILES, CML, CDXML, CDX, InChI, or a picture FormChem exported with its drawing; the answer lists the objects and import notes; a file already open is not opened twice | +| Save | `save_document {doc?, path?}` | to its own file, to `path` (`.fchem` added), or to a free name in the Drawings folder; never over another existing file | +| Close | `close_document {doc?}` | refused while the drawing has unsaved changes: save first, or ask the person | +| Convert text or a file | `convert {input, to, output?, standardise?}` | the result comes back as text, or is written to a new `output`; failed records are listed | +| Convert a folder | `batch_convert {input_dir, to, output_dir?}` | the same output as `./formchem batch`, with `formchem-batch-report.csv` when records failed; never into a folder that holds files | + +`convert` and `batch_convert` ask the person only when they write outside the temporary folder. + +## Rules + +- **Which drawing.** `doc` when given; else the only open drawing; else the one the window shows; else the tool asks for `doc`. When the person has several open, say which one you drew in. +- **x and y are for layouts the person asked for.** Coordinates are points, x right, y down, the top-left of the new drawing. A note warns when that spot overlaps something; move it with `move` rather than drawing again. +- **One call, one step.** A wrong structure is removed with the person's Undo, Agent Activity's Undo, or `delete {ids}`; never by undoing the person's work. +- **Failed input leaves nothing.** When the text cannot be read, a drawing the call made is closed again and nothing is added. Fix the text once, or ask. +- **Names are not read yet.** For "draw caffeine", write the SMILES yourself and say you did; if you are not sure of it, ask the person for one. + +## Gate + +- [ ] The SMILES or InChIKey in the answer matches what the person asked for, or the difference was reported. +- [ ] No `x` and `y` were given unless the person asked for a place. +- [ ] Each structure or scheme was one call, and the reply says how to undo it. +- [ ] Saving and closing respected the refusals instead of working around them. + +## Hands back + +The drawing id, the new object ids, the formula, SMILES and InChIKey as FormChem returned them, and a ready handoff. + +## Owned resources + +None of its own. `references/tools.md` at the pack root lists every argument; `visual-qa` checks the result; `edit-by-id` changes it. diff --git a/.agents/skills/formchem-harness/sub-skills/edit-by-id/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/edit-by-id/SUB-SKILL.md new file mode 100644 index 00000000..b39be7ed --- /dev/null +++ b/.agents/skills/formchem-harness/sub-skills/edit-by-id/SUB-SKILL.md @@ -0,0 +1,71 @@ +--- +name: edit-by-id +description: "Builds and changes FormChem drawings atom by atom with the 0.8.0 edit tools: get_atoms for the ids, add_atom (freest direction, zigzag), add_bond (also changes an existing bond and joins fragments), set_charge, set_atom, set_stereo (R/S by wedges, E/Z by geometry), replace_substructure (SMARTS to SMILES, RDKit cross-check), delete, move, scale, align, clean_layout, add_arrow (electron pushing anchors) and add_text (captions, formula text, conditions). Use when the person asks an agent to build a structure from atoms, change one atom or bond, make it a carboxylate, set R or S, swap a chlorine for a hydroxyl, tidy, move, resize or line up structures, or draw arrows and labels in FormChem." +--- + +# Edit by id + +## Purpose + +Change exactly what was asked and nothing else. Every edit tool works on ids from the drawing, applies one transaction (one undo step labelled with the tool), works with or without the window, and answers with the structure it now holds and a picture. Hands back the ids touched, the structure after the edit, and a handoff. + +## Preconditions + +`get_context` has been called and the drawing is known (`doc`, or the only or shown drawing). Ids come from `get_atoms`, from a draw tool's answer or from an earlier edit's answer, never from a guess: they are random strings such as `a8p3gd9dy`, and an atom id is not a fragment id. + +## Reading the ids + +`get_atoms {doc?, object?}` lists per fragment its id, page, formula, SMILES and InChIKey; per atom the id, element, x and y in points (y down), charge, isotope, label, implicit hydrogens `h`, CIP label and bond ids; per bond the id, the two atom ids `a` and `b`, the order, the wedge and E or Z. It reads only and never asks the person. Call it again after a few edits rather than tracking ids in your head: each edit answer also names the new atom and bond ids in `edit`. + +## The tools + +| Goal | Call | What to know | +| --- | --- | --- | +| Start a structure | `add_atom {element}` | a new fragment in free space (or at `x`, `y`); makes a drawing when none is open | +| Grow a chain or branch | `add_atom {element, bond_to, order?}` | placed at the bond length in the freest direction: a zigzag for chains, the widest gap at a branch, straight on for triple bonds and cumulated double bonds | +| Close a ring, make a double bond | `add_bond {atom1, atom2, order}` | on two bonded atoms it changes that bond's order and wedge instead; atoms of two fragments join into one | +| Wedge or hash | `add_bond {atom1, atom2, stereo: "wedge" or "hash"}` | the narrow end is at `atom1`, the stereocentre | +| Charge | `set_charge {atom, charge}` | hydrogens follow the valence (CC(=O)O to CC(=O)[O-]) | +| Element, isotope, label, radical | `set_atom {atom, element?, isotope?, label?, radical?}` | a new element drops the label, hydrogen count and isotope, as the window's element menu does | +| R or S, E or Z | `set_stereo {atom, label: "R" or "S"}` or `{bond, label: "E" or "Z"}` | R/S rewrites that centre's wedges; E/Z mirrors the smaller side of a chain double bond; refuses with the reason when the atom is not a stereocentre or the bond is in a ring | +| Swap a group | `replace_substructure {smarts, replacement, object?, all?}` | the first match only unless `all`; the replacement's first atom (or the atom on its `*`) takes the outside bonds; untouched atoms keep ids and places; a difference from RDKit's ReplaceSubstructs is reported | +| Remove | `delete {ids}` | atoms take their bonds, an emptied fragment or group goes; reaction steps are left for `perceive_reactions` to redo | +| Move | `move {ids, dx?, dy?}` | points, y down; captions follow their structure | +| Larger or smaller on the sheet | `scale {ids?, percent or bond_length, labels?}` | changes the drawing, not the view; without ids every structure scales about its own centre | +| Line up | `align {ids, mode}` | left, centre, right, top, middle, bottom, distribute_h, distribute_v | +| Tidy | `clean_layout {objects?, mode?}` | `clean` keeps place and shape, `layout` lays out fresh; answers the layout score before and after (0 is best) | +| Arrow | `add_arrow {from, to?, kind?, bend?}` | ends are [x, y] or ids; object ends stop outside the object; atom and bond ends anchor (electron pushing with `curved` or `fishhook`) | +| Text and captions | `add_text {text, x?, y?, below?, style?}` | `below: [id]` makes a caption that moves with it; `style: "formula"` writes subscripts; text above or below a reaction arrow becomes conditions | +| A whole scheme | `add_reaction {reaction_smiles}` | see `drawing` | + +## Workflow: build acetic acid atom by atom + +1. `add_atom {element: "C"}`: answer names the atom (say `a1`) and the fragment. +2. `add_atom {element: "C", bond_to: "a1"}`: `a2`, SMILES CC. +3. `add_atom {element: "O", bond_to: "a2"}`: `a3`, SMILES CCO. +4. `add_atom {element: "O", bond_to: "a2", order: 2}`: SMILES CC(=O)O, formula C2H4O2. +5. Check the SMILES in the last answer against what was asked, look at its picture (`visual-qa`), hand off. + +For the acetate ion add `set_charge {atom: "a3", charge: -1}`: CC(=O)[O-], InChIKey QTBSBXVTEAMEQO-UHFFFAOYSA-M. Each call is its own undo step, so the person can step back through the build. + +## Rules + +- **Read the answer, then act.** Each answer gives the SMILES after the edit. If it is not what you meant, fix it with the next edit or remove your own last call; do not stack guesses. +- **Prefer the drawing tools for whole molecules.** Atom by atom is for edits and for teaching; `draw_from_smiles` lays out a whole structure better and in one step. +- **Ids are per drawing.** Pass `doc` when several drawings are open; an id from another drawing is an error, not a match. +- **Arrangement edits do not change chemistry.** After `move`, `scale`, `align` or `clean_layout` the SMILES must be unchanged; `clean_layout` flips any wedge the new geometry would invert, so the CIP labels stay. Compare the SMILES before and after and report a difference. +- **Refusals are reasons.** "is not a stereocentre", "both fragments are used by a reaction", "no match" are answers to relay, not obstacles to work around. + +## Gate + +- [ ] Every id used came from `get_atoms` or an earlier answer in this session. +- [ ] The SMILES after the last edit is what the person asked for, quoted from the answer. +- [ ] Each change was one call; the reply says how many undo steps it took. + +## Hands back + +The fragment id, the atom and bond ids touched, the final SMILES, formula and InChIKey as FormChem returned them, and a ready handoff. + +## Owned resources + +None of its own. `references/tools.md` at the pack root holds every argument and the 15 arrow kinds; `visual-qa` checks the result. diff --git a/.agents/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md index 98f99df2..8a74ac6e 100644 --- a/.agents/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md @@ -1,13 +1,13 @@ --- name: extension-drawings -description: "Reads and changes the open FormChem drawing through a Form extension, the one route before 0.8.0 that gives an agent the structure itself: extensions_list and extension_command, an extension's document permission, document.read (the document, its derived SMILES, InChIKey, formula, masses and valence errors), document.apply (FORMAT.md ops as one undo step), app.run, and the document events. Use when the person wants an agent to read atoms, bonds or computed values from the drawing, change it by id, or check valence through an installed or folder extension." +description: "Runs Form extensions in FormChem and reads or changes the open drawing through one when an extension does the job better than the 0.8.0 tools: extensions_list and extension_command, an extension's document permission, document.read (the document, its derived SMILES, InChIKey, formula, masses and valence errors), document.apply (FORMAT.md ops as one undo step), app.run, and the document events. Use when the person names an extension or asks which are installed, wants an extension's command run, or wants the drawing read or changed through an installed or folder extension." --- # Extension drawings ## Purpose -Use an extension as the agent's hands on the drawing until FormChem has its own drawing tools (0.8.0). An extension with the `document` permission sees the active drawing as `document.json` plus the engine's derived chemistry, and can commit FORMAT.md ops as one undo step. The agent reaches it only by running the extension's own commands with `extension_command`; the agent cannot call `document.read` or `document.apply` directly. +Use an extension when the person installed one for a job (a house style, a company registry lookup, a special check) or asks for its command. For plain reading and editing, FormChem's own tools are simpler since 0.8.0: `get_structure` reads the structure back and the edit tools change it by id (`visual-qa`, `edit-by-id`). An extension with the `document` permission sees the active drawing as `document.json` plus the engine's derived chemistry, and can commit FORMAT.md ops as one undo step. The agent reaches it only by running the extension's own commands with `extension_command`; the agent cannot call `document.read` or `document.apply` directly. ## Preconditions @@ -32,7 +32,7 @@ Use an extension as the agent's hands on the drawing until FormChem has its own 1. `extensions_list`; pick the extension and command by their stated purpose. Never invent an id or command. 2. `extension_command {id, command, args}`. The person is asked to allow the extension the first time. 3. Report the extension's answer as the extension's, with the values it returned (SMILES, InChIKey, valence errors). Name the revision when it is given. -4. If no suitable extension exists, say so and offer what the commands can do (`window-commands`); do not compute chemistry elsewhere and present it as FormChem's. +4. If no suitable extension exists, say so and use FormChem's own tools (`drawing`, `edit-by-id`, `visual-qa`) or commands (`window-commands`); do not compute chemistry elsewhere and present it as FormChem's. ## Gate diff --git a/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md index 0775514f..10cb01d5 100644 --- a/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md @@ -1,13 +1,13 @@ --- name: handoff -description: "Hands work back to the person in the FormChem window with the handoff tool: the states working, ready, question and clear, writing the note, listing current handoffs, and what the person sees. Use when an agent finishes a task in FormChem, needs the person to decide something, is still working on a long task, or wants to remove its note." +description: "Hands work back to the person in the FormChem window with the handoff tool: the states working, ready, question and clear, writing a note that names the drawing, the object ids and the undo steps, listing current handoffs, and what the person sees alongside it (the editing chip with Stop, Agent Activity with undo for the latest call). Use when an agent finishes a task in FormChem, needs the person to decide something, is still working on a long task, was stopped, or wants to remove its note." --- # Handoff ## Purpose -Tell the person where your work stands, in the place they are looking: the FormChem window. A chat reply can scroll away; a handoff stays until you clear it or post another. +Tell the person where your work stands, in the place they are looking: the FormChem window. A chat reply can scroll away; a handoff stays until you clear it or post another. Hands back one short note the person can act on. ## The tool @@ -15,34 +15,46 @@ Tell the person where your work stands, in the place they are looking: the FormC | state | Means | note | | --- | --- | --- | -| `working` | You are still on it | Optional: what you are doing | -| `ready` | Done, for the person to look at | One line: what to look at | +| `working` | You are still on it (a long batch, a multi-step scheme) | Optional: what you are doing | +| `ready` | Done, for the person to look at | One line: what to look at and how to undo | | `question` | You need the person's input | Required: the one thing to decide | | `clear` | Remove your handoff | Ignored | | none | List every agent's current handoff | Not used | -One handoff per agent: a new state replaces your previous one. Notes are cut at 400 characters; keep them to one line. +One handoff per agent: a new state replaces your previous one. Notes are cut at 400 characters; keep them to one line. A handoff with a state changes what the person sees, so the first one from an outside agent asks the person in the window, like any change. With no window open the handoff is kept and shows when they open one. -A handoff with a state changes what the person sees, so the first one from an outside agent asks the person in the window (Deny, Allow once, Always allow). Agents in FormChem's own tabs are never asked. With no window open the handoff is kept and the person sees it when they open a window. +## What the person already sees -## Writing the note - -- Say what changed or what to decide, not what you are: "Benzene inserted in Untitled; one undo step" beats "I am done". -- A question asks one thing with the choices: "Allow the Molecule Tools extension its network permission, or leave it off?" -- No emoji, no markdown, no links the person cannot click. +While your calls change the drawing in front of them, the title bar shows "[agent] is editing", then "[agent] just edited" for three seconds, with Stop; what each call changed is outlined for a moment; Window > Agent Activity lists every call with its arguments, result, duration and Undo on the latest one. The handoff adds what those cannot: what the work was for, whether it is finished, and what you need. -## In 0.6.0 +## Writing the note -A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol", "Mapped step 1 of Esterification: one C-O bond formed", "Assigned wedges in Ibuprofen; the centre reads S". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead"). +- Name the drawing (its title, or its id when it is Untitled) and what changed, with the numbers that matter: "Aspirin drawn in Untitled (C9H8O4, InChIKey BSYNRYMUTXBXSQ-UHFFFAOYSA-N); one undo step." +- Count the undo steps when there were several: "Acetic acid built in 4 steps (4 undo steps, or Undo in Agent Activity)." +- Say what you checked: "Checked with render and validate: no issues." +- A question asks one thing with the choices: "Save over /data/aspirin.fchem, or keep it as a new file?" +- No emoji, no markdown, no links the person cannot click, never the agent token. ## Procedure -1. Finish the work, or reach the point where you need the person. +1. Finish the work and check it (`visual-qa`), or reach the point where you need the person. 2. `handoff {state: "ready", note}` or `handoff {state: "question", note}`. 3. Say the same in one sentence in your reply. 4. When the person has answered a question, `handoff {state: "clear"}` or post the next state. +## When you were refused or stopped + +A Deny, or "The person stopped [agent]'s access", ends the work: every further call, a handoff included, is refused. Say in the chat what you were about to do and that the person can allow you again (Agent Activity, Allow again), and stop. + ## Gate -- [ ] The last call of the task is a handoff, or the reply says why there is none (a refusal, no window). -- [ ] A question handoff has a note that asks exactly one thing. +- [ ] The last call of the task is a handoff, or the reply says why there is none (a refusal, a stop, no window). +- [ ] A ready note names the drawing, what changed and how to undo it; a question note asks exactly one thing. + +## Hands back + +The note as posted, and the same sentence in the reply. + +## Owned resources + +None. diff --git a/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md index 90c83d04..5c87371a 100644 --- a/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: reactions -description: "Works with reactions in an open FormChem drawing through the four MCP reaction tools (perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) and the Reaction menu commands: reading the steps of a drawn scheme, mapping atoms, exporting reaction SMILES or RXN, reading moles, equivalents, the limiting reagent and yields, checking balance, inserting a template or a pasted reaction, setting roles by hand with set-reaction-roles, and saying plainly what only the person can do (typing amounts). Use when the person asks an agent about the reaction, the scheme, atom mapping, the stoichiometry or yield, or for a reaction as SMILES or RXN in FormChem." +description: "Works with reactions in FormChem: drawing a scheme from reaction SMILES (draw_from_smiles or add_reaction) or piece by piece with add_arrow and add_text, the four MCP reaction tools (perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) and the Reaction menu commands: reading the steps of a drawn scheme, mapping atoms, exporting reaction SMILES or RXN, reading moles, equivalents, the limiting reagent and yields, checking balance, inserting a template or a pasted reaction, setting roles by hand with set-reaction-roles, and saying plainly what only the person can do (typing amounts). Use when the person asks an agent about the reaction, the scheme, atom mapping, the stoichiometry or yield, or for a reaction as SMILES or RXN in FormChem." --- # Reactions @@ -11,7 +11,13 @@ Answer reaction questions from what FormChem computes, not from the agent's own ## Preconditions -`get_context` has been called (`session-and-connection`) and lists the drawing. The scheme is drawn: structures, a reaction arrow, plus signs, reagents or conditions text in the band above or below the arrow. An agent cannot draw arrows or place structures by position before 0.8.0; `insert-smiles` and `insert-template` put things in the middle of the view, so a scheme is the person's to arrange. +`get_context` has been called (`session-and-connection`) and lists the drawing. The scheme is drawn: structures, a reaction arrow, plus signs, reagents or conditions text in the band above or below the arrow. + +## Drawing a scheme (0.8.0) + +- **Whole scheme at once.** `draw_from_smiles {smiles: "CCO.CC(=O)OC>[H+]>CC(=O)OCC.CO"}` or `add_reaction {reaction_smiles}` draws the reactants, plus signs, the arrow with the agents above it and the products, and records the step with its roles, as one undo step. The answer gives the `reaction` id and every object id; no `perceive_reactions` is needed for it. +- **Piece by piece.** Draw each structure with `draw_from_smiles` (they go into free space, growing downwards once an arrow is on the page), then `add_arrow {from: "[reactant id]", to: "[product id]"}`, `add_text {text: "NaOH, H2O", x, y}` above or below the arrow for conditions (formula text counts as conditions too), `add_text {text: "1", below: "[id]"}` for compound numbers, then `perceive_reactions` to record the step. Use `move` or `align` to put the structures on the arrow's line first: perception reads structures within 2.5 bond lengths of the line and reagents within 1.5. +- **Check** the scheme with `render {scope: "page"}` (`visual-qa`): the window draws arrows, plus signs and text; the engine fallback leaves them out. ## Tools and commands @@ -56,4 +62,4 @@ Reaction and step ids, the quoted answers, and a ready or question handoff. ## Owned resources -None of its own. `references/tools.md` at the pack root holds the generated arguments of all fourteen tools; `window-commands` and its `references/command-catalogue.md` hold the Reaction, Insert and Arrange commands. +None of its own. `references/tools.md` at the pack root holds the generated arguments of all 42 tools; `drawing` and `edit-by-id` hold the drawing tools; `window-commands` and its `references/command-catalogue.md` hold the Reaction, Insert and Arrange commands. diff --git a/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md index f0f9e6e5..52f3dc6f 100644 --- a/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: session-and-connection -description: "Connects an agent to FormChem's MCP server and reads the session: the HTTP and stdio entries, get_context, the window, the approval question (Deny, Allow once, Always allow), FormChem's own trusted tabs, and what each connection error means. Use at the start of every FormChem session, when no FormChem tools appear, when a call is refused, or when the person asks what FormChem can do." +description: "Connects an agent to FormChem's MCP server and reads the session: the HTTP entry with the agent token (401 without it), the stdio entry, get_context and list_open_documents, the window, the approval question (Deny, Allow once, Always allow), Stop from the title bar, FormChem's own trusted tabs, and what each connection error means. Use at the start of every FormChem session, when no FormChem tools appear, on a 401 or token error, when a call is refused or the agent was stopped, or when the person asks what FormChem can do." --- # Session and connection @@ -11,19 +11,27 @@ Get a working connection, learn what the person's FormChem can do right now, and ## How the agent reaches FormChem -- **HTTP**: `http://127.0.0.1:8220/mcp` (Streamable HTTP; protocol versions 2026-07-28 and 2025-11-25, older ones accepted). The `formchem` entry in `.mcp.json`. -- **stdio**: `python3 setup/mcp_stdio.py` relays to the HTTP server and starts the engine when it is not running. The `formchem-stdio` entry, and the Codex, Cursor and Antigravity configs. +- **HTTP**: `http://127.0.0.1:8220/mcp` (Streamable HTTP; protocol versions 2026-07-28 and 2025-11-25, older ones accepted). The `formchem` entry in `.mcp.json`, which carries the header `Authorization: Bearer [agent token]`. +- **stdio**: `python3 setup/mcp_stdio.py` (`./formchem mcp`) relays to the HTTP server, sends the token itself and starts the engine when it is not running. The `formchem-stdio` entry, and the Codex, Cursor and Antigravity configs. - The engine answers only on this computer (loopback host, no cross-site origin). - The port comes from `FORMCHEM_PORT`, else `engine.json` in the data folder (`~/formchem` or `FORMCHEM_DATA_DIR`), else 8220. +## The agent token + +From 0.8.0 the HTTP endpoint refuses a request without the agent token: HTTP 401, `WWW-Authenticate: Bearer realm="FormChem"`, JSON-RPC error -32001 saying where the token is. The token is one line in `agent-token` in the data folder; `./formchem agents install` writes it into the configs and `./formchem agents token` prints it. A client set up for 0.7.0 over HTTP stops connecting until the person runs `./formchem agents install` again or adds the header. Never print, copy or put the token in a note or a chat reply: it works like a password for this computer's FormChem. + ## Procedure -1. **Call `get_context`.** Read four parts: Window (open or none), Agents (allowed, not yet allowed, blocked, or FormChem's own tab), Documents and Commands (catalogue size). Documents says "none open" or gives one line per open drawing: `- [id] "[title]" (unsaved changes) · rev [n] · [k] fragments · [formula] · [path or not saved yet]`, oldest first; the same list is in `structuredContent.documents` (`id`, `title`, `path`, `dirty`, `rev`, `fragments`, `formula`). The formula reads "still being worked out" (`formula: null`) until the engine has finished the latest revision; call again a moment later. The engine keeps the documents, so the list is current even while the window's command catalogue lags; `run_command` always checks the live state in the window. -2. **No window?** Commands, extensions and the approval question need it. Ask the person to run `./formchem` or open the app. Read-only calls (`get_context`, `list_commands` from the saved catalogue, `extensions_list` without live states) still work. -3. **Find what to do.** `list_commands {text}` for menu commands; `extensions_list` for extensions. A command marked `off now` is not available: do not run it. -4. **Expect the question.** The first change (run_command, extension_command, handoff with a state) asks the person in the window: Deny, Allow once, Always allow. Wait for the answer; the call returns when they choose. +1. **Call `get_context`.** Read four parts: Window (open or none), Agents (allowed, not yet allowed, blocked, or FormChem's own tab), Documents and Commands (catalogue size). Documents says "none open" or gives one line per open drawing: `- [id] "[title]" (unsaved changes) · rev [n] · [k] fragments · [formula] · [path or not saved yet]`, oldest first; the same list is in `structuredContent.documents` (`id`, `title`, `path`, `dirty`, `rev`, `fragments`, `formula`). The formula reads "still being worked out" (`formula: null`) until the engine has finished the latest revision; call again a moment later. The engine keeps the documents, so the list is current even while the window's command catalogue lags; `structuredContent.drawingTools` is true from 0.8.0. `list_open_documents` gives the same list plus `active`, the drawing the window shows, which the tools use when `doc` is left out. +2. **No window?** The drawing, edit and checking tools work without one (`render` then draws with the engine). The approval question, window commands, extensions and the person's selection need it, so an outside agent's first change fails with "No FormChem window is open to ask the person" unless the person chose Always allow before. Ask the person to run `./formchem` or open the app. +3. **Pick the route.** Drawing and editing go through the tools (`drawing`, `edit-by-id`); menu commands through `list_commands {text}` and `run_command`; extensions through `extensions_list`. A command marked `off now` is not available: do not run it. +4. **Expect the question.** The first change of an outside agent (a draw, edit or document tool, `run_command`, `extension_command`, a handoff with a state, a conversion that writes outside the temporary folder) asks the person in the window: Deny, Allow once (this call only), Always allow. Wait for the answer; the call returns when they choose. Reading never asks. 5. **Act once, report.** On a refusal, tell the person what you wanted to do and stop. +## Stop + +While your calls change the drawing the person is looking at, the title bar shows your client's name ("[agent] is editing") with a Stop button. Stop refuses every further call of yours, reads included, with "The person stopped [agent]'s access to FormChem from the window", and withdraws Always allow. A call that was already running finishes. Do not retry, reconnect under another name or work around it: say what you were about to do and that the person can let you back in with Allow again in Window > Agent Activity, after which your next change asks again. + ## Who is never asked Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tabs carry a per-tab token (`FORMCHEM_INAPP_TOKEN`, sent as a header) and are trusted for as long as the tab is open. `get_context` says "you run in FormChem's own tab" when that is you. Never copy or print that token. @@ -33,7 +41,9 @@ Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tab | Text | Do | | --- | --- | | Connection refused, or the stdio relay says the engine could not be started | Ask the person to run `./formchem install` once, then `./formchem` | +| HTTP 401, "needs the agent token", "refused the request without the agent token" | Ask the person to run `./formchem agents install` in the FormChem folder and restart the client, or to add `Authorization: Bearer` and the output of `./formchem agents token` to the FormChem entry | | "No FormChem window is open" | Ask the person to open the window, then retry once | +| "The person stopped [agent]'s access" | Stop working; see Stop above | | "did not allow agents" | Stop and report; the person can allow agents in Preferences | | "has blocked agents" | Stop; only the person can change it in Preferences | | "consent service is missing" | This build cannot ask; report it, outside agents cannot make changes here | @@ -42,5 +52,5 @@ Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tab ## Gate - [ ] `get_context` was the first call. -- [ ] The plan uses only the fourteen tools in the pack root's `references/tools.md` and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools. -- [ ] No change was attempted after a refusal. +- [ ] The plan uses only the 42 tools in the pack root's `references/tools.md` and the commands and extensions they report. +- [ ] No change was attempted after a refusal or a stop, and the agent token never appeared in a reply or a note. diff --git a/.agents/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md index ae33befa..f5e60860 100644 --- a/.agents/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: structure-analysis -description: "Reads and edits the chemistry of an open FormChem drawing through the four MCP analysis tools (properties, check_structure, stereo, substructure) and the 0.6.0 chemistry commands run with run_command: drug-like properties with their RDKit methods, the structure check with codes and severities, CIP labels (R, S, r, s, E, Z) and enhanced stereo groups (abs, and, or), substructure hits by SMARTS or a drawn query, Assign Wedges, stereo groups, explicit hydrogens, abbreviations, atom lists, query bonds, R-groups and Markush enumeration. Use when the person asks an agent for cLogP, TPSA, Lipinski, a structure check, R or S, a stereo group, a substructure match or SMARTS, or to add hydrogens, contract or expand an abbreviation, or define an R-group in FormChem." +description: "Reads and edits the chemistry of an open FormChem drawing through the MCP analysis tools (properties or compute_properties, check_structure or validate, stereo, substructure), set_stereo, and the 0.6.0 chemistry commands run with run_command: drug-like properties with their RDKit methods, the structure check with codes and severities, CIP labels (R, S, r, s, E, Z) and enhanced stereo groups (abs, and, or), substructure hits by SMARTS or a drawn query, Assign Wedges, stereo groups, explicit hydrogens, abbreviations, atom lists, query bonds, R-groups and Markush enumeration. Use when the person asks an agent for cLogP, TPSA, Lipinski, a structure check, R or S, a stereo group, a substructure match or SMARTS, or to add hydrogens, contract or expand an abbreviation, or define an R-group in FormChem." --- # Structure analysis @@ -22,7 +22,9 @@ Answer chemistry questions about the drawing with FormChem's own numbers, quoted | Stereo | `stereo {doc?, object?}` | centres, double bonds and axes with label, `state` (defined, undefined, unknown) and group (`abs`, `and1`, `or1`), the stereo groups, the chiral flag and CXSMILES | | Substructure | `substructure {doc?, smarts or query_object, objects?, chirality?, max_hits?}` | hits with the fragment id, matched atom and bond ids and the query-to-target map; `count`, `truncated` | -`doc` may be left out when one drawing is open; `object` left out means every fragment. `structuredContent` carries the same JSON as the engine's `/api/analysis` routes. The isotope pattern has no tool: it is in the person's Analysis panel (`show-analysis`). +From 0.8.0 `compute_properties` and `validate` are the same answers as `properties` and `check_structure` under the spec's names, and they take the drawing the window shows when `doc` is left out; `validate` adds `valid`. To set R or S on a centre, or E or Z on a double bond, by id, use `set_stereo` (`edit-by-id`), then read it back with `stereo`. + +`doc` may be left out when one drawing is open (the four 0.6.0 tools need it when several are open); `object` left out means every fragment. `structuredContent` carries the same JSON as the engine's `/api/analysis` routes. The isotope pattern has no tool: it is in the person's Analysis panel (`show-analysis`). ## Chemistry commands (run_command) @@ -37,6 +39,7 @@ They act on the person's selection, or on the page when nothing is selected; the | `set-atom-list`, the `set-query-bond-` commands, `clear-query-bond` | atom lists (a dialog) and query bonds on the selection | | `define-rgroup`, `enumerate-markush` | R-group definition and enumeration open dialogs for the person | | `copy-smarts`, `compute-properties`, `check-structure`, `search-substructure` | copy SMARTS to the person's clipboard, or open the panels; the tools above return the same data to the agent | +| `standardise {steps}` (0.7.0) | removes salts and solvents, neutralises, normalises functional groups, picks the canonical tautomer and more, on the selection or the page, as one undo step; read the result back with `stereo` (its CXSMILES) or `properties`. Without `steps` the dialog opens for the person | ## Procedure @@ -52,7 +55,7 @@ They act on the person's selection, or on the page when nothing is selected; the - A check issue with `fix` (`wedges` or `expand`) is repaired by the person's Fix button or by `assign-wedges` or `expand-abbreviation` on the selection; say which. - A structure check on a query drawing without `query: true` reports `query_feature` notes; they are expected, not errors. - Metal cations such as Na+ in a salt are not valence errors; do not report them as such. -- Export SMARTS in the desktop app copies instead of saving until 0.7.0; dialogs (atom list, R-group, abbreviation label) belong to the person. +- Dialogs (atom list, R-group, abbreviation label) belong to the person. ## Gate @@ -66,4 +69,4 @@ Fragment, atom and bond ids, the quoted answers, and a ready or question handoff ## Owned resources -None of its own. `references/tools.md` at the pack root holds the generated arguments of all fourteen tools; `window-commands/references/command-catalogue.md` lists the chemistry commands with the rest of the catalogue. +None of its own. `references/tools.md` at the pack root holds the generated arguments of all 42 tools; `window-commands/references/command-catalogue.md` lists the chemistry commands with the rest of the catalogue. diff --git a/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md index f4d176cd..0d6e998e 100644 --- a/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md @@ -1,46 +1,61 @@ --- name: visual-qa -description: "Checks what the person sees in FormChem when the agent cannot see the window: reading command states from list_commands, confirming a command ran, undo availability as evidence of a change, extension states and the derived values an extension returns, asking the person to look with a question handoff, and the render and validation tools that arrive in 0.8.0. Use after running a command or extension, when the person says something looks wrong, or before saying a drawing change worked." +description: "Checks an agent's own work in FormChem before it claims anything: render (a PNG or SVG of objects, the person's selection or the page, drawn by the window's own renderer, or by the engine when no window is open), get_structure (SMILES, CXSMILES, InChI, InChIKey, molfile V2000 or V3000, masses), validate (the structure check with valid), compute_properties, the write result's own structure and picture, and list_commands or Agent Activity for command states. Use after drawing or editing, before saying a drawing is right, when the person asks to see it or says something looks wrong, or when an InChIKey, SMILES or molfile is wanted." --- # Visual QA ## Purpose -Never claim a visible result you did not confirm. In 0.6.0 an agent still has no picture of the window and no render tool (it arrives in 0.8.0). Confirm through what the tools report (the reaction tools print the steps, map numbers and amounts they found; `stereo`, `check_structure` and `properties` read the chemistry after a command), and ask the person for the rest. +Never claim a visible or chemical result you did not confirm. From 0.8.0 the agent can see what the person sees and read the structure back in machine form, so every claim about a drawing rests on a tool answer from after the change. Hands back what was checked, with the values quoted and the renderer named. -## What you can confirm today +## Preconditions -| Question | How | -| --- | --- | -| Did the command run? | `run_command` returned without `isError`; its text is the window's answer | -| Is a toggle on (show-grid, menus-in-window)? | `list_commands {id}`: `checked` in the entry, when the window reports it | -| Is a command available? | `list_commands`: `off now` means not available; the catalogue comes from the window | -| Is an extension usable? | `extensions_list`: state ready, needs-permission or refused (with the reason) | -| Is the window there? | `get_context`: Window line | -| Did a drawing change land? | The command's answer, then `list_commands {id: "undo"}`: on means the active drawing has a step to undo (the catalogue can lag a moment) | -| Is a drawing open? | `list_commands {id: "save"}`: on only while one is open | -| What structure is in the drawing, and is it valid? | Only through an extension that returns `document.read` values: its SMILES, InChIKey, formula and `valence_errors` for the current revision (`extension-drawings`) | +A drawing exists and its ids are known (from a draw or edit answer, `get_structure`, `get_atoms` or `list_open_documents`). The checking tools only read: they never ask the person and never add an undo step. -The catalogue is mirrored from the window when it opens and when commands change; right after a command, a second `list_commands {id}` shows the state the window last sent. +## The checks -## What you cannot confirm today +| Question | Tool | What to read | +| --- | --- | --- | +| Is it the structure that was asked for? | the write result itself, or `get_structure {object}` | `smiles` and `inchikey`; compare InChIKeys (the first block is the connectivity, the second stereo and isotopes, the last letter the protonation: N neutral, M one proton fewer) | +| Does it look right? | `render {ids}` (or `scope: "page"`, `scope: "selection"`) | the image: overlaps, crossing bonds, labels touching, wedges where expected, a scheme in reading order | +| Is it chemically valid? | `validate {object?}` | `valid`, then each issue's `code`, `severity`, `text`, `atoms`, `bonds` | +| What are its properties? | `compute_properties {object?}` | each value with its `method`; quote both | +| The molfile, InChI or masses | `get_structure {object}` | `molfile` and `molfile_version` (V3000 only when the structure needs it), `inchi`, `mw`, `exact_mass`, `mz` for charged structures | +| What did the person select? | `get_structure {selection: true}` or `render {scope: "selection"}` | needs the window open | +| Did a window command work? | the `run_command` answer, then `list_commands {id}` | `checked` for toggles, `off now` with its reason | -How the window looks: the drawing on the canvas, layout, theme, a dialog's contents, the Analysis panel's values, whether a panel is in the way. For those, post `handoff {state: "question", note}` asking the person to look ("Does the Analysis panel show C9H8O4 for the new structure?") and wait for their answer in the conversation. +## Reading a picture -## From 0.8.0 +`render` answers with the image and `renderer`: -The agent drawing tools add `render` (an image of an object, a selection or the page), `get_structure` and `validate`, so an agent can check its own drawing. Until then never describe a drawing as checked or as looking right on the strength of a command's answer alone. +- **`window`**: the FormChem window drew it with the same renderer as File > Export, in the person's display preferences, on white. This is what the person sees; arrows, plus signs, text, brackets and captions are included. +- **`engine`**: no window answered, so the engine drew the structures with RDKit in the journal style. Arrows, plus signs and text are left out (a warning says how many), and label placement differs from the window. Good for checking a structure, not for judging the layout the person sees. + +Size it to what you need: the default PNG is 144 dpi; pass `width` or `height` (pixels) to fit, or `format: "svg"` to read the drawing as text. Every write already carries a PNG of what it touched, up to 640 x 480, so a separate `render` is for the whole page, a scheme, or a closer look. ## Procedure -1. Act (`run_command`, `extension_command`). -2. Read the result text. An error ends the check: report it. -3. Confirm the state with `list_commands {id}` or `extensions_list` when the question is a state. -4. For anything only the eye can judge, ask the person with a question handoff. -5. Report what was confirmed and what the person was asked to look at. +1. After a change, read the write result: its SMILES, InChIKey, warnings and picture. +2. If the request had a specific target (a named molecule, a stereoisomer, a charge), compare it with `get_structure` or the result's InChIKey. Report a mismatch plainly, with both values. +3. If how it looks matters (a scheme, a figure, several structures on a page), `render {scope: "page"}` and look for overlaps, crossings and reading order. Fix with `move`, `align` or `clean_layout` (`edit-by-id`), one call each. +4. When the person cares about correctness, `validate` and report errors and warnings by code. +5. Say what you checked and how ("checked with get_structure: InChIKey BSYNRYMUTXBXSQ-UHFFFAOYSA-N, as expected; the window's picture shows no overlaps"). + +## What still needs the person + +The person's screen beyond the drawing: panels, dialogs, menus, the theme. A dialog a command opened waits for them. For those, ask with `handoff {state: "question", note}` and wait. ## Gate -- [ ] Every "it worked" in the reply rests on a tool result. -- [ ] Anything visual that no tool confirms was put to the person, not assumed. +- [ ] Every "it is right" or "it looks right" rests on a tool answer from after the last change. +- [ ] The renderer of any picture relied on was named when it was the engine. +- [ ] Values were quoted as the tools gave them (InChIKey in full, properties with methods). + +## Hands back + +What was checked, the quoted values, and any problem found with the ids involved. + +## Owned resources + +None of its own. `references/tools.md` at the pack root lists the arguments of `render`, `get_structure`, `validate` and `compute_properties`. diff --git a/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md b/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md index 6dc92811..f27eb4fe 100644 --- a/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md +++ b/.agents/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md @@ -1,13 +1,13 @@ --- name: window-commands -description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles} or a template with insert-template {id}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, stacking order, group and ungroup, clean-structure, layout-structure, check-structure, the 0.6.0 chemistry commands, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist." +description: "Runs the FormChem window's own commands through run_command for what the 0.8.0 drawing tools do not cover: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles} or a template with insert-template {id}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, stacking order, group and ungroup, clean-structure, layout-structure, check-structure, the 0.6.0 chemistry commands, the 0.7.0 import, export, print, copy, standardise, scale, grid and dark page commands, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, import, insert, tidy, arrange, resize, export, copy, undo or save something in FormChem, or asks which drawing commands exist." --- # Window commands ## Purpose -Do drawing work in FormChem with the commands the person has, honestly. `run_command` runs one command in the window exactly as the person's click would, so whatever a command does for the person it does for the agent, prompts included. The agent cannot type into a prompt in the window, cannot see the canvas, cannot pick single atoms and cannot draw atoms one by one. +Reach what only the window's commands do, honestly: export and print for the person, the clipboard, Standardise, templates, the grid and dark page, the chemistry commands and their dialogs, Preferences. `run_command` runs one command in the window exactly as the person's click would, so whatever a command does for the person it does for the agent, prompts included. The agent cannot type into a prompt in the window and cannot pick single atoms on the canvas. From 0.8.0 drawing, editing by id, reading back, rendering and converting have their own tools (`drawing`, `edit-by-id`, `visual-qa`); prefer them, because they place in free space, work without the window and answer with the structure. Most canvas commands act on the canvas selection. The agent sets the selection two ways only: `select-all`, or `insert-smiles {smiles}`, which leaves the inserted structure selected. Anything else the person selected stays as they left it, so say what the command will act on. @@ -23,19 +23,27 @@ Most canvas commands act on the canvas selection. The agent sets the selection t | The person asks | Do | | --- | --- | -| Open this file (absolute path to a `.fchem`, `.mol`, `.sdf`, `.smi`, `.cml`, `.cdxml`) | `run_command {id: "open-recent", params: {path}}`; a structure file becomes a new unsaved drawing | -| Draw or insert a structure from SMILES | `run_command {id: "insert-smiles", params: {smiles: "[SMILES]"}}`: one undo step into the active drawing (a new one when none is open), centred in the visible page and selected; the answer names the new fragment ids and the drawing. Then `get_context` for the formula. If `list_commands {id: "insert-smiles"}` lists no `smiles` param (an older build), run it bare and post `handoff {state: "question", note: "Paste [SMILES] into the SMILES prompt and press Insert"}`; never claim the structure was drawn until the person confirms | +| Open this file (absolute path to a `.fchem`, a chemistry file, or a `.svg`, `.png`, `.pdf` or `.eps` FormChem exported) | `run_command {id: "open-recent", params: {path}}`; a structure file becomes a new unsaved drawing | +| Draw or insert a structure from SMILES | Use `draw_from_smiles` (`drawing`): it places the structure in free space and answers with its SMILES, InChIKey and a picture. `run_command {id: "insert-smiles", params: {smiles}}` still works when the person wants it in the middle of the view and selected, so the next selection command acts on it; the answer names the new fragment ids | | Insert a ring, amino acid, sugar, protecting group, reagent or glassware | `run_command {id: "insert-template", params: {id: "[template id]"}}`: one undo step, centred in view at the drawing's bond length, selected; without `id` it opens the library for the person. Ids such as `benzene`, `l-alanine` come from the engine's `GET /api/templates` | -| Draw from a name, a molfile text or by atoms; place an arrow, a shape or a caption | No command does this before 0.8.0 (the insert-arrow, insert-shape and insert-table commands only pick the person's tool). Offer SMILES through `insert-smiles {smiles}`, a template, or a file through `open-recent` | +| Draw by atoms; place an arrow, a caption or text | The edit tools do it by id (`edit-by-id`): `add_atom`, `add_bond`, `add_arrow`, `add_text`. Shapes, brackets and tables have no tool and no drawing command (insert-arrow, insert-shape and insert-table only pick the person's tool): ask the person | +| Draw from a name | Not yet in any version up to 0.8.0: write the SMILES and use `draw_from_smiles`, saying you did | | Stack or group objects | `bring-front`, `bring-forward`, `send-backward`, `send-back`, `group`, `ungroup` on the selection; off with "Select something on the canvas first" when nothing is selected | | Anything about the reaction in the drawing | Load `reactions` | | Undo the last change | `run_command {id: "undo"}`: one transaction, whoever made it | | Tidy or lay out the structure | `clean-structure` (bond lengths and angles, keeps place and stereo) or `layout-structure` (fresh 2D coordinates): they act on the selection, or on every structure on the page when nothing is selected. Right after `insert-smiles` they act on the inserted structure | | Delete, duplicate, flip, rotate, align, distribute | `select-all` (or the structure `insert-smiles` just selected), then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h` or `distribute-v`. They are off with "Select something on the canvas first" when nothing is selected | | Save | `save`; a drawing never saved before asks the person for a name, so say so in the handoff | -| Check the structure | The `check_structure` tool returns the issues with codes and ids (`structure-analysis`); `check-structure` opens the Check Structure panel for the person | -| Show the formula, masses or properties | `get_context` gives the formula of each open drawing and the `properties` tool every value with its method (`structure-analysis`); `show-analysis` or `compute-properties` opens the Analysis panel with the isotope pattern for the person | +| Check the structure | The `validate` tool returns the issues with codes and ids (`visual-qa`); `check-structure` opens the Check Structure panel for the person | +| Show the formula, masses or properties | `get_structure` gives formula and masses and `compute_properties` every value with its method (`visual-qa`, `structure-analysis`); `show-analysis` or `compute-properties` opens the Analysis panel with the isotope pattern for the person | | Stereo, hydrogens, abbreviations, query features, R-groups | Load `structure-analysis` for the commands and the tools that read the result | +| Bring a file's structures into the open drawing | `run_command {id: "import", params: {path: "[absolute path]"}}`: chemistry files (molfile, SD, RXN, RD, SMILES, CXSMILES, SMARTS, InChI, CML, CDXML, CDX), `.fchem` drawings and pictures FormChem exported; lands in free space, selected, one undo step; an SD file brings at most 50 structures and the answer says what came in. `open-recent {path}` opens a file as its own drawing instead | +| Save a picture or a chemistry file | `export-png`, `export-svg`, `export-pdf`, `export-eps`, `export-cdxml`, `export-mol`, `export-smiles` (whole page), or `export-picture` (the dialog: scope, resolution, background, scale). In the desktop app each shows the person's save dialog; in a browser it downloads. The agent does not receive the file: say where the person will find it, and that pictures keep the drawing inside so they reopen editable | +| Print | `print`: the system print dialog for the person; the page at real size, or the selection in its place | +| Put the structure on the person's clipboard | `copy-smiles`, `copy-cxsmiles`, `copy-molfile`, `copy-inchi`, `copy-inchikey`, `copy-smarts`, `copy-svg`, `copy-png`, `copy-cdxml` (the selection, or the page); `copy` writes the drawing, SMILES and a picture at once. To read SMILES, a molfile or another format yourself, use `get_structure` or `convert` instead | +| Make a structure larger or smaller on the sheet | `scale-selection {percent: 150}` or `{bond_length: 20}` (with `labels: false` to keep line widths and fonts), `scale-up`, `scale-down` (10 percent, exact inverses); the selection, or every structure on the page about its own centre. `zoom-in` only changes the view: never use zoom when the person wants the drawing larger | +| Remove salts, neutralise, pick the tautomer | `standardise {steps: ["salts", "neutralise"]}` (steps: cleanup, normalise, salts, largest, reionise, neutralise, tautomer, isotopes, stereo, strip_h); without `steps` the dialog opens for the person | +| Grid, snapping, dark page | `grid-type {type}` (lines, dots, crosses, isometric, isometric-dots, hex, hex-dots), `grid-spacing {value, unit}` (a number or "bond"), `grid-settings {...}`, `snap-to-grid {on}`, `show-grid {on}`, `dark-page {on}`; `scope: "default"` changes the default for new drawings. The grid is saved with the drawing; the dark page is a screen choice and never reaches exports | ## Rules diff --git a/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md b/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md index 7f9e876c..dc93e5af 100644 --- a/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md +++ b/.agents/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md @@ -1,6 +1,6 @@ # Commands that touch a drawing -The window's command registry, as far as it concerns drawings, for FormChem 0.6.0. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. +The window's command registry, as far as it concerns drawings, for FormChem 0.8.0 (the commands are those of 0.7.0, plus `agent-activity`, which opens Window > Agent Activity for the person). From 0.8.0 the agent's own tools draw, edit, read back, render and convert; this page covers what the window's commands add. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. ## Contents @@ -10,7 +10,9 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.6. - Templates, objects and arrangement - Reactions - Stereo, queries and analysis -- The canvas and the view +- Import, export, print and the clipboard +- Standardise and size on the sheet +- The canvas, the view and the grid - Registered but off until a later version - What no command does yet @@ -23,7 +25,7 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.6. | Command | Params | What it does | | --- | --- | --- | | `new-document` | | creates an empty drawing and makes it active (Home closes) | -| `open-recent` | `path` (absolute) | opens that file: a `.fchem` drawing, or a structure file (molfile, SDF, RXN, SMILES, CXSMILES, InChI, CML, cdxml, cdx) imported into a new unsaved drawing; without `path` it shows Home | +| `open-recent` | `path` (absolute) | opens that file: a `.fchem` drawing, a chemistry file (molfile, SD, RXN, RD, SMILES, CXSMILES, SMARTS, InChI, CML, CDXML, CDX) imported into a new unsaved drawing with an import report for the person, or a picture FormChem exported with its drawing inside; without `path` it shows Home | | `open` | | shows the file chooser to the person; an agent cannot answer it | | `save` | | saves the active drawing; a drawing with no file yet asks the person for a name in the browser window | | `save-as`, `save-copy` | | ask the person where or under what name | @@ -38,7 +40,7 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.6. | `undo`, `redo` | | undoes or redoes the last change to the active drawing (one transaction each); off when there is nothing to undo or redo | | `select-all` | | selects everything on the active page of the canvas; while a text field has focus it selects the field's text | | `delete` | | removes the selection (bare carbons left behind go with it); keys Delete, Backspace | -| `duplicate` | | copies the selection 10 pt down and right and selects the copy; key Mod+D | +| `duplicate` | | copies the selection 10 pt down and right and selects the copy, with its stereo groups, R-groups and reaction steps; key Mod+D | | `flip-horizontal`, `flip-vertical` | | mirror the selection about its centre | | `rotate-90` | | turns the selection 90 degrees clockwise about its centre | | `align-left`, `align-center`, `align-right`, `align-top`, `align-middle`, `align-bottom` | | line up the selected objects on that edge or centre | @@ -94,18 +96,52 @@ From 0.6.0. They act on the selection, or the page when nothing is selected, and | `set-query-bond-any`, `set-query-bond-single_or_double`, `set-query-bond-single_or_aromatic`, `set-query-bond-double_or_aromatic`, `clear-query-bond` | query bonds on the selected bonds (list_commands gives the exact ids) | | `define-rgroup`, `enumerate-markush` | open the R-group and enumeration dialogs for the person | | `search-substructure` | selects matches of the selected atoms, or asks the person for SMARTS | -| `copy-smarts`, `export-smarts` | SMARTS to the person's clipboard, or a `.sma` file (the desktop app copies instead until 0.7.0) | +| `copy-smarts`, `export-smarts` | SMARTS to the person's clipboard, or a `.sma` file the person saves | | `compute-properties`, `copy-analysis` | open the Analysis panel on the selection; copy its values with methods to the person's clipboard | | `show-stereo`, `show-stereo-groups`, `show-query-marks` | toggle the CIP labels, the enhanced stereo group labels and the query tags on the canvas | -## The canvas and the view +## Import, export, print and the clipboard + +From 0.7.0. Exports and copies act on the selection where the command says so, else the active page; none changes the drawing. + +| Command | Params | What it does | +| --- | --- | --- | +| `import` | `path` (absolute, optional) | inserts a chemistry file, a `.fchem` drawing or a picture with its FormChem drawing into the active drawing (a new one when none is open), in free space right of or below what is there, selected, one undo step per file, with the import report for the person; an SD file brings at most 50 structures. The answer names what came in. Without `path` the person picks files in a dialog | +| `export-png`, `export-svg`, `export-pdf`, `export-eps` | | save the whole page as a picture with the drawing kept inside (300 dpi PNG by default); the desktop app shows the person's save dialog, a browser downloads | +| `export-picture` | | opens the Export Picture dialog for the person (format, scope, resolution, background, scale, margin) | +| `export-cdxml`, `export-mol`, `export-smiles` | | save the page as CDXML, molfile or SMILES; warn and error report items show to the person | +| `print` | | the print dialog for the person: the page at real size, or the selection in its place (Mod+P) | +| `copy`, `cut`, `paste` | | the drawing on the person's clipboard (the selection, or the whole page for `copy`); `paste` reads it back at the view centre, one undo step | +| `copy-smiles`, `copy-cxsmiles`, `copy-molfile`, `copy-inchi`, `copy-inchikey`, `copy-smarts`, `copy-svg`, `copy-png`, `copy-cdxml` | | one form on the person's clipboard; reactions become reaction SMILES or RXN | +| `paste-special` | | lists what the clipboard holds for the person to choose (Shift+Mod+V) | + +The agent never receives the saved file or the clipboard text. To read a structure as text, use `get_structure` (SMILES, CXSMILES, InChI, InChIKey, molfile); for another format `convert`; for a picture `render` (the `drawing` and `visual-qa` sub-skills of this pack). + +## Standardise and size on the sheet + +| Command | Params | What it does | +| --- | --- | --- | +| `standardise` | `steps` (list, optional) | standardises the selected structures, or every structure on the page together, as one undo step: `cleanup`, `normalise`, `salts`, `largest`, `reionise`, `neutralise`, `tautomer`, `isotopes`, `stereo`, `strip_h`, always in that order; without `steps` it opens the dialog with a preview for the person | +| `scale-selection` | `percent` (5 to 2000) or `bond_length` (1 to 500 pt), `labels` (boolean, optional) | makes the selection, or every structure on the page about its own centre, larger or smaller on the sheet, one undo step; answers "Scaled to 138.9%, bond length 20.0 pt". `labels: false` keeps line widths and fonts. Both `percent` and `bond_length` is an error; no params opens the Scale dialog | +| `scale-up`, `scale-down` | | 10 percent up, or the exact inverse (Alt+Mod+=, Alt+Mod+-) | +| `scale-labels` | | toggles whether labels and text scale with structures (on by default) | + +Zoom never changes the drawing; use these when the person wants a structure larger. + +## The canvas, the view and the grid | Command | What it does | | --- | --- | | `zoom-in`, `zoom-out` | zoom the canvas one step in or out (Mod+=, Mod+-) | | `zoom-fit` | fits the whole page in the view (Mod+0) | | `zoom-100` | actual size (Mod+1) | -| `show-grid` | toggles the paper grid; the result says whether it is now on | +| `show-grid` | param `on` (optional): shows or hides the grid in this window; the result says whether it is now on | +| `dark-page` | param `on` (optional): the dark page view on or off (on by default); screen only, never in exports; returns `{on}` | +| `snap-to-grid` | param `on` (optional): new bonds, chains, rings and objects and moves land on grid points | +| `grid-type` | params `type` (`lines`, `dots`, `crosses`, `isometric`, `isometric-dots`, `hex`, `hex-dots`), `scope` (`"default"` for new drawings): one undo step in the drawing | +| `grid-spacing` | params `value` (a number or `"bond"`), `unit` (`pt`, `mm`, `cm`, `in`), `scope` | +| `grid-settings` | params `type`, `spacing`, `unit`, `major` (0 to 50), `strength` (`faint`, `normal`, `strong`), `scope`; no params opens the Grid Settings dialog for the person | +| `grid-lines`, `grid-dots`, `grid-crosses`, `grid-isometric`, `grid-isometric-dots`, `grid-hex`, `grid-hex-dots` | the View > Grid radio items | | `show-analysis` | opens the Analysis panel | | `find`, `show-rulers` | Edit > Find (next, previous, replace) and View > Show Rulers with guides, for the person | | `toggle-analysis`, `analysis-panel` | shows or hides the Analysis panel (formula, masses, m/z, elemental analysis from the engine, for the selection or the whole page) | @@ -113,8 +149,8 @@ From 0.6.0. They act on the selection, or the page when nothing is selected, and ## Registered but off until a later version -`import`, `print`, `copy-smiles`, `copy-molfile`, `copy-inchi`, `copy-svg` and the whole-drawing `export-png`, `export-svg`, `export-pdf`, `export-cdxml`, `export-mol`, `export-smiles` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); `demos` (0.13.0). The reaction copy and export commands and `copy-smarts` and `export-smarts` already work. Running one returns "is not available right now: Arrives in [version]". Say so; do not retry. +`insert-name` (0.9.0); the 3D commands `view-3d`, `build-3d`, `minimize-3d`, `conformers` (0.10.0); `demos` (0.13.0). Every 0.7.0 placeholder is now a working command. Running an off one returns "is not available right now: Arrives in [version]". Say so; do not retry. ## What no command does yet -Drawing atoms, bonds, arrows or shapes at given positions, selecting particular atoms or objects, typing stoichiometry amounts, filling the person's dialogs (atom list, R-group, abbreviation label), reading the whole structure back beyond what `get_context` and the analysis tools give (the formula, SMILES and CXSMILES in `stereo`, properties, issues and substructure hits), rendering an image or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel. +Selecting particular atoms or objects, typing stoichiometry amounts, and filling the person's dialogs (atom list, R-group, abbreviation label). Drawing atoms, bonds, arrows and text at given positions, reading the structure back, rendering and converting are not commands: the 0.8.0 tools do them (`drawing`, `edit-by-id`, `visual-qa`). An installed extension with the `document` permission can also read and change the drawing (`extension-drawings`). diff --git a/.agents/skills/formchem-skillset/EVALS.json b/.agents/skills/formchem-skillset/EVALS.json index 46a20dac..95dd8f8c 100644 --- a/.agents/skills/formchem-skillset/EVALS.json +++ b/.agents/skills/formchem-skillset/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-skillset", - "notes": "Run in a FormChem checkout at 0.6.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", + "notes": "Run in a FormChem checkout at 0.8.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", "evals": [ { "id": 1, @@ -64,8 +64,8 @@ "files": [], "expected_behavior": [ "Edits no file in the repository and makes no commit", - "Points the request at formchem-harness (driving FormChem through its MCP server) rather than adding drawing code", - "Does not add an MCP drawing tool ahead of its phase (0.8.0)" + "Points the request at formchem-harness (draw_from_smiles through FormChem's MCP server) rather than adding drawing code", + "Does not add a draw_from_name tool or any tool of a later phase" ] }, { @@ -156,10 +156,73 @@ "Sets @tauri-apps/cli in frontend/package.json to a 2.13 release in the same change as package-lock.json, checking the @tauri-apps/plugin-* packages against their tauri-plugin-* crates", "Runs ./formchem desktop check (not a full tauri build on a small machine) and records the bump in the HASHOUT log" ] + }, + { + "id": 15, + "name": "new-export-format", + "prompt": "Let FormChem export XYZ files from a drawing.", + "files": [], + "expected_behavior": [ + "Loads formats-and-export and clean-room before editing", + "Adds one record to formats.TABLE with every feature XYZ cannot hold in loses, and a writer in writers.py that reports what it leaves out", + "Adds the extension to the Open lists and files.SUFFIXES only where it reads or saves it, updates docs/FORMATS.md, and round-trips a scratch corpus outside the repository" + ] + }, + { + "id": 16, + "name": "pdf-export-lost-text", + "prompt": "PDF exports from the macOS FormChem app have no atom labels, but the browser version is fine.", + "files": [], + "expected_behavior": [ + "Loads formats-and-export and desktop", + "Checks /api/pictures/capabilities in the frozen engine and that fontTools' submodules are collected in setup/freeze_backend, its .bat twin and build_app's own freeze", + "Never builds the picture from the live canvas and records the fix in the backend HASHOUT log" + ] + }, + { + "id": 17, + "name": "batch-convert-stops", + "prompt": "./formchem convert stops at record 512 of my SD file with a valence error; make it keep going.", + "files": [], + "expected_behavior": [ + "Loads command-line and reads services/chem/stream.py and services/batch.py", + "Keeps one reader: the failing record is reported with its number, name and RDKit's own reason through stream.explain, and the run continues", + "Checks exit code 0, output order and a byte-identical result with --jobs 2 on a scratch file" + ] + }, + { + "id": 18, + "name": "add-an-edit-tool", + "prompt": "Add an MCP tool to FormChem that flips a structure horizontally by id.", + "files": [], + "expected_behavior": [ + "Loads the agents sub-skill and reads services/agent_edits.py and routers/mcp.py before editing", + "Writes a pure builder fn(doc, args) -> (ops, info) in agent_edits.py that mirrors the window's Flip and raises EditError with the next step", + "Adds the _tool entry, a t_ handler that goes through _edit with an undo label, and the name to MUTATING", + "Runs ./formchem agents sync and sync --check, and checks on a scratch engine that one call raises the revision by one and answers with an image" + ] + }, + { + "id": 19, + "name": "agent-call-shows-done-after-undo", + "prompt": "Agent Activity shows an agent call as Done again after I undid it and kept drawing; fix it.", + "files": [], + "expected_behavior": [ + "Loads the agents sub-skill and reads services/agent_log.py after_change and _stacks", + "Keeps undone true while the call's transaction is not back on the undo stack, rather than reading the redo stack alone", + "Leaves the window mirror (app/agent-calls.ts) to follow the engine's agentCall messages instead of computing undone itself" + ] } ], "trigger_evals": [ + {"query": "the formchem agent render tool falls back to the engine picture", "should_trigger": true}, + {"query": "add a field to formchem's agent call log in services/agent_log.py", "should_trigger": true}, {"query": "add an MCP tool to formchem", "should_trigger": true}, + {"query": "formchem's CDXML export drops the reaction arrow", "should_trigger": true}, + {"query": "the formchem desktop app takes 30 seconds to open on macOS", "should_trigger": true}, + {"query": "paste from formchem into Word loses the structure, fix the clipboard flavours", "should_trigger": true}, + {"query": "formchem lays out Taxol with labels touching", "should_trigger": true}, + {"query": "export my FormChem drawing as PDF", "should_trigger": false}, {"query": "formchem shows (S) on the wrong side of the stereocentre after contracting CO2H", "should_trigger": true}, {"query": "fix formchem's SMARTS export for atom lists in services/chem/query.py", "should_trigger": true}, {"query": "formchem build_app stops with the Tauri CLI did not install", "should_trigger": true}, diff --git a/.agents/skills/formchem-skillset/SKILL.md b/.agents/skills/formchem-skillset/SKILL.md index bc0400e8..4bde2c2d 100644 --- a/.agents/skills/formchem-skillset/SKILL.md +++ b/.agents/skills/formchem-skillset/SKILL.md @@ -1,17 +1,17 @@ --- name: formchem-skillset -description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (docs/FORMAT.md, model.ts, model.py, ops, undo, the fchem package), the engine store, the RDKit service (SMILES, InChIKey, masses, layout, warnings, CIP and enhanced stereo, wedges, abbreviations, queries, SMARTS, R-groups, properties, the structure check, isotope patterns), reactions (perception, Indigo mapping, balance, stoichiometry, RXN, roles), the SVG canvas renderer and marks, drawing tools, hover hotkeys, hit testing, arrows, shapes, captions, templates, the window shell, menus, themes, the agent dock, Form extensions, an MCP tool, the Tauri shell and desktop build, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck, and not for standalone RDKit scripts." +description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (FORMAT.md, model.ts, model.py, ops, undo), the engine store, the RDKit service (identifiers, the scored 2D layout, CIP, stereo groups, abbreviations, queries, SMARTS, R-groups, properties, the structure check), reactions, file formats and loss reports, picture export with the embedded drawing, the clipboard, the command line, Standardise, the SVG canvas, dark page, grids, scaling, tools, annotations, the shell, menus, the dock, Form extensions, the MCP server and agent tools (agent_out, agent_edits, agent_log, the render bridge, the agent token, Agent Activity), the Tauri shell and one-folder engine, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for using FormChem (formchem-harness), other Form apps such as FormDeck, or standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.6.0" + version: "0.8.0" --- # FormChem skillset -Route every change to FormChem's code through this file. It maps the subsystems that exist today, states the laws that hold everywhere and names the specialist to load. FormChem is a Python 3.12 FastAPI engine (`backend/`, port 8220), a vanilla TypeScript and Vite window (`frontend/`, port 5220, no framework) that talks to the engine over REST and one WebSocket, and a Tauri 2 shell (`src-tauri/`) that runs the frozen engine as a sidecar. +Route every change to FormChem's code through this file. It maps the subsystems that exist today, states the laws that hold everywhere and names the specialist to load. FormChem is a Python 3.12 FastAPI engine (`backend/`, port 8220), a vanilla TypeScript and Vite window (`frontend/`, port 5220, no framework) that talks to the engine over REST and one WebSocket, and a Tauri 2 shell (`src-tauri/`) that runs the frozen engine from a folder inside the app on macOS and as a sidecar elsewhere. -**Where FormChem is (0.6.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 added the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. 0.5.0 added reactions and annotations: every drawn object kind through one renderer registry with its tool and handles, z-order and groups, the engine's reaction perception, mapping, balance, stoichiometry and RXN exchange with the Reaction menu and four MCP tools, the Stoichiometry panel, the template library and media. 0.6.0 adds stereo, queries and analysis: enhanced stereo groups and the chiral flag in RDKit, the CIP report, wedge assignment, abbreviations and explicit hydrogens, query atoms and bonds, SMARTS, substructure search, V3000 query molfiles, R-groups and Markush enumeration, properties with methods, the structure check, the isotope pattern, the `/api/analysis` router with four read-only MCP tools, the keyed marks layer, the chemistry commands and dialogs, Set Reaction Roles, and the Tauri CLI pin for the desktop build. Exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled. +**Where FormChem is (0.8.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 added the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. 0.5.0 added reactions and annotations: every drawn object kind through one renderer registry with its tool and handles, z-order and groups, the engine's reaction perception, mapping, balance, stoichiometry and RXN exchange with the Reaction menu and four MCP tools, the Stoichiometry panel, the template library and media. 0.6.0 added stereo, queries and analysis: enhanced stereo, CIP, wedges, abbreviations, hydrogens, queries and SMARTS, substructure search, R-groups and Markush, properties with methods, the structure check, the isotope pattern, the `/api/analysis` router with four read-only MCP tools, the marks layer and the chemistry commands. 0.7.0 added formats and exchange (readers, writers and report items, CDXML and CDX through Indigo, pictures with the embedded drawing and the engine's own PDF and EPS writer, print, the clipboard, File > Import, the command line, Standardise) plus the desktop test fixes: the one-folder macOS engine, the scored 2D layout, the dark page, scaling, grids and snapping, the folding menu row and the quick command state mirror. 0.8.0 adds the agent tools (42 MCP tools: documents, drawing, `render` through the window, reading back, conversion, 14 edit tools by id), the agent call log with Agent Activity and Stop, and the agent token. Names, spectra (0.9.0) and 3D (0.10.0) come later (`DEV_PLAN.md`). Do not write a later phase's code ahead of it; its commands stay registered and disabled. ## Subsystem map @@ -22,16 +22,19 @@ Route every change to FormChem's code through this file. It maps the subsystems | The format contract: document.json, styles, ids, ops and inverses, transactions, validation, coalescing, the derived cache shape | `docs/FORMAT.md`, `frontend/src/engine/model.ts`, `engine/ops.ts`, `backend/app/services/model.py`, `services/ops.py` | `document-format` | | Chemistry engine on RDKit: conversion, sanitising, valence, aromaticity, identifiers, formula, masses, layout, file reading and writing, the derived cache | `backend/app/services/chem/`, `backend/app/routers/chem.py` | `chemistry-engine` | | Window documents and chemistry: the document client and session, the actions behind File and Insert, the Analysis panel, local valence, rings, labels and formula | `frontend/src/engine/client.ts`, `engine/session.ts`, `engine/client-api.ts`, `app/documents.ts`, `ui/analysis-panel.ts`, `frontend/src/chem/` | `window-shell` (chemistry rules in `chemistry-engine`) | -| Canvas: SVG renderer, drawing tools and hover hotkeys, view, hit testing, selection, text editor, canvas context menus, tool rail | `frontend/src/canvas/` (`render/`, `tools/`, `geom.ts`, `view.ts`, `hit.ts`, `selection.ts`, `text-editor.ts`, `context.ts`, `types.ts`), `ui/tool-rail.ts`, `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | `canvas` | +| Canvas: SVG renderer, drawing tools and hover hotkeys, view, hit testing, selection, text editor, canvas context menus, tool rail; from 0.7.0 the dark page, grids and snapping, scale handles | `frontend/src/canvas/` (`render/`, `tools/`, `dark-page.ts`, `grid.ts`, `grid-layer.ts`, `tools/scale.ts`, `geom.ts`, `view.ts`, `hit.ts`, `selection.ts`, `text-editor.ts`, `context.ts`, `types.ts`), `ui/tool-rail.ts`, `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | `canvas` | | Drawn objects: the object kind registry and kind modules, anchors, bounds, drawn-outline hits, annotation tools and handles, captions, z-order and groups, the template library, media | `frontend/src/canvas/render/objects.ts` and its kind modules, `canvas/hit-objects.ts`, `canvas/tools/objects.ts`, `tools/handles.ts`, `app/object-commands.ts`, `ui/template-*.ts`, `backend/app/services/templates.py`, `routers/templates.py`, `backend/app/data/templates/`, the media routes in `routers/documents.py` | `annotations` | | Reactions: perception, atom mapping, balance, stoichiometry (engine and window), reaction SMILES and RXN, the Reaction menu, the MCP reaction tools | `backend/app/services/chem/` (`geometry`, `reactions`, `mapping`, `balance`, `stoich`, `rxnio`, `scheme`), `routers/reactions.py`, `frontend/src/chem/stoich.ts`, `ui/stoich-panel.ts`, `app/reaction-commands.ts`, `engine/reactions-api.ts`, `docs/REACTIONS.md` | `reactions` | | Stereo, queries and analysis: stereo groups, CIP report, wedges, abbreviations, hydrogens, queries and SMARTS, substructure search, V3000 queries, Markush, properties, the structure check, the isotope pattern, their routes, tools, commands, marks and panels | `backend/app/services/chem/` (`stereo`, `superatom`, `hydrogens`, `query`, `search`, `v3000`, `markush`, `props`, `check`, `isotopes`), `routers/analysis.py`, `frontend/src/engine/analysis-api.ts`, `app/chem-edits.ts`, `app/chem-commands.ts`, `canvas/render/marks-*.ts`, the 0.6.0 dialogs in `ui/`, `docs/ANALYSIS.md` | `stereo-and-queries` | +| Formats and export: the formats table, report items, readers and writers, CDXML and CDX through Indigo, RD files, CML, the export, parse, import and file write routes, pictures (SVG, PNG, PDF, EPS) with the embedded drawing, the save path, print, the import report, File > Import | `backend/app/services/chem/` (`formats`, `report`, `io`, `writers`, `cdxio`, `rdfio`, `cml`), `services/embedded_source.py`, `services/pictures/`, `services/importers.py`, `routers/files.py`, `routers/pictures.py`, `frontend/src/app/` (`picture`, `embedded-source`, `save-file`, `export-commands`, `print`, `import-files`), `ui/export-dialog.ts`, `ui/import-report.ts`, `docs/FORMATS.md` | `formats-and-export` | +| Clipboard: the native payload and paste plan, text formats, flavours per platform, Copy As, Paste Special, Duplicate | `frontend/src/app/clip-*.ts`, `app/clipboard.ts`, `ui/paste-special-dialog.ts`, `ui/native-menu.ts` `ALWAYS_NATIVE` | `clipboard` | +| Command line and batch: convert, batch, descriptors, render, the stream reader, Standardise (engine, route, dialog) | `backend/app/cli.py`, `services/batch.py`, `services/chem/` (`stream`, `records`, `standardise`, `depict`), `setup/convert`, `frontend/src/ui/standardise-dialog.ts`, `app/standardise-command.ts`, `docs/CLI.md` | `command-line` | | Window shell: app root, command registry, palette, Home, title bar, status bar, Preferences, dialogs, themes, i18n, styles | `frontend/src/app.ts`, `app/commands-shell.ts`, `commands/registry.ts`, `io/`, `ui/`, `i18n/`, `styles/` | `window-shell` | | Menus: in-window menu bar, native macOS menus, context menus | `frontend/src/ui/menu.ts`, `ui/native-menu.ts`, `ui/context-menu.ts`, `app/menus.ts`, `styles/menu.css` | `menus` | | Terminal and agent dock | `frontend/src/dock/` (vendored), `frontend/src/dock-adapter.ts`, `backend/app/routers/terminal.py`, `services/terminal.py`, `services/claude_code.py`, `services/agent_programs.py`, `services/agent_lookup.py` (vendored) | `dock` | | Form extensions (host API 1) | `frontend/src/extensions/`, `backend/app/routers/extensions.py`, `services/formext_host.py` (vendored), `docs/EXTENSIONS.md` | `extensions` | -| MCP server, commands catalogue, agent setup and skills | `backend/app/routers/mcp.py`, `routers/commands.py`, `setup/mcp_stdio.py`, `setup/agents.py`, `setup/catalogue.py`, `agents/manifest.json`, `.claude/skills`, `.agents/skills` | `agents` | -| Desktop app and sidecar | `src-tauri/`, `backend/formchem_engine.py`, `setup/freeze_backend`, `setup/desktop_*`, `build_app` | `desktop` | +| MCP server, agent tools, the call log and Agent Activity, the agent token, commands catalogue, agent setup and skills | `backend/app/routers/mcp.py`, `services/agent_*.py`, `core/agent_token.py`, `routers/agent_activity.py`, `routers/commands.py`, `frontend/src/app/agent-*.ts`, `ui/agent-*.ts`, `canvas/agent-marks.ts`, `setup/mcp_stdio.py`, `setup/agents.py`, `docs/AGENTS.md`, `.claude/skills` | `agents` | +| Desktop app, the macOS engine folder and the sidecar | `src-tauri/` (`packaged.rs`, `tauri.macos.conf.json`), `backend/formchem_engine.py`, `setup/freeze_backend`, `setup/lib.sh`, `setup/desktop_*`, `build_app` | `desktop` | | Versions, changelog, notices, CI, formcompiler | `.docs/BRANCHING.md`, `CHANGELOG.md`, `NOTICE.md`, `setup/notices.py`, `.github/workflows/` | `release` | | Where any FormChem feature may come from | the owner's clean-room specifications | `clean-room` | @@ -55,8 +58,14 @@ backend services/model.py, ops.py -> nothing (pure; the contract) services/store.py -> model, ops, package, history, importers, hub; chem.derive imported lazily services/chem/ -> rdkit, indigo, model (never the store or routers) backend routers -> core, services (hub, bridge, library, store, chem, terminal, formext_host) -mcp.py -> commands, extensions, consent, claude_code (in-app tokens), bridge, hub; - routers/analysis imported lazily by the analysis tools +mcp.py -> commands, extensions, consent, claude_code (in-app tokens), bridge, hub, agent_token; + routers/analysis and the agent_* services imported lazily by the tools +services/agent_*.py -> store, bridge, chem (agent_edits is pure: model and chem only); agent_log hooks AFTER_CHANGE +app/picture.ts -> canvas/render (a fresh renderer off screen), never the live canvas view +app/clip-*.ts, import-files -> engine/model, ops, the export and parse routes; one paste plan (clip-data.ts) +services/chem/writers, stream -> formats, report, io, rdkit, indigo (never the store) +services/batch.py, app/cli.py -> chem/stream, records, standardise, depict, props (never routers or the store) +services/pictures/ -> fontTools and the bundled fonts only window-only abilities -> reach the engine as window tools over /api/live (bridge.window_call) desktop shell -> frozen engine (formchem_engine.py) -> serves frontend/dist ``` @@ -90,16 +99,22 @@ The window reaches the engine only through `frontend/src/io/api.ts` (REST with t | An arrow, bracket, shape, line, table, TLC plate, orbital, picture or caption: drawing, hitting, handles, its tool; z-order and groups; a template; picture upload | `annotations`, with `canvas` for the laws it builds on | | Reaction roles, atom mapping, balance, the stoichiometry panel or grid, reaction SMILES or RXN, a reaction route, command or MCP tool | `reactions`, with `chemistry-engine` for RDKit and `agents` for a tool | | A CIP label, stereo group, wedge, abbreviation, explicit hydrogen, atom list, query bond, SMARTS, substructure hit, R-group, property, check issue or isotope peak; an `/api/analysis` route, an analysis MCP tool, a stereo or query mark | `stereo-and-queries`, with `chemistry-engine` for the converter and `agents` for a tool | +| A file that opens wrong or loses something, an export or import report, a new format, File > Import, picture export, the drawing inside a picture, saving in the desktop app, print | `formats-and-export`, with `chemistry-engine` for RDKit and `clean-room` for a new format | +| Copy, Cut, Paste, Copy As, Paste Special, Duplicate, a clipboard flavour on one platform | `clipboard`, with `formats-and-export` for the text formats and pictures | +| `./formchem convert`, `batch`, `descriptors`, `render`, the stream reader, per-record failures, Standardise | `command-line`, with `chemistry-engine` for RDKit | +| A crowded or crossing 2D layout, Lay Out or Clean Up | `chemistry-engine` (the scored layout) | +| The dark page, a grid type, snapping, scale handles, Scale Up and Down | `canvas`, with `document-format` for `style.grid` | | New, Open, Save, Insert from SMILES, the Analysis panel, the status bar formula, the dirty mark | `window-shell`, with `chemistry-engine` for the values | | Home, the title bar, status bar, palette, Preferences, About, dialogs, themes, translations, styles | `window-shell` | | A menu item, a submenu, a shortcut label, macOS native menus, menu overlap | `menus`, then `window-shell` for the command | | Terminal tabs, Claude Code, Codex, Cursor or Antigravity tabs, the consent dialog, chat | `dock` | | The extensions pane, an extension API call, FormPortal or form.ext integration | `extensions` | -| A new MCP tool, the commands catalogue, `./formchem agents`, skills, the manifest | `agents` | -| Desktop build, `build_app`, the Tauri CLI version, sidecar, updater, Tauri commands, title bar overlay | `desktop` | +| An MCP tool, an edit builder, agent render or placement, the call log, Agent Activity, Stop, the token, `./formchem agents`, skills | `agents` | +| Desktop build, `build_app`, a slow desktop start, the macOS engine folder and its flatten rule, the Tauri CLI version, sidecar, updater, Tauri commands, title bar overlay | `desktop` | +| A menu that clips or overlaps the title, More menus, Escape or arrows with a menu open | `menus` | | A release, version sites, CHANGELOG, NOTICE, CI | `release` | | Any chemistry feature, a file format, a name for a command or panel | `clean-room` first | -| Use FormChem: insert a structure, run a menu command, hand off in the window | Not this pack: `formchem-harness` | +| Use FormChem: draw or edit a structure with the agent tools, run a menu command, hand off in the window | Not this pack: `formchem-harness` | ## Layout of this pack @@ -108,8 +123,9 @@ formchem-skillset/ SKILL.md this router, the subsystem map and the laws in short references/repo-laws.md each law with its reason and exact format EVALS.json evaluation prompts and the trigger tests (should and should not load) - sub-skills/ engine, document-format, chemistry-engine, reactions, stereo-and-queries, canvas, annotations, - window-shell, menus, dock, extensions, agents, desktop, release, clean-room + sub-skills/ engine, document-format, chemistry-engine, reactions, stereo-and-queries, formats-and-export, + clipboard, command-line, canvas, annotations, window-shell, menus, dock, extensions, agents, + desktop, release, clean-room chemistry-engine/references/warning-codes.md every ChemWarning code and where it comes from stereo-and-queries/references/routes-and-codes.md the /api/analysis routes, check codes and service warning codes canvas/references/hover-keys.md the hover key map with the code that implements it @@ -130,6 +146,7 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's folder; `references ./formchem backend | frontend one side ./formchem serve built frontend served by the engine (FORMCHEM_DIST) ./formchem doctor toolchain, installs and ports +./formchem convert IN OUT the conversion command line (also batch, descriptors, render; docs/CLI.md) ./formchem agents sync --check tools reference, skills mirror and agents/manifest.json in step cd frontend && npx tsc --noEmit type-check backend/venv/bin/python -m compileall -q backend/app setup diff --git a/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md index b0021068..d474d33a 100644 --- a/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md @@ -1,52 +1,83 @@ --- name: agents -description: "FormChem's agent surface: the MCP server in the engine (Streamable HTTP at /mcp, TOOLS and t_ handlers, the approval gate, in-app trust, the formchem://guide resource), the command catalogue mirror and runner that lets agents run window commands such as insert-smiles, the stdio relay, ./formchem agents install and sync, agents/manifest.json, the client configs and the two skill packs. Use when adding or changing an MCP tool, when an agent is refused or trusted wrongly, when the catalogue is empty, when the server's guide text is out of date, when sync --check fails, or when editing the harness or skillset packs." +description: "FormChem's agent surface: the MCP server in the engine (Streamable HTTP at /mcp with the agent token, TOOLS and t_ handlers, the consent gate, in-app trust, the formchem://guide resource), the 0.8.0 agent tools (agent_out write_result and render through the window, agent_draw placement, agent_edits pure builders, agent_convert on the CLI runners), the agent call log (agent_log, AFTER_CHANGE, /api/agents, Agent Activity, the chip, Stop), the window tools render, selection and show, the command catalogue mirror and runner, the stdio relay, ./formchem agents install, sync and token, agents/manifest.json and the two skill packs. Use when adding or changing an MCP tool or edit builder, when an agent call does not undo in one step, is attributed wrongly, is refused or trusted wrongly, when render falls back, when the token or 401 misbehaves, when sync --check fails, or when editing the harness or skillset packs." --- # Agents ## Purpose -Give agents a small, honest tool surface that only describes what FormChem can do now, gates every change on the person's consent, and stays in step with its skills and manifest. +Give agents an honest tool surface that only describes what FormChem can do now, makes every change one undo step the person can see, check and stop, and stays in step with its skills and manifest. ## File map | Path | Role | | --- | --- | -| `backend/app/routers/mcp.py` | `VERSIONS`, `LEGACY`, `SERVER`, `INSTRUCTIONS`, `GUIDE` (`formchem://guide`), `TOOLS` (`_tool(...)` entries), `MUTATING`, `_mutating`, `_gate`, `_inapp`, `t_[name]` handlers collected into `HANDLERS`, `HANDOFFS`, `POST/GET/DELETE /mcp` | -| `backend/app/routers/commands.py` | `/api/commands`: `POST /catalogue` (from the window), `GET ""`, `GET /{id}`, `POST /run`, `POST /batch`, `POST /{id}`; `find`, `search`, `execute` (through `bridge.window_call("run_command")`) | -| `backend/app/services/consent.py` | `async def ask(agent_name, summary) -> bool`: asks the person in the window | -| `setup/mcp_stdio.py` | stdio relay to the HTTP server; starts the engine if needed; `DEFAULT_PORT = 8220`; forwards `FORMCHEM_INAPP_TOKEN` as the in-app header | -| `setup/agents.py` | `install [--dry-run]`, `sync [--check]`; `SKILLS`, `DOCK`, `DOCK_MODULE`, `LOOKUP_HASHES`; generates the harness `references/tools.md` from `TOOLS`; writes `agents/manifest.json` | -| `setup/catalogue.py` | `./formchem cli`: the catalogue and runner from a terminal, as the outside agent `formchem-cli` | -| `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` | Repo configs (portable paths); `install` writes the same entries for the home and caller folders and Antigravity's `~/.gemini/config/mcp_config.json` | -| `.claude/skills/formchem-harness`, `formchem-skillset` | The packs; `.agents/skills` is a mirror written by sync. Both are made and repaired only through the god-tier-skill-creator pipeline, and its `scripts/validate_skill.py` reports zero FAIL before a commit | +| `backend/app/routers/mcp.py` | `VERSIONS`, `LEGACY`, `SERVER`, `INSTRUCTIONS`, `WORKFLOW`, `GUIDE` (`formchem://guide`), `DRAWING_FROM`, `TOOLS` (`_tool(...)` entries), `MUTATING`, `_mutating`, `_gate`, `_inapp`, `_authorised`, `_unauthorised`, `call_tool` (logs, refuses stopped agents) and `_dispatch`, `_doc_id`, `_show`, `_draw`, `_edit`, `_edit_doc`, `_apply`, the `t_[name]` handlers collected into `HANDLERS`, `HANDOFFS`, `POST/GET/DELETE /mcp` | +| `backend/app/services/agent_out.py` | `write_result` (the answer of every write), `render_image` (window first, engine fallback), `selection`, `structure_of`, `full_structures` (get_structure rows with the molfile), `engine_picture`, `free_spot`, `page_of`, `fragments_in`, `RenderError` | +| `backend/app/services/agent_draw.py` | `structure_ops` and `reaction_ops`: text to ops in free space (Insert Reaction's `scheme.insert_ops` for reaction SMILES), `DrawError` | +| `backend/app/services/agent_edits.py` | one pure builder per edit tool, `fn(doc, args) -> (ops, info)`, plus `listing` (get_atoms), `Target`, `locate_atom`, `locate_bond`, `remove_objects_ops`, `merge_ops`, `map_ops`, `fragment_diff_ops`, `EditError` | +| `backend/app/services/agent_convert.py` | `convert` and `batch_convert` on `services/batch.py` with the CLI's `Options`; never overwrite; `ConvertError` | +| `backend/app/services/agent_log.py` | the call log: `begin`, `end`, `summary`, `after_change` (on `store.AFTER_CHANGE`), `undoable`, `listing`, `clear`, the JSONL files | +| `backend/app/routers/agent_activity.py` | `/api/agents`: `GET /calls`, `POST /calls/clear`, `POST /calls/{id}/undo`, `POST /stop`, `POST /allow`, `GET /token` | +| `backend/app/core/agent_token.py` | `value`, `valid`, `path`: the token file `agent-token` in the data folder | +| `backend/app/services/consent.py` | `refusal`, `ask`, and from 0.8.0 `STOPPED`, `stop`, `resume`, `stopped` | +| `backend/app/routers/commands.py` | `/api/commands`: the catalogue mirror, `POST /state`, `execute` through `bridge.window_call("run_command")` | +| `frontend/src/app/agent-window.ts` | the window tools `render` (export renderer, own PNG rasteriser), `selection`, `show`, registered with `addWindowTool` (`app/window-tools.ts`) | +| `frontend/src/app/agent-calls.ts`, `app/agent-activity.ts`, `ui/agent-activity.ts`, `ui/agent-chip.ts`, `canvas/agent-marks.ts`, `styles/agent-activity.css` | the call log mirror, Agent Activity, the editing chip with Stop, the flash marks, the `agent-activity` command | +| `setup/mcp_stdio.py` | stdio relay; sends the token (or the in-app token), retries once on a fresh token, starts the engine if needed | +| `setup/agents.py` | `install [--dry-run]` (writes the token into the Claude Code HTTP entries), `sync [--check]`, `token`; generates the harness `references/tools.md` from `TOOLS`; writes `agents/manifest.json` | +| `setup/catalogue.py` | `./formchem cli`: the catalogue and runner from a terminal as the outside agent `formchem-cli`, with the token | +| `docs/AGENTS.md` | the public reference of every tool, the token and the call log | +| `.claude/skills/formchem-harness`, `formchem-skillset` | the packs; `.agents/skills` is a mirror written by sync. Made and repaired only through the god-tier-skill-creator pipeline; its `scripts/validate_skill.py` reports zero FAIL before a commit | -## Adding a tool +## The tool surface (0.8.0) + +42 tools: the six of the shell (`get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`); the reaction tools of 0.5.0 and the analysis tools of 0.6.0 (owned by `reactions` and `stereo-and-queries`); and the 28 of 0.8.0: `list_open_documents`, `new_document`, `open_document`, `save_document`, `close_document`, `draw_from_smiles`, `draw_from_molfile`, `render`, `get_structure`, `validate`, `compute_properties`, `convert`, `batch_convert`, `get_atoms` and the 14 edit tools `add_atom`, `add_bond`, `set_charge`, `set_atom`, `set_stereo`, `replace_substructure`, `delete`, `move`, `scale`, `align`, `clean_layout`, `add_arrow`, `add_text`, `add_reaction`. `draw_from_name` waits for the naming decision (Q7 in the plan); do not add it early. + +## Laws of the agent tools + +1. **One call, one transaction.** Every writing tool builds its ops first, then applies them once through `_apply` (`STORE.apply(doc_id, tx, "agent", agent=name)`, no coalesce key), so one Undo removes the whole call and calls never merge. A builder that fails raises before anything is applied; a drawing the call created is closed again. +2. **Every write answers with the structure and a picture.** Return `agent_out.write_result(doc_id, tx, touched_ids, text, extra)`. Never build a write answer by hand: the rows come from the derived cache after the transaction (`derive_now`), and a picture failure leaves the image out instead of failing the write. +3. **Builders are pure.** An edit tool is `fn(doc, args) -> (ops, info)` in `agent_edits.py`, on a deep copy, with no store, window or I/O, raising `EditError` with the next step in its text. It runs in a thread; `_edit` does the rest. Mirror the window's own semantics (deleteSelectionOps, mapObject, scale.ts) rather than inventing new ones, and say in the HASHOUT log which window function it mirrors. +4. **Pictures come from the window.** `render_image` sends the document and derived cache to the window tool `render`; the engine draws only as a fallback (no window, error, 25 s) and every answer names its renderer. `render` and `selection` are in `bridge.READ_ONLY`; `show` is not. +5. **Place, do not cover.** New structures go through `agent_out.free_spot` (right of the content, else below; always below when the page has an arrow) unless the agent gave x and y; overlaps are reported as a note. +6. **Never destroy the person's work.** `save_document` refuses another existing file, `close_document` refuses unsaved changes, `convert` and `batch_convert` refuse existing files and non-empty folders. The refusal names the window action that lets the person do it. +7. **Gate every write.** A tool that changes what the person sees goes in `MUTATING`, or in `_mutating` when only some arguments write. Reading tools set `read=True` (readOnlyHint) and never ask. +8. **Same names as the spec, old names kept.** `validate` and `compute_properties` call the 0.6.0 handlers through `_same_as`; keep `check_structure` and `properties` for agents written against 0.6.0. -1. Add one `_tool(name, description, props, required, read=..., destructive=...)` to `TOOLS`. Props are literal dicts or module-level names, so `agents.py` can read them without running the server. -2. Add `async def t_[name](a, args) -> dict` returning `_ok(text, data)` or raising `ToolError` with a sentence that names the next step. -3. If it changes anything the person sees, add it to `MUTATING`, or to `_mutating` as `if name == "[name]": return ...` when only some arguments change things. Never skip the gate for outside agents. -4. Describe only what works now. A tool for a later phase lands in that phase. -5. Run `./formchem agents sync`, then `sync --check`, and commit `mcp.py` with the regenerated `references/tools.md`, the `.agents/skills` mirror and `agents/manifest.json`. +## The call log and Stop -## What agents can reach in 0.6.0 +- `call_tool` is the only entry: HTTP, stdio, in-app tabs and the chat panel (chat/tools.py) all pass through it, so a new tool is logged without code of its own. It refuses a stopped agent (`consent.stopped`) before `_dispatch`, and `_dispatch` tags gate refusals `_refused`. +- Attribution: `agent_log.begin` sets a contextvar that flows into `store.AFTER_CHANGE`, so direct writes are exact; a window command's `user` transaction goes to the single writing window-tool call running or ended within `SETTLE_SECONDS` (1.5). Keep new hooks on `AFTER_CHANGE` async and exception-safe; the store logs and ignores a failing hook. +- After every change, undo and redo the hook broadcasts `agentUndoable {doc, call}` for the call owning the top of the undo stack; `undone` is "in redo, or was undone and not back on the undo stack". The window offers Undo only where the engine says so, and `POST /calls/{id}/undo` answers 409 otherwise. +- Argument summaries hide keys matching `SECRET` and clip long text; never log raw arguments. +- `consent.stop` writes `agentsAllowed: false` and refuses reads too; `resume` lets the next change ask again. Stopped names live in memory for the engine run. + +## The agent token + +- `core/agent_token.py`: one line in `agent-token` in the data folder, mode 0600, made with O_EXCL by the engine at start or by `agents install`, cached by mtime, compared with `hmac.compare_digest`. +- `POST /mcp` and `DELETE /mcp` accept the token, a live in-app tab token or the window key; anything else is 401 with `WWW-Authenticate: Bearer realm="FormChem"` and JSON-RPC -32001. `/mcp` stays in `window_key.OPEN`. +- The stdio relay and `./formchem cli` read the file themselves; `agents install` writes it into the Claude Code HTTP entries; the Agents dialog fills it in from `GET /api/agents/token` (window key). Never put the token in a prompt, a log line, a handoff or a test fixture. + +## Adding a tool -- Fourteen tools: the six of the shell; `perceive_reactions` and `map_reaction` (in `MUTATING`, so gated) and `export_reaction` and `reaction_stoichiometry` (read-only), which call the reaction services and commit through `_apply` (`STORE.apply` with origin `agent`), owned by `reactions`; and the read-only analysis tools `properties`, `check_structure`, `stereo` and `substructure` (outside `MUTATING`, never asking), which reuse the analysis router's source rules through `_analysis_source` with a lazy import so mcp.py does not load RDKit at import, owned by `stereo-and-queries`. The other drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, edit ops, `convert`) land in 0.8.0; do not add them early or describe them as present. -- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, `insert-template {id}`, the canvas, arrange and Reaction commands, `set-reaction-roles {role, objects}` and the 0.6.0 chemistry commands such as `assign-wedges`, `set-stereo-group-and`, `add-hydrogens` and `expand-abbreviation`) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`). -- `INSTRUCTIONS`, `WORKFLOW`, `GUIDE` and the `get_context` text name the reaction tools, the analysis tools and the chemistry commands; `DRAWING_FROM = "0.8.0"` names when the atom and bond tools arrive. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows. -- `insert-smiles` takes an optional `smiles` param (`commands-shell.ts`, `DocumentActions.insertSmiles(given)`): with it the window inserts without the prompt, throws the parser's reason on failure (the agent gets it as the tool error) and returns a sentence naming the fragment ids and the drawing. -- A future engine-side agent write goes through `await STORE.apply(doc_id, tx, "agent", agent=name)` and catches `ops.OpError`, so it is one undo step with origin `agent`, autosaved at once and broadcast to every window. +1. Add one `_tool(name, description, props, required, read=..., destructive=...)` to `TOOLS`. Props are literal dicts or module-level names (`_DOC`, `_IDS`), so `agents.py` can read them without running the server. Describe only what works now. +2. Add `async def t_[name](a, args) -> dict`. Resolve the drawing with `_doc_id` (or `_edit_doc`); for a write, build ops in a thread and return `write_result`; for a read, return `_ok(text, data)`. Raise `ToolError` with a sentence that names the next step. +3. Gate it (`MUTATING` or `_mutating`). Give it an undo label the person will read in Edit > Undo, in the window's own words where a command exists. +4. Update `INSTRUCTIONS`, `WORKFLOW` and `GUIDE` when the tool changes how an agent should work. +5. Run `./formchem agents sync`, then `sync --check`, and commit `mcp.py` with the regenerated `references/tools.md`, the `.agents/skills` mirror and `agents/manifest.json`. Update `docs/AGENTS.md` and the harness sub-skill that routes to the tool. ## Rules - Agents in FormChem's own tabs send a live tab token in `x-formchem-inapp` and are never asked; everyone else goes through `consent.ask`. A refusal returns a sentence, never an exception. -- Window-only abilities are window tools over `/api/live` through `bridge.window_call`; the engine never fakes a window answer. +- Window-only abilities are window tools over `/api/live` through `bridge.window_call`, added with `addWindowTool` in the module that owns them; the engine never fakes a window answer. Window tool answers go to agents and need no i18n keys. +- The window's agent UI patches keyed nodes (`patchList` rows, a `Keyed` marks layer); never rebuild the panel or the chip to change one call. - The `handoff` live message is `{t: "handoff", agent, state, note, at}`; a window asks for the current list with `{t: "handoffs"}`. -- The manifest and `references/tools.md` of formchem-harness are generated by `setup/agents.py`, never edited by hand; the generator writes the tools reference's `## Contents` list, which the skill validator requires past 100 lines. +- The manifest and `references/tools.md` of formchem-harness are generated by `setup/agents.py`, never edited by hand. ## Gate -- [ ] `backend/venv/bin/python -m compileall -q backend/app setup` is clean. +- [ ] `backend/venv/bin/python -m compileall -q backend/app setup` is clean and `cd frontend && npx tsc --noEmit` shows no new errors. - [ ] `python3 setup/agents.py sync --check` prints "agents: in step". -- [ ] A scratch FastAPI app with the router answers `initialize` and `tools/list`, and the new tool returns its text. +- [ ] A scratch engine (`FORMCHEM_DATA_DIR` in a scratch folder) answers `initialize` and `tools/list` with the token and 401 without it; a new writing tool raises the revision by exactly one and its answer carries `undo: "one step"` and an image; `GET /api/agents/calls` lists the call with its `tx`. diff --git a/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md index 20e43a6d..cd2b126c 100644 --- a/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md @@ -23,7 +23,10 @@ Let the person draw at the speed of thought while the document stays the only tr | `frontend/src/ui/tool-rail.ts` | The tool rail, flyouts and tool commands (`tool-select` and the rest); from 0.5.0 also the arrow (W), symbol (P), bracket (K), shape (G), table, TLC, image and orbital (O) groups | | Stereo and query marks (0.6.0) | `render/marks-layer.ts` (`ChemMarks`, one keyed layer cached per fragment; replaced `render/stereo.ts`), `marks-stereo.ts`, `marks-query.ts` and `canvas/marks-options.ts` belong to the `stereo-and-queries` specialist; the view toggles reach the renderer through `RenderDisplay.enhancedStereo`, `queryMarks` and `groupColours` | | Drawn objects (0.5.0) | The object kind registry (`render/objects.ts` and one module per kind), `hit-objects.ts`, the annotation tools, `tools/handles.ts` and `app/object-commands.ts` belong to the `annotations` specialist; load it for anything that is not atoms, bonds, labels or text | -| `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | Canvas styles, `@font-face` for the bundled fonts, the document grid on the paper | +| `canvas/dark-page.ts` (0.7.0) | `darkPageOn`, `setDarkPage`, `onDarkPage`, `initDarkPage` (the zero-size defs svg with the `#fc-page-undark` colour matrices); state is `data-page-dark` on the root, set before first paint in `index.html`, key `formchem.darkPage` | +| `canvas/grid.ts`, `canvas/grid-layer.ts` (0.7.0) | Lattices, `docSpec` (read straight from `doc.style.grid`), the window default and snap state in localStorage, `snapStart`, `snapPoint`, `latticeDirections`, `snapRingCentre`; `GridLayer` and `planGrid` draw one svg inside the paper as page-sized paths (patterns only for dots and crosses) | +| `canvas/tools/scale.ts` (0.7.0) | `scaleSelection` (positions, sizes and, with Scale Labels on, per-object style overrides; residue-free), `scaleHandles`, `scaleHandleAt`, `scaleFromDrag`; the select tool's `scale` mode; the readout is one node patched by `view.setReadout` | +| `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | Canvas styles, `@font-face` for the bundled fonts, the dark page filter (inside `@media screen`) | | `references/hover-keys.md` | The hover and tool key map with routing rules. Open before adding or changing a key | ## Laws on the canvas @@ -38,6 +41,10 @@ Let the person draw at the speed of thought while the document stays the only tr **Geometry rules.** Points, y down, angles counter-clockwise as seen; the default bond length is 14.4 pt and the chain angle 120 degrees. Free drags snap to 15 degrees, growth from a bonded atom to 30 degree steps; Alt is free. +**The dark page filters whole boxes (0.7.0).** WebKit ignores CSS filter functions on SVG children, so the dark page puts `invert(0.9) hue-rotate(180deg)` on `.fc-canvas-paper` and the whole `.fc-canvas-svg`, and the selection, hover, warning and preview layers live in the sibling unfiltered `svg.fc-canvas-marks` with the same transform. Never move a coloured mark back into the drawing svg, never put a filter function on an SVG child (pictures use the `#fc-page-undark` url filter), and never let an export read the live canvas (`formats-and-export`). + +**Snapping and scaling (0.7.0).** Snapping keeps bond geometry on square grids and lands lattice atoms on isometric and hex grids at the bond length; `Alt` bypasses everywhere, `Shift` keeps its constraint meaning, scale corners and rotation never snap. Scaling is uniform from the corners only, one transaction on release, Escape cancels; Scale Up and Scale Down are exact inverses. Zoom never changes the drawing. + **The document is the state.** Selection and hover live in the view; everything else is read from `client.view` (the mirror with any preview applied). Implicit hydrogens and double bond sides come from local rules until `derived` for the current revision arrives (`chemistry-engine`). ## Adding a tool diff --git a/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md index 12b5a79d..e16e9fbc 100644 --- a/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: chemistry-engine -description: "FormChem's chemistry: the RDKit service in backend/app/services/chem (conversion from fragments, sanitising, valence, aromaticity, stereo and CIP, canonical SMILES, CXSMILES, InChI and InChIKey, Hill formula, masses, m/z, elemental analysis, isotope pattern, 2D clean-up and layout with CoordGen, file reading and writing through RDKit and Indigo), the /api/chem routes, the derived cache broadcast after every transaction, and the window's local valence, ring and label rules in frontend/src/chem. Use when a computed value is wrong, a warning or valence error appears or is missing, a structure file reads upside down or loses atoms, a layout moves the wrong atoms, or a new chemistry computation is added." +description: "FormChem's chemistry: the RDKit service in backend/app/services/chem (conversion from fragments, sanitising, valence, aromaticity, stereo and CIP, canonical SMILES, CXSMILES, InChI and InChIKey, Hill formula, masses, m/z, elemental analysis, isotope pattern, 2D clean-up and the scored layout: CoordGen and RDKit candidates, layout_score and layout_refine), the /api/chem routes, the derived cache broadcast after every transaction, and the window's local valence, ring and label rules in frontend/src/chem. Use when a computed value is wrong, a warning or valence error appears or is missing, a structure reads upside down or loses atoms, a layout is crowded, crosses bonds or moves the wrong atoms, or a new chemistry computation is added." --- # Chemistry engine @@ -18,8 +18,9 @@ Compute everything chemical in one place, from the drawing as the person drew it | `chem/perceive.py` | `prepare(frag)` (sanitised plus stereo; every other module starts here), `perceive(frag)` (implicit H, valence errors, aromatic rings, CIP, warnings), `allowed_valences`, `explicit_valence` | | `chem/ids.py` | `smiles`, `cxsmiles`, `inchi` (standard only), `formula` (Hill, own writer), `component_formulas`, `identifiers(conv)` | | `chem/mass.py` | `average_mass`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `isotope_pattern`, `properties(conv)` | -| `chem/layout.py` | `compute_coords(frag, ids, bond_length, fixed)` (CoordGen, RDKit fallback), `clean(frag, ids)`, `restereo(frag, coords)` (wedge fixes after a move) | -| `chem/io.py` | `detect`, `read_text`, `read_file` (`ParseResult` with fragments, warnings, reaction), `export`, `to_molfile`, `to_smiles`; SDF, RXN, reaction SMILES, CML, cdxml and cdx (Indigo), InChI; at most 1000 records per call | +| `chem/layout.py` | `depict(mol, reference)` (the scored candidates, returns the chosen Score), `compute_coords(frag, ids, bond_length, fixed)`, `clean(frag, ids)`, `restereo(frag, coords)` (wedge fixes after a move), `score_fragment` | +| `chem/layout_score.py`, `chem/layout_refine.py` (0.7.0) | `shape`, `evaluate`, `score_mol`, `Score` (hard terms close, cross, near, label; a soft tie-breaker; `crowded` atoms); `refine` (swing or mirror crowded acyclic branches) | +| `chem/io.py` | `detect`, `read_text`, `read_file`, `read_bytes` (`ParseResult` with fragments, objects, reaction, reactions, warnings, report); at most 1000 records per call. From 0.7.0 the formats table, writers, report items, CDXML and CDX through Indigo, RD files, CML and the stream reader belong to `formats-and-export` and `command-line` | | `chem/abbrev.py` | 106 built-in abbreviations in six categories plus the person's `abbreviations.json`; `resolve`, `element_like`, `reversed_label`, `library`, `match` | | `chem/derive.py` | `derive_fragment(frag, expansions, rev)`, `derive_document(doc, rev, only)`, `content_key`, an LRU cache of 2048 fragments | | `backend/app/routers/chem.py` | `POST /api/chem/parse`, `/derive`, `/layout`, `/convert`, `/properties`; 422 for bad input, 413 over 20 MB of text, at most 5000 atoms | @@ -37,6 +38,7 @@ Compute everything chemical in one place, from the drawing as the person drew it - **One converter.** Every computation enters RDKit through `convert.to_mol` (atoms and bonds in sorted id order, bond begin = `a`), so indices are stable between conversions and the wedge's narrow end is RDKit's begin atom. Do not build an `RWMol` anywhere else. - **Coordinates and the y axis.** FormChem pages are points with y down; molblocks and RDKit conformers have y up. `to_mol` scales to a 1.5 unit median bond and negates y; `from_mol` scales back to the requested bond length, negates y and puts the top-left at `origin` (default 72, 72). A structure that imports upside down has lost one of those negations. Imports never keep foreign absolute positions. - **Layout keeps its place.** `compute_coords` and `clean` fit the result back onto the old positions (rotation plus translation; `clean` may mirror), keep fixed atoms exactly, and return wedge swaps in `stereo` that the caller applies in the same transaction as the moves. +- **Layout is scored (0.7.0).** `depict` tries CoordGen, RDKit native with and without ring templates, native with sampled rotatable-bond flips (up to 150 atoms) and straightened copies, scores each with `layout_score.evaluate` (coordinates scaled to a median bond of 1; the label boxes follow the renderer's default journal style) and keeps the first, in that order, within 0.5 of the lowest total, so CoordGen stays the house style. `refine` then rotates crowded branches by 12, 24 or 36 degrees or mirrors them, keeping hinge angles of at least 60 degrees (45 at a four-connected hinge), every E/Z and every fixed atom; work is capped by a count of evaluations, never a clock, so results are deterministic. Above 300 atoms it is plain CoordGen; `score_fragment` is null above 600. Ring systems are never moved, so bridged polycycles such as morphine can still cross. Clean Up passes `reference` and takes the candidate nearest the drawing among those with the lowest hard penalty. A layout change must keep every CIP label and the canonical SMILES; check Taxol (score 10.14 to 0.68), erythromycin and vancomycin, and that benzene, aspirin and cholesterol stay byte-identical. - **Warnings, not exceptions.** Sanitising never throws; problems become warnings naming atoms and bonds, valence problems become `valence_errors`, and any exception for a fragment becomes `engine_error` with empty values. Metals are never flagged. - **Window guesses are temporary.** The window draws at once from its default-valence table and ring perception, then uses `derived` only when `derived.rev` equals the client's `rev`. Do not add a third local implementation; extend the engine and let the derived cache carry it. - **Libraries.** RDKit (BSD-3-Clause) and Indigo (Apache-2.0) are already in `NOTICE.md` and in `MODULES` of `backend/formchem_engine.py`; anything else needs a `NOTICE.md` row first. File formats come from public specifications and open implementations only (`clean-room`). diff --git a/.agents/skills/formchem-skillset/sub-skills/clipboard/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/clipboard/SUB-SKILL.md new file mode 100644 index 00000000..d5d1806e --- /dev/null +++ b/.agents/skills/formchem-skillset/sub-skills/clipboard/SUB-SKILL.md @@ -0,0 +1,48 @@ +--- +name: clipboard +description: "FormChem's clipboard from 0.7.0: the native payload and paste plan (clip-data.ts extractClip, pastePlan with fresh ids and remapped references), text formats out and in (clip-formats.ts), the clipboard flavours and platform fallbacks (clip-system.ts), pictures with their drawing (clip-picture.ts), the controller with Copy, Cut, Paste, Copy As and Paste Special (clipboard.ts), Duplicate and File > Import on the same plan, the macOS system Edit items and the desktop clipboard access. Use when Copy or Paste loses something, a paste lands in the wrong place or with the wrong look, a flavour is missing on a platform, a keyboard shortcut does nothing on the canvas, or a new Copy As format is added." +--- + +# Clipboard + +## Purpose + +Copy and paste drawings between FormChem windows without losing anything, and with other programs in the forms they understand, on every platform's webview. The person's keyboard path must never hit a permission prompt. + +## File map + +| Path | Role | +| --- | --- | +| `frontend/src/app/clip-data.ts` | `extractClip(doc, page, selection)` (a mini document.json that passes `validate`, with style, expansions, media records, R-group definitions and reaction steps filtered to what was copied, `meta.clipboard`), `pastePlan(target, page, clip, {at, keepStyle, media, offset})` (translate, fresh ids, remap every reference, style difference into each object's `style`), `CLIP_MIME`, `CLIP_KIND` | +| `app/clip-formats.ts` | `clipText(clip, format)` through `POST /api/chem/export` (older routes only on 404 or 405); `parseClipText(text)`: native JSON, reaction text, everything `/api/chem/parse` reads, then SMARTS; `looksLikeName` | +| `app/clip-system.ts` | `writeClipboard(sync, rich, event)`, `readClipboard`, `flavoursOfTransfer`, `htmlFlavour`, `WEB_CLIP_MIME`, `HTML_SOURCE_ATTR` | +| `app/clip-picture.ts` | Copy as SVG and PNG through `picture.ts`; `sourceOfPicture` through `embedded-source.ts` (`formats-and-export`) | +| `app/clipboard.ts` | `mountClipboard`: the copy, cut and paste events (and `beforecopy`, `beforecut`, `beforepaste`), the commands `copy-*` and `paste-special`, `insert(clip, {label, keepStyle, spot, alsoSelect})` for File > Import | +| `ui/paste-special-dialog.ts`, `styles/clipboard.css` | Paste Special | +| `app/commands-shell.ts`, `app/menus.ts` | `cut`, `copy`, `paste` fall back to text fields, else call the canvas; Copy As and Paste Special in Edit | +| `ui/native-menu.ts` | `ALWAYS_NATIVE`: Cut, Copy, Paste and Select All are predefined system items on macOS | +| `src-tauri/src/main.rs` | `.enable_clipboard_access()` on every window (WebKitGTK and WebView2) | + +## Rules + +- **One payload.** The native clipboard form is document.json under `application/x-formchem+json`, the same payload pictures embed, so clipboard, pictures and File > Import paste through one reader and one plan. +- **Fresh ids, every reference remapped.** Bond ends, stereo groups, R-group members and attachments, caption targets, arrow anchors, bracket atoms, orbital atoms, table cells, stoichiometry, group children and reaction members. Expansions are reused when identical, kept when free, renamed otherwise. A picture whose bytes cannot be found is left out, never left pointing at nothing. +- **Keep the look.** Native data carries the source style; the plan writes the difference from the target's style into each pasted object's `style`. Text formats take the target's bond length and style. +- **Keyboard through events, menus through the API.** Keyboard copy and paste answer the DOM events, which carry every flavour without a prompt; the menu commands use `navigator.clipboard` (a click is a gesture). The capture keydown listener stops the app's own dispatch of Mod+C, X, V but never prevents the default. +- **Synchronous flavours first.** Write text/plain SMILES, text/html with the payload and the custom type into the copy event, then everything through one `ClipboardItem` whose values are promises, so WebKit keeps the user activation while the engine and renderer work. Keep only types `ClipboardItem.supports` accepts and retry with basic types. +- **The HTML picture is the real carrier.** Chromium re-encodes clipboard PNGs (the iTXt chunk is lost) and sanitises SVG (metadata and fonts dropped); the `data-formchem-source` attribute and the PNG data URL survive. Do not rely on PNG or SVG chunks on the clipboard. +- **Names are not read** (plan Q7): name-like text pastes as a text object with a note. Do not add name lookups through an outside service. +- **One undo step per paste**, the pasted items selected; Duplicate is `extractClip` plus `pastePlan` with a 10 pt offset. + +## Adding a Copy As format + +1. The engine must write it through `writers.export_fragments` (`formats-and-export`). +2. Add the `copy-[format]` command in `clipboard.ts` with its label through `t()` and an English description for agents, and the id in `app/menus.ts` Copy As. +3. Make `parseClipText` recognise it, or say in the description that it does not paste back. + +## Gate + +- [ ] Copy Taxol, paste into a new drawing: same canonical SMILES and CIP labels, one undo removes it. +- [ ] Each Copy As format reads back as text; each text format pastes; Copy as SVG and as PNG paste back as the drawing in Chromium. +- [ ] A structure copied from a 14.4 pt drawing into a 30 pt one keeps its size and line widths. +- [ ] No permission prompt on `Ctrl+V` in Chromium; WebKitGTK paste works with clipboard access on. diff --git a/.agents/skills/formchem-skillset/sub-skills/command-line/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/command-line/SUB-SKILL.md new file mode 100644 index 00000000..f2364410 --- /dev/null +++ b/.agents/skills/formchem-skillset/sub-skills/command-line/SUB-SKILL.md @@ -0,0 +1,50 @@ +--- +name: command-line +description: "FormChem's conversion command line and batch services from 0.7.0: ./formchem convert, batch, descriptors and render (backend/app/cli.py, setup/convert), the runners in services/batch.py, the one stream reader (chem/stream.py iter_records, convert, explain), the record adapter (chem/records.py), the Standardise pipeline shared with the window (chem/standardise.py, /api/analysis/standardise, the Standardise dialog and command), RDKit drawing for render (chem/depict.py) and props.measure. Use when a conversion is slow, wrong or stops on a bad record, a failure reason is unhelpful, a CLI option or format is added, standardising gives a different result in the window and the CLI, or the 0.8.0 convert and batch_convert MCP tools are built." +--- + +# Command line, batch and Standardise + +## Purpose + +Convert, describe, draw and standardise whole files of structures quickly, record by record, without opening the window, and give the window's Standardise the same pipeline. `docs/CLI.md` in the repository is the public reference with timings. + +## File map + +| Path | Role | +| --- | --- | +| `backend/app/cli.py` | argparse front end, `USAGE`; started as `python -m app.cli` from `backend/`; paths relative to `FORMCHEM_CALLER_DIR` | +| `setup/convert`, `setup/convert.bat`; `formchem`, `formchem.bat` | Launchers for `convert`, `batch`, `descriptors`, `render`; the `.bat` passes `%*` untouched so comma lists survive | +| `backend/app/services/batch.py` | `convert_file`, `batch`, `descriptors_file`, `render_file`, `Options`, `Summary`, `BadArguments`, `write_report`; chunking and the process pool | +| `chem/stream.py` | `iter_records(path or text or file, fmt)` yielding `Record(index, mol, name, block, error)` for SD, molfile, SMILES, CXSMILES, InChI and RD files (gzip read transparently, `#` lines skipped); `convert(source, to, out, fmt, limit)`; `explain(parse)` for RDKit's own reason | +| `chem/records.py` | `parse_chunk`, `document`, `write_document`, `mol_text`, `reaction_text`: records to the writers and to `.fchem` | +| `chem/standardise.py` | `STEPS`, `DEFAULT`, `ALIASES`, `run(mol, steps, track)`, `_fragment_ops` (write-back as one transaction) | +| `routers/analysis.py` | `GET` and `POST /api/analysis/standardise` (`standardise_steps`, `standardise_structures`) | +| `frontend/src/engine/standardise-api.ts`, `ui/standardise-dialog.ts`, `app/standardise-command.ts` | The window client, the dialog with its preview, the `standardise {steps?}` command | +| `chem/depict.py` | `svg`, `png`, `Style`: RDKit MolDraw2D set close to the journal style | +| `chem/props.py` | `measure(mol)`: the Analysis panel's values without a drawing | + +## Rules + +- **One reader.** Batch work reads through `stream.iter_records` only and never builds drawable fragments (about 1 ms a record, ten times the cost). Do not add a second SD or SMILES splitter. +- **Failures never stop a run.** Each failed record keeps its index (counted from 1 for people) and name, and its reason is RDKit's own message through `explain`. `explain` swaps `sys.stderr` process-wide for a moment: fine in the CLI and single calls, not in the engine's thread pool. +- **Order and exit codes.** Output order equals input order with any `--jobs`. Exit 0 when something was written, 1 when nothing was (and no empty file is left), 2 for bad arguments, 130 for Ctrl+C. +- **Pool only when it pays.** Inputs split into chunks of 1000 records; the pool starts at two chunks or more. Worker functions stay module-level and picklable for the spawn start method of macOS and Windows. +- **Standardise is one pipeline.** Steps always run in the fixed order of `STEPS`, whatever order is given; each reports changed, a detail or its error, and a failing step is skipped. The window and the CLI call the same `run`, so they cannot disagree. The tautomer step keeps sp3 and double bond stereo. In the window, write-back is one transaction checked against fragments changed meanwhile. +- **Same output for the MCP tools.** The 0.8.0 `convert` and `batch_convert` tools must call `batch.convert_file` and `batch.batch`, not their own code. +- **`./formchem batch` is not `./formchem cli batch`.** Keep the two apart in usage text and docs. +- **Render is not the window's drawing.** `depict.py` uses RDKit's own label, wedge and double bond placement; File > Export is the faithful picture. +- **Spelling.** The UI says Standardise (the app is British); the CLI accepts `--standardise` and `--standardize` and the -ize step names through `ALIASES`. + +## Adding an option or a format + +1. Add the option to `cli.py` and carry it in `batch.Options`; a format must read through `stream.iter_records` or write through `records` or `writers.export_fragments`. +2. Update `USAGE`, the `./formchem` and `formchem.bat` usage lines, `docs/CLI.md` and the wiki page Command-Line. +3. Time it on a 10,000-record SD file outside the repository, with and without `--jobs 2`, and compare the outputs byte for byte. + +## Gate + +- [ ] 10,000 SD records to SMILES in under 10 s with failures reported per record (about 1.4 s on two cores). +- [ ] Output with `--jobs 2` is byte-identical to one process. +- [ ] Standardise in the dialog and `./formchem convert --standardise` give the same SMILES for sodium benzoate, a glycine zwitterion and 2-hydroxypyridine with the tautomer step. +- [ ] `backend/venv/bin/python -m compileall -q backend/app setup` is clean. diff --git a/.agents/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md index 0bd95c76..2006b054 100644 --- a/.agents/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md @@ -1,20 +1,22 @@ --- name: desktop -description: "FormChem's Tauri 2 desktop shell: tauri.conf.json, the Rust entry point and its modules (engine start, splash-to-window reveal, macOS traffic lights in the overlay title bar, the Windows job object), the frozen engine sidecar formchem-engine built with PyInstaller, the updater, and the desktop scripts. Use when the desktop app will not start, the engine sidecar fails or keeps running, the title bar row or traffic lights are wrong, the splash hangs, or a desktop build or updater setting changes." +description: "FormChem's Tauri 2 desktop shell: tauri.conf.json and tauri.macos.conf.json, the Rust entry point and its modules (engine start from the macOS engine folder or the sidecar, packaged.rs, splash-to-window reveal, macOS traffic lights, the Windows job object, clipboard access), the frozen engine formchem-engine built with PyInstaller (a flattened one-folder on macOS, one file elsewhere), the Tauri CLI pin, the updater and the desktop scripts. Use when the desktop app is slow to open or will not start, the engine fails or keeps running, a frozen build misses a module or data folder, the title bar or traffic lights are wrong, the splash hangs, or a desktop build or updater setting changes." --- # Desktop ## Purpose -Wrap the same window and engine in a native app: a thin Rust shell that starts the frozen engine as a sidecar, reveals the window without a flash, and stops the engine with the app. +Wrap the same window and engine in a native app: a thin Rust shell that starts the frozen engine (a folder inside the app on macOS, a sidecar elsewhere), reveals the window without a flash, and stops the engine with the app. ## File map | Path | Role | | --- | --- | | `src-tauri/tauri.conf.json` | productName FormChem, identifier `ai.nodemode.formchem`, `externalBin binaries/formchem-engine`, bundle resources (LICENSE, NOTICE.md, THIRD-PARTY-NOTICES.txt), updater endpoint `https://dl.formai.studio/formchem/updates/latest.json`; the version formcompiler reads | -| `src-tauri/src/main.rs` | App setup, windows, commands (`app_ready` among them); starts the sidecar with `FORMCHEM_PORT=0`, `FORMCHEM_PORT_PREFER=8221` and `FORMCHEM_WINDOW_KEY_STDOUT=1`, reads `formchem-window-key: ` from its stdout and injects `__FORMCHEM_WINDOW_KEY` into the page | +| `src-tauri/tauri.macos.conf.json` | macOS only: `externalBin: []` and the resource `"engine": "engine"`, so `src-tauri/engine` lands in `Contents/Resources/engine` | +| `src-tauri/src/packaged.rs` | `engine_folder()`: `[exe dir]/../Resources/engine/formchem-engine` (the bundle) or `[exe dir]/engine/formchem-engine` (`tauri dev`), else None and the shell uses the sidecar | +| `src-tauri/src/main.rs` | App setup, windows, commands (`app_ready` among them); `.enable_clipboard_access()` in `chrome()`; starts the engine folder through `shell().command(program)` or the sidecar with `FORMCHEM_PORT=0`, `FORMCHEM_PORT_PREFER=8221` and `FORMCHEM_WINDOW_KEY_STDOUT=1`, reads `formchem-window-key: ` from its stdout and injects `__FORMCHEM_WINDOW_KEY` into the page | | `src-tauri/src/engine_start.rs` | Start helpers: waits for the address and the key, `FORMCHEM_SHELL_PID`, the data folder and engine log path, the failure sentence shown to the person | | `src-tauri/src/reveal.rs` | Splash to window: the page calls `app_ready` with its background colour once painted; the splash closes after `window.formchemSplashDone()` | | `src-tauri/src/traffic_lights.rs` | macOS overlay title bar: traffic lights placed in the 38 px title row | @@ -22,12 +24,25 @@ Wrap the same window and engine in a native app: a thin Rust shell that starts t | `src-tauri/Cargo.toml`, `Cargo.lock`, `capabilities/`, `Info.plist`, `entitlements.plist`, `flatpak/` | Crate, permissions, macOS plist and entitlements, Flatpak manifest and AppStream metainfo | | `backend/formchem_engine.py` | Frozen engine entry; `--selfcheck`; `MODULES` (fastapi, uvicorn, keyring, rdkit, indigo) | | `setup/freeze_backend`, `setup/install_desktop`, `setup/desktop_dev`, `setup/desktop_build`, `setup/desktop_check`, `build_app` (each with a `.bat` twin) | Freeze, toolchain, dev run, build, checks | +| `setup/lib.sh` | `fc_engine_folder` (copy to `src-tauri/engine`, flatten, sign, `--selfcheck`), `fc_flatten_engine`, `fc_sign_engine`; shared by `freeze_backend` and `build_app` | ## Rules - The window is the same `frontend/dist`; desktop-only behaviour is detected (`inTauri()`), never forked into a second UI. - macOS: overlay title bar with a hidden title; the pre-paint boot sets `has-overlay-titlebar` so the row never jumps from 44 to 38 px. Native menus unless Menus in Window is on. -- The sidecar binary name is `formchem-engine` (plus the target triple in `src-tauri/binaries/`); RDKit and Indigo are collected whole when freezing. +- The engine is `formchem-engine` everywhere: the sidecar (plus the target triple in `src-tauri/binaries/`) on Linux and Windows, the program inside `src-tauri/engine` on macOS. RDKit and Indigo are collected whole and fontTools' submodules collected when freezing. +- A frozen module or data folder must be added to `setup/freeze_backend`, its `.bat` twin and `build_app`'s own PyInstaller call, which runs separately: entries 98 and 117 of the backend log record two misses of this kind. + +## The one-folder engine on macOS + +A PyInstaller one-file engine unpacks everything (several hundred MB, over 400 libraries) into a new temporary folder at every launch, and macOS scans each new library again: the owner's app took about 30 seconds to open. On macOS the engine is frozen `--onedir`, copied to `src-tauri/engine` and shipped as a resource, so it is unpacked once, at install (on Linux the frozen start went from 1.5 s to 0.55 s; not yet measured on a Mac). Rules: + +- **Flatten before bundling.** A bundle resource may hold no symbolic links and no `.framework`: `fc_flatten_engine` replaces links with copies and `_internal/Python.framework` with a plain `_internal/Python`. `desktop_check` fails on a folder with either, or without the program. +- **Sign every Mach-O** when `APPLE_SIGNING_IDENTITY` is set (PyInstaller's `--codesign-identity` plus `fc_sign_engine` for what it left); releases are signed by formcompiler. +- **Pipes under pipefail** use `grep ... >/dev/null`, never `grep -q`, because an early exit turns a match into a failure. +- On macOS `cargo check`, `cargo build` and `tauri dev` need `src-tauri/engine`; `desktop_dev` freezes when it is missing. `clean` and `build_app --clean` remove it; `.gitignore` lists it. +- Linux and Windows stay one-file until a real bundle test: Linux packages put resources in `/usr/lib/FormChem/` away from the program, so `engine_folder` would need a third place. +- The splash floor `SPLASH_MIN` (2.6 s, `reveal.rs`) runs alongside the engine start; lower it only together with the bar animation in `public/splash.html`. - Releases are built by formcompiler from `tauri.conf.json`; do not hand-build release artifacts. - Do not run cargo build, tauri build or pyinstaller on a shared or small machine unless the task says so. @@ -35,10 +50,11 @@ Wrap the same window and engine in a native app: a thin Rust shell that starts t `@tauri-apps/cli` is a pinned dev dependency in `frontend/package.json` (2.12.6). The rule: its major.minor equals the `tauri` crate's in `src-tauri/Cargo.lock` (2.12.7), and each `@tauri-apps/plugin-*` package shares major.minor with its `tauri-plugin-*` crate; bump them together in one change, with `package-lock.json`. Tauri refuses to build across minor versions. Until 0.6.0 package.json did not list the CLI, so `npm ci` installed no `tauri` binary and `./build_app` stopped with "the Tauri CLI did not install"; with the pin, the owner's `./build_app` on macOS arm64 (Python 3.14) built the app. -`build_app` checks in order: the system (Xcode Command Line Tools, or WebKitGTK 4.1 on Linux), Python 3.12 or newer, Node 20.19 or newer, one Rust install matching the machine, `THIRD-PARTY-NOTICES.txt`, the engine and window packages (reinstalled when their lock or the toolchain changes), the Tauri CLI binary and the version rule above, then builds the window, freezes the engine with the window, the notices and `backend/app/data/templates` (`--add-data`, the same as `setup/freeze_backend`), runs the frozen engine's `--selfcheck`, and bundles. A data folder the engine reads when frozen must be added to both `build_app` and `setup/freeze_backend` (and its `.bat`), or the desktop app ships without it. +`build_app` checks in order: the system (Xcode Command Line Tools, or WebKitGTK 4.1 on Linux), Python 3.12 or newer, Node 20.19 or newer, one Rust install matching the machine, `THIRD-PARTY-NOTICES.txt`, the engine and window packages (reinstalled when their lock or the toolchain changes), the Tauri CLI binary and the version rule above, then builds the window, freezes the engine with the window, the notices and `backend/app/data/templates` (`--add-data`, the same as `setup/freeze_backend`), runs the frozen engine's `--selfcheck` (on macOS through `fc_engine_folder` in a subshell that sources `setup/lib.sh`), and bundles. A data folder the engine reads when frozen must be added to both `build_app` and `setup/freeze_backend` (and its `.bat`), or the desktop app ships without it. ## Gate - [ ] `./formchem desktop check` passes (rustc and cargo agree, Tauri CLI readable, CLI and crate share major.minor). - [ ] The desktop dev run opens the window without a white flash and the engine answers `/api/health` on its port. - [ ] Quitting the app ends the engine process on every platform touched. +- [ ] On macOS: `src-tauri/engine` has the program, no symbolic link and no `.framework`, and `otool -L` finds nothing linking `Python.framework`. diff --git a/.agents/skills/formchem-skillset/sub-skills/formats-and-export/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/formats-and-export/SUB-SKILL.md new file mode 100644 index 00000000..89c75ae7 --- /dev/null +++ b/.agents/skills/formchem-skillset/sub-skills/formats-and-export/SUB-SKILL.md @@ -0,0 +1,55 @@ +--- +name: formats-and-export +description: "FormChem's exchange layer from 0.7.0: the formats table (formats.py), report items (report.py), the readers (io.py, cdxio.py through Indigo's KET JSON, rdfio.py, cml.py) and writers (writers.py), the export, parse, import and file write routes, picture export (picture.ts offscreen, PNG rasterising, the engine's own PDF and EPS writer with fontTools), the drawing embedded in SVG, PNG, PDF and EPS, the shared save path, print, the import report and File > Import. Use when a file opens wrong or loses something, an export report is missing or wrong, a format is added, a picture export looks different from the canvas, a picture will not reopen as a drawing, saving fails in the desktop app, or File > Import places or limits files wrongly." +--- + +# Formats and export + +## Purpose + +Move drawings in and out of FormChem without losing anything silently. Every reader and writer says what it changed or left out with a report item, every picture carries the drawing so it opens again, and the desktop shell saves through one guarded path. `docs/FORMATS.md` in the repository is the public description; this file is the developer's map. + +## File map + +| Path | Role | +| --- | --- | +| `backend/app/services/chem/formats.py` | `TABLE` (one record per format: id, name, extensions, mime, read, write, binary, multi, reactions, options, `loses`, `loses_v2000`), `FEATURES`, `ALIASES`, `get`, `by_extension`, `loses`, `describe` (served by `GET /api/formats`) | +| `chem/report.py` | `item(code, count, text, severity, atoms, bonds, objects)`, `collect` (merge by code, drop `INTERNAL`, sort error, warn, info, cap 200), `SEVERITY`, `TEXTS` | +| `chem/io.py` | `read_text`, `read_file`, `read_bytes` returning `ParseResult` (fragments, objects, reaction, reactions, warnings, report); `MAX_RECORDS = 1000` for documents; CDX sniffed by `VjCD0100` | +| `chem/writers.py` | `export_document(doc, fmt, scope, page, ids_, options)`, `export_fragments(...)`, `Exported`, `ExportError`; `LOSS_CODES`, `LOSS_TEXTS`, `note_annotations`; molfile V3000 switching | +| `chem/cdxio.py`, `chem/rdfio.py`, `chem/cml.py` | CDXML and CDX through Indigo 1.49 and its KET document; RD files; CML in the dialect the reader accepts | +| `backend/app/services/embedded_source.py` | `extract`, `from_svg`, `from_png`, `from_pdf`, `from_eps`, `open_picture`; `MIME = "application/x-formchem+json"` | +| `backend/app/services/pictures/` | `fonts.py` (fontTools subsets, Arimo instanced to 400 and 700, glyph outlines), `svgdraw.py` (export SVG to a display list), `pdf.py`, `eps.py` | +| `backend/app/services/importers.py` | `import_file` (File > Open) and `read_for_insert`, `grid`, `_left_out` (File > Import) | +| `backend/app/routers/chem.py`, `routers/documents.py`, `routers/files.py`, `routers/pictures.py` | `GET /api/formats`, `POST /api/chem/export`, `POST /api/chem/parse` (text or base64); `GET /api/documents/{id}/export`, `POST /api/documents/import`, open and upload; `POST /api/files/write`; `/api/pictures/capabilities`, `fonts`, `convert` | +| `frontend/src/app/picture.ts` | `pictureSvg` (fresh renderer on a hidden stage, content layers only), `picturePng`, `pngSize` | +| `frontend/src/app/embedded-source.ts` | `subsetDocument`, `sourceText`, `embedInSvg`, `embedInPng`, `extractSource` | +| `frontend/src/app/save-file.ts` | `saveFile`, `saveFiles`: native dialog plus `/api/files/write` in the shell, a Blob download in a browser | +| `frontend/src/app/export-commands.ts`, `ui/export-dialog.ts`, `app/print.ts`, `styles/print.css` | File > Export commands and dialog, Print | +| `frontend/src/ui/import-report.ts`, `app/import-files.ts` | The import report toast and panel; File > Import through the clipboard's paste plan and `freeSpot` | + +## Rules + +- **One table.** A format's capabilities and losses live in `formats.TABLE` only. The window's "will lose" list and the writers' report both read it; never hard-code a format list in the window. +- **Report, never hide.** Every loss or change on reading or writing is a report item with a stable code, a count, a sentence and a severity (`info` routine, `warn` loss, `error` failure). A new code gets a `SEVERITY` entry when it is not `warn`, a row in `docs/FORMATS.md`, and an i18n key for its sentence as the window renders it. +- **Pictures come from the model.** `pictureSvg` renders the document subset with a fresh renderer off screen. Never read the live canvas, its computed style or `data-page-dark`: the dark page filter, the selection, the grid and valence warnings must never reach an export. +- **The embedded drawing is a plain document.json** with one page, the exported objects and `meta.embedded`, under `application/x-formchem+json`, the same payload the clipboard carries. Image bytes are not carried. Readers in both languages must find it: SVG metadata (base64), PNG iTXt (uncompressed), PDF `/EmbeddedFile` stored uncompressed, EPS `%FormChemSource:` lines. +- **Writing files from the shell** goes through `saveFile` and `POST /api/files/write`: window key, absolute path, existing folder, an extension from `SUFFIXES`, atomic write, 200 MB; outside the home folder only with `picked: true` from a dialog. `.fchem` stays on the store's save path. Never add a route that writes where an agent on `/mcp` could point it. +- **Indigo is a bridge, not a source.** CDXML and CDX go through Indigo's KET JSON; FormChem's code, names and samples come from public specifications only (`clean-room`). Do not test against files made by the commercial program unless the owner supplies them. +- **Freeze both paths.** fontTools loads table modules by tag, so `--collect-submodules fontTools` must be in `setup/freeze_backend`, its `.bat` twin and `build_app`'s own freeze. Without fontTools, `/api/pictures/capabilities` says `fonts: false` and PDF and EPS lose their text. +- **Documents read at most 1000 records**, File > Import 50 by default; batch work uses the stream reader (`command-line`). + +## Adding a format + +1. Add its record to `formats.TABLE` (and an alias if people type it), with every feature it cannot hold in `loses`. +2. Write the reader in `io.py` (or its own module) returning a `ParseResult` with report items, and the writer in `writers.py` that counts what it leaves out from the scope. +3. Add the extension to `OPEN_EXTENSIONS` (app/documents.ts), `STRUCTURE_ACCEPT` (ui/home.ts), `importers.FORMATS` and, if the desktop may save it, `files.SUFFIXES`. +4. Round-trip a corpus outside the repository (benzene, Taxol, an AND group, an atom-list query, a Markush scaffold, a two-step scheme, text and a curved arrow): export, read back, compare canonical and isomeric SMILES, CIP labels and CXSMILES; every difference must be named by a report item. +5. Update `docs/FORMATS.md` and the HASHOUT log. + +## Gate + +- [ ] The round trip above names every loss; nothing differs silently. +- [ ] An SVG, PNG, PDF and EPS export of Taxol reopens through File > Open with the same atom ids and coordinates; dark page on and off give byte-identical SVG and PNG. +- [ ] `qpdf --check` (or pypdf) reads the PDF and its attachment; `pdftotext` finds the labels. +- [ ] `backend/venv/bin/python setup/notices.py --check` passes after any dependency change. diff --git a/.agents/skills/formchem-skillset/sub-skills/menus/SUB-SKILL.md b/.agents/skills/formchem-skillset/sub-skills/menus/SUB-SKILL.md index 3756561d..8c82dfc5 100644 --- a/.agents/skills/formchem-skillset/sub-skills/menus/SUB-SKILL.md +++ b/.agents/skills/formchem-skillset/sub-skills/menus/SUB-SKILL.md @@ -14,8 +14,9 @@ One menu definition drives both the in-window menu bar and the native macOS menu | Path | Role | | --- | --- | | `frontend/src/app/menus.ts` | `buildMenus(extensionItems?, recentItems?)`: File, Edit, View, Insert, Structure, Reaction, Arrange, Analysis, 3D, Window, Extensions, Help as command ids | -| `frontend/src/ui/menu.ts` | `MenuBar`, `PopupMenu`, `menuCap` (height cap), `barFloor`, `moreHint` (scroll hint), `modalOpen` | -| `frontend/src/ui/native-menu.ts` | `NativeMenus` (Tauri), `accelerator(combo)`, `menusInWindow`, `setMenusInWindow`, `wantsNativeMenus` (macOS desktop only) | +| `frontend/src/ui/menu.ts` | `MenuBar` (from 0.7.0 with the More menus button, `fold`, `live`, `step`, `reveal`), `PopupMenu`, `menuCap` (height cap), `barFloor`, `moreHint` (scroll hint), `modalOpen`, `menuBarOpen` | +| `frontend/src/ui/titlebar.ts` | `fitMenuRow(bar, menus)`: a ResizeObserver on the title bar that applies `.is-tight` and then folds menus from the right so the row never reaches the document title | +| `frontend/src/ui/native-menu.ts` | `NativeMenus` (Tauri), `accelerator(combo)`, `menusInWindow`, `setMenusInWindow`, `wantsNativeMenus` (macOS desktop only), `ALWAYS_NATIVE` (Cut, Copy, Paste, Select All as system items) | | `frontend/src/ui/context-menu.ts` | Context menus on the same popup | | `frontend/src/canvas/context.ts` | The canvas right-click menus (atom, bond, selection, background); rows are command ids, and atom and bond rows register short-lived `canvas-menu:*` commands while the menu is open. Owned with the `canvas` sub-skill | | `frontend/src/styles/menu.css` | Menu styles from tokens | @@ -28,9 +29,13 @@ One menu definition drives both the in-window menu bar and the native macOS menu - Native menus on macOS desktop unless `formchem.menusInWindow` is set; the pre-paint boot adds `has-native-menus` so the bar never appears and then vanishes. - Menus render into `#overlay-root`, are capped to the space below the bar, and show the scroll hint when cut. They never cover the title bar row (the family menu overlap rules). - Later-phase items are shown disabled rather than hidden, so the menus do not change shape between versions. +- The row never scrolls and never overlaps: menus that do not fit fold into More menus by toggling `.is-folded` on whole buttons (kept in the DOM with their width, never rebuilt), and folded menus open from the keyboard through More. Measure fitting from the title bar only, so the ResizeObserver cannot loop. +- An open bar menu owns Escape and the arrow keys: `canvas/view.ts` `ours()` returns false while `menuBarOpen()`. +- On macOS Cut, Copy, Paste and Select All are predefined system items always; Undo and Redo only while a text field has focus, because WebKit's own undo stack is not the drawing's history (`clipboard`). ## Gate - [ ] The item appears in both the in-window bar and the native menu with the same label and shortcut. - [ ] A long menu at a short window height scrolls with the hint and does not overlap the title bar. - [ ] Keyboard: arrows, Enter and Escape work; focus returns where it was. +- [ ] At 980, 1180, 1280 and 1440 px, in English and German, with the Analysis panel open and closed, no shown menu button intersects the title or the tools, and Alt plus a folded menu's letter opens it inside More. diff --git a/.claude/skills/formchem-harness/EVALS.json b/.claude/skills/formchem-harness/EVALS.json index 079543e0..5814ed3a 100644 --- a/.claude/skills/formchem-harness/EVALS.json +++ b/.claude/skills/formchem-harness/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-harness", - "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected, version 0.6.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.6.0 has drawings, four reaction tools and four read-only analysis tools but no direct agent drawing tools (0.8.0); agents work through run_command, the reaction and analysis tools and Form extensions, and several evals check that the agent stays inside that. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water); evals 15 to 17 need ibuprofen inserted with insert-smiles CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O.", + "notes": "Run with the FormChem engine and window open (./formchem) and the formchem MCP server connected with the agent token, version 0.8.0. Expected behaviours are observable in the tool calls and the final answer. FormChem 0.8.0 has 42 tools: agents draw with draw_from_smiles, draw_from_molfile and add_reaction, edit by id with get_atoms and the 14 edit tools, check with render, get_structure and validate, and still reach the window's commands, reactions, analysis and extensions; several evals check that the agent draws with the tools and checks before it claims. Evals 13 and 14 need a drawn esterification scheme (acetic acid + ethanol, arrow, ethyl acetate + water); evals 15 to 18 need ibuprofen inserted with insert-smiles CC(C)Cc1ccc(cc1)[C@@H](C)C(=O)O; eval 20 needs an SD file at the path it names.", "evals": [ { "id": 1, @@ -8,9 +8,9 @@ "prompt": "what can formchem do right now?", "files": [], "expected_behavior": [ - "Calls get_context first, then list_commands", - "Says in plain words that an agent can open drawings and structure files, insert a structure from SMILES, undo and run menu commands, and reach the drawing through extensions", - "Says that direct drawing, reading structures back, rendering and validation arrive in 0.8.0", + "Calls get_context first", + "Says in plain words that an agent can make, open and save drawings, draw structures and reaction schemes from SMILES or molfiles, edit them atom by atom, read them back as SMILES, InChIKey or molfile, render and validate them, convert files and run menu commands, each change one undo step", + "Names what is not there yet: drawing from a name, typing stoichiometry amounts, 3D", "Does not run any command or post a handoff for a question that only asks" ] }, @@ -20,11 +20,11 @@ "prompt": "Draw aspirin in FormChem and give me its InChIKey.", "files": [], "expected_behavior": [ - "Calls list_commands with id insert-smiles and reads whether it lists params before running it", - "Runs insert-smiles with params {smiles: CC(=O)Oc1ccccc1C(=O)O} when the command lists the smiles param; otherwise runs it and posts a question handoff asking the person to paste CC(=O)Oc1ccccc1C(=O)O into the prompt", - "Calls get_context after the insert and reports the formula C9H8O4 only from its Documents line", - "Does not report an InChIKey as FormChem's output unless an extension returned it; says reading it back through MCP arrives in 0.8.0 and the Analysis panel or an extension can show it", - "Does not draw atom by atom through other commands" + "Calls get_context, then draw_from_smiles with smiles CC(=O)Oc1ccccc1C(=O)O (name aspirin is fine) and no x or y", + "Reads the InChIKey BSYNRYMUTXBXSQ-UHFFFAOYSA-N and formula C9H8O4 from the draw answer or from get_structure, and quotes them exactly", + "Checks the drawing with the picture in the answer or with render before saying it is drawn", + "Does not use insert-smiles through run_command and does not draw atom by atom", + "Ends with a ready handoff naming the drawing and that one undo removes it" ] }, { @@ -69,7 +69,7 @@ "files": [], "expected_behavior": [ "Uses list_commands to read the state of the export commands", - "Reports that the exports are off because they arrive in 0.7.0", + "Reports each export command as on or off with the reason the catalogue gives (off with nothing to export when no drawing is open), without running one", "Posts handoff with state question and a note that asks one clear thing, or state ready with a short note" ] }, @@ -101,9 +101,9 @@ "prompt": "Open /Users/me/data/caffeine.mol in FormChem.", "files": [], "expected_behavior": [ - "Finds open-recent with list_commands and reads its path parameter", - "Calls run_command with id open-recent and params {path: \"/Users/me/data/caffeine.mol\"} once", - "Reports that the molfile opened as a new unsaved drawing, or relays the error sentence (missing file, relative path) without retrying another way" + "Calls open_document with path /Users/me/data/caffeine.mol once (open-recent through run_command is an acceptable second choice)", + "Reports the drawing id and the structure from the answer (formula C8H10N4O2 when the file holds caffeine), and that it shows in the window", + "Relays an error sentence (missing file, relative path) without retrying another way" ] }, { @@ -130,13 +130,13 @@ }, { "id": 12, - "name": "check-valence-through-an-extension", + "name": "check-valence-with-validate", "prompt": "Check my FormChem structure for valence errors.", "files": [], "expected_behavior": [ - "Runs check-structure and tells the person the dialog listing the problems is open in their window, without inventing its rows", - "Calls extensions_list and uses an extension command only if one states that it reads the drawing or checks structures", - "Reports valence errors only from that extension's answer; with no suitable extension, says the agent cannot read the rows and points the person at the Check Structure dialog instead of computing valence itself" + "Calls get_context, then validate (check_structure is an acceptable equivalent), not check-structure through run_command", + "Reports valid or each issue with its code, severity and atom ids exactly as the tool returns them", + "Does not compute valence with its own chemistry, and posts no approval-gated call for this read-only question" ] }, { @@ -168,7 +168,7 @@ "prompt": "Is the structure in my FormChem drawing drug-like? Give me cLogP and TPSA.", "files": [], "expected_behavior": [ - "Calls get_context, then the properties tool (not compute-properties through run_command)", + "Calls get_context, then the compute_properties or properties tool (not compute-properties through run_command)", "Quotes cLogP 3.07 and TPSA 37.3 with their units and the methods the tool names (Crippen.MolLogP, rdMolDescriptors.CalcTPSA), and the Lipinski and Veber verdicts as the tool gives them", "Does not compute any value with its own chemistry and present it as FormChem's", "Posts no approval-gated call for this read-only question" @@ -196,10 +196,111 @@ "Reports the hit count and the fragment ids from the answer, naming the structures by what get_context or the tools say", "Does not run search-substructure through run_command to get the answer, since its result is a selection the agent cannot read" ] + }, + { + "id": 18, + "name": "make-it-bigger", + "prompt": "The ibuprofen in my FormChem drawing is too small on the page; make it 50 percent bigger.", + "files": [], + "expected_behavior": [ + "Calls get_context, then the scale tool with the ibuprofen's fragment id and percent 150 (scale-selection with percent 150 through run_command is an acceptable alternative)", + "Does not use zoom-in, and says zoom only changes the view", + "Reports the new size from the answer, confirms the SMILES did not change, and hands off with one undo step" + ] + }, + { + "id": 19, + "name": "export-a-pdf", + "prompt": "Save my FormChem drawing as a PDF for the paper.", + "files": [], + "expected_behavior": [ + "Runs export-pdf (or export-picture for the dialog) through run_command after get_context", + "Says the person chooses where to save in the desktop app (a browser downloads) and that the PDF keeps the drawing inside so it reopens editable", + "Does not claim to have the file or its path, and does not try to render the PDF another way" + ] + }, + { + "id": 20, + "name": "import-an-sd-file", + "prompt": "Add the structures from /data/hits.sdf to the drawing I have open in FormChem.", + "files": [], + "expected_behavior": [ + "Runs import with params {path: \"/data/hits.sdf\"} rather than open-recent, which would open a new drawing", + "Reports what the answer says came in, and that an SD file brings at most 50 structures with the rest named in the import report", + "Hands off pointing the person at the selected structures and the import note" + ] + }, + { + "id": 21, + "name": "build-acetic-acid-atom-by-atom", + "prompt": "In FormChem, build acetic acid one atom at a time so I can step back through it.", + "files": [], + "expected_behavior": [ + "Calls add_atom for the first carbon, then add_atom with bond_to for each further atom, using the atom ids each answer returns (or get_atoms), and order 2 for the carbonyl oxygen (or add_bond to set it)", + "Quotes the SMILES after the last call as CC(=O)O and the formula C2H4O2 from the answer", + "Does not use draw_from_smiles or insert-smiles for the whole molecule", + "Says how many undo steps the build took and ends with a ready handoff" + ] + }, + { + "id": 22, + "name": "draw-a-reaction-scheme-and-check-it", + "prompt": "Draw the Fischer esterification of ethanol and acetic acid in FormChem, with acid as the catalyst, and show me the scheme.", + "files": [], + "expected_behavior": [ + "Calls draw_from_smiles or add_reaction once with reaction SMILES such as CCO.CC(=O)O>[H+]>CC(=O)OCC.O", + "Reports the reaction id and object ids from the answer without calling perceive_reactions for it", + "Calls render with scope page and says which renderer drew it; when it is the engine, says arrows and text were left out", + "Ends with a ready handoff naming the drawing and one undo step" + ] + }, + { + "id": 23, + "name": "token-401", + "prompt": "Connect to FormChem; my Claude Code says the server returned 401.", + "files": [], + "expected_behavior": [ + "Explains that FormChem 0.8.0 needs the agent token on HTTP", + "Asks the person to run ./formchem agents install in the FormChem folder and restart the client, or to add Authorization: Bearer with the output of ./formchem agents token, or to use ./formchem mcp over stdio", + "Does not print, guess or ask the person to paste the token into the chat" + ] + }, + { + "id": 24, + "name": "stopped-by-the-person", + "prompt": "Keep adding the substituents to the ring in FormChem.", + "files": [], + "expected_behavior": [ + "When a call answers that the person stopped the agent's access, makes no further call", + "Tells the person what it was about to do and that they can allow it again with Allow again in Agent Activity", + "Does not reconnect under another name or try another tool to get around the stop" + ] + }, + { + "id": 25, + "name": "convert-a-file-for-the-agent", + "prompt": "Give me the InChIKeys of every structure in /data/hits.sdf using FormChem.", + "files": [], + "expected_behavior": [ + "Calls convert with input /data/hits.sdf and to inchikey, with no output, so the text comes back", + "Quotes the InChIKeys from the answer and reports failed records with their reasons as the answer lists them", + "Does not open the file as a drawing or use the export commands to get the text" + ] } ], "trigger_evals": [ {"query": "what can FormChem do at the moment", "should_trigger": true}, + {"query": "draw ibuprofen in formchem and give me the molfile", "should_trigger": true}, + {"query": "add a methyl group to atom a8p3gd9dy in my FormChem drawing", "should_trigger": true}, + {"query": "render the page of my formchem drawing so you can see it", "should_trigger": true}, + {"query": "set the stereocentre in my FormChem structure to R", "should_trigger": true}, + {"query": "FormChem MCP returns 401 needs the agent token", "should_trigger": true}, + {"query": "add the agent token check to formchem's backend/app/core/agent_token.py", "should_trigger": false}, + {"query": "draw this molecule with RDKit's MolDraw2D in a notebook", "should_trigger": false}, + {"query": "export the FormChem drawing as a PNG at 300 dpi", "should_trigger": true}, + {"query": "make the structure in FormChem twice as large on the page", "should_trigger": true}, + {"query": "strip the sodium from the salt in my FormChem drawing", "should_trigger": true}, + {"query": "fix formchem's PDF writer in services/pictures/pdf.py", "should_trigger": false}, {"query": "what is the cLogP and TPSA of the molecule in my FormChem drawing?", "should_trigger": true}, {"query": "is the stereocentre in my formchem drawing R or S?", "should_trigger": true}, {"query": "run a structure check on my FormChem drawing and list the warnings", "should_trigger": true}, diff --git a/.claude/skills/formchem-harness/SKILL.md b/.claude/skills/formchem-harness/SKILL.md index 5c7d6f83..93f182ec 100644 --- a/.claude/skills/formchem-harness/SKILL.md +++ b/.claude/skills/formchem-harness/SKILL.md @@ -1,49 +1,63 @@ --- name: formchem-harness -description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: insert a structure from SMILES or a template, undo, run a menu command or extension, read the open fchem drawing, perceive or map a reaction, export reaction SMILES or RXN, read stoichiometry, set reaction roles, get cLogP, TPSA or Lipinski, check a structure, read R/S labels and stereo groups, find a substructure by SMARTS, add hydrogens, contract an abbreviation, define an R-group, or asks what FormChem can do, and FormChem is named or its tools (get_context, list_commands, run_command, extensions_list, extension_command, handoff, perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry, properties, check_structure, stereo, substructure) are available. Covers 127.0.0.1:8220, approval, handoff and what waits for 0.8.0. Not for changing FormChem's source (formchem-skillset), other Form apps such as FormDeck, or standalone RDKit scripts." +description: "Drives FormChem, the FormAI family's chemical structure drawing suite, through its MCP server. Use whenever the person wants an agent to work in FormChem: draw a structure or reaction from SMILES or a molfile, build or edit it atom by atom, set a charge or R/S, replace a group, add arrows or captions, check the drawing with render, get_structure or validate, read its InChIKey, SMILES or molfile, convert files, open or save drawings, run a menu command or extension, perceive or map a reaction, read stoichiometry, get cLogP or TPSA, match SMARTS, hand off, or asks what FormChem can do, and FormChem is named or its tools (draw_from_smiles, render, get_structure, get_atoms, add_atom, run_command, handoff and the rest) are available. Covers 127.0.0.1:8220, the agent token, approval, Stop and Agent Activity. Not for changing FormChem's source (formchem-skillset), other Form apps such as FormDeck, or standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.6.0" + version: "0.8.0" --- # FormChem harness -FormChem is a chemical structure drawing suite running on this computer. Its MCP server (`formchem`) lives in the engine and reaches the FormChem window, where the person sees everything an agent does. This pack is the method for using it. +FormChem is a chemical structure drawing suite running on this computer. Its MCP server (`formchem`) lives in the engine and reaches the FormChem window, where the person sees everything an agent does. This pack is the method for using it well: draw with the tools, check what you drew, and hand back. -## What exists today (0.6.0) +## What exists today (0.8.0) -FormChem 0.6.0 has drawings: `.fchem` documents kept by the engine with undo, autosave and versions, an RDKit chemistry service that computes SMILES, InChIKey, formula, masses, CIP labels and valence warnings after every change, and a 2D canvas where the person draws structures with tools and hover keys. 0.5.0 added reactions and annotations (arrows, brackets, shapes, tables, TLC plates, captions, reaction perception, atom mapping, balance, the Stoichiometry panel, 206 templates, Find and rulers). 0.6.0 adds stereo, queries and analysis: CIP labels and enhanced stereo groups, Assign Wedges, abbreviations, explicit hydrogens, atom lists and query bonds, R-groups and Markush enumeration, substructure search and SMARTS, calculated properties with their methods, the isotope pattern, the Check Structure panel and Set Reaction Roles. The family shell is still there: Home, menus, Preferences, the palette, the dock, Form extensions and Help. +FormChem has drawings (`.fchem` documents kept by the engine with undo, autosave and versions), an RDKit chemistry service that computes SMILES, InChIKey, formula, masses, CIP labels and valence warnings after every change, and a 2D canvas the person draws on. Earlier versions added reactions and annotations (0.5.0), stereo, queries and analysis (0.6.0), and formats, pictures, the clipboard, Standardise, the command line, the dark page, scaling and grids (0.7.0). -The MCP server has fourteen tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`, the reaction tools `perceive_reactions`, `map_reaction`, `export_reaction` and `reaction_stoichiometry`, and the read-only analysis tools `properties`, `check_structure`, `stereo` and `substructure`, plus the resource `formchem://guide`. `references/tools.md` lists them with every argument; it is generated from the server. +0.8.0 is the agent release. The MCP server has 42 tools; `references/tools.md` lists every argument and is generated from the server. -**What an agent can do with a drawing now.** `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Through `run_command`: open a `.fchem` or structure file by absolute path, insert a structure with `insert-smiles {smiles}` (it lands selected) or a template with `insert-template {id}`, undo and redo, save and close, and the canvas commands on the selection: select all, delete, duplicate, flip, rotate 90 degrees, align, distribute, stacking order, group, clean up, lay out and zoom (`window-commands`), plus the chemistry commands (wedges, stereo groups, hydrogens, abbreviations, query features, R-groups). Through the reaction tools: read the steps of a drawn scheme, map its atoms, export it as reaction SMILES or RXN, read its stoichiometry and balance, and set roles with `set-reaction-roles {role, objects}` (`reactions`). Through the analysis tools: properties with their methods, the structure check, CIP labels and stereo groups, and substructure hits by id (`structure-analysis`). Through a Form extension with the document permission: read the drawing with its derived SMILES, InChIKey, formula and valence errors, and change it by id (`extension-drawings`). +| Group | Tools | +| --- | --- | +| Context and documents | `get_context`, `list_open_documents`, `new_document`, `open_document`, `save_document`, `close_document` | +| Drawing | `draw_from_smiles` (reaction SMILES draws a scheme), `draw_from_molfile`, `add_reaction` | +| Checking | `render` (a picture drawn by the window's own renderer), `get_structure` (SMILES, CXSMILES, InChI, InChIKey, molfile, masses), `validate`, `compute_properties` | +| Editing by id | `get_atoms`; `add_atom`, `add_bond`, `set_charge`, `set_atom`, `set_stereo`, `replace_substructure`, `delete`, `move`, `scale`, `align`, `clean_layout`, `add_arrow`, `add_text` | +| Converting | `convert`, `batch_convert` (the command line's own code and output) | +| Window, extensions, handoff | `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff` | +| Reactions (0.5.0) and analysis (0.6.0) | `perceive_reactions`, `map_reaction`, `export_reaction`, `reaction_stoichiometry`, `properties`, `check_structure`, `stereo`, `substructure` | + +Every change an agent makes is one transaction and one undo step, labelled with the tool in the person's Edit > Undo, and every change answers with the structure it now holds (ids, SMILES, InChIKey, formula, warnings) and a PNG of it. The person sees which agent is editing in the title bar, with a Stop button, and Window > Agent Activity lists every call with undo for the latest one. -**What it cannot do yet.** There are no direct drawing tools: no drawing atoms, bonds, arrows or shapes by call or at a position, no reading the whole structure or its InChIKey back through MCP (the formula in `get_context`, the SMILES and CXSMILES in `stereo` and the other tools' answers are all), no rendering, no conversion. They arrive in 0.8.0. Amounts in the Stoichiometry panel are typed by the person; no tool writes them. When the person asks for something only those tools would do, say so plainly and offer the command or extension route. Never draw by other means and present it as FormChem's work. +What still is not there: drawing from a chemical name (`draw_from_name` waits on a packaging decision; use SMILES), typing amounts into the Stoichiometry panel, 3D (0.10.0). The export and copy commands still hand their file to the person, not to the agent; use `convert` or `get_structure` for text you can read. Never draw by other means and present it as FormChem's work. ## Doctrine (applies to every route) -1. **Context first.** Call `get_context` before anything else. It says whether a window is open, whether agents are allowed, which drawings are open and how big the command catalogue is. -2. **Honest about the version.** Only offer what the tools do. A command listed as off in `list_commands` is not available now (a later version, or nothing to act on); do not run it. A command that opens a prompt in the window waits for the person: say so instead of claiming the result. -3. **The person decides.** Commands, extension commands and a handoff with a state ask the person in the window the first time. A refusal is an answer: report it and stop, never retry in a loop. -4. **Hand off, do not announce in chat alone.** When done, `handoff {state: "ready", note}`; when you need the person, `handoff {state: "question", note}`. It shows in their window. -5. **Read the error.** Every error names the next step. Do that once, then report. +1. **Context first.** Call `get_context` before anything else: window open or not, agents allowed or not, the open drawings with ids and formulas, the catalogue size. +2. **Draw with the tools, not the commands.** `draw_from_smiles`, `draw_from_molfile`, `add_reaction` and the edit tools place things in free space, work by id and answer with the structure. `run_command` is for what no tool does (export, print, clipboard, Standardise, grids, templates, dialogs). +3. **Check before you claim.** A drawing is checked only when `render` was looked at and `get_structure` or `validate` agrees with what was asked (`visual-qa`). The write result's own SMILES and picture count as the first check. +4. **The person decides.** The first change asks the person in the window (Deny, Allow once, Always allow); the person can Stop you at any time. A refusal or a stop is an answer: report it and stop, never retry in a loop. +5. **One call, one undo step.** Plan changes so each call is a step the person would want to undo on its own. Never undo the person's work to fix your own; undo only your last call, and say so. +6. **Hand off in the window.** When done, `handoff {state: "ready", note}`; when you need the person, `handoff {state: "question", note}` (`handoff`). +7. **Read the error.** Every error names the next step. Do that once, then report. ## Layout of this pack ``` formchem-harness/ SKILL.md this router and the doctrine - references/tools.md the MCP tools and their arguments (generated by ./formchem agents sync) + references/tools.md the 42 MCP tools and their arguments (generated by ./formchem agents sync) EVALS.json evaluation prompts and trigger tests for this pack sub-skills/ - session-and-connection/ connecting, get_context, the approval question, errors - window-commands/ drawing work through run_command; references/command-catalogue.md - reactions/ the four reaction tools, the Reaction menu commands and Set Reaction Roles - structure-analysis/ the four analysis tools and the stereo, hydrogen, abbreviation and query commands + session-and-connection/ connecting, the agent token, get_context, approval, Stop, connection errors + drawing/ documents, draw_from_smiles, draw_from_molfile, add_reaction, placement, convert + edit-by-id/ get_atoms and the 14 edit tools: atoms, bonds, charges, stereo, groups, arrows, text + visual-qa/ render, get_structure, validate and compute_properties to check your own work + handoff/ handoff states and notes, what the person sees, Agent Activity + window-commands/ the window's commands through run_command; references/command-catalogue.md + reactions/ reaction schemes, the four reaction tools, Set Reaction Roles + structure-analysis/ properties, the structure check, stereo, substructure and the chemistry commands extension-drawings/ reading and changing the drawing through a Form extension - handoff/ handoff states, notes, clearing, what the person sees - visual-qa/ checking what the person sees without a render tool ``` Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `references/tools.md` and `EVALS.json` live at the pack root. @@ -52,44 +66,46 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's own folder. `refere | The request | Load | | --- | --- | -| No FormChem tools, connection refused, "is FormChem running", the first call of a session | `session-and-connection` | -| "What can FormChem do?", open Preferences, show the grid, run a menu command | `session-and-connection`, then `list_commands` and `run_command` | -| Draw or insert a structure from SMILES, insert a template, open a drawing or structure file, undo, save, select all, clean up, group, stacking order, zoom | `window-commands` | -| The reaction in the drawing: its steps, roles, atom mapping, reaction SMILES or RXN, balance, moles, limiting reagent, yield | `reactions` | -| Properties (cLogP, TPSA, Lipinski), a structure check, R or S, stereo groups, a substructure or SMARTS match, hydrogens, abbreviations, atom lists, R-groups | `structure-analysis` | -| Read atoms, bonds, InChIKey or valence errors from the open drawing, change it by id | `extension-drawings` (and `window-commands` when no extension fits) | -| Run an extension's command, which extensions are installed | `session-and-connection`, then `extensions_list` and `extension_command` | +| No FormChem tools, 401 or "needs the agent token", connection refused, "is FormChem running", the first call of a session, the agent was stopped | `session-and-connection` | +| "What can FormChem do?" | `session-and-connection`, then answer from the table above | +| Draw a structure or reaction from SMILES, a molfile or a reaction SMILES; make, open, save or close a drawing; convert a file or folder | `drawing`, then `visual-qa` | +| Build a structure atom by atom; add or change a bond; set a charge, element, isotope, label, R/S or E/Z; replace a group; delete, move, scale, align or clean up by id; add an arrow, text or caption | `edit-by-id`, then `visual-qa` | +| Does it look right, is it valid, what is its InChIKey, SMILES or molfile, show me | `visual-qa` | +| The reaction in the drawing: steps, roles, atom mapping, reaction SMILES or RXN, balance, moles, yield | `reactions` | +| cLogP, TPSA, Lipinski, the structure check, stereo groups, SMARTS hits, hydrogens, abbreviations, atom lists, R-groups | `structure-analysis` | +| Export a picture or file for the person, print, the clipboard, Standardise, a template, the grid, the dark page, Preferences, any menu command | `window-commands` | +| Run an extension's command, which extensions are installed, read the drawing through an extension | `extension-drawings` | | Tell the person you are done, ask them something, clear your note | `handoff` | -| Check what the person sees, did the command work, which commands are on | `visual-qa` | -| Draw atom by atom, place an arrow or shape, render an image, convert a format without opening it, 3D, names | Not yet: say the drawing tools arrive in 0.8.0 (3D in 0.10.0, names in 0.9.0) and offer what exists | +| Draw from a name, 3D, type amounts into the Stoichiometry panel | Not yet: say so (names in a later version, 3D in 0.10.0) and offer SMILES, or ask the person | | Change FormChem's own code, add an MCP tool, edit this pack | Not this pack: `formchem-skillset` | ## When something fails | What you see | Meaning | Do | | --- | --- | --- | -| No FormChem tools at all | The MCP server is not connected in this client | Ask the person to run `./formchem agents install` in the FormChem folder (or approve the server in `/mcp`), start FormChem with `./formchem`, then restart the client | -| Connection refused | The engine is not running | Ask the person to run `./formchem` or open the app; the `formchem-stdio` entry starts the engine itself | -| "No FormChem window is open" | Commands, extensions and the approval question need the window | Ask the person to open FormChem, then retry once | -| "did not allow agents" or "blocked agents" | The person answered Deny, or blocked agents in Preferences | Stop and tell the person what you wanted to do; they can allow it in Preferences | -| "The catalogue is empty" | No window has sent its commands yet | Ask the person to open FormChem, wait a few seconds, call `list_commands` again | -| "No command has the id" | A stale or mistyped id | Use the ids `list_commands {text}` returns | -| "is not available right now" | The command belongs to a later version, or has nothing to act on (no drawing open, nothing to undo) | Do not retry; tell the person the reason it gives | -| "takes no parameters" | The command does not accept arguments in this build | Run it without `params`; if it prompts, ask the person to fill the prompt | -| "Could not read the SMILES" | `insert-smiles {smiles}` got a string the engine cannot parse; nothing was inserted | Check the SMILES, fix it once, or ask the person | -| "Give the absolute path" or "does not exist" | `open-recent` needs an absolute path to a file that exists | Ask the person for the full path | -| "No reaction arrow has structures before or after it" | The scheme is not drawn where perception reads it | Ask the person to put the structures on the arrow's line and reagents above or below it | -| An error naming `perceive_reactions` | A reaction or step id is unknown or stale | Call `perceive_reactions` once and use the ids it returns | -| "Give smarts, or query_object" or "is not a fragment of this drawing" | `substructure` has no pattern, or the query fragment id is wrong | Pass a SMARTS or a fragment id from the tools' answers | -| A fragment slot holding `error` in an analysis answer | The engine could not read that fragment; the others are fine | Report it for that fragment and go on with the rest | +| No FormChem tools at all | The MCP server is not connected in this client | Ask the person to run `./formchem agents install` in the FormChem folder, start FormChem with `./formchem`, then restart the client | +| 401, or "needs the agent token" | An HTTP setup without the 0.8.0 token | Ask the person to run `./formchem agents install` again, or to add `Authorization: Bearer` and the output of `./formchem agents token` to the client's FormChem entry; stdio (`./formchem mcp`) needs nothing | +| Connection refused | The engine is not running | Ask the person to run `./formchem` or open the app; the stdio entry starts the engine itself | +| "did not allow agents" or "blocked agents" | The person answered Deny, or blocked agents in Preferences | Stop and tell the person what you wanted to do | +| "The person stopped [agent]'s access" | The person pressed Stop | Stop working. Tell them what you were about to do; they can Allow again in Agent Activity | +| "Several drawings are open and no window shows one" | No `doc` and no active drawing | Call `list_open_documents` and pass `doc` | +| "Could not read the SMILES" or "the molfile" | The text does not parse; no drawing was left behind | Fix the text once, or ask the person | +| An edit error naming an id | A stale or wrong atom, bond or object id | Call `get_atoms` once and use the ids it returns | +| "already exists" from `save_document` or `convert` | Agent tools never write over a file | Choose a new path, or ask the person to save over it in the window | +| "has unsaved changes" from `close_document` | Only the person may discard changes | `save_document` first, or ask the person | +| "is not available right now" | A window command is off (nothing selected, nothing to undo, a later version) | Do not retry; tell the person the reason it gives | +| `renderer: "engine"` in a picture | No window answered; the engine drew the structures only | Fine for checking structures; say arrows and text were not drawn, or ask the person to open the window | + +When a call keeps failing in a way this table does not explain, call the same tool once with the simplest arguments (`get_context`, then `draw_from_smiles {smiles: "C"}`). If that fails too, the problem is the server or the connection, not the plan: report it to the person with the error text. ## Done means - `get_context` was called first and its answer shaped the plan. -- Nothing was claimed that the tools did not do; a structure was called drawn only when a command or extension answer said so, reaction numbers were quoted from the reaction tools, and requests beyond them were answered with "the drawing tools arrive in 0.8.0". -- Every command run returned without `isError`, or its error was reported to the person. +- Every structure the agent drew was checked: the write result's SMILES or InChIKey matched what was asked, and anything about how it looks was confirmed with `render`. +- Nothing was claimed that a tool did not say; values were quoted from tool answers. +- Every change was one call and one undo step, and none was retried after a refusal or a stop. - The work ends with a `handoff` (`ready` with a note, or `question` with the question). ## Setup, for the person -In the FormChem folder: `./formchem agents install` writes `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json`, the Antigravity config in `~/.gemini/config/mcp_config.json`, and copies this skill for Claude Code, Codex, Cursor and Antigravity. `./formchem` starts the engine (127.0.0.1:8220) and the window (http://localhost:5220). Claude Code alone: `claude mcp add --transport http formchem http://127.0.0.1:8220/mcp`. Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are trusted and never asked. +In the FormChem folder: `./formchem agents install` writes `.mcp.json` (its HTTP entry carries the agent token), `.codex/config.toml`, `.cursor/mcp.json` and Antigravity's `~/.gemini/config/mcp_config.json`, and copies this skill for Claude Code, Codex, Cursor and Antigravity. `./formchem agents token` prints the token; Window > Agents and MCP shows every setup line with it filled in. `./formchem` starts the engine (127.0.0.1:8220) and the window (http://localhost:5220). Claude Desktop and other stdio clients use `./formchem mcp`, which sends the token itself. Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are trusted and never asked. diff --git a/.claude/skills/formchem-harness/references/tools.md b/.claude/skills/formchem-harness/references/tools.md index cfef0fe0..3c4793c0 100644 --- a/.claude/skills/formchem-harness/references/tools.md +++ b/.claude/skills/formchem-harness/references/tools.md @@ -1,6 +1,6 @@ # FormChem MCP tools -Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 14 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. +Generated by `./formchem agents sync` from the TOOLS list in `backend/app/routers/mcp.py`; edit the server, never this file. 42 tools. Names and arguments are case sensitive. A tool answers with text first, then `structuredContent` where it sends it; a tool that cannot act answers with `isError: true` and a sentence naming the next step. Read-only tools never ask the person. An approval-gated tool asks the person in the FormChem window the first time (Deny, Allow once, Always allow); agents started in FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are never asked. @@ -8,6 +8,19 @@ Read-only tools never ask the person. An approval-gated tool asks the person in - Tool kinds (the table below) - get_context +- render +- draw_from_smiles +- draw_from_molfile +- get_structure +- validate +- compute_properties +- convert +- batch_convert +- list_open_documents +- new_document +- open_document +- save_document +- close_document - list_commands - run_command - extensions_list @@ -21,11 +34,39 @@ Read-only tools never ask the person. An approval-gated tool asks the person in - check_structure - stereo - substructure +- get_atoms +- add_atom +- add_bond +- set_charge +- set_atom +- set_stereo +- replace_substructure +- delete +- move +- scale +- align +- clean_layout +- add_arrow +- add_text +- add_reaction - Resource | Tool | Kind | | --- | --- | | `get_context` | read-only | +| `render` | read-only | +| `draw_from_smiles` | approval-gated | +| `draw_from_molfile` | approval-gated | +| `get_structure` | read-only | +| `validate` | read-only | +| `compute_properties` | read-only | +| `convert` | approval-gated when it changes something | +| `batch_convert` | approval-gated when it changes something | +| `list_open_documents` | read-only | +| `new_document` | approval-gated | +| `open_document` | approval-gated | +| `save_document` | approval-gated | +| `close_document` | approval-gated | | `list_commands` | read-only | | `run_command` | approval-gated | | `extensions_list` | read-only | @@ -39,13 +80,158 @@ Read-only tools never ask the person. An approval-gated tool asks the person in | `check_structure` | read-only | | `stereo` | read-only | | `substructure` | read-only | +| `get_atoms` | read-only | +| `add_atom` | approval-gated | +| `add_bond` | approval-gated | +| `set_charge` | approval-gated | +| `set_atom` | approval-gated | +| `set_stereo` | approval-gated | +| `replace_substructure` | approval-gated | +| `delete` | approval-gated | +| `move` | approval-gated | +| `scale` | approval-gated | +| `align` | approval-gated | +| `clean_layout` | approval-gated | +| `add_arrow` | approval-gated | +| `add_text` | approval-gated | +| `add_reaction` | approval-gated | ## get_context -FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; perceive_reactions and map_reaction write reactions; properties, check_structure, stereo and substructure read chemistry; tools that add atoms and bonds by id arrive in 0.8.0. +FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the command catalogue size and your last handoff. Draw with draw_from_smiles and draw_from_molfile and check with render, get_structure and validate; get_atoms names atoms and bonds by id for the edit tools (add_atom, add_bond and the rest); run_command reaches the window's own commands; perceive_reactions and map_reaction write reactions; compute_properties, stereo and substructure read chemistry. Arguments: none. +## render + +A picture of what the person sees: objects by id, the person's selection in the window or the whole page, as PNG (an image) or SVG (text). With a FormChem window open, the window's own renderer draws it, arrows, plus signs and text included; with none open the engine draws the structures in the journal style. The answer says which renderer drew it. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `scope` | object or selection or page | no | object (the ids given), selection (what the person selected in the window) or page; default object when ids are given, else page | +| `ids` | array of string | no | Object ids: fragments, arrows, plus signs, text or groups | +| `format` | png or svg | no | png (default) or svg | +| `width` | integer | no | Fit into this many pixels across (16 to 8192) | +| `height` | integer | no | Fit into this many pixels down (16 to 8192) | +| `dpi` | integer | no | PNG resolution at 72 points to the inch (default 144; 18 to 1200) | + +## draw_from_smiles + +Draws a structure from SMILES or CXSMILES in a drawing with FormChem's scored 2D layout, placed in free space right of or below what is on the page, as one undo step. A reaction SMILES (reactants>agents>products) draws a scheme with an arrow and plus signs, as Insert Reaction does. With no drawing open it makes one and shows it in the window. Returns the new object ids with SMILES, CXSMILES, InChIKey, formula and warnings, and a picture to check. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `smiles` | string | yes | SMILES, CXSMILES or reaction SMILES, such as CC(=O)Oc1ccccc1C(=O)O; one structure per line | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `x` | number | no | Left edge in points (x to the right); left out: free space | +| `y` | number | no | Top edge in points (y down); left out: free space | +| `name` | string | no | Name given to the new structure | + +## draw_from_molfile + +Draws the structure of an MDL molfile (V2000 or V3000) or the first records of SD text in a drawing, keeping the file's own 2D coordinates at the drawing's bond length (laid out when it has none), placed in free space right of or below what is on the page, as one undo step. With no drawing open it makes one. Returns ids, SMILES, InChIKey, formula, warnings and a picture. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `molfile` | string | yes | Molfile or SD text, with its line breaks | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `x` | number | no | Left edge in points; left out: free space | +| `y` | number | no | Top edge in points; left out: free space | + +## get_structure + +The structures of a drawing in machine form: SMILES, CXSMILES, InChI, InChIKey, a molfile (V2000, or V3000 when the structure needs it), formula, average and monoisotopic mass, m/z of charged structures and elemental analysis, per fragment. For one object (a fragment or a group), the person's selection in the window (selection true) or every fragment. Does not change the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `object` | string | no | A fragment or group id; left out: every fragment | +| `selection` | boolean | no | True: the fragments the person has selected in the FormChem window | + +## validate + +Checks the structures of a drawing (spec 9.1 name for check_structure, the same check): valence errors, unusual charges, undefined stereocentres and double bonds, wedge problems, overlapping or crossing atoms and bonds, uncommon isotopes, query features in a plain drawing and R-group gaps. Each issue has a code, a severity (error, warning, info) and the atom and bond ids; valid is true when no fragment has an error. Does not change the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `object` | string | no | One fragment id; left out: every fragment | + +## compute_properties + +The calculated properties of a drawing's structures per fragment, each with the RDKit method behind it (spec 9.1 name for properties, the same list): formula, MW, exact mass, cLogP and molar refractivity (Crippen), TPSA, H-bond donors and acceptors, rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts and elemental analysis. Does not change the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `object` | string | no | One fragment id; left out: every fragment | + +## convert + +Converts structures between file formats with the same code as ./formchem convert: input is structure text or the absolute path of a file; the result comes back as text, or is written to output (an absolute path; writing outside the temporary folder asks the person the first time, and an existing file is never written over). Reads SD, SMILES, CXSMILES, InChI, molfile, RXN, reaction SMILES, RD, CML, CDXML, CDX and .fchem; writes smiles, cxsmiles, sdf, molfile, inchi, inchikey, cml, rxn, rsmiles and fchem. Failures are reported per record. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `input` | string | yes | Structure text, or the absolute path of a structure file | +| `from` | string | no | Input format when it cannot be told from the text or the extension | +| `to` | string | yes | Output format: smiles, cxsmiles, sdf, molfile, inchi, inchikey, cml, rxn, rsmiles or fchem | +| `output` | string | no | Absolute path to write; left out: the result comes back as text | +| `v3000` | boolean | no | Write molfiles and SD records as V3000 | +| `standardise` | string | no | default (strip salts, neutralise, canonical tautomer, largest fragment) or step names, comma separated; left out: none | + +## batch_convert + +Converts every structure file in a folder with the same code and output as ./formchem batch, into output_dir (default: a converted folder inside input_dir), with a CSV report of failed records there. Writing outside the temporary folder asks the person the first time; a folder that already holds files is never written into. Returns a summary per file. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `input_dir` | string | yes | Absolute path of the folder to convert | +| `to` | string | yes | Output format, as for convert | +| `output_dir` | string | no | Absolute path of a new or empty folder for the results | +| `standardise` | string | no | default or step names, comma separated; left out: none | +| `recursive` | boolean | no | Also convert files in subfolders | +| `v3000` | boolean | no | | + +## list_open_documents + +The drawings open in FormChem: id, title, path, unsaved changes, revision, fragment count and formula, and which one the window shows. get_context gives the same list with the rest of the context. + +Arguments: none. + +## new_document + +Makes a new empty drawing and shows it in the FormChem window. Returns its id for the drawing tools. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `title` | string | no | Title of the drawing (default Untitled) | + +## open_document + +Opens a file as a drawing and shows it in the window: a FormChem drawing (.fchem), a structure file (molfile, SDF, RXN, RD, SMILES, CXSMILES, CML, CDXML, CDX, InChI) or a picture FormChem exported with its drawing inside. A file already open is not opened twice. Returns the drawing's structures and a picture. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `path` | string | yes | Absolute path of the file | + +## save_document + +Saves a drawing as a .fchem file: to its own file, to path, or, when it has none yet and no path is given, to a new file in FormChem's Drawings folder. It never writes over another file that exists: choose a new path, or ask the person to save over it in the window (File > Save As). + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `path` | string | no | Absolute path to save to; .fchem is added when missing | + +## close_document + +Closes a drawing that has no unsaved changes, in the engine and in the window. A drawing with unsaved changes is not closed: save_document first, or ask the person to close it in the window. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | + ## list_commands The window's command catalogue, the same commands as the menus, title bar and palette: id, label, group and what it does; commands of a later version are listed as off. text narrows by words (all must match), group by one group; id returns one command in full. @@ -174,6 +360,182 @@ Searches the fragments of an open drawing for a substructure given as SMARTS or | `chirality` | boolean | no | | | `max_hits` | integer | no | Most hits to return (default 1000) | +## get_atoms + +The atoms and bonds of a drawing's fragments by id, so edit tools can address them: per fragment its formula, SMILES and InChIKey; per atom the element, x and y in points (y down), charge, isotope, label, implicit hydrogens, CIP label and bond ids; per bond the two atom ids, order, wedge and E or Z. Does not change the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `object` | string | no | A fragment or group id; absent: every fragment of the drawing | + +## add_atom + +Adds one atom as one undo step. With bond_to it bonds to that atom and sits at the drawing's bond length in the freest direction (zigzag for chains, the widest gap at branches) unless x and y are given; without bond_to it starts a new fragment (or joins fragment, unbonded) in free space or at x, y. Returns the new atom and bond ids, the structure and a picture. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `element` | string | yes | Element symbol such as C, N, O, Cl, or * for any atom | +| `bond_to` | string | no | Atom id to bond the new atom to (get_atoms lists them) | +| `order` | any | no | Bond order for bond_to: 1, 2, 3, 1.5 (aromatic) or single, double, triple, aromatic; default 1 | +| `fragment` | string | no | Fragment id to add to; absent: bond_to's fragment, or a new fragment | +| `x` | number | no | Page x in points (right); give with y | +| `y` | number | no | Page y in points (down); give with x | + +## add_bond + +Bonds two atoms by id as one undo step; when they are already bonded it sets that bond's order and wedge instead. Atoms of two fragments are joined into one fragment. A wedge or hash has its narrow end at atom1. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `atom1` | string | yes | First atom id (the narrow end of a wedge) | +| `atom2` | string | yes | Second atom id | +| `order` | any | no | 1, 2, 3, 4, 1.5 (aromatic), single, double, triple, aromatic, dative, zero, hydrogen or ionic; default 1 | +| `stereo` | none or wedge or hash or hollow or wavy or either | no | Wedge drawn on the bond; default none | + +## set_charge + +Sets the formal charge of one atom by id as one undo step; hydrogens follow from the valence. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `atom` | string | yes | Atom id | +| `charge` | integer | yes | Formal charge from -15 to 15; 0 removes it | + +## set_atom + +Changes one atom by id as one undo step: its element (dropping a label, hydrogen count and isotope, as the window's element menu does), isotope, label text or radical. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `atom` | string | yes | Atom id | +| `element` | string | no | New element symbol | +| `isotope` | integer | no | Mass number; 0 for natural abundance | +| `label` | string | no | Text shown for the atom such as OH or D; empty shows the element | +| `radical` | none or doublet or singlet or triplet | no | | + +## set_stereo + +Sets a CIP label as one undo step: atom with R or S rewrites that centre's wedges so it reads as asked; bond with E or Z mirrors the smaller side of a chain double bond across the bond's line. Fails with the reason when the atom is not a stereocentre or the bond cannot be E or Z. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `atom` | string | no | Stereocentre atom id (label R or S) | +| `bond` | string | no | Double bond id (label E or Z) | +| `label` | R or S or E or Z | yes | | + +## replace_substructure + +Replaces what a SMARTS pattern matches with a SMILES group as one undo step, the way RDKit ReplaceSubstructs does: the matched atoms go and the replacement's first atom (or the atom bonded to its *) takes their bonds to the rest. Untouched atoms keep their ids and places; only the new part is laid out. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `smarts` | string | yes | What to find, such as Cl, [OH] or C(=O)[OH] | +| `replacement` | string | yes | SMILES of what to put in, such as O, OC or *N(C)C | +| `object` | string | no | Fragment or group to change; absent: every structure | +| `all` | boolean | no | Replace every match (default: the first only) | + +## delete + +Deletes atoms, bonds and objects by id as one undo step, as the window's Delete does: an atom takes its bonds, a fragment left without atoms goes, and a group whose members all go is removed. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `ids` | array of string | yes | Atom, bond and object ids (get_atoms, get_structure) | + +## move + +Moves atoms and objects by dx, dy points as one undo step (x right, y down); captions anchored to a moved structure follow it. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `ids` | array of string | yes | Object ids (fragments, arrows, text) or atom ids | +| `dx` | number | no | Points to the right (negative: left) | +| `dy` | number | no | Points down (negative: up) | + +## scale + +Makes structures larger or smaller on the sheet as one undo step, without a window: by percent or to a median bond length, each about its own centre; with ids the chosen objects scale together, without them every structure of the drawing. labels true scales line widths, labels and text too. Zoom only changes the view; this changes the drawing. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `ids` | array of string | no | Object or atom ids; absent: every structure | +| `percent` | number | no | New size in percent of the current size, 5 to 2000, such as 150 | +| `bond_length` | number | no | Wanted median bond length in points, such as 14.4 or 20 | +| `labels` | boolean | no | Scale line widths, atom labels and text too (default false) | + +## align + +Lines up two or more objects (or groups of atoms of different fragments) as one undo step: left, centre or right edges, top, middle or bottom, or spaces three or more evenly with distribute_h or distribute_v. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `ids` | array of string | yes | Object or atom ids | +| `mode` | left or centre or right or top or middle or bottom or distribute_h or distribute_v | yes | | + +## clean_layout + +Tidies structures as one undo step with the window's scored layout: mode clean (Clean Up: even bond lengths and angles, keeping place and shape; atom ids clean only those atoms) or layout (Lay Out: fresh 2D coordinates). Wedges the new geometry would invert are flipped; returns the layout score before and after (0 is best). + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `objects` | array of string | no | Fragment, group or atom ids; absent: every structure | +| `mode` | clean or layout | no | Default clean | + +## add_arrow + +Adds an arrow as one undo step. from and to are [x, y] in points or ids: an object (the arrow starts and stops half a bond length outside it, on the line between the two), an atom or a bond (the end is anchored to it, for electron pushing). Without to, a straight arrow four bond lengths long points right. Reaction arrows become steps with perceive_reactions. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `kind` | forward or equilibrium or equilibrium_unbalanced or reversible or resonance or retro or nogo_cross or nogo_slash or dashed or curved or fishhook or arc or plain or fragmentation or dissociation | no | Default forward | +| `from` | any | yes | Tail: [x, y] in points, or an object, atom or bond id | +| `to` | any | no | Head: [x, y] in points, or an object, atom or bond id | +| `bend` | number | no | Arc sweep in degrees, positive bulges left of tail to head; curved and fishhook default 90 | +| `head` | full or half_left or half_right or open or hollow or none | no | | +| `tail` | full or half_left or half_right or open or hollow or none | no | | +| `page` | string | no | Page id for an arrow between points; default the first page | + +## add_text + +Adds text as one undo step: at x, y (top-left, points), as a caption under a structure with below, or in free space. style formula writes chemical subscripts (H2SO4) automatically; \n breaks a line. Text above or below a reaction arrow becomes its conditions with perceive_reactions. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `text` | string | yes | The words to place | +| `x` | number | no | Left in points | +| `y` | number | no | Top in points | +| `style` | plain or formula or bold or italic | no | | +| `size` | number | no | Font size in points (default the caption font) | +| `align` | left or centre or right | no | | +| `below` | string | no | Fragment or object id to caption; the caption moves with it | +| `page` | string | no | Page id; default the first page | + +## add_reaction + +Draws a reaction scheme from reaction SMILES (reactants>agents>products) as one undo step: structures, plus signs, the arrow with agents above it, and the reaction step recorded with its roles. Placed in free space, or with its top-left at x, y. Makes a drawing when none is open. + +| Argument | Type | Required | Notes | +| --- | --- | --- | --- | +| `doc` | string | no | Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one | +| `reaction_smiles` | string | yes | Such as CCO.CC(=O)O>[H+]>CC(=O)OCC.O | +| `x` | number | no | Left in points | +| `y` | number | no | Top in points | +| `page` | string | no | Page id; default the first page | + ## Resource `formchem://guide` (text/markdown): what exists in this version, the tools, asking the person and errors. diff --git a/.claude/skills/formchem-harness/sub-skills/drawing/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/drawing/SUB-SKILL.md new file mode 100644 index 00000000..bdb17e10 --- /dev/null +++ b/.claude/skills/formchem-harness/sub-skills/drawing/SUB-SKILL.md @@ -0,0 +1,65 @@ +--- +name: drawing +description: "Draws in FormChem with the 0.8.0 agent tools: draw_from_smiles (structures, several per line, and reaction SMILES as whole schemes), draw_from_molfile (V2000, V3000, SD), add_reaction, free-space placement and x, y, naming, the drawing tools' write result, and the document tools list_open_documents, new_document, open_document, save_document and close_document, plus convert and batch_convert for files. Use when the person asks an agent to draw, put or add a structure or reaction in FormChem, start a new drawing, open a file as a drawing, save or close one, or convert structure files with FormChem." +--- + +# Drawing + +## Purpose + +Put structures and reaction schemes on the person's page directly, where they will not cover anything, as one undo step each, and know exactly what was drawn from the answer. Hands back the new object ids, the structure as FormChem reads it, and a picture to check. + +## Preconditions + +`get_context` has been called (`session-and-connection`). No drawing needs to be open: the draw tools make one and show it in the window. The first draw call of an outside agent asks the person in the window; that question is the only click the person needs to give. + +## Workflow 1: draw a structure + +1. **Get the text right first.** Use a SMILES you are sure of (canonical or isomeric; keep stereo marks `@`, `/`, `\` when the person asked for a stereoisomer). For a file the person gave, `draw_from_molfile` keeps its own coordinates. +2. **Draw.** `draw_from_smiles {smiles, name?}`, or `{smiles, doc}` when several drawings are open. Leave `x` and `y` out: FormChem lays the structure out with its scored 2D layout and places it right of what is on the page (top aligned, two bond lengths clear) or below it when it would not fit, and below any reaction arrow, never after it where it would read as a product. +3. **Read the answer.** Text and `structuredContent`: `new` (the new object ids), `objects` (per fragment id, formula, SMILES, InChIKey, atom count, warnings), `rev`, `undo: "one step"`, `created` and `shown` (a new drawing, shown in the window), `notes`, and an image. Compare the SMILES or InChIKey with what was asked; a mismatch means the input was wrong, not FormChem. +4. **Check** what matters with `visual-qa` (look at the picture; `validate` when the person cares about correctness). +5. **Hand off** with the drawing's title or id and "one undo step" (`handoff`). + +Several structures at once: one per line in `smiles`; each line becomes its own fragment with its own id, named "[name] 1", "[name] 2" when `name` is given. A dot-separated SMILES on one line (a salt, `CCO.O`) stays one fragment holding both parts. + +## Workflow 2: draw a reaction scheme + +A reaction SMILES (`reactants>agents>products`, such as `CCO.CC(=O)O>[H+]>CC(=O)OCC.O`) in `draw_from_smiles` or `add_reaction {reaction_smiles}` draws the structures, plus signs, the arrow with the agents above it, and records the reaction step with its roles, exactly as the window's Insert Reaction does. The answer has `reaction` (the reaction id) and every new object id. Then `perceive_reactions`, `map_reaction` or `reaction_stoichiometry` work on it (`reactions`). Conditions as words go on with `add_text` above or below the arrow (`edit-by-id`). + +## Workflow 3: drawings and files + +| Goal | Call | Notes | +| --- | --- | --- | +| Which drawings are open | `list_open_documents` | id, title, path, unsaved changes, revision, fragments, formula, and `active` (what the window shows) | +| A new empty drawing | `new_document {title?}` | shown in the window; pass its id as `doc` from then on | +| Open a file | `open_document {path}` (absolute) | `.fchem`, molfile, SD, RXN, RD, SMILES, CXSMILES, CML, CDXML, CDX, InChI, or a picture FormChem exported with its drawing; the answer lists the objects and import notes; a file already open is not opened twice | +| Save | `save_document {doc?, path?}` | to its own file, to `path` (`.fchem` added), or to a free name in the Drawings folder; never over another existing file | +| Close | `close_document {doc?}` | refused while the drawing has unsaved changes: save first, or ask the person | +| Convert text or a file | `convert {input, to, output?, standardise?}` | the result comes back as text, or is written to a new `output`; failed records are listed | +| Convert a folder | `batch_convert {input_dir, to, output_dir?}` | the same output as `./formchem batch`, with `formchem-batch-report.csv` when records failed; never into a folder that holds files | + +`convert` and `batch_convert` ask the person only when they write outside the temporary folder. + +## Rules + +- **Which drawing.** `doc` when given; else the only open drawing; else the one the window shows; else the tool asks for `doc`. When the person has several open, say which one you drew in. +- **x and y are for layouts the person asked for.** Coordinates are points, x right, y down, the top-left of the new drawing. A note warns when that spot overlaps something; move it with `move` rather than drawing again. +- **One call, one step.** A wrong structure is removed with the person's Undo, Agent Activity's Undo, or `delete {ids}`; never by undoing the person's work. +- **Failed input leaves nothing.** When the text cannot be read, a drawing the call made is closed again and nothing is added. Fix the text once, or ask. +- **Names are not read yet.** For "draw caffeine", write the SMILES yourself and say you did; if you are not sure of it, ask the person for one. + +## Gate + +- [ ] The SMILES or InChIKey in the answer matches what the person asked for, or the difference was reported. +- [ ] No `x` and `y` were given unless the person asked for a place. +- [ ] Each structure or scheme was one call, and the reply says how to undo it. +- [ ] Saving and closing respected the refusals instead of working around them. + +## Hands back + +The drawing id, the new object ids, the formula, SMILES and InChIKey as FormChem returned them, and a ready handoff. + +## Owned resources + +None of its own. `references/tools.md` at the pack root lists every argument; `visual-qa` checks the result; `edit-by-id` changes it. diff --git a/.claude/skills/formchem-harness/sub-skills/edit-by-id/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/edit-by-id/SUB-SKILL.md new file mode 100644 index 00000000..b39be7ed --- /dev/null +++ b/.claude/skills/formchem-harness/sub-skills/edit-by-id/SUB-SKILL.md @@ -0,0 +1,71 @@ +--- +name: edit-by-id +description: "Builds and changes FormChem drawings atom by atom with the 0.8.0 edit tools: get_atoms for the ids, add_atom (freest direction, zigzag), add_bond (also changes an existing bond and joins fragments), set_charge, set_atom, set_stereo (R/S by wedges, E/Z by geometry), replace_substructure (SMARTS to SMILES, RDKit cross-check), delete, move, scale, align, clean_layout, add_arrow (electron pushing anchors) and add_text (captions, formula text, conditions). Use when the person asks an agent to build a structure from atoms, change one atom or bond, make it a carboxylate, set R or S, swap a chlorine for a hydroxyl, tidy, move, resize or line up structures, or draw arrows and labels in FormChem." +--- + +# Edit by id + +## Purpose + +Change exactly what was asked and nothing else. Every edit tool works on ids from the drawing, applies one transaction (one undo step labelled with the tool), works with or without the window, and answers with the structure it now holds and a picture. Hands back the ids touched, the structure after the edit, and a handoff. + +## Preconditions + +`get_context` has been called and the drawing is known (`doc`, or the only or shown drawing). Ids come from `get_atoms`, from a draw tool's answer or from an earlier edit's answer, never from a guess: they are random strings such as `a8p3gd9dy`, and an atom id is not a fragment id. + +## Reading the ids + +`get_atoms {doc?, object?}` lists per fragment its id, page, formula, SMILES and InChIKey; per atom the id, element, x and y in points (y down), charge, isotope, label, implicit hydrogens `h`, CIP label and bond ids; per bond the id, the two atom ids `a` and `b`, the order, the wedge and E or Z. It reads only and never asks the person. Call it again after a few edits rather than tracking ids in your head: each edit answer also names the new atom and bond ids in `edit`. + +## The tools + +| Goal | Call | What to know | +| --- | --- | --- | +| Start a structure | `add_atom {element}` | a new fragment in free space (or at `x`, `y`); makes a drawing when none is open | +| Grow a chain or branch | `add_atom {element, bond_to, order?}` | placed at the bond length in the freest direction: a zigzag for chains, the widest gap at a branch, straight on for triple bonds and cumulated double bonds | +| Close a ring, make a double bond | `add_bond {atom1, atom2, order}` | on two bonded atoms it changes that bond's order and wedge instead; atoms of two fragments join into one | +| Wedge or hash | `add_bond {atom1, atom2, stereo: "wedge" or "hash"}` | the narrow end is at `atom1`, the stereocentre | +| Charge | `set_charge {atom, charge}` | hydrogens follow the valence (CC(=O)O to CC(=O)[O-]) | +| Element, isotope, label, radical | `set_atom {atom, element?, isotope?, label?, radical?}` | a new element drops the label, hydrogen count and isotope, as the window's element menu does | +| R or S, E or Z | `set_stereo {atom, label: "R" or "S"}` or `{bond, label: "E" or "Z"}` | R/S rewrites that centre's wedges; E/Z mirrors the smaller side of a chain double bond; refuses with the reason when the atom is not a stereocentre or the bond is in a ring | +| Swap a group | `replace_substructure {smarts, replacement, object?, all?}` | the first match only unless `all`; the replacement's first atom (or the atom on its `*`) takes the outside bonds; untouched atoms keep ids and places; a difference from RDKit's ReplaceSubstructs is reported | +| Remove | `delete {ids}` | atoms take their bonds, an emptied fragment or group goes; reaction steps are left for `perceive_reactions` to redo | +| Move | `move {ids, dx?, dy?}` | points, y down; captions follow their structure | +| Larger or smaller on the sheet | `scale {ids?, percent or bond_length, labels?}` | changes the drawing, not the view; without ids every structure scales about its own centre | +| Line up | `align {ids, mode}` | left, centre, right, top, middle, bottom, distribute_h, distribute_v | +| Tidy | `clean_layout {objects?, mode?}` | `clean` keeps place and shape, `layout` lays out fresh; answers the layout score before and after (0 is best) | +| Arrow | `add_arrow {from, to?, kind?, bend?}` | ends are [x, y] or ids; object ends stop outside the object; atom and bond ends anchor (electron pushing with `curved` or `fishhook`) | +| Text and captions | `add_text {text, x?, y?, below?, style?}` | `below: [id]` makes a caption that moves with it; `style: "formula"` writes subscripts; text above or below a reaction arrow becomes conditions | +| A whole scheme | `add_reaction {reaction_smiles}` | see `drawing` | + +## Workflow: build acetic acid atom by atom + +1. `add_atom {element: "C"}`: answer names the atom (say `a1`) and the fragment. +2. `add_atom {element: "C", bond_to: "a1"}`: `a2`, SMILES CC. +3. `add_atom {element: "O", bond_to: "a2"}`: `a3`, SMILES CCO. +4. `add_atom {element: "O", bond_to: "a2", order: 2}`: SMILES CC(=O)O, formula C2H4O2. +5. Check the SMILES in the last answer against what was asked, look at its picture (`visual-qa`), hand off. + +For the acetate ion add `set_charge {atom: "a3", charge: -1}`: CC(=O)[O-], InChIKey QTBSBXVTEAMEQO-UHFFFAOYSA-M. Each call is its own undo step, so the person can step back through the build. + +## Rules + +- **Read the answer, then act.** Each answer gives the SMILES after the edit. If it is not what you meant, fix it with the next edit or remove your own last call; do not stack guesses. +- **Prefer the drawing tools for whole molecules.** Atom by atom is for edits and for teaching; `draw_from_smiles` lays out a whole structure better and in one step. +- **Ids are per drawing.** Pass `doc` when several drawings are open; an id from another drawing is an error, not a match. +- **Arrangement edits do not change chemistry.** After `move`, `scale`, `align` or `clean_layout` the SMILES must be unchanged; `clean_layout` flips any wedge the new geometry would invert, so the CIP labels stay. Compare the SMILES before and after and report a difference. +- **Refusals are reasons.** "is not a stereocentre", "both fragments are used by a reaction", "no match" are answers to relay, not obstacles to work around. + +## Gate + +- [ ] Every id used came from `get_atoms` or an earlier answer in this session. +- [ ] The SMILES after the last edit is what the person asked for, quoted from the answer. +- [ ] Each change was one call; the reply says how many undo steps it took. + +## Hands back + +The fragment id, the atom and bond ids touched, the final SMILES, formula and InChIKey as FormChem returned them, and a ready handoff. + +## Owned resources + +None of its own. `references/tools.md` at the pack root holds every argument and the 15 arrow kinds; `visual-qa` checks the result. diff --git a/.claude/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md index 98f99df2..8a74ac6e 100644 --- a/.claude/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/extension-drawings/SUB-SKILL.md @@ -1,13 +1,13 @@ --- name: extension-drawings -description: "Reads and changes the open FormChem drawing through a Form extension, the one route before 0.8.0 that gives an agent the structure itself: extensions_list and extension_command, an extension's document permission, document.read (the document, its derived SMILES, InChIKey, formula, masses and valence errors), document.apply (FORMAT.md ops as one undo step), app.run, and the document events. Use when the person wants an agent to read atoms, bonds or computed values from the drawing, change it by id, or check valence through an installed or folder extension." +description: "Runs Form extensions in FormChem and reads or changes the open drawing through one when an extension does the job better than the 0.8.0 tools: extensions_list and extension_command, an extension's document permission, document.read (the document, its derived SMILES, InChIKey, formula, masses and valence errors), document.apply (FORMAT.md ops as one undo step), app.run, and the document events. Use when the person names an extension or asks which are installed, wants an extension's command run, or wants the drawing read or changed through an installed or folder extension." --- # Extension drawings ## Purpose -Use an extension as the agent's hands on the drawing until FormChem has its own drawing tools (0.8.0). An extension with the `document` permission sees the active drawing as `document.json` plus the engine's derived chemistry, and can commit FORMAT.md ops as one undo step. The agent reaches it only by running the extension's own commands with `extension_command`; the agent cannot call `document.read` or `document.apply` directly. +Use an extension when the person installed one for a job (a house style, a company registry lookup, a special check) or asks for its command. For plain reading and editing, FormChem's own tools are simpler since 0.8.0: `get_structure` reads the structure back and the edit tools change it by id (`visual-qa`, `edit-by-id`). An extension with the `document` permission sees the active drawing as `document.json` plus the engine's derived chemistry, and can commit FORMAT.md ops as one undo step. The agent reaches it only by running the extension's own commands with `extension_command`; the agent cannot call `document.read` or `document.apply` directly. ## Preconditions @@ -32,7 +32,7 @@ Use an extension as the agent's hands on the drawing until FormChem has its own 1. `extensions_list`; pick the extension and command by their stated purpose. Never invent an id or command. 2. `extension_command {id, command, args}`. The person is asked to allow the extension the first time. 3. Report the extension's answer as the extension's, with the values it returned (SMILES, InChIKey, valence errors). Name the revision when it is given. -4. If no suitable extension exists, say so and offer what the commands can do (`window-commands`); do not compute chemistry elsewhere and present it as FormChem's. +4. If no suitable extension exists, say so and use FormChem's own tools (`drawing`, `edit-by-id`, `visual-qa`) or commands (`window-commands`); do not compute chemistry elsewhere and present it as FormChem's. ## Gate diff --git a/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md index 0775514f..10cb01d5 100644 --- a/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/handoff/SUB-SKILL.md @@ -1,13 +1,13 @@ --- name: handoff -description: "Hands work back to the person in the FormChem window with the handoff tool: the states working, ready, question and clear, writing the note, listing current handoffs, and what the person sees. Use when an agent finishes a task in FormChem, needs the person to decide something, is still working on a long task, or wants to remove its note." +description: "Hands work back to the person in the FormChem window with the handoff tool: the states working, ready, question and clear, writing a note that names the drawing, the object ids and the undo steps, listing current handoffs, and what the person sees alongside it (the editing chip with Stop, Agent Activity with undo for the latest call). Use when an agent finishes a task in FormChem, needs the person to decide something, is still working on a long task, was stopped, or wants to remove its note." --- # Handoff ## Purpose -Tell the person where your work stands, in the place they are looking: the FormChem window. A chat reply can scroll away; a handoff stays until you clear it or post another. +Tell the person where your work stands, in the place they are looking: the FormChem window. A chat reply can scroll away; a handoff stays until you clear it or post another. Hands back one short note the person can act on. ## The tool @@ -15,34 +15,46 @@ Tell the person where your work stands, in the place they are looking: the FormC | state | Means | note | | --- | --- | --- | -| `working` | You are still on it | Optional: what you are doing | -| `ready` | Done, for the person to look at | One line: what to look at | +| `working` | You are still on it (a long batch, a multi-step scheme) | Optional: what you are doing | +| `ready` | Done, for the person to look at | One line: what to look at and how to undo | | `question` | You need the person's input | Required: the one thing to decide | | `clear` | Remove your handoff | Ignored | | none | List every agent's current handoff | Not used | -One handoff per agent: a new state replaces your previous one. Notes are cut at 400 characters; keep them to one line. +One handoff per agent: a new state replaces your previous one. Notes are cut at 400 characters; keep them to one line. A handoff with a state changes what the person sees, so the first one from an outside agent asks the person in the window, like any change. With no window open the handoff is kept and shows when they open one. -A handoff with a state changes what the person sees, so the first one from an outside agent asks the person in the window (Deny, Allow once, Always allow). Agents in FormChem's own tabs are never asked. With no window open the handoff is kept and the person sees it when they open a window. +## What the person already sees -## Writing the note - -- Say what changed or what to decide, not what you are: "Benzene inserted in Untitled; one undo step" beats "I am done". -- A question asks one thing with the choices: "Allow the Molecule Tools extension its network permission, or leave it off?" -- No emoji, no markdown, no links the person cannot click. +While your calls change the drawing in front of them, the title bar shows "[agent] is editing", then "[agent] just edited" for three seconds, with Stop; what each call changed is outlined for a moment; Window > Agent Activity lists every call with its arguments, result, duration and Undo on the latest one. The handoff adds what those cannot: what the work was for, whether it is finished, and what you need. -## In 0.6.0 +## Writing the note -A handoff is plain text in the window; it cannot link to a drawing or an atom yet. Name the drawing by its title and say what changed in words: "Aspirin inserted in Untitled; Undo removes it", "Cleaned up the structure in Phenol", "Mapped step 1 of Esterification: one C-O bond formed", "Assigned wedges in Ibuprofen; the centre reads S". When a command left a prompt open for the person (a SMILES prompt, a save name), the handoff is a question that says exactly what to type or choose. When a request needs the drawing tools of 0.8.0, say that and what you did instead ("Drawing atom by atom arrives in 0.8.0; I opened the molfile instead"). +- Name the drawing (its title, or its id when it is Untitled) and what changed, with the numbers that matter: "Aspirin drawn in Untitled (C9H8O4, InChIKey BSYNRYMUTXBXSQ-UHFFFAOYSA-N); one undo step." +- Count the undo steps when there were several: "Acetic acid built in 4 steps (4 undo steps, or Undo in Agent Activity)." +- Say what you checked: "Checked with render and validate: no issues." +- A question asks one thing with the choices: "Save over /data/aspirin.fchem, or keep it as a new file?" +- No emoji, no markdown, no links the person cannot click, never the agent token. ## Procedure -1. Finish the work, or reach the point where you need the person. +1. Finish the work and check it (`visual-qa`), or reach the point where you need the person. 2. `handoff {state: "ready", note}` or `handoff {state: "question", note}`. 3. Say the same in one sentence in your reply. 4. When the person has answered a question, `handoff {state: "clear"}` or post the next state. +## When you were refused or stopped + +A Deny, or "The person stopped [agent]'s access", ends the work: every further call, a handoff included, is refused. Say in the chat what you were about to do and that the person can allow you again (Agent Activity, Allow again), and stop. + ## Gate -- [ ] The last call of the task is a handoff, or the reply says why there is none (a refusal, no window). -- [ ] A question handoff has a note that asks exactly one thing. +- [ ] The last call of the task is a handoff, or the reply says why there is none (a refusal, a stop, no window). +- [ ] A ready note names the drawing, what changed and how to undo it; a question note asks exactly one thing. + +## Hands back + +The note as posted, and the same sentence in the reply. + +## Owned resources + +None. diff --git a/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md index 90c83d04..5c87371a 100644 --- a/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/reactions/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: reactions -description: "Works with reactions in an open FormChem drawing through the four MCP reaction tools (perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) and the Reaction menu commands: reading the steps of a drawn scheme, mapping atoms, exporting reaction SMILES or RXN, reading moles, equivalents, the limiting reagent and yields, checking balance, inserting a template or a pasted reaction, setting roles by hand with set-reaction-roles, and saying plainly what only the person can do (typing amounts). Use when the person asks an agent about the reaction, the scheme, atom mapping, the stoichiometry or yield, or for a reaction as SMILES or RXN in FormChem." +description: "Works with reactions in FormChem: drawing a scheme from reaction SMILES (draw_from_smiles or add_reaction) or piece by piece with add_arrow and add_text, the four MCP reaction tools (perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) and the Reaction menu commands: reading the steps of a drawn scheme, mapping atoms, exporting reaction SMILES or RXN, reading moles, equivalents, the limiting reagent and yields, checking balance, inserting a template or a pasted reaction, setting roles by hand with set-reaction-roles, and saying plainly what only the person can do (typing amounts). Use when the person asks an agent about the reaction, the scheme, atom mapping, the stoichiometry or yield, or for a reaction as SMILES or RXN in FormChem." --- # Reactions @@ -11,7 +11,13 @@ Answer reaction questions from what FormChem computes, not from the agent's own ## Preconditions -`get_context` has been called (`session-and-connection`) and lists the drawing. The scheme is drawn: structures, a reaction arrow, plus signs, reagents or conditions text in the band above or below the arrow. An agent cannot draw arrows or place structures by position before 0.8.0; `insert-smiles` and `insert-template` put things in the middle of the view, so a scheme is the person's to arrange. +`get_context` has been called (`session-and-connection`) and lists the drawing. The scheme is drawn: structures, a reaction arrow, plus signs, reagents or conditions text in the band above or below the arrow. + +## Drawing a scheme (0.8.0) + +- **Whole scheme at once.** `draw_from_smiles {smiles: "CCO.CC(=O)OC>[H+]>CC(=O)OCC.CO"}` or `add_reaction {reaction_smiles}` draws the reactants, plus signs, the arrow with the agents above it and the products, and records the step with its roles, as one undo step. The answer gives the `reaction` id and every object id; no `perceive_reactions` is needed for it. +- **Piece by piece.** Draw each structure with `draw_from_smiles` (they go into free space, growing downwards once an arrow is on the page), then `add_arrow {from: "[reactant id]", to: "[product id]"}`, `add_text {text: "NaOH, H2O", x, y}` above or below the arrow for conditions (formula text counts as conditions too), `add_text {text: "1", below: "[id]"}` for compound numbers, then `perceive_reactions` to record the step. Use `move` or `align` to put the structures on the arrow's line first: perception reads structures within 2.5 bond lengths of the line and reagents within 1.5. +- **Check** the scheme with `render {scope: "page"}` (`visual-qa`): the window draws arrows, plus signs and text; the engine fallback leaves them out. ## Tools and commands @@ -56,4 +62,4 @@ Reaction and step ids, the quoted answers, and a ready or question handoff. ## Owned resources -None of its own. `references/tools.md` at the pack root holds the generated arguments of all fourteen tools; `window-commands` and its `references/command-catalogue.md` hold the Reaction, Insert and Arrange commands. +None of its own. `references/tools.md` at the pack root holds the generated arguments of all 42 tools; `drawing` and `edit-by-id` hold the drawing tools; `window-commands` and its `references/command-catalogue.md` hold the Reaction, Insert and Arrange commands. diff --git a/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md index f0f9e6e5..52f3dc6f 100644 --- a/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/session-and-connection/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: session-and-connection -description: "Connects an agent to FormChem's MCP server and reads the session: the HTTP and stdio entries, get_context, the window, the approval question (Deny, Allow once, Always allow), FormChem's own trusted tabs, and what each connection error means. Use at the start of every FormChem session, when no FormChem tools appear, when a call is refused, or when the person asks what FormChem can do." +description: "Connects an agent to FormChem's MCP server and reads the session: the HTTP entry with the agent token (401 without it), the stdio entry, get_context and list_open_documents, the window, the approval question (Deny, Allow once, Always allow), Stop from the title bar, FormChem's own trusted tabs, and what each connection error means. Use at the start of every FormChem session, when no FormChem tools appear, on a 401 or token error, when a call is refused or the agent was stopped, or when the person asks what FormChem can do." --- # Session and connection @@ -11,19 +11,27 @@ Get a working connection, learn what the person's FormChem can do right now, and ## How the agent reaches FormChem -- **HTTP**: `http://127.0.0.1:8220/mcp` (Streamable HTTP; protocol versions 2026-07-28 and 2025-11-25, older ones accepted). The `formchem` entry in `.mcp.json`. -- **stdio**: `python3 setup/mcp_stdio.py` relays to the HTTP server and starts the engine when it is not running. The `formchem-stdio` entry, and the Codex, Cursor and Antigravity configs. +- **HTTP**: `http://127.0.0.1:8220/mcp` (Streamable HTTP; protocol versions 2026-07-28 and 2025-11-25, older ones accepted). The `formchem` entry in `.mcp.json`, which carries the header `Authorization: Bearer [agent token]`. +- **stdio**: `python3 setup/mcp_stdio.py` (`./formchem mcp`) relays to the HTTP server, sends the token itself and starts the engine when it is not running. The `formchem-stdio` entry, and the Codex, Cursor and Antigravity configs. - The engine answers only on this computer (loopback host, no cross-site origin). - The port comes from `FORMCHEM_PORT`, else `engine.json` in the data folder (`~/formchem` or `FORMCHEM_DATA_DIR`), else 8220. +## The agent token + +From 0.8.0 the HTTP endpoint refuses a request without the agent token: HTTP 401, `WWW-Authenticate: Bearer realm="FormChem"`, JSON-RPC error -32001 saying where the token is. The token is one line in `agent-token` in the data folder; `./formchem agents install` writes it into the configs and `./formchem agents token` prints it. A client set up for 0.7.0 over HTTP stops connecting until the person runs `./formchem agents install` again or adds the header. Never print, copy or put the token in a note or a chat reply: it works like a password for this computer's FormChem. + ## Procedure -1. **Call `get_context`.** Read four parts: Window (open or none), Agents (allowed, not yet allowed, blocked, or FormChem's own tab), Documents and Commands (catalogue size). Documents says "none open" or gives one line per open drawing: `- [id] "[title]" (unsaved changes) · rev [n] · [k] fragments · [formula] · [path or not saved yet]`, oldest first; the same list is in `structuredContent.documents` (`id`, `title`, `path`, `dirty`, `rev`, `fragments`, `formula`). The formula reads "still being worked out" (`formula: null`) until the engine has finished the latest revision; call again a moment later. The engine keeps the documents, so the list is current even while the window's command catalogue lags; `run_command` always checks the live state in the window. -2. **No window?** Commands, extensions and the approval question need it. Ask the person to run `./formchem` or open the app. Read-only calls (`get_context`, `list_commands` from the saved catalogue, `extensions_list` without live states) still work. -3. **Find what to do.** `list_commands {text}` for menu commands; `extensions_list` for extensions. A command marked `off now` is not available: do not run it. -4. **Expect the question.** The first change (run_command, extension_command, handoff with a state) asks the person in the window: Deny, Allow once, Always allow. Wait for the answer; the call returns when they choose. +1. **Call `get_context`.** Read four parts: Window (open or none), Agents (allowed, not yet allowed, blocked, or FormChem's own tab), Documents and Commands (catalogue size). Documents says "none open" or gives one line per open drawing: `- [id] "[title]" (unsaved changes) · rev [n] · [k] fragments · [formula] · [path or not saved yet]`, oldest first; the same list is in `structuredContent.documents` (`id`, `title`, `path`, `dirty`, `rev`, `fragments`, `formula`). The formula reads "still being worked out" (`formula: null`) until the engine has finished the latest revision; call again a moment later. The engine keeps the documents, so the list is current even while the window's command catalogue lags; `structuredContent.drawingTools` is true from 0.8.0. `list_open_documents` gives the same list plus `active`, the drawing the window shows, which the tools use when `doc` is left out. +2. **No window?** The drawing, edit and checking tools work without one (`render` then draws with the engine). The approval question, window commands, extensions and the person's selection need it, so an outside agent's first change fails with "No FormChem window is open to ask the person" unless the person chose Always allow before. Ask the person to run `./formchem` or open the app. +3. **Pick the route.** Drawing and editing go through the tools (`drawing`, `edit-by-id`); menu commands through `list_commands {text}` and `run_command`; extensions through `extensions_list`. A command marked `off now` is not available: do not run it. +4. **Expect the question.** The first change of an outside agent (a draw, edit or document tool, `run_command`, `extension_command`, a handoff with a state, a conversion that writes outside the temporary folder) asks the person in the window: Deny, Allow once (this call only), Always allow. Wait for the answer; the call returns when they choose. Reading never asks. 5. **Act once, report.** On a refusal, tell the person what you wanted to do and stop. +## Stop + +While your calls change the drawing the person is looking at, the title bar shows your client's name ("[agent] is editing") with a Stop button. Stop refuses every further call of yours, reads included, with "The person stopped [agent]'s access to FormChem from the window", and withdraws Always allow. A call that was already running finishes. Do not retry, reconnect under another name or work around it: say what you were about to do and that the person can let you back in with Allow again in Window > Agent Activity, after which your next change asks again. + ## Who is never asked Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tabs carry a per-tab token (`FORMCHEM_INAPP_TOKEN`, sent as a header) and are trusted for as long as the tab is open. `get_context` says "you run in FormChem's own tab" when that is you. Never copy or print that token. @@ -33,7 +41,9 @@ Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tab | Text | Do | | --- | --- | | Connection refused, or the stdio relay says the engine could not be started | Ask the person to run `./formchem install` once, then `./formchem` | +| HTTP 401, "needs the agent token", "refused the request without the agent token" | Ask the person to run `./formchem agents install` in the FormChem folder and restart the client, or to add `Authorization: Bearer` and the output of `./formchem agents token` to the FormChem entry | | "No FormChem window is open" | Ask the person to open the window, then retry once | +| "The person stopped [agent]'s access" | Stop working; see Stop above | | "did not allow agents" | Stop and report; the person can allow agents in Preferences | | "has blocked agents" | Stop; only the person can change it in Preferences | | "consent service is missing" | This build cannot ask; report it, outside agents cannot make changes here | @@ -42,5 +52,5 @@ Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tab ## Gate - [ ] `get_context` was the first call. -- [ ] The plan uses only the fourteen tools in the pack root's `references/tools.md` and the commands and extensions they report; nothing assumes the 0.8.0 drawing tools. -- [ ] No change was attempted after a refusal. +- [ ] The plan uses only the 42 tools in the pack root's `references/tools.md` and the commands and extensions they report. +- [ ] No change was attempted after a refusal or a stop, and the agent token never appeared in a reply or a note. diff --git a/.claude/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md index ae33befa..f5e60860 100644 --- a/.claude/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/structure-analysis/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: structure-analysis -description: "Reads and edits the chemistry of an open FormChem drawing through the four MCP analysis tools (properties, check_structure, stereo, substructure) and the 0.6.0 chemistry commands run with run_command: drug-like properties with their RDKit methods, the structure check with codes and severities, CIP labels (R, S, r, s, E, Z) and enhanced stereo groups (abs, and, or), substructure hits by SMARTS or a drawn query, Assign Wedges, stereo groups, explicit hydrogens, abbreviations, atom lists, query bonds, R-groups and Markush enumeration. Use when the person asks an agent for cLogP, TPSA, Lipinski, a structure check, R or S, a stereo group, a substructure match or SMARTS, or to add hydrogens, contract or expand an abbreviation, or define an R-group in FormChem." +description: "Reads and edits the chemistry of an open FormChem drawing through the MCP analysis tools (properties or compute_properties, check_structure or validate, stereo, substructure), set_stereo, and the 0.6.0 chemistry commands run with run_command: drug-like properties with their RDKit methods, the structure check with codes and severities, CIP labels (R, S, r, s, E, Z) and enhanced stereo groups (abs, and, or), substructure hits by SMARTS or a drawn query, Assign Wedges, stereo groups, explicit hydrogens, abbreviations, atom lists, query bonds, R-groups and Markush enumeration. Use when the person asks an agent for cLogP, TPSA, Lipinski, a structure check, R or S, a stereo group, a substructure match or SMARTS, or to add hydrogens, contract or expand an abbreviation, or define an R-group in FormChem." --- # Structure analysis @@ -22,7 +22,9 @@ Answer chemistry questions about the drawing with FormChem's own numbers, quoted | Stereo | `stereo {doc?, object?}` | centres, double bonds and axes with label, `state` (defined, undefined, unknown) and group (`abs`, `and1`, `or1`), the stereo groups, the chiral flag and CXSMILES | | Substructure | `substructure {doc?, smarts or query_object, objects?, chirality?, max_hits?}` | hits with the fragment id, matched atom and bond ids and the query-to-target map; `count`, `truncated` | -`doc` may be left out when one drawing is open; `object` left out means every fragment. `structuredContent` carries the same JSON as the engine's `/api/analysis` routes. The isotope pattern has no tool: it is in the person's Analysis panel (`show-analysis`). +From 0.8.0 `compute_properties` and `validate` are the same answers as `properties` and `check_structure` under the spec's names, and they take the drawing the window shows when `doc` is left out; `validate` adds `valid`. To set R or S on a centre, or E or Z on a double bond, by id, use `set_stereo` (`edit-by-id`), then read it back with `stereo`. + +`doc` may be left out when one drawing is open (the four 0.6.0 tools need it when several are open); `object` left out means every fragment. `structuredContent` carries the same JSON as the engine's `/api/analysis` routes. The isotope pattern has no tool: it is in the person's Analysis panel (`show-analysis`). ## Chemistry commands (run_command) @@ -37,6 +39,7 @@ They act on the person's selection, or on the page when nothing is selected; the | `set-atom-list`, the `set-query-bond-` commands, `clear-query-bond` | atom lists (a dialog) and query bonds on the selection | | `define-rgroup`, `enumerate-markush` | R-group definition and enumeration open dialogs for the person | | `copy-smarts`, `compute-properties`, `check-structure`, `search-substructure` | copy SMARTS to the person's clipboard, or open the panels; the tools above return the same data to the agent | +| `standardise {steps}` (0.7.0) | removes salts and solvents, neutralises, normalises functional groups, picks the canonical tautomer and more, on the selection or the page, as one undo step; read the result back with `stereo` (its CXSMILES) or `properties`. Without `steps` the dialog opens for the person | ## Procedure @@ -52,7 +55,7 @@ They act on the person's selection, or on the page when nothing is selected; the - A check issue with `fix` (`wedges` or `expand`) is repaired by the person's Fix button or by `assign-wedges` or `expand-abbreviation` on the selection; say which. - A structure check on a query drawing without `query: true` reports `query_feature` notes; they are expected, not errors. - Metal cations such as Na+ in a salt are not valence errors; do not report them as such. -- Export SMARTS in the desktop app copies instead of saving until 0.7.0; dialogs (atom list, R-group, abbreviation label) belong to the person. +- Dialogs (atom list, R-group, abbreviation label) belong to the person. ## Gate @@ -66,4 +69,4 @@ Fragment, atom and bond ids, the quoted answers, and a ready or question handoff ## Owned resources -None of its own. `references/tools.md` at the pack root holds the generated arguments of all fourteen tools; `window-commands/references/command-catalogue.md` lists the chemistry commands with the rest of the catalogue. +None of its own. `references/tools.md` at the pack root holds the generated arguments of all 42 tools; `window-commands/references/command-catalogue.md` lists the chemistry commands with the rest of the catalogue. diff --git a/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md index f4d176cd..0d6e998e 100644 --- a/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/visual-qa/SUB-SKILL.md @@ -1,46 +1,61 @@ --- name: visual-qa -description: "Checks what the person sees in FormChem when the agent cannot see the window: reading command states from list_commands, confirming a command ran, undo availability as evidence of a change, extension states and the derived values an extension returns, asking the person to look with a question handoff, and the render and validation tools that arrive in 0.8.0. Use after running a command or extension, when the person says something looks wrong, or before saying a drawing change worked." +description: "Checks an agent's own work in FormChem before it claims anything: render (a PNG or SVG of objects, the person's selection or the page, drawn by the window's own renderer, or by the engine when no window is open), get_structure (SMILES, CXSMILES, InChI, InChIKey, molfile V2000 or V3000, masses), validate (the structure check with valid), compute_properties, the write result's own structure and picture, and list_commands or Agent Activity for command states. Use after drawing or editing, before saying a drawing is right, when the person asks to see it or says something looks wrong, or when an InChIKey, SMILES or molfile is wanted." --- # Visual QA ## Purpose -Never claim a visible result you did not confirm. In 0.6.0 an agent still has no picture of the window and no render tool (it arrives in 0.8.0). Confirm through what the tools report (the reaction tools print the steps, map numbers and amounts they found; `stereo`, `check_structure` and `properties` read the chemistry after a command), and ask the person for the rest. +Never claim a visible or chemical result you did not confirm. From 0.8.0 the agent can see what the person sees and read the structure back in machine form, so every claim about a drawing rests on a tool answer from after the change. Hands back what was checked, with the values quoted and the renderer named. -## What you can confirm today +## Preconditions -| Question | How | -| --- | --- | -| Did the command run? | `run_command` returned without `isError`; its text is the window's answer | -| Is a toggle on (show-grid, menus-in-window)? | `list_commands {id}`: `checked` in the entry, when the window reports it | -| Is a command available? | `list_commands`: `off now` means not available; the catalogue comes from the window | -| Is an extension usable? | `extensions_list`: state ready, needs-permission or refused (with the reason) | -| Is the window there? | `get_context`: Window line | -| Did a drawing change land? | The command's answer, then `list_commands {id: "undo"}`: on means the active drawing has a step to undo (the catalogue can lag a moment) | -| Is a drawing open? | `list_commands {id: "save"}`: on only while one is open | -| What structure is in the drawing, and is it valid? | Only through an extension that returns `document.read` values: its SMILES, InChIKey, formula and `valence_errors` for the current revision (`extension-drawings`) | +A drawing exists and its ids are known (from a draw or edit answer, `get_structure`, `get_atoms` or `list_open_documents`). The checking tools only read: they never ask the person and never add an undo step. -The catalogue is mirrored from the window when it opens and when commands change; right after a command, a second `list_commands {id}` shows the state the window last sent. +## The checks -## What you cannot confirm today +| Question | Tool | What to read | +| --- | --- | --- | +| Is it the structure that was asked for? | the write result itself, or `get_structure {object}` | `smiles` and `inchikey`; compare InChIKeys (the first block is the connectivity, the second stereo and isotopes, the last letter the protonation: N neutral, M one proton fewer) | +| Does it look right? | `render {ids}` (or `scope: "page"`, `scope: "selection"`) | the image: overlaps, crossing bonds, labels touching, wedges where expected, a scheme in reading order | +| Is it chemically valid? | `validate {object?}` | `valid`, then each issue's `code`, `severity`, `text`, `atoms`, `bonds` | +| What are its properties? | `compute_properties {object?}` | each value with its `method`; quote both | +| The molfile, InChI or masses | `get_structure {object}` | `molfile` and `molfile_version` (V3000 only when the structure needs it), `inchi`, `mw`, `exact_mass`, `mz` for charged structures | +| What did the person select? | `get_structure {selection: true}` or `render {scope: "selection"}` | needs the window open | +| Did a window command work? | the `run_command` answer, then `list_commands {id}` | `checked` for toggles, `off now` with its reason | -How the window looks: the drawing on the canvas, layout, theme, a dialog's contents, the Analysis panel's values, whether a panel is in the way. For those, post `handoff {state: "question", note}` asking the person to look ("Does the Analysis panel show C9H8O4 for the new structure?") and wait for their answer in the conversation. +## Reading a picture -## From 0.8.0 +`render` answers with the image and `renderer`: -The agent drawing tools add `render` (an image of an object, a selection or the page), `get_structure` and `validate`, so an agent can check its own drawing. Until then never describe a drawing as checked or as looking right on the strength of a command's answer alone. +- **`window`**: the FormChem window drew it with the same renderer as File > Export, in the person's display preferences, on white. This is what the person sees; arrows, plus signs, text, brackets and captions are included. +- **`engine`**: no window answered, so the engine drew the structures with RDKit in the journal style. Arrows, plus signs and text are left out (a warning says how many), and label placement differs from the window. Good for checking a structure, not for judging the layout the person sees. + +Size it to what you need: the default PNG is 144 dpi; pass `width` or `height` (pixels) to fit, or `format: "svg"` to read the drawing as text. Every write already carries a PNG of what it touched, up to 640 x 480, so a separate `render` is for the whole page, a scheme, or a closer look. ## Procedure -1. Act (`run_command`, `extension_command`). -2. Read the result text. An error ends the check: report it. -3. Confirm the state with `list_commands {id}` or `extensions_list` when the question is a state. -4. For anything only the eye can judge, ask the person with a question handoff. -5. Report what was confirmed and what the person was asked to look at. +1. After a change, read the write result: its SMILES, InChIKey, warnings and picture. +2. If the request had a specific target (a named molecule, a stereoisomer, a charge), compare it with `get_structure` or the result's InChIKey. Report a mismatch plainly, with both values. +3. If how it looks matters (a scheme, a figure, several structures on a page), `render {scope: "page"}` and look for overlaps, crossings and reading order. Fix with `move`, `align` or `clean_layout` (`edit-by-id`), one call each. +4. When the person cares about correctness, `validate` and report errors and warnings by code. +5. Say what you checked and how ("checked with get_structure: InChIKey BSYNRYMUTXBXSQ-UHFFFAOYSA-N, as expected; the window's picture shows no overlaps"). + +## What still needs the person + +The person's screen beyond the drawing: panels, dialogs, menus, the theme. A dialog a command opened waits for them. For those, ask with `handoff {state: "question", note}` and wait. ## Gate -- [ ] Every "it worked" in the reply rests on a tool result. -- [ ] Anything visual that no tool confirms was put to the person, not assumed. +- [ ] Every "it is right" or "it looks right" rests on a tool answer from after the last change. +- [ ] The renderer of any picture relied on was named when it was the engine. +- [ ] Values were quoted as the tools gave them (InChIKey in full, properties with methods). + +## Hands back + +What was checked, the quoted values, and any problem found with the ids involved. + +## Owned resources + +None of its own. `references/tools.md` at the pack root lists the arguments of `render`, `get_structure`, `validate` and `compute_properties`. diff --git a/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md b/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md index 6dc92811..f27eb4fe 100644 --- a/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md +++ b/.claude/skills/formchem-harness/sub-skills/window-commands/SUB-SKILL.md @@ -1,13 +1,13 @@ --- name: window-commands -description: "Works on FormChem drawings through run_command, the only way an agent changes the window before the drawing tools of 0.8.0: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles} or a template with insert-template {id}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, stacking order, group and ungroup, clean-structure, layout-structure, check-structure, the 0.6.0 chemistry commands, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, insert, tidy, arrange, undo or save something in FormChem, or asks which drawing commands exist." +description: "Runs the FormChem window's own commands through run_command for what the 0.8.0 drawing tools do not cover: finding commands with list_commands, opening a .fchem or structure file by path with open-recent, inserting a structure with insert-smiles {smiles} or a template with insert-template {id}, undo and redo, select-all, delete, duplicate, flips, rotate-90, align, distribute, stacking order, group and ungroup, clean-structure, layout-structure, check-structure, the 0.6.0 chemistry commands, the 0.7.0 import, export, print, copy, standardise, scale, grid and dark page commands, zoom and the Analysis panel, reading params and off-now states, and telling the person what only they can do. Use when the person asks an agent to open, import, insert, tidy, arrange, resize, export, copy, undo or save something in FormChem, or asks which drawing commands exist." --- # Window commands ## Purpose -Do drawing work in FormChem with the commands the person has, honestly. `run_command` runs one command in the window exactly as the person's click would, so whatever a command does for the person it does for the agent, prompts included. The agent cannot type into a prompt in the window, cannot see the canvas, cannot pick single atoms and cannot draw atoms one by one. +Reach what only the window's commands do, honestly: export and print for the person, the clipboard, Standardise, templates, the grid and dark page, the chemistry commands and their dialogs, Preferences. `run_command` runs one command in the window exactly as the person's click would, so whatever a command does for the person it does for the agent, prompts included. The agent cannot type into a prompt in the window and cannot pick single atoms on the canvas. From 0.8.0 drawing, editing by id, reading back, rendering and converting have their own tools (`drawing`, `edit-by-id`, `visual-qa`); prefer them, because they place in free space, work without the window and answer with the structure. Most canvas commands act on the canvas selection. The agent sets the selection two ways only: `select-all`, or `insert-smiles {smiles}`, which leaves the inserted structure selected. Anything else the person selected stays as they left it, so say what the command will act on. @@ -23,19 +23,27 @@ Most canvas commands act on the canvas selection. The agent sets the selection t | The person asks | Do | | --- | --- | -| Open this file (absolute path to a `.fchem`, `.mol`, `.sdf`, `.smi`, `.cml`, `.cdxml`) | `run_command {id: "open-recent", params: {path}}`; a structure file becomes a new unsaved drawing | -| Draw or insert a structure from SMILES | `run_command {id: "insert-smiles", params: {smiles: "[SMILES]"}}`: one undo step into the active drawing (a new one when none is open), centred in the visible page and selected; the answer names the new fragment ids and the drawing. Then `get_context` for the formula. If `list_commands {id: "insert-smiles"}` lists no `smiles` param (an older build), run it bare and post `handoff {state: "question", note: "Paste [SMILES] into the SMILES prompt and press Insert"}`; never claim the structure was drawn until the person confirms | +| Open this file (absolute path to a `.fchem`, a chemistry file, or a `.svg`, `.png`, `.pdf` or `.eps` FormChem exported) | `run_command {id: "open-recent", params: {path}}`; a structure file becomes a new unsaved drawing | +| Draw or insert a structure from SMILES | Use `draw_from_smiles` (`drawing`): it places the structure in free space and answers with its SMILES, InChIKey and a picture. `run_command {id: "insert-smiles", params: {smiles}}` still works when the person wants it in the middle of the view and selected, so the next selection command acts on it; the answer names the new fragment ids | | Insert a ring, amino acid, sugar, protecting group, reagent or glassware | `run_command {id: "insert-template", params: {id: "[template id]"}}`: one undo step, centred in view at the drawing's bond length, selected; without `id` it opens the library for the person. Ids such as `benzene`, `l-alanine` come from the engine's `GET /api/templates` | -| Draw from a name, a molfile text or by atoms; place an arrow, a shape or a caption | No command does this before 0.8.0 (the insert-arrow, insert-shape and insert-table commands only pick the person's tool). Offer SMILES through `insert-smiles {smiles}`, a template, or a file through `open-recent` | +| Draw by atoms; place an arrow, a caption or text | The edit tools do it by id (`edit-by-id`): `add_atom`, `add_bond`, `add_arrow`, `add_text`. Shapes, brackets and tables have no tool and no drawing command (insert-arrow, insert-shape and insert-table only pick the person's tool): ask the person | +| Draw from a name | Not yet in any version up to 0.8.0: write the SMILES and use `draw_from_smiles`, saying you did | | Stack or group objects | `bring-front`, `bring-forward`, `send-backward`, `send-back`, `group`, `ungroup` on the selection; off with "Select something on the canvas first" when nothing is selected | | Anything about the reaction in the drawing | Load `reactions` | | Undo the last change | `run_command {id: "undo"}`: one transaction, whoever made it | | Tidy or lay out the structure | `clean-structure` (bond lengths and angles, keeps place and stereo) or `layout-structure` (fresh 2D coordinates): they act on the selection, or on every structure on the page when nothing is selected. Right after `insert-smiles` they act on the inserted structure | | Delete, duplicate, flip, rotate, align, distribute | `select-all` (or the structure `insert-smiles` just selected), then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h` or `distribute-v`. They are off with "Select something on the canvas first" when nothing is selected | | Save | `save`; a drawing never saved before asks the person for a name, so say so in the handoff | -| Check the structure | The `check_structure` tool returns the issues with codes and ids (`structure-analysis`); `check-structure` opens the Check Structure panel for the person | -| Show the formula, masses or properties | `get_context` gives the formula of each open drawing and the `properties` tool every value with its method (`structure-analysis`); `show-analysis` or `compute-properties` opens the Analysis panel with the isotope pattern for the person | +| Check the structure | The `validate` tool returns the issues with codes and ids (`visual-qa`); `check-structure` opens the Check Structure panel for the person | +| Show the formula, masses or properties | `get_structure` gives formula and masses and `compute_properties` every value with its method (`visual-qa`, `structure-analysis`); `show-analysis` or `compute-properties` opens the Analysis panel with the isotope pattern for the person | | Stereo, hydrogens, abbreviations, query features, R-groups | Load `structure-analysis` for the commands and the tools that read the result | +| Bring a file's structures into the open drawing | `run_command {id: "import", params: {path: "[absolute path]"}}`: chemistry files (molfile, SD, RXN, RD, SMILES, CXSMILES, SMARTS, InChI, CML, CDXML, CDX), `.fchem` drawings and pictures FormChem exported; lands in free space, selected, one undo step; an SD file brings at most 50 structures and the answer says what came in. `open-recent {path}` opens a file as its own drawing instead | +| Save a picture or a chemistry file | `export-png`, `export-svg`, `export-pdf`, `export-eps`, `export-cdxml`, `export-mol`, `export-smiles` (whole page), or `export-picture` (the dialog: scope, resolution, background, scale). In the desktop app each shows the person's save dialog; in a browser it downloads. The agent does not receive the file: say where the person will find it, and that pictures keep the drawing inside so they reopen editable | +| Print | `print`: the system print dialog for the person; the page at real size, or the selection in its place | +| Put the structure on the person's clipboard | `copy-smiles`, `copy-cxsmiles`, `copy-molfile`, `copy-inchi`, `copy-inchikey`, `copy-smarts`, `copy-svg`, `copy-png`, `copy-cdxml` (the selection, or the page); `copy` writes the drawing, SMILES and a picture at once. To read SMILES, a molfile or another format yourself, use `get_structure` or `convert` instead | +| Make a structure larger or smaller on the sheet | `scale-selection {percent: 150}` or `{bond_length: 20}` (with `labels: false` to keep line widths and fonts), `scale-up`, `scale-down` (10 percent, exact inverses); the selection, or every structure on the page about its own centre. `zoom-in` only changes the view: never use zoom when the person wants the drawing larger | +| Remove salts, neutralise, pick the tautomer | `standardise {steps: ["salts", "neutralise"]}` (steps: cleanup, normalise, salts, largest, reionise, neutralise, tautomer, isotopes, stereo, strip_h); without `steps` the dialog opens for the person | +| Grid, snapping, dark page | `grid-type {type}` (lines, dots, crosses, isometric, isometric-dots, hex, hex-dots), `grid-spacing {value, unit}` (a number or "bond"), `grid-settings {...}`, `snap-to-grid {on}`, `show-grid {on}`, `dark-page {on}`; `scope: "default"` changes the default for new drawings. The grid is saved with the drawing; the dark page is a screen choice and never reaches exports | ## Rules diff --git a/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md b/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md index 7f9e876c..dc93e5af 100644 --- a/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md +++ b/.claude/skills/formchem-harness/sub-skills/window-commands/references/command-catalogue.md @@ -1,6 +1,6 @@ # Commands that touch a drawing -The window's command registry, as far as it concerns drawings, for FormChem 0.6.0. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. +The window's command registry, as far as it concerns drawings, for FormChem 0.8.0 (the commands are those of 0.7.0, plus `agent-activity`, which opens Window > Agent Activity for the person). From 0.8.0 the agent's own tools draw, edit, read back, render and convert; this page covers what the window's commands add. This page is a map, not the authority: `list_commands` is. A command marked `off now` there is not available in the running build, whatever this page says, and a command that lists `params` there takes exactly those. ## Contents @@ -10,7 +10,9 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.6. - Templates, objects and arrangement - Reactions - Stereo, queries and analysis -- The canvas and the view +- Import, export, print and the clipboard +- Standardise and size on the sheet +- The canvas, the view and the grid - Registered but off until a later version - What no command does yet @@ -23,7 +25,7 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.6. | Command | Params | What it does | | --- | --- | --- | | `new-document` | | creates an empty drawing and makes it active (Home closes) | -| `open-recent` | `path` (absolute) | opens that file: a `.fchem` drawing, or a structure file (molfile, SDF, RXN, SMILES, CXSMILES, InChI, CML, cdxml, cdx) imported into a new unsaved drawing; without `path` it shows Home | +| `open-recent` | `path` (absolute) | opens that file: a `.fchem` drawing, a chemistry file (molfile, SD, RXN, RD, SMILES, CXSMILES, SMARTS, InChI, CML, CDXML, CDX) imported into a new unsaved drawing with an import report for the person, or a picture FormChem exported with its drawing inside; without `path` it shows Home | | `open` | | shows the file chooser to the person; an agent cannot answer it | | `save` | | saves the active drawing; a drawing with no file yet asks the person for a name in the browser window | | `save-as`, `save-copy` | | ask the person where or under what name | @@ -38,7 +40,7 @@ The window's command registry, as far as it concerns drawings, for FormChem 0.6. | `undo`, `redo` | | undoes or redoes the last change to the active drawing (one transaction each); off when there is nothing to undo or redo | | `select-all` | | selects everything on the active page of the canvas; while a text field has focus it selects the field's text | | `delete` | | removes the selection (bare carbons left behind go with it); keys Delete, Backspace | -| `duplicate` | | copies the selection 10 pt down and right and selects the copy; key Mod+D | +| `duplicate` | | copies the selection 10 pt down and right and selects the copy, with its stereo groups, R-groups and reaction steps; key Mod+D | | `flip-horizontal`, `flip-vertical` | | mirror the selection about its centre | | `rotate-90` | | turns the selection 90 degrees clockwise about its centre | | `align-left`, `align-center`, `align-right`, `align-top`, `align-middle`, `align-bottom` | | line up the selected objects on that edge or centre | @@ -94,18 +96,52 @@ From 0.6.0. They act on the selection, or the page when nothing is selected, and | `set-query-bond-any`, `set-query-bond-single_or_double`, `set-query-bond-single_or_aromatic`, `set-query-bond-double_or_aromatic`, `clear-query-bond` | query bonds on the selected bonds (list_commands gives the exact ids) | | `define-rgroup`, `enumerate-markush` | open the R-group and enumeration dialogs for the person | | `search-substructure` | selects matches of the selected atoms, or asks the person for SMARTS | -| `copy-smarts`, `export-smarts` | SMARTS to the person's clipboard, or a `.sma` file (the desktop app copies instead until 0.7.0) | +| `copy-smarts`, `export-smarts` | SMARTS to the person's clipboard, or a `.sma` file the person saves | | `compute-properties`, `copy-analysis` | open the Analysis panel on the selection; copy its values with methods to the person's clipboard | | `show-stereo`, `show-stereo-groups`, `show-query-marks` | toggle the CIP labels, the enhanced stereo group labels and the query tags on the canvas | -## The canvas and the view +## Import, export, print and the clipboard + +From 0.7.0. Exports and copies act on the selection where the command says so, else the active page; none changes the drawing. + +| Command | Params | What it does | +| --- | --- | --- | +| `import` | `path` (absolute, optional) | inserts a chemistry file, a `.fchem` drawing or a picture with its FormChem drawing into the active drawing (a new one when none is open), in free space right of or below what is there, selected, one undo step per file, with the import report for the person; an SD file brings at most 50 structures. The answer names what came in. Without `path` the person picks files in a dialog | +| `export-png`, `export-svg`, `export-pdf`, `export-eps` | | save the whole page as a picture with the drawing kept inside (300 dpi PNG by default); the desktop app shows the person's save dialog, a browser downloads | +| `export-picture` | | opens the Export Picture dialog for the person (format, scope, resolution, background, scale, margin) | +| `export-cdxml`, `export-mol`, `export-smiles` | | save the page as CDXML, molfile or SMILES; warn and error report items show to the person | +| `print` | | the print dialog for the person: the page at real size, or the selection in its place (Mod+P) | +| `copy`, `cut`, `paste` | | the drawing on the person's clipboard (the selection, or the whole page for `copy`); `paste` reads it back at the view centre, one undo step | +| `copy-smiles`, `copy-cxsmiles`, `copy-molfile`, `copy-inchi`, `copy-inchikey`, `copy-smarts`, `copy-svg`, `copy-png`, `copy-cdxml` | | one form on the person's clipboard; reactions become reaction SMILES or RXN | +| `paste-special` | | lists what the clipboard holds for the person to choose (Shift+Mod+V) | + +The agent never receives the saved file or the clipboard text. To read a structure as text, use `get_structure` (SMILES, CXSMILES, InChI, InChIKey, molfile); for another format `convert`; for a picture `render` (the `drawing` and `visual-qa` sub-skills of this pack). + +## Standardise and size on the sheet + +| Command | Params | What it does | +| --- | --- | --- | +| `standardise` | `steps` (list, optional) | standardises the selected structures, or every structure on the page together, as one undo step: `cleanup`, `normalise`, `salts`, `largest`, `reionise`, `neutralise`, `tautomer`, `isotopes`, `stereo`, `strip_h`, always in that order; without `steps` it opens the dialog with a preview for the person | +| `scale-selection` | `percent` (5 to 2000) or `bond_length` (1 to 500 pt), `labels` (boolean, optional) | makes the selection, or every structure on the page about its own centre, larger or smaller on the sheet, one undo step; answers "Scaled to 138.9%, bond length 20.0 pt". `labels: false` keeps line widths and fonts. Both `percent` and `bond_length` is an error; no params opens the Scale dialog | +| `scale-up`, `scale-down` | | 10 percent up, or the exact inverse (Alt+Mod+=, Alt+Mod+-) | +| `scale-labels` | | toggles whether labels and text scale with structures (on by default) | + +Zoom never changes the drawing; use these when the person wants a structure larger. + +## The canvas, the view and the grid | Command | What it does | | --- | --- | | `zoom-in`, `zoom-out` | zoom the canvas one step in or out (Mod+=, Mod+-) | | `zoom-fit` | fits the whole page in the view (Mod+0) | | `zoom-100` | actual size (Mod+1) | -| `show-grid` | toggles the paper grid; the result says whether it is now on | +| `show-grid` | param `on` (optional): shows or hides the grid in this window; the result says whether it is now on | +| `dark-page` | param `on` (optional): the dark page view on or off (on by default); screen only, never in exports; returns `{on}` | +| `snap-to-grid` | param `on` (optional): new bonds, chains, rings and objects and moves land on grid points | +| `grid-type` | params `type` (`lines`, `dots`, `crosses`, `isometric`, `isometric-dots`, `hex`, `hex-dots`), `scope` (`"default"` for new drawings): one undo step in the drawing | +| `grid-spacing` | params `value` (a number or `"bond"`), `unit` (`pt`, `mm`, `cm`, `in`), `scope` | +| `grid-settings` | params `type`, `spacing`, `unit`, `major` (0 to 50), `strength` (`faint`, `normal`, `strong`), `scope`; no params opens the Grid Settings dialog for the person | +| `grid-lines`, `grid-dots`, `grid-crosses`, `grid-isometric`, `grid-isometric-dots`, `grid-hex`, `grid-hex-dots` | the View > Grid radio items | | `show-analysis` | opens the Analysis panel | | `find`, `show-rulers` | Edit > Find (next, previous, replace) and View > Show Rulers with guides, for the person | | `toggle-analysis`, `analysis-panel` | shows or hides the Analysis panel (formula, masses, m/z, elemental analysis from the engine, for the selection or the whole page) | @@ -113,8 +149,8 @@ From 0.6.0. They act on the selection, or the page when nothing is selected, and ## Registered but off until a later version -`import`, `print`, `copy-smiles`, `copy-molfile`, `copy-inchi`, `copy-svg` and the whole-drawing `export-png`, `export-svg`, `export-pdf`, `export-cdxml`, `export-mol`, `export-smiles` (0.7.0); `insert-name` (0.9.0); the 3D commands (0.10.0); `demos` (0.13.0). The reaction copy and export commands and `copy-smarts` and `export-smarts` already work. Running one returns "is not available right now: Arrives in [version]". Say so; do not retry. +`insert-name` (0.9.0); the 3D commands `view-3d`, `build-3d`, `minimize-3d`, `conformers` (0.10.0); `demos` (0.13.0). Every 0.7.0 placeholder is now a working command. Running an off one returns "is not available right now: Arrives in [version]". Say so; do not retry. ## What no command does yet -Drawing atoms, bonds, arrows or shapes at given positions, selecting particular atoms or objects, typing stoichiometry amounts, filling the person's dialogs (atom list, R-group, abbreviation label), reading the whole structure back beyond what `get_context` and the analysis tools give (the formula, SMILES and CXSMILES in `stereo`, properties, issues and substructure hits), rendering an image or converting a file without opening it. The direct agent tools for these arrive in 0.8.0. Until then an installed extension with the `document` permission can read and change the drawing (the `extension-drawings` sub-skill of this pack), and the person can read the Analysis panel. +Selecting particular atoms or objects, typing stoichiometry amounts, and filling the person's dialogs (atom list, R-group, abbreviation label). Drawing atoms, bonds, arrows and text at given positions, reading the structure back, rendering and converting are not commands: the 0.8.0 tools do them (`drawing`, `edit-by-id`, `visual-qa`). An installed extension with the `document` permission can also read and change the drawing (`extension-drawings`). diff --git a/.claude/skills/formchem-skillset/EVALS.json b/.claude/skills/formchem-skillset/EVALS.json index 46a20dac..95dd8f8c 100644 --- a/.claude/skills/formchem-skillset/EVALS.json +++ b/.claude/skills/formchem-skillset/EVALS.json @@ -1,6 +1,6 @@ { "skill_name": "formchem-skillset", - "notes": "Run in a FormChem checkout at 0.6.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", + "notes": "Run in a FormChem checkout at 0.8.0 with CLAUDE.md present. Expected behaviours are observable in the files read, the edits made and the commits.", "evals": [ { "id": 1, @@ -64,8 +64,8 @@ "files": [], "expected_behavior": [ "Edits no file in the repository and makes no commit", - "Points the request at formchem-harness (driving FormChem through its MCP server) rather than adding drawing code", - "Does not add an MCP drawing tool ahead of its phase (0.8.0)" + "Points the request at formchem-harness (draw_from_smiles through FormChem's MCP server) rather than adding drawing code", + "Does not add a draw_from_name tool or any tool of a later phase" ] }, { @@ -156,10 +156,73 @@ "Sets @tauri-apps/cli in frontend/package.json to a 2.13 release in the same change as package-lock.json, checking the @tauri-apps/plugin-* packages against their tauri-plugin-* crates", "Runs ./formchem desktop check (not a full tauri build on a small machine) and records the bump in the HASHOUT log" ] + }, + { + "id": 15, + "name": "new-export-format", + "prompt": "Let FormChem export XYZ files from a drawing.", + "files": [], + "expected_behavior": [ + "Loads formats-and-export and clean-room before editing", + "Adds one record to formats.TABLE with every feature XYZ cannot hold in loses, and a writer in writers.py that reports what it leaves out", + "Adds the extension to the Open lists and files.SUFFIXES only where it reads or saves it, updates docs/FORMATS.md, and round-trips a scratch corpus outside the repository" + ] + }, + { + "id": 16, + "name": "pdf-export-lost-text", + "prompt": "PDF exports from the macOS FormChem app have no atom labels, but the browser version is fine.", + "files": [], + "expected_behavior": [ + "Loads formats-and-export and desktop", + "Checks /api/pictures/capabilities in the frozen engine and that fontTools' submodules are collected in setup/freeze_backend, its .bat twin and build_app's own freeze", + "Never builds the picture from the live canvas and records the fix in the backend HASHOUT log" + ] + }, + { + "id": 17, + "name": "batch-convert-stops", + "prompt": "./formchem convert stops at record 512 of my SD file with a valence error; make it keep going.", + "files": [], + "expected_behavior": [ + "Loads command-line and reads services/chem/stream.py and services/batch.py", + "Keeps one reader: the failing record is reported with its number, name and RDKit's own reason through stream.explain, and the run continues", + "Checks exit code 0, output order and a byte-identical result with --jobs 2 on a scratch file" + ] + }, + { + "id": 18, + "name": "add-an-edit-tool", + "prompt": "Add an MCP tool to FormChem that flips a structure horizontally by id.", + "files": [], + "expected_behavior": [ + "Loads the agents sub-skill and reads services/agent_edits.py and routers/mcp.py before editing", + "Writes a pure builder fn(doc, args) -> (ops, info) in agent_edits.py that mirrors the window's Flip and raises EditError with the next step", + "Adds the _tool entry, a t_ handler that goes through _edit with an undo label, and the name to MUTATING", + "Runs ./formchem agents sync and sync --check, and checks on a scratch engine that one call raises the revision by one and answers with an image" + ] + }, + { + "id": 19, + "name": "agent-call-shows-done-after-undo", + "prompt": "Agent Activity shows an agent call as Done again after I undid it and kept drawing; fix it.", + "files": [], + "expected_behavior": [ + "Loads the agents sub-skill and reads services/agent_log.py after_change and _stacks", + "Keeps undone true while the call's transaction is not back on the undo stack, rather than reading the redo stack alone", + "Leaves the window mirror (app/agent-calls.ts) to follow the engine's agentCall messages instead of computing undone itself" + ] } ], "trigger_evals": [ + {"query": "the formchem agent render tool falls back to the engine picture", "should_trigger": true}, + {"query": "add a field to formchem's agent call log in services/agent_log.py", "should_trigger": true}, {"query": "add an MCP tool to formchem", "should_trigger": true}, + {"query": "formchem's CDXML export drops the reaction arrow", "should_trigger": true}, + {"query": "the formchem desktop app takes 30 seconds to open on macOS", "should_trigger": true}, + {"query": "paste from formchem into Word loses the structure, fix the clipboard flavours", "should_trigger": true}, + {"query": "formchem lays out Taxol with labels touching", "should_trigger": true}, + {"query": "export my FormChem drawing as PDF", "should_trigger": false}, {"query": "formchem shows (S) on the wrong side of the stereocentre after contracting CO2H", "should_trigger": true}, {"query": "fix formchem's SMARTS export for atom lists in services/chem/query.py", "should_trigger": true}, {"query": "formchem build_app stops with the Tauri CLI did not install", "should_trigger": true}, diff --git a/.claude/skills/formchem-skillset/SKILL.md b/.claude/skills/formchem-skillset/SKILL.md index bc0400e8..4bde2c2d 100644 --- a/.claude/skills/formchem-skillset/SKILL.md +++ b/.claude/skills/formchem-skillset/SKILL.md @@ -1,17 +1,17 @@ --- name: formchem-skillset -description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (docs/FORMAT.md, model.ts, model.py, ops, undo, the fchem package), the engine store, the RDKit service (SMILES, InChIKey, masses, layout, warnings, CIP and enhanced stereo, wedges, abbreviations, queries, SMARTS, R-groups, properties, the structure check, isotope patterns), reactions (perception, Indigo mapping, balance, stoichiometry, RXN, roles), the SVG canvas renderer and marks, drawing tools, hover hotkeys, hit testing, arrows, shapes, captions, templates, the window shell, menus, themes, the agent dock, Form extensions, an MCP tool, the Tauri shell and desktop build, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for driving FormChem as a user (use formchem-harness), not for other Form apps such as FormDeck, and not for standalone RDKit scripts." +description: "Guides development of the FormChem codebase, the FormAI family's chemical structure drawing suite. Use whenever a task changes, fixes or explains FormChem code: the document format (FORMAT.md, model.ts, model.py, ops, undo), the engine store, the RDKit service (identifiers, the scored 2D layout, CIP, stereo groups, abbreviations, queries, SMARTS, R-groups, properties, the structure check), reactions, file formats and loss reports, picture export with the embedded drawing, the clipboard, the command line, Standardise, the SVG canvas, dark page, grids, scaling, tools, annotations, the shell, menus, the dock, Form extensions, the MCP server and agent tools (agent_out, agent_edits, agent_log, the render bridge, the agent token, Agent Activity), the Tauri shell and one-folder engine, or a release. Trigger on FormChem or formchem with backend/app, frontend/src, src-tauri, FORMAT.md, port 8220 or 5220. Not for using FormChem (formchem-harness), other Form apps such as FormDeck, or standalone RDKit scripts." license: Apache-2.0 metadata: author: nodemode-ai - version: "0.6.0" + version: "0.8.0" --- # FormChem skillset -Route every change to FormChem's code through this file. It maps the subsystems that exist today, states the laws that hold everywhere and names the specialist to load. FormChem is a Python 3.12 FastAPI engine (`backend/`, port 8220), a vanilla TypeScript and Vite window (`frontend/`, port 5220, no framework) that talks to the engine over REST and one WebSocket, and a Tauri 2 shell (`src-tauri/`) that runs the frozen engine as a sidecar. +Route every change to FormChem's code through this file. It maps the subsystems that exist today, states the laws that hold everywhere and names the specialist to load. FormChem is a Python 3.12 FastAPI engine (`backend/`, port 8220), a vanilla TypeScript and Vite window (`frontend/`, port 5220, no framework) that talks to the engine over REST and one WebSocket, and a Tauri 2 shell (`src-tauri/`) that runs the frozen engine from a folder inside the app on macOS and as a sidecar elsewhere. -**Where FormChem is (0.6.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 added the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. 0.5.0 added reactions and annotations: every drawn object kind through one renderer registry with its tool and handles, z-order and groups, the engine's reaction perception, mapping, balance, stoichiometry and RXN exchange with the Reaction menu and four MCP tools, the Stoichiometry panel, the template library and media. 0.6.0 adds stereo, queries and analysis: enhanced stereo groups and the chiral flag in RDKit, the CIP report, wedge assignment, abbreviations and explicit hydrogens, query atoms and bonds, SMARTS, substructure search, V3000 query molfiles, R-groups and Markush enumeration, properties with methods, the structure check, the isotope pattern, the `/api/analysis` router with four read-only MCP tools, the keyed marks layer, the chemistry commands and dialogs, Set Reaction Roles, and the Tauri CLI pin for the desktop build. Exchange formats and export (0.7.0) and the agent drawing tools (0.8.0) come later, per `DEV_PLAN.md` in the owner's planning sidecar. Do not write a later phase's code ahead of it; its commands stay registered and disabled. +**Where FormChem is (0.8.0).** Phases 1 and 2 built the family skeleton and shell. 0.3.0 added the document format and ops, the engine's document store with undo, autosave, versions and importers, the RDKit chemistry service, and the window's document client and local chemistry. 0.4.0 added the 2D canvas: the SVG renderer, the drawing tools and hover hotkeys, the canvas view with hit testing, selection, context menus and the tool rail. 0.5.0 added reactions and annotations: every drawn object kind through one renderer registry with its tool and handles, z-order and groups, the engine's reaction perception, mapping, balance, stoichiometry and RXN exchange with the Reaction menu and four MCP tools, the Stoichiometry panel, the template library and media. 0.6.0 added stereo, queries and analysis: enhanced stereo, CIP, wedges, abbreviations, hydrogens, queries and SMARTS, substructure search, R-groups and Markush, properties with methods, the structure check, the isotope pattern, the `/api/analysis` router with four read-only MCP tools, the marks layer and the chemistry commands. 0.7.0 added formats and exchange (readers, writers and report items, CDXML and CDX through Indigo, pictures with the embedded drawing and the engine's own PDF and EPS writer, print, the clipboard, File > Import, the command line, Standardise) plus the desktop test fixes: the one-folder macOS engine, the scored 2D layout, the dark page, scaling, grids and snapping, the folding menu row and the quick command state mirror. 0.8.0 adds the agent tools (42 MCP tools: documents, drawing, `render` through the window, reading back, conversion, 14 edit tools by id), the agent call log with Agent Activity and Stop, and the agent token. Names, spectra (0.9.0) and 3D (0.10.0) come later (`DEV_PLAN.md`). Do not write a later phase's code ahead of it; its commands stay registered and disabled. ## Subsystem map @@ -22,16 +22,19 @@ Route every change to FormChem's code through this file. It maps the subsystems | The format contract: document.json, styles, ids, ops and inverses, transactions, validation, coalescing, the derived cache shape | `docs/FORMAT.md`, `frontend/src/engine/model.ts`, `engine/ops.ts`, `backend/app/services/model.py`, `services/ops.py` | `document-format` | | Chemistry engine on RDKit: conversion, sanitising, valence, aromaticity, identifiers, formula, masses, layout, file reading and writing, the derived cache | `backend/app/services/chem/`, `backend/app/routers/chem.py` | `chemistry-engine` | | Window documents and chemistry: the document client and session, the actions behind File and Insert, the Analysis panel, local valence, rings, labels and formula | `frontend/src/engine/client.ts`, `engine/session.ts`, `engine/client-api.ts`, `app/documents.ts`, `ui/analysis-panel.ts`, `frontend/src/chem/` | `window-shell` (chemistry rules in `chemistry-engine`) | -| Canvas: SVG renderer, drawing tools and hover hotkeys, view, hit testing, selection, text editor, canvas context menus, tool rail | `frontend/src/canvas/` (`render/`, `tools/`, `geom.ts`, `view.ts`, `hit.ts`, `selection.ts`, `text-editor.ts`, `context.ts`, `types.ts`), `ui/tool-rail.ts`, `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | `canvas` | +| Canvas: SVG renderer, drawing tools and hover hotkeys, view, hit testing, selection, text editor, canvas context menus, tool rail; from 0.7.0 the dark page, grids and snapping, scale handles | `frontend/src/canvas/` (`render/`, `tools/`, `dark-page.ts`, `grid.ts`, `grid-layer.ts`, `tools/scale.ts`, `geom.ts`, `view.ts`, `hit.ts`, `selection.ts`, `text-editor.ts`, `context.ts`, `types.ts`), `ui/tool-rail.ts`, `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | `canvas` | | Drawn objects: the object kind registry and kind modules, anchors, bounds, drawn-outline hits, annotation tools and handles, captions, z-order and groups, the template library, media | `frontend/src/canvas/render/objects.ts` and its kind modules, `canvas/hit-objects.ts`, `canvas/tools/objects.ts`, `tools/handles.ts`, `app/object-commands.ts`, `ui/template-*.ts`, `backend/app/services/templates.py`, `routers/templates.py`, `backend/app/data/templates/`, the media routes in `routers/documents.py` | `annotations` | | Reactions: perception, atom mapping, balance, stoichiometry (engine and window), reaction SMILES and RXN, the Reaction menu, the MCP reaction tools | `backend/app/services/chem/` (`geometry`, `reactions`, `mapping`, `balance`, `stoich`, `rxnio`, `scheme`), `routers/reactions.py`, `frontend/src/chem/stoich.ts`, `ui/stoich-panel.ts`, `app/reaction-commands.ts`, `engine/reactions-api.ts`, `docs/REACTIONS.md` | `reactions` | | Stereo, queries and analysis: stereo groups, CIP report, wedges, abbreviations, hydrogens, queries and SMARTS, substructure search, V3000 queries, Markush, properties, the structure check, the isotope pattern, their routes, tools, commands, marks and panels | `backend/app/services/chem/` (`stereo`, `superatom`, `hydrogens`, `query`, `search`, `v3000`, `markush`, `props`, `check`, `isotopes`), `routers/analysis.py`, `frontend/src/engine/analysis-api.ts`, `app/chem-edits.ts`, `app/chem-commands.ts`, `canvas/render/marks-*.ts`, the 0.6.0 dialogs in `ui/`, `docs/ANALYSIS.md` | `stereo-and-queries` | +| Formats and export: the formats table, report items, readers and writers, CDXML and CDX through Indigo, RD files, CML, the export, parse, import and file write routes, pictures (SVG, PNG, PDF, EPS) with the embedded drawing, the save path, print, the import report, File > Import | `backend/app/services/chem/` (`formats`, `report`, `io`, `writers`, `cdxio`, `rdfio`, `cml`), `services/embedded_source.py`, `services/pictures/`, `services/importers.py`, `routers/files.py`, `routers/pictures.py`, `frontend/src/app/` (`picture`, `embedded-source`, `save-file`, `export-commands`, `print`, `import-files`), `ui/export-dialog.ts`, `ui/import-report.ts`, `docs/FORMATS.md` | `formats-and-export` | +| Clipboard: the native payload and paste plan, text formats, flavours per platform, Copy As, Paste Special, Duplicate | `frontend/src/app/clip-*.ts`, `app/clipboard.ts`, `ui/paste-special-dialog.ts`, `ui/native-menu.ts` `ALWAYS_NATIVE` | `clipboard` | +| Command line and batch: convert, batch, descriptors, render, the stream reader, Standardise (engine, route, dialog) | `backend/app/cli.py`, `services/batch.py`, `services/chem/` (`stream`, `records`, `standardise`, `depict`), `setup/convert`, `frontend/src/ui/standardise-dialog.ts`, `app/standardise-command.ts`, `docs/CLI.md` | `command-line` | | Window shell: app root, command registry, palette, Home, title bar, status bar, Preferences, dialogs, themes, i18n, styles | `frontend/src/app.ts`, `app/commands-shell.ts`, `commands/registry.ts`, `io/`, `ui/`, `i18n/`, `styles/` | `window-shell` | | Menus: in-window menu bar, native macOS menus, context menus | `frontend/src/ui/menu.ts`, `ui/native-menu.ts`, `ui/context-menu.ts`, `app/menus.ts`, `styles/menu.css` | `menus` | | Terminal and agent dock | `frontend/src/dock/` (vendored), `frontend/src/dock-adapter.ts`, `backend/app/routers/terminal.py`, `services/terminal.py`, `services/claude_code.py`, `services/agent_programs.py`, `services/agent_lookup.py` (vendored) | `dock` | | Form extensions (host API 1) | `frontend/src/extensions/`, `backend/app/routers/extensions.py`, `services/formext_host.py` (vendored), `docs/EXTENSIONS.md` | `extensions` | -| MCP server, commands catalogue, agent setup and skills | `backend/app/routers/mcp.py`, `routers/commands.py`, `setup/mcp_stdio.py`, `setup/agents.py`, `setup/catalogue.py`, `agents/manifest.json`, `.claude/skills`, `.agents/skills` | `agents` | -| Desktop app and sidecar | `src-tauri/`, `backend/formchem_engine.py`, `setup/freeze_backend`, `setup/desktop_*`, `build_app` | `desktop` | +| MCP server, agent tools, the call log and Agent Activity, the agent token, commands catalogue, agent setup and skills | `backend/app/routers/mcp.py`, `services/agent_*.py`, `core/agent_token.py`, `routers/agent_activity.py`, `routers/commands.py`, `frontend/src/app/agent-*.ts`, `ui/agent-*.ts`, `canvas/agent-marks.ts`, `setup/mcp_stdio.py`, `setup/agents.py`, `docs/AGENTS.md`, `.claude/skills` | `agents` | +| Desktop app, the macOS engine folder and the sidecar | `src-tauri/` (`packaged.rs`, `tauri.macos.conf.json`), `backend/formchem_engine.py`, `setup/freeze_backend`, `setup/lib.sh`, `setup/desktop_*`, `build_app` | `desktop` | | Versions, changelog, notices, CI, formcompiler | `.docs/BRANCHING.md`, `CHANGELOG.md`, `NOTICE.md`, `setup/notices.py`, `.github/workflows/` | `release` | | Where any FormChem feature may come from | the owner's clean-room specifications | `clean-room` | @@ -55,8 +58,14 @@ backend services/model.py, ops.py -> nothing (pure; the contract) services/store.py -> model, ops, package, history, importers, hub; chem.derive imported lazily services/chem/ -> rdkit, indigo, model (never the store or routers) backend routers -> core, services (hub, bridge, library, store, chem, terminal, formext_host) -mcp.py -> commands, extensions, consent, claude_code (in-app tokens), bridge, hub; - routers/analysis imported lazily by the analysis tools +mcp.py -> commands, extensions, consent, claude_code (in-app tokens), bridge, hub, agent_token; + routers/analysis and the agent_* services imported lazily by the tools +services/agent_*.py -> store, bridge, chem (agent_edits is pure: model and chem only); agent_log hooks AFTER_CHANGE +app/picture.ts -> canvas/render (a fresh renderer off screen), never the live canvas view +app/clip-*.ts, import-files -> engine/model, ops, the export and parse routes; one paste plan (clip-data.ts) +services/chem/writers, stream -> formats, report, io, rdkit, indigo (never the store) +services/batch.py, app/cli.py -> chem/stream, records, standardise, depict, props (never routers or the store) +services/pictures/ -> fontTools and the bundled fonts only window-only abilities -> reach the engine as window tools over /api/live (bridge.window_call) desktop shell -> frozen engine (formchem_engine.py) -> serves frontend/dist ``` @@ -90,16 +99,22 @@ The window reaches the engine only through `frontend/src/io/api.ts` (REST with t | An arrow, bracket, shape, line, table, TLC plate, orbital, picture or caption: drawing, hitting, handles, its tool; z-order and groups; a template; picture upload | `annotations`, with `canvas` for the laws it builds on | | Reaction roles, atom mapping, balance, the stoichiometry panel or grid, reaction SMILES or RXN, a reaction route, command or MCP tool | `reactions`, with `chemistry-engine` for RDKit and `agents` for a tool | | A CIP label, stereo group, wedge, abbreviation, explicit hydrogen, atom list, query bond, SMARTS, substructure hit, R-group, property, check issue or isotope peak; an `/api/analysis` route, an analysis MCP tool, a stereo or query mark | `stereo-and-queries`, with `chemistry-engine` for the converter and `agents` for a tool | +| A file that opens wrong or loses something, an export or import report, a new format, File > Import, picture export, the drawing inside a picture, saving in the desktop app, print | `formats-and-export`, with `chemistry-engine` for RDKit and `clean-room` for a new format | +| Copy, Cut, Paste, Copy As, Paste Special, Duplicate, a clipboard flavour on one platform | `clipboard`, with `formats-and-export` for the text formats and pictures | +| `./formchem convert`, `batch`, `descriptors`, `render`, the stream reader, per-record failures, Standardise | `command-line`, with `chemistry-engine` for RDKit | +| A crowded or crossing 2D layout, Lay Out or Clean Up | `chemistry-engine` (the scored layout) | +| The dark page, a grid type, snapping, scale handles, Scale Up and Down | `canvas`, with `document-format` for `style.grid` | | New, Open, Save, Insert from SMILES, the Analysis panel, the status bar formula, the dirty mark | `window-shell`, with `chemistry-engine` for the values | | Home, the title bar, status bar, palette, Preferences, About, dialogs, themes, translations, styles | `window-shell` | | A menu item, a submenu, a shortcut label, macOS native menus, menu overlap | `menus`, then `window-shell` for the command | | Terminal tabs, Claude Code, Codex, Cursor or Antigravity tabs, the consent dialog, chat | `dock` | | The extensions pane, an extension API call, FormPortal or form.ext integration | `extensions` | -| A new MCP tool, the commands catalogue, `./formchem agents`, skills, the manifest | `agents` | -| Desktop build, `build_app`, the Tauri CLI version, sidecar, updater, Tauri commands, title bar overlay | `desktop` | +| An MCP tool, an edit builder, agent render or placement, the call log, Agent Activity, Stop, the token, `./formchem agents`, skills | `agents` | +| Desktop build, `build_app`, a slow desktop start, the macOS engine folder and its flatten rule, the Tauri CLI version, sidecar, updater, Tauri commands, title bar overlay | `desktop` | +| A menu that clips or overlaps the title, More menus, Escape or arrows with a menu open | `menus` | | A release, version sites, CHANGELOG, NOTICE, CI | `release` | | Any chemistry feature, a file format, a name for a command or panel | `clean-room` first | -| Use FormChem: insert a structure, run a menu command, hand off in the window | Not this pack: `formchem-harness` | +| Use FormChem: draw or edit a structure with the agent tools, run a menu command, hand off in the window | Not this pack: `formchem-harness` | ## Layout of this pack @@ -108,8 +123,9 @@ formchem-skillset/ SKILL.md this router, the subsystem map and the laws in short references/repo-laws.md each law with its reason and exact format EVALS.json evaluation prompts and the trigger tests (should and should not load) - sub-skills/ engine, document-format, chemistry-engine, reactions, stereo-and-queries, canvas, annotations, - window-shell, menus, dock, extensions, agents, desktop, release, clean-room + sub-skills/ engine, document-format, chemistry-engine, reactions, stereo-and-queries, formats-and-export, + clipboard, command-line, canvas, annotations, window-shell, menus, dock, extensions, agents, + desktop, release, clean-room chemistry-engine/references/warning-codes.md every ChemWarning code and where it comes from stereo-and-queries/references/routes-and-codes.md the /api/analysis routes, check codes and service warning codes canvas/references/hover-keys.md the hover key map with the code that implements it @@ -130,6 +146,7 @@ Paths inside a SUB-SKILL.md resolve against that sub-skill's folder; `references ./formchem backend | frontend one side ./formchem serve built frontend served by the engine (FORMCHEM_DIST) ./formchem doctor toolchain, installs and ports +./formchem convert IN OUT the conversion command line (also batch, descriptors, render; docs/CLI.md) ./formchem agents sync --check tools reference, skills mirror and agents/manifest.json in step cd frontend && npx tsc --noEmit type-check backend/venv/bin/python -m compileall -q backend/app setup diff --git a/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md index b0021068..d474d33a 100644 --- a/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/agents/SUB-SKILL.md @@ -1,52 +1,83 @@ --- name: agents -description: "FormChem's agent surface: the MCP server in the engine (Streamable HTTP at /mcp, TOOLS and t_ handlers, the approval gate, in-app trust, the formchem://guide resource), the command catalogue mirror and runner that lets agents run window commands such as insert-smiles, the stdio relay, ./formchem agents install and sync, agents/manifest.json, the client configs and the two skill packs. Use when adding or changing an MCP tool, when an agent is refused or trusted wrongly, when the catalogue is empty, when the server's guide text is out of date, when sync --check fails, or when editing the harness or skillset packs." +description: "FormChem's agent surface: the MCP server in the engine (Streamable HTTP at /mcp with the agent token, TOOLS and t_ handlers, the consent gate, in-app trust, the formchem://guide resource), the 0.8.0 agent tools (agent_out write_result and render through the window, agent_draw placement, agent_edits pure builders, agent_convert on the CLI runners), the agent call log (agent_log, AFTER_CHANGE, /api/agents, Agent Activity, the chip, Stop), the window tools render, selection and show, the command catalogue mirror and runner, the stdio relay, ./formchem agents install, sync and token, agents/manifest.json and the two skill packs. Use when adding or changing an MCP tool or edit builder, when an agent call does not undo in one step, is attributed wrongly, is refused or trusted wrongly, when render falls back, when the token or 401 misbehaves, when sync --check fails, or when editing the harness or skillset packs." --- # Agents ## Purpose -Give agents a small, honest tool surface that only describes what FormChem can do now, gates every change on the person's consent, and stays in step with its skills and manifest. +Give agents an honest tool surface that only describes what FormChem can do now, makes every change one undo step the person can see, check and stop, and stays in step with its skills and manifest. ## File map | Path | Role | | --- | --- | -| `backend/app/routers/mcp.py` | `VERSIONS`, `LEGACY`, `SERVER`, `INSTRUCTIONS`, `GUIDE` (`formchem://guide`), `TOOLS` (`_tool(...)` entries), `MUTATING`, `_mutating`, `_gate`, `_inapp`, `t_[name]` handlers collected into `HANDLERS`, `HANDOFFS`, `POST/GET/DELETE /mcp` | -| `backend/app/routers/commands.py` | `/api/commands`: `POST /catalogue` (from the window), `GET ""`, `GET /{id}`, `POST /run`, `POST /batch`, `POST /{id}`; `find`, `search`, `execute` (through `bridge.window_call("run_command")`) | -| `backend/app/services/consent.py` | `async def ask(agent_name, summary) -> bool`: asks the person in the window | -| `setup/mcp_stdio.py` | stdio relay to the HTTP server; starts the engine if needed; `DEFAULT_PORT = 8220`; forwards `FORMCHEM_INAPP_TOKEN` as the in-app header | -| `setup/agents.py` | `install [--dry-run]`, `sync [--check]`; `SKILLS`, `DOCK`, `DOCK_MODULE`, `LOOKUP_HASHES`; generates the harness `references/tools.md` from `TOOLS`; writes `agents/manifest.json` | -| `setup/catalogue.py` | `./formchem cli`: the catalogue and runner from a terminal, as the outside agent `formchem-cli` | -| `.mcp.json`, `.codex/config.toml`, `.cursor/mcp.json` | Repo configs (portable paths); `install` writes the same entries for the home and caller folders and Antigravity's `~/.gemini/config/mcp_config.json` | -| `.claude/skills/formchem-harness`, `formchem-skillset` | The packs; `.agents/skills` is a mirror written by sync. Both are made and repaired only through the god-tier-skill-creator pipeline, and its `scripts/validate_skill.py` reports zero FAIL before a commit | +| `backend/app/routers/mcp.py` | `VERSIONS`, `LEGACY`, `SERVER`, `INSTRUCTIONS`, `WORKFLOW`, `GUIDE` (`formchem://guide`), `DRAWING_FROM`, `TOOLS` (`_tool(...)` entries), `MUTATING`, `_mutating`, `_gate`, `_inapp`, `_authorised`, `_unauthorised`, `call_tool` (logs, refuses stopped agents) and `_dispatch`, `_doc_id`, `_show`, `_draw`, `_edit`, `_edit_doc`, `_apply`, the `t_[name]` handlers collected into `HANDLERS`, `HANDOFFS`, `POST/GET/DELETE /mcp` | +| `backend/app/services/agent_out.py` | `write_result` (the answer of every write), `render_image` (window first, engine fallback), `selection`, `structure_of`, `full_structures` (get_structure rows with the molfile), `engine_picture`, `free_spot`, `page_of`, `fragments_in`, `RenderError` | +| `backend/app/services/agent_draw.py` | `structure_ops` and `reaction_ops`: text to ops in free space (Insert Reaction's `scheme.insert_ops` for reaction SMILES), `DrawError` | +| `backend/app/services/agent_edits.py` | one pure builder per edit tool, `fn(doc, args) -> (ops, info)`, plus `listing` (get_atoms), `Target`, `locate_atom`, `locate_bond`, `remove_objects_ops`, `merge_ops`, `map_ops`, `fragment_diff_ops`, `EditError` | +| `backend/app/services/agent_convert.py` | `convert` and `batch_convert` on `services/batch.py` with the CLI's `Options`; never overwrite; `ConvertError` | +| `backend/app/services/agent_log.py` | the call log: `begin`, `end`, `summary`, `after_change` (on `store.AFTER_CHANGE`), `undoable`, `listing`, `clear`, the JSONL files | +| `backend/app/routers/agent_activity.py` | `/api/agents`: `GET /calls`, `POST /calls/clear`, `POST /calls/{id}/undo`, `POST /stop`, `POST /allow`, `GET /token` | +| `backend/app/core/agent_token.py` | `value`, `valid`, `path`: the token file `agent-token` in the data folder | +| `backend/app/services/consent.py` | `refusal`, `ask`, and from 0.8.0 `STOPPED`, `stop`, `resume`, `stopped` | +| `backend/app/routers/commands.py` | `/api/commands`: the catalogue mirror, `POST /state`, `execute` through `bridge.window_call("run_command")` | +| `frontend/src/app/agent-window.ts` | the window tools `render` (export renderer, own PNG rasteriser), `selection`, `show`, registered with `addWindowTool` (`app/window-tools.ts`) | +| `frontend/src/app/agent-calls.ts`, `app/agent-activity.ts`, `ui/agent-activity.ts`, `ui/agent-chip.ts`, `canvas/agent-marks.ts`, `styles/agent-activity.css` | the call log mirror, Agent Activity, the editing chip with Stop, the flash marks, the `agent-activity` command | +| `setup/mcp_stdio.py` | stdio relay; sends the token (or the in-app token), retries once on a fresh token, starts the engine if needed | +| `setup/agents.py` | `install [--dry-run]` (writes the token into the Claude Code HTTP entries), `sync [--check]`, `token`; generates the harness `references/tools.md` from `TOOLS`; writes `agents/manifest.json` | +| `setup/catalogue.py` | `./formchem cli`: the catalogue and runner from a terminal as the outside agent `formchem-cli`, with the token | +| `docs/AGENTS.md` | the public reference of every tool, the token and the call log | +| `.claude/skills/formchem-harness`, `formchem-skillset` | the packs; `.agents/skills` is a mirror written by sync. Made and repaired only through the god-tier-skill-creator pipeline; its `scripts/validate_skill.py` reports zero FAIL before a commit | -## Adding a tool +## The tool surface (0.8.0) + +42 tools: the six of the shell (`get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff`); the reaction tools of 0.5.0 and the analysis tools of 0.6.0 (owned by `reactions` and `stereo-and-queries`); and the 28 of 0.8.0: `list_open_documents`, `new_document`, `open_document`, `save_document`, `close_document`, `draw_from_smiles`, `draw_from_molfile`, `render`, `get_structure`, `validate`, `compute_properties`, `convert`, `batch_convert`, `get_atoms` and the 14 edit tools `add_atom`, `add_bond`, `set_charge`, `set_atom`, `set_stereo`, `replace_substructure`, `delete`, `move`, `scale`, `align`, `clean_layout`, `add_arrow`, `add_text`, `add_reaction`. `draw_from_name` waits for the naming decision (Q7 in the plan); do not add it early. + +## Laws of the agent tools + +1. **One call, one transaction.** Every writing tool builds its ops first, then applies them once through `_apply` (`STORE.apply(doc_id, tx, "agent", agent=name)`, no coalesce key), so one Undo removes the whole call and calls never merge. A builder that fails raises before anything is applied; a drawing the call created is closed again. +2. **Every write answers with the structure and a picture.** Return `agent_out.write_result(doc_id, tx, touched_ids, text, extra)`. Never build a write answer by hand: the rows come from the derived cache after the transaction (`derive_now`), and a picture failure leaves the image out instead of failing the write. +3. **Builders are pure.** An edit tool is `fn(doc, args) -> (ops, info)` in `agent_edits.py`, on a deep copy, with no store, window or I/O, raising `EditError` with the next step in its text. It runs in a thread; `_edit` does the rest. Mirror the window's own semantics (deleteSelectionOps, mapObject, scale.ts) rather than inventing new ones, and say in the HASHOUT log which window function it mirrors. +4. **Pictures come from the window.** `render_image` sends the document and derived cache to the window tool `render`; the engine draws only as a fallback (no window, error, 25 s) and every answer names its renderer. `render` and `selection` are in `bridge.READ_ONLY`; `show` is not. +5. **Place, do not cover.** New structures go through `agent_out.free_spot` (right of the content, else below; always below when the page has an arrow) unless the agent gave x and y; overlaps are reported as a note. +6. **Never destroy the person's work.** `save_document` refuses another existing file, `close_document` refuses unsaved changes, `convert` and `batch_convert` refuse existing files and non-empty folders. The refusal names the window action that lets the person do it. +7. **Gate every write.** A tool that changes what the person sees goes in `MUTATING`, or in `_mutating` when only some arguments write. Reading tools set `read=True` (readOnlyHint) and never ask. +8. **Same names as the spec, old names kept.** `validate` and `compute_properties` call the 0.6.0 handlers through `_same_as`; keep `check_structure` and `properties` for agents written against 0.6.0. -1. Add one `_tool(name, description, props, required, read=..., destructive=...)` to `TOOLS`. Props are literal dicts or module-level names, so `agents.py` can read them without running the server. -2. Add `async def t_[name](a, args) -> dict` returning `_ok(text, data)` or raising `ToolError` with a sentence that names the next step. -3. If it changes anything the person sees, add it to `MUTATING`, or to `_mutating` as `if name == "[name]": return ...` when only some arguments change things. Never skip the gate for outside agents. -4. Describe only what works now. A tool for a later phase lands in that phase. -5. Run `./formchem agents sync`, then `sync --check`, and commit `mcp.py` with the regenerated `references/tools.md`, the `.agents/skills` mirror and `agents/manifest.json`. +## The call log and Stop -## What agents can reach in 0.6.0 +- `call_tool` is the only entry: HTTP, stdio, in-app tabs and the chat panel (chat/tools.py) all pass through it, so a new tool is logged without code of its own. It refuses a stopped agent (`consent.stopped`) before `_dispatch`, and `_dispatch` tags gate refusals `_refused`. +- Attribution: `agent_log.begin` sets a contextvar that flows into `store.AFTER_CHANGE`, so direct writes are exact; a window command's `user` transaction goes to the single writing window-tool call running or ended within `SETTLE_SECONDS` (1.5). Keep new hooks on `AFTER_CHANGE` async and exception-safe; the store logs and ignores a failing hook. +- After every change, undo and redo the hook broadcasts `agentUndoable {doc, call}` for the call owning the top of the undo stack; `undone` is "in redo, or was undone and not back on the undo stack". The window offers Undo only where the engine says so, and `POST /calls/{id}/undo` answers 409 otherwise. +- Argument summaries hide keys matching `SECRET` and clip long text; never log raw arguments. +- `consent.stop` writes `agentsAllowed: false` and refuses reads too; `resume` lets the next change ask again. Stopped names live in memory for the engine run. + +## The agent token + +- `core/agent_token.py`: one line in `agent-token` in the data folder, mode 0600, made with O_EXCL by the engine at start or by `agents install`, cached by mtime, compared with `hmac.compare_digest`. +- `POST /mcp` and `DELETE /mcp` accept the token, a live in-app tab token or the window key; anything else is 401 with `WWW-Authenticate: Bearer realm="FormChem"` and JSON-RPC -32001. `/mcp` stays in `window_key.OPEN`. +- The stdio relay and `./formchem cli` read the file themselves; `agents install` writes it into the Claude Code HTTP entries; the Agents dialog fills it in from `GET /api/agents/token` (window key). Never put the token in a prompt, a log line, a handoff or a test fixture. + +## Adding a tool -- Fourteen tools: the six of the shell; `perceive_reactions` and `map_reaction` (in `MUTATING`, so gated) and `export_reaction` and `reaction_stoichiometry` (read-only), which call the reaction services and commit through `_apply` (`STORE.apply` with origin `agent`), owned by `reactions`; and the read-only analysis tools `properties`, `check_structure`, `stereo` and `substructure` (outside `MUTATING`, never asking), which reuse the analysis router's source rules through `_analysis_source` with a lazy import so mcp.py does not load RDKit at import, owned by `stereo-and-queries`. The other drawing tools of the plan (documents, `draw_from_smiles`, `get_structure`, `render`, edit ops, `convert`) land in 0.8.0; do not add them early or describe them as present. -- Agents change drawings today through `run_command` (every enabled command in the window's registry: `insert-smiles`, `undo`, `redo`, `select-all`, the save and close commands, `insert-template {id}`, the canvas, arrange and Reaction commands, `set-reaction-roles {role, objects}` and the 0.6.0 chemistry commands such as `assign-wedges`, `set-stereo-group-and`, `add-hydrogens` and `expand-abbreviation`) and through Form extensions, whose `document.read` and `document.apply` reach the active drawing (`extensions`). -- `INSTRUCTIONS`, `WORKFLOW`, `GUIDE` and the `get_context` text name the reaction tools, the analysis tools and the chemistry commands; `DRAWING_FROM = "0.8.0"` names when the atom and bond tools arrive. `get_context` lists the open drawings from `STORE.sessions` through `_documents()` (id, title, path, dirty, rev, fragment count, and the fragments' formulas joined with " + " from the derived cache when it matches `rev`, else `None`), as Documents lines and as `structuredContent.documents`. Keep that list read-only; after changing any of this text run sync so `references/tools.md` follows. -- `insert-smiles` takes an optional `smiles` param (`commands-shell.ts`, `DocumentActions.insertSmiles(given)`): with it the window inserts without the prompt, throws the parser's reason on failure (the agent gets it as the tool error) and returns a sentence naming the fragment ids and the drawing. -- A future engine-side agent write goes through `await STORE.apply(doc_id, tx, "agent", agent=name)` and catches `ops.OpError`, so it is one undo step with origin `agent`, autosaved at once and broadcast to every window. +1. Add one `_tool(name, description, props, required, read=..., destructive=...)` to `TOOLS`. Props are literal dicts or module-level names (`_DOC`, `_IDS`), so `agents.py` can read them without running the server. Describe only what works now. +2. Add `async def t_[name](a, args) -> dict`. Resolve the drawing with `_doc_id` (or `_edit_doc`); for a write, build ops in a thread and return `write_result`; for a read, return `_ok(text, data)`. Raise `ToolError` with a sentence that names the next step. +3. Gate it (`MUTATING` or `_mutating`). Give it an undo label the person will read in Edit > Undo, in the window's own words where a command exists. +4. Update `INSTRUCTIONS`, `WORKFLOW` and `GUIDE` when the tool changes how an agent should work. +5. Run `./formchem agents sync`, then `sync --check`, and commit `mcp.py` with the regenerated `references/tools.md`, the `.agents/skills` mirror and `agents/manifest.json`. Update `docs/AGENTS.md` and the harness sub-skill that routes to the tool. ## Rules - Agents in FormChem's own tabs send a live tab token in `x-formchem-inapp` and are never asked; everyone else goes through `consent.ask`. A refusal returns a sentence, never an exception. -- Window-only abilities are window tools over `/api/live` through `bridge.window_call`; the engine never fakes a window answer. +- Window-only abilities are window tools over `/api/live` through `bridge.window_call`, added with `addWindowTool` in the module that owns them; the engine never fakes a window answer. Window tool answers go to agents and need no i18n keys. +- The window's agent UI patches keyed nodes (`patchList` rows, a `Keyed` marks layer); never rebuild the panel or the chip to change one call. - The `handoff` live message is `{t: "handoff", agent, state, note, at}`; a window asks for the current list with `{t: "handoffs"}`. -- The manifest and `references/tools.md` of formchem-harness are generated by `setup/agents.py`, never edited by hand; the generator writes the tools reference's `## Contents` list, which the skill validator requires past 100 lines. +- The manifest and `references/tools.md` of formchem-harness are generated by `setup/agents.py`, never edited by hand. ## Gate -- [ ] `backend/venv/bin/python -m compileall -q backend/app setup` is clean. +- [ ] `backend/venv/bin/python -m compileall -q backend/app setup` is clean and `cd frontend && npx tsc --noEmit` shows no new errors. - [ ] `python3 setup/agents.py sync --check` prints "agents: in step". -- [ ] A scratch FastAPI app with the router answers `initialize` and `tools/list`, and the new tool returns its text. +- [ ] A scratch engine (`FORMCHEM_DATA_DIR` in a scratch folder) answers `initialize` and `tools/list` with the token and 401 without it; a new writing tool raises the revision by exactly one and its answer carries `undo: "one step"` and an image; `GET /api/agents/calls` lists the call with its `tx`. diff --git a/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md index 20e43a6d..cd2b126c 100644 --- a/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/canvas/SUB-SKILL.md @@ -23,7 +23,10 @@ Let the person draw at the speed of thought while the document stays the only tr | `frontend/src/ui/tool-rail.ts` | The tool rail, flyouts and tool commands (`tool-select` and the rest); from 0.5.0 also the arrow (W), symbol (P), bracket (K), shape (G), table, TLC, image and orbital (O) groups | | Stereo and query marks (0.6.0) | `render/marks-layer.ts` (`ChemMarks`, one keyed layer cached per fragment; replaced `render/stereo.ts`), `marks-stereo.ts`, `marks-query.ts` and `canvas/marks-options.ts` belong to the `stereo-and-queries` specialist; the view toggles reach the renderer through `RenderDisplay.enhancedStereo`, `queryMarks` and `groupColours` | | Drawn objects (0.5.0) | The object kind registry (`render/objects.ts` and one module per kind), `hit-objects.ts`, the annotation tools, `tools/handles.ts` and `app/object-commands.ts` belong to the `annotations` specialist; load it for anything that is not atoms, bonds, labels or text | -| `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | Canvas styles, `@font-face` for the bundled fonts, the document grid on the paper | +| `canvas/dark-page.ts` (0.7.0) | `darkPageOn`, `setDarkPage`, `onDarkPage`, `initDarkPage` (the zero-size defs svg with the `#fc-page-undark` colour matrices); state is `data-page-dark` on the root, set before first paint in `index.html`, key `formchem.darkPage` | +| `canvas/grid.ts`, `canvas/grid-layer.ts` (0.7.0) | Lattices, `docSpec` (read straight from `doc.style.grid`), the window default and snap state in localStorage, `snapStart`, `snapPoint`, `latticeDirections`, `snapRingCentre`; `GridLayer` and `planGrid` draw one svg inside the paper as page-sized paths (patterns only for dots and crosses) | +| `canvas/tools/scale.ts` (0.7.0) | `scaleSelection` (positions, sizes and, with Scale Labels on, per-object style overrides; residue-free), `scaleHandles`, `scaleHandleAt`, `scaleFromDrag`; the select tool's `scale` mode; the readout is one node patched by `view.setReadout` | +| `styles/canvas.css`, `styles/canvas-view.css`, `styles/tool-rail.css`, `public/fonts/` | Canvas styles, `@font-face` for the bundled fonts, the dark page filter (inside `@media screen`) | | `references/hover-keys.md` | The hover and tool key map with routing rules. Open before adding or changing a key | ## Laws on the canvas @@ -38,6 +41,10 @@ Let the person draw at the speed of thought while the document stays the only tr **Geometry rules.** Points, y down, angles counter-clockwise as seen; the default bond length is 14.4 pt and the chain angle 120 degrees. Free drags snap to 15 degrees, growth from a bonded atom to 30 degree steps; Alt is free. +**The dark page filters whole boxes (0.7.0).** WebKit ignores CSS filter functions on SVG children, so the dark page puts `invert(0.9) hue-rotate(180deg)` on `.fc-canvas-paper` and the whole `.fc-canvas-svg`, and the selection, hover, warning and preview layers live in the sibling unfiltered `svg.fc-canvas-marks` with the same transform. Never move a coloured mark back into the drawing svg, never put a filter function on an SVG child (pictures use the `#fc-page-undark` url filter), and never let an export read the live canvas (`formats-and-export`). + +**Snapping and scaling (0.7.0).** Snapping keeps bond geometry on square grids and lands lattice atoms on isometric and hex grids at the bond length; `Alt` bypasses everywhere, `Shift` keeps its constraint meaning, scale corners and rotation never snap. Scaling is uniform from the corners only, one transaction on release, Escape cancels; Scale Up and Scale Down are exact inverses. Zoom never changes the drawing. + **The document is the state.** Selection and hover live in the view; everything else is read from `client.view` (the mirror with any preview applied). Implicit hydrogens and double bond sides come from local rules until `derived` for the current revision arrives (`chemistry-engine`). ## Adding a tool diff --git a/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md index 12b5a79d..e16e9fbc 100644 --- a/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/chemistry-engine/SUB-SKILL.md @@ -1,6 +1,6 @@ --- name: chemistry-engine -description: "FormChem's chemistry: the RDKit service in backend/app/services/chem (conversion from fragments, sanitising, valence, aromaticity, stereo and CIP, canonical SMILES, CXSMILES, InChI and InChIKey, Hill formula, masses, m/z, elemental analysis, isotope pattern, 2D clean-up and layout with CoordGen, file reading and writing through RDKit and Indigo), the /api/chem routes, the derived cache broadcast after every transaction, and the window's local valence, ring and label rules in frontend/src/chem. Use when a computed value is wrong, a warning or valence error appears or is missing, a structure file reads upside down or loses atoms, a layout moves the wrong atoms, or a new chemistry computation is added." +description: "FormChem's chemistry: the RDKit service in backend/app/services/chem (conversion from fragments, sanitising, valence, aromaticity, stereo and CIP, canonical SMILES, CXSMILES, InChI and InChIKey, Hill formula, masses, m/z, elemental analysis, isotope pattern, 2D clean-up and the scored layout: CoordGen and RDKit candidates, layout_score and layout_refine), the /api/chem routes, the derived cache broadcast after every transaction, and the window's local valence, ring and label rules in frontend/src/chem. Use when a computed value is wrong, a warning or valence error appears or is missing, a structure reads upside down or loses atoms, a layout is crowded, crosses bonds or moves the wrong atoms, or a new chemistry computation is added." --- # Chemistry engine @@ -18,8 +18,9 @@ Compute everything chemical in one place, from the drawing as the person drew it | `chem/perceive.py` | `prepare(frag)` (sanitised plus stereo; every other module starts here), `perceive(frag)` (implicit H, valence errors, aromatic rings, CIP, warnings), `allowed_valences`, `explicit_valence` | | `chem/ids.py` | `smiles`, `cxsmiles`, `inchi` (standard only), `formula` (Hill, own writer), `component_formulas`, `identifiers(conv)` | | `chem/mass.py` | `average_mass`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `isotope_pattern`, `properties(conv)` | -| `chem/layout.py` | `compute_coords(frag, ids, bond_length, fixed)` (CoordGen, RDKit fallback), `clean(frag, ids)`, `restereo(frag, coords)` (wedge fixes after a move) | -| `chem/io.py` | `detect`, `read_text`, `read_file` (`ParseResult` with fragments, warnings, reaction), `export`, `to_molfile`, `to_smiles`; SDF, RXN, reaction SMILES, CML, cdxml and cdx (Indigo), InChI; at most 1000 records per call | +| `chem/layout.py` | `depict(mol, reference)` (the scored candidates, returns the chosen Score), `compute_coords(frag, ids, bond_length, fixed)`, `clean(frag, ids)`, `restereo(frag, coords)` (wedge fixes after a move), `score_fragment` | +| `chem/layout_score.py`, `chem/layout_refine.py` (0.7.0) | `shape`, `evaluate`, `score_mol`, `Score` (hard terms close, cross, near, label; a soft tie-breaker; `crowded` atoms); `refine` (swing or mirror crowded acyclic branches) | +| `chem/io.py` | `detect`, `read_text`, `read_file`, `read_bytes` (`ParseResult` with fragments, objects, reaction, reactions, warnings, report); at most 1000 records per call. From 0.7.0 the formats table, writers, report items, CDXML and CDX through Indigo, RD files, CML and the stream reader belong to `formats-and-export` and `command-line` | | `chem/abbrev.py` | 106 built-in abbreviations in six categories plus the person's `abbreviations.json`; `resolve`, `element_like`, `reversed_label`, `library`, `match` | | `chem/derive.py` | `derive_fragment(frag, expansions, rev)`, `derive_document(doc, rev, only)`, `content_key`, an LRU cache of 2048 fragments | | `backend/app/routers/chem.py` | `POST /api/chem/parse`, `/derive`, `/layout`, `/convert`, `/properties`; 422 for bad input, 413 over 20 MB of text, at most 5000 atoms | @@ -37,6 +38,7 @@ Compute everything chemical in one place, from the drawing as the person drew it - **One converter.** Every computation enters RDKit through `convert.to_mol` (atoms and bonds in sorted id order, bond begin = `a`), so indices are stable between conversions and the wedge's narrow end is RDKit's begin atom. Do not build an `RWMol` anywhere else. - **Coordinates and the y axis.** FormChem pages are points with y down; molblocks and RDKit conformers have y up. `to_mol` scales to a 1.5 unit median bond and negates y; `from_mol` scales back to the requested bond length, negates y and puts the top-left at `origin` (default 72, 72). A structure that imports upside down has lost one of those negations. Imports never keep foreign absolute positions. - **Layout keeps its place.** `compute_coords` and `clean` fit the result back onto the old positions (rotation plus translation; `clean` may mirror), keep fixed atoms exactly, and return wedge swaps in `stereo` that the caller applies in the same transaction as the moves. +- **Layout is scored (0.7.0).** `depict` tries CoordGen, RDKit native with and without ring templates, native with sampled rotatable-bond flips (up to 150 atoms) and straightened copies, scores each with `layout_score.evaluate` (coordinates scaled to a median bond of 1; the label boxes follow the renderer's default journal style) and keeps the first, in that order, within 0.5 of the lowest total, so CoordGen stays the house style. `refine` then rotates crowded branches by 12, 24 or 36 degrees or mirrors them, keeping hinge angles of at least 60 degrees (45 at a four-connected hinge), every E/Z and every fixed atom; work is capped by a count of evaluations, never a clock, so results are deterministic. Above 300 atoms it is plain CoordGen; `score_fragment` is null above 600. Ring systems are never moved, so bridged polycycles such as morphine can still cross. Clean Up passes `reference` and takes the candidate nearest the drawing among those with the lowest hard penalty. A layout change must keep every CIP label and the canonical SMILES; check Taxol (score 10.14 to 0.68), erythromycin and vancomycin, and that benzene, aspirin and cholesterol stay byte-identical. - **Warnings, not exceptions.** Sanitising never throws; problems become warnings naming atoms and bonds, valence problems become `valence_errors`, and any exception for a fragment becomes `engine_error` with empty values. Metals are never flagged. - **Window guesses are temporary.** The window draws at once from its default-valence table and ring perception, then uses `derived` only when `derived.rev` equals the client's `rev`. Do not add a third local implementation; extend the engine and let the derived cache carry it. - **Libraries.** RDKit (BSD-3-Clause) and Indigo (Apache-2.0) are already in `NOTICE.md` and in `MODULES` of `backend/formchem_engine.py`; anything else needs a `NOTICE.md` row first. File formats come from public specifications and open implementations only (`clean-room`). diff --git a/.claude/skills/formchem-skillset/sub-skills/clipboard/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/clipboard/SUB-SKILL.md new file mode 100644 index 00000000..d5d1806e --- /dev/null +++ b/.claude/skills/formchem-skillset/sub-skills/clipboard/SUB-SKILL.md @@ -0,0 +1,48 @@ +--- +name: clipboard +description: "FormChem's clipboard from 0.7.0: the native payload and paste plan (clip-data.ts extractClip, pastePlan with fresh ids and remapped references), text formats out and in (clip-formats.ts), the clipboard flavours and platform fallbacks (clip-system.ts), pictures with their drawing (clip-picture.ts), the controller with Copy, Cut, Paste, Copy As and Paste Special (clipboard.ts), Duplicate and File > Import on the same plan, the macOS system Edit items and the desktop clipboard access. Use when Copy or Paste loses something, a paste lands in the wrong place or with the wrong look, a flavour is missing on a platform, a keyboard shortcut does nothing on the canvas, or a new Copy As format is added." +--- + +# Clipboard + +## Purpose + +Copy and paste drawings between FormChem windows without losing anything, and with other programs in the forms they understand, on every platform's webview. The person's keyboard path must never hit a permission prompt. + +## File map + +| Path | Role | +| --- | --- | +| `frontend/src/app/clip-data.ts` | `extractClip(doc, page, selection)` (a mini document.json that passes `validate`, with style, expansions, media records, R-group definitions and reaction steps filtered to what was copied, `meta.clipboard`), `pastePlan(target, page, clip, {at, keepStyle, media, offset})` (translate, fresh ids, remap every reference, style difference into each object's `style`), `CLIP_MIME`, `CLIP_KIND` | +| `app/clip-formats.ts` | `clipText(clip, format)` through `POST /api/chem/export` (older routes only on 404 or 405); `parseClipText(text)`: native JSON, reaction text, everything `/api/chem/parse` reads, then SMARTS; `looksLikeName` | +| `app/clip-system.ts` | `writeClipboard(sync, rich, event)`, `readClipboard`, `flavoursOfTransfer`, `htmlFlavour`, `WEB_CLIP_MIME`, `HTML_SOURCE_ATTR` | +| `app/clip-picture.ts` | Copy as SVG and PNG through `picture.ts`; `sourceOfPicture` through `embedded-source.ts` (`formats-and-export`) | +| `app/clipboard.ts` | `mountClipboard`: the copy, cut and paste events (and `beforecopy`, `beforecut`, `beforepaste`), the commands `copy-*` and `paste-special`, `insert(clip, {label, keepStyle, spot, alsoSelect})` for File > Import | +| `ui/paste-special-dialog.ts`, `styles/clipboard.css` | Paste Special | +| `app/commands-shell.ts`, `app/menus.ts` | `cut`, `copy`, `paste` fall back to text fields, else call the canvas; Copy As and Paste Special in Edit | +| `ui/native-menu.ts` | `ALWAYS_NATIVE`: Cut, Copy, Paste and Select All are predefined system items on macOS | +| `src-tauri/src/main.rs` | `.enable_clipboard_access()` on every window (WebKitGTK and WebView2) | + +## Rules + +- **One payload.** The native clipboard form is document.json under `application/x-formchem+json`, the same payload pictures embed, so clipboard, pictures and File > Import paste through one reader and one plan. +- **Fresh ids, every reference remapped.** Bond ends, stereo groups, R-group members and attachments, caption targets, arrow anchors, bracket atoms, orbital atoms, table cells, stoichiometry, group children and reaction members. Expansions are reused when identical, kept when free, renamed otherwise. A picture whose bytes cannot be found is left out, never left pointing at nothing. +- **Keep the look.** Native data carries the source style; the plan writes the difference from the target's style into each pasted object's `style`. Text formats take the target's bond length and style. +- **Keyboard through events, menus through the API.** Keyboard copy and paste answer the DOM events, which carry every flavour without a prompt; the menu commands use `navigator.clipboard` (a click is a gesture). The capture keydown listener stops the app's own dispatch of Mod+C, X, V but never prevents the default. +- **Synchronous flavours first.** Write text/plain SMILES, text/html with the payload and the custom type into the copy event, then everything through one `ClipboardItem` whose values are promises, so WebKit keeps the user activation while the engine and renderer work. Keep only types `ClipboardItem.supports` accepts and retry with basic types. +- **The HTML picture is the real carrier.** Chromium re-encodes clipboard PNGs (the iTXt chunk is lost) and sanitises SVG (metadata and fonts dropped); the `data-formchem-source` attribute and the PNG data URL survive. Do not rely on PNG or SVG chunks on the clipboard. +- **Names are not read** (plan Q7): name-like text pastes as a text object with a note. Do not add name lookups through an outside service. +- **One undo step per paste**, the pasted items selected; Duplicate is `extractClip` plus `pastePlan` with a 10 pt offset. + +## Adding a Copy As format + +1. The engine must write it through `writers.export_fragments` (`formats-and-export`). +2. Add the `copy-[format]` command in `clipboard.ts` with its label through `t()` and an English description for agents, and the id in `app/menus.ts` Copy As. +3. Make `parseClipText` recognise it, or say in the description that it does not paste back. + +## Gate + +- [ ] Copy Taxol, paste into a new drawing: same canonical SMILES and CIP labels, one undo removes it. +- [ ] Each Copy As format reads back as text; each text format pastes; Copy as SVG and as PNG paste back as the drawing in Chromium. +- [ ] A structure copied from a 14.4 pt drawing into a 30 pt one keeps its size and line widths. +- [ ] No permission prompt on `Ctrl+V` in Chromium; WebKitGTK paste works with clipboard access on. diff --git a/.claude/skills/formchem-skillset/sub-skills/command-line/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/command-line/SUB-SKILL.md new file mode 100644 index 00000000..f2364410 --- /dev/null +++ b/.claude/skills/formchem-skillset/sub-skills/command-line/SUB-SKILL.md @@ -0,0 +1,50 @@ +--- +name: command-line +description: "FormChem's conversion command line and batch services from 0.7.0: ./formchem convert, batch, descriptors and render (backend/app/cli.py, setup/convert), the runners in services/batch.py, the one stream reader (chem/stream.py iter_records, convert, explain), the record adapter (chem/records.py), the Standardise pipeline shared with the window (chem/standardise.py, /api/analysis/standardise, the Standardise dialog and command), RDKit drawing for render (chem/depict.py) and props.measure. Use when a conversion is slow, wrong or stops on a bad record, a failure reason is unhelpful, a CLI option or format is added, standardising gives a different result in the window and the CLI, or the 0.8.0 convert and batch_convert MCP tools are built." +--- + +# Command line, batch and Standardise + +## Purpose + +Convert, describe, draw and standardise whole files of structures quickly, record by record, without opening the window, and give the window's Standardise the same pipeline. `docs/CLI.md` in the repository is the public reference with timings. + +## File map + +| Path | Role | +| --- | --- | +| `backend/app/cli.py` | argparse front end, `USAGE`; started as `python -m app.cli` from `backend/`; paths relative to `FORMCHEM_CALLER_DIR` | +| `setup/convert`, `setup/convert.bat`; `formchem`, `formchem.bat` | Launchers for `convert`, `batch`, `descriptors`, `render`; the `.bat` passes `%*` untouched so comma lists survive | +| `backend/app/services/batch.py` | `convert_file`, `batch`, `descriptors_file`, `render_file`, `Options`, `Summary`, `BadArguments`, `write_report`; chunking and the process pool | +| `chem/stream.py` | `iter_records(path or text or file, fmt)` yielding `Record(index, mol, name, block, error)` for SD, molfile, SMILES, CXSMILES, InChI and RD files (gzip read transparently, `#` lines skipped); `convert(source, to, out, fmt, limit)`; `explain(parse)` for RDKit's own reason | +| `chem/records.py` | `parse_chunk`, `document`, `write_document`, `mol_text`, `reaction_text`: records to the writers and to `.fchem` | +| `chem/standardise.py` | `STEPS`, `DEFAULT`, `ALIASES`, `run(mol, steps, track)`, `_fragment_ops` (write-back as one transaction) | +| `routers/analysis.py` | `GET` and `POST /api/analysis/standardise` (`standardise_steps`, `standardise_structures`) | +| `frontend/src/engine/standardise-api.ts`, `ui/standardise-dialog.ts`, `app/standardise-command.ts` | The window client, the dialog with its preview, the `standardise {steps?}` command | +| `chem/depict.py` | `svg`, `png`, `Style`: RDKit MolDraw2D set close to the journal style | +| `chem/props.py` | `measure(mol)`: the Analysis panel's values without a drawing | + +## Rules + +- **One reader.** Batch work reads through `stream.iter_records` only and never builds drawable fragments (about 1 ms a record, ten times the cost). Do not add a second SD or SMILES splitter. +- **Failures never stop a run.** Each failed record keeps its index (counted from 1 for people) and name, and its reason is RDKit's own message through `explain`. `explain` swaps `sys.stderr` process-wide for a moment: fine in the CLI and single calls, not in the engine's thread pool. +- **Order and exit codes.** Output order equals input order with any `--jobs`. Exit 0 when something was written, 1 when nothing was (and no empty file is left), 2 for bad arguments, 130 for Ctrl+C. +- **Pool only when it pays.** Inputs split into chunks of 1000 records; the pool starts at two chunks or more. Worker functions stay module-level and picklable for the spawn start method of macOS and Windows. +- **Standardise is one pipeline.** Steps always run in the fixed order of `STEPS`, whatever order is given; each reports changed, a detail or its error, and a failing step is skipped. The window and the CLI call the same `run`, so they cannot disagree. The tautomer step keeps sp3 and double bond stereo. In the window, write-back is one transaction checked against fragments changed meanwhile. +- **Same output for the MCP tools.** The 0.8.0 `convert` and `batch_convert` tools must call `batch.convert_file` and `batch.batch`, not their own code. +- **`./formchem batch` is not `./formchem cli batch`.** Keep the two apart in usage text and docs. +- **Render is not the window's drawing.** `depict.py` uses RDKit's own label, wedge and double bond placement; File > Export is the faithful picture. +- **Spelling.** The UI says Standardise (the app is British); the CLI accepts `--standardise` and `--standardize` and the -ize step names through `ALIASES`. + +## Adding an option or a format + +1. Add the option to `cli.py` and carry it in `batch.Options`; a format must read through `stream.iter_records` or write through `records` or `writers.export_fragments`. +2. Update `USAGE`, the `./formchem` and `formchem.bat` usage lines, `docs/CLI.md` and the wiki page Command-Line. +3. Time it on a 10,000-record SD file outside the repository, with and without `--jobs 2`, and compare the outputs byte for byte. + +## Gate + +- [ ] 10,000 SD records to SMILES in under 10 s with failures reported per record (about 1.4 s on two cores). +- [ ] Output with `--jobs 2` is byte-identical to one process. +- [ ] Standardise in the dialog and `./formchem convert --standardise` give the same SMILES for sodium benzoate, a glycine zwitterion and 2-hydroxypyridine with the tautomer step. +- [ ] `backend/venv/bin/python -m compileall -q backend/app setup` is clean. diff --git a/.claude/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md index 0bd95c76..2006b054 100644 --- a/.claude/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/desktop/SUB-SKILL.md @@ -1,20 +1,22 @@ --- name: desktop -description: "FormChem's Tauri 2 desktop shell: tauri.conf.json, the Rust entry point and its modules (engine start, splash-to-window reveal, macOS traffic lights in the overlay title bar, the Windows job object), the frozen engine sidecar formchem-engine built with PyInstaller, the updater, and the desktop scripts. Use when the desktop app will not start, the engine sidecar fails or keeps running, the title bar row or traffic lights are wrong, the splash hangs, or a desktop build or updater setting changes." +description: "FormChem's Tauri 2 desktop shell: tauri.conf.json and tauri.macos.conf.json, the Rust entry point and its modules (engine start from the macOS engine folder or the sidecar, packaged.rs, splash-to-window reveal, macOS traffic lights, the Windows job object, clipboard access), the frozen engine formchem-engine built with PyInstaller (a flattened one-folder on macOS, one file elsewhere), the Tauri CLI pin, the updater and the desktop scripts. Use when the desktop app is slow to open or will not start, the engine fails or keeps running, a frozen build misses a module or data folder, the title bar or traffic lights are wrong, the splash hangs, or a desktop build or updater setting changes." --- # Desktop ## Purpose -Wrap the same window and engine in a native app: a thin Rust shell that starts the frozen engine as a sidecar, reveals the window without a flash, and stops the engine with the app. +Wrap the same window and engine in a native app: a thin Rust shell that starts the frozen engine (a folder inside the app on macOS, a sidecar elsewhere), reveals the window without a flash, and stops the engine with the app. ## File map | Path | Role | | --- | --- | | `src-tauri/tauri.conf.json` | productName FormChem, identifier `ai.nodemode.formchem`, `externalBin binaries/formchem-engine`, bundle resources (LICENSE, NOTICE.md, THIRD-PARTY-NOTICES.txt), updater endpoint `https://dl.formai.studio/formchem/updates/latest.json`; the version formcompiler reads | -| `src-tauri/src/main.rs` | App setup, windows, commands (`app_ready` among them); starts the sidecar with `FORMCHEM_PORT=0`, `FORMCHEM_PORT_PREFER=8221` and `FORMCHEM_WINDOW_KEY_STDOUT=1`, reads `formchem-window-key: ` from its stdout and injects `__FORMCHEM_WINDOW_KEY` into the page | +| `src-tauri/tauri.macos.conf.json` | macOS only: `externalBin: []` and the resource `"engine": "engine"`, so `src-tauri/engine` lands in `Contents/Resources/engine` | +| `src-tauri/src/packaged.rs` | `engine_folder()`: `[exe dir]/../Resources/engine/formchem-engine` (the bundle) or `[exe dir]/engine/formchem-engine` (`tauri dev`), else None and the shell uses the sidecar | +| `src-tauri/src/main.rs` | App setup, windows, commands (`app_ready` among them); `.enable_clipboard_access()` in `chrome()`; starts the engine folder through `shell().command(program)` or the sidecar with `FORMCHEM_PORT=0`, `FORMCHEM_PORT_PREFER=8221` and `FORMCHEM_WINDOW_KEY_STDOUT=1`, reads `formchem-window-key: ` from its stdout and injects `__FORMCHEM_WINDOW_KEY` into the page | | `src-tauri/src/engine_start.rs` | Start helpers: waits for the address and the key, `FORMCHEM_SHELL_PID`, the data folder and engine log path, the failure sentence shown to the person | | `src-tauri/src/reveal.rs` | Splash to window: the page calls `app_ready` with its background colour once painted; the splash closes after `window.formchemSplashDone()` | | `src-tauri/src/traffic_lights.rs` | macOS overlay title bar: traffic lights placed in the 38 px title row | @@ -22,12 +24,25 @@ Wrap the same window and engine in a native app: a thin Rust shell that starts t | `src-tauri/Cargo.toml`, `Cargo.lock`, `capabilities/`, `Info.plist`, `entitlements.plist`, `flatpak/` | Crate, permissions, macOS plist and entitlements, Flatpak manifest and AppStream metainfo | | `backend/formchem_engine.py` | Frozen engine entry; `--selfcheck`; `MODULES` (fastapi, uvicorn, keyring, rdkit, indigo) | | `setup/freeze_backend`, `setup/install_desktop`, `setup/desktop_dev`, `setup/desktop_build`, `setup/desktop_check`, `build_app` (each with a `.bat` twin) | Freeze, toolchain, dev run, build, checks | +| `setup/lib.sh` | `fc_engine_folder` (copy to `src-tauri/engine`, flatten, sign, `--selfcheck`), `fc_flatten_engine`, `fc_sign_engine`; shared by `freeze_backend` and `build_app` | ## Rules - The window is the same `frontend/dist`; desktop-only behaviour is detected (`inTauri()`), never forked into a second UI. - macOS: overlay title bar with a hidden title; the pre-paint boot sets `has-overlay-titlebar` so the row never jumps from 44 to 38 px. Native menus unless Menus in Window is on. -- The sidecar binary name is `formchem-engine` (plus the target triple in `src-tauri/binaries/`); RDKit and Indigo are collected whole when freezing. +- The engine is `formchem-engine` everywhere: the sidecar (plus the target triple in `src-tauri/binaries/`) on Linux and Windows, the program inside `src-tauri/engine` on macOS. RDKit and Indigo are collected whole and fontTools' submodules collected when freezing. +- A frozen module or data folder must be added to `setup/freeze_backend`, its `.bat` twin and `build_app`'s own PyInstaller call, which runs separately: entries 98 and 117 of the backend log record two misses of this kind. + +## The one-folder engine on macOS + +A PyInstaller one-file engine unpacks everything (several hundred MB, over 400 libraries) into a new temporary folder at every launch, and macOS scans each new library again: the owner's app took about 30 seconds to open. On macOS the engine is frozen `--onedir`, copied to `src-tauri/engine` and shipped as a resource, so it is unpacked once, at install (on Linux the frozen start went from 1.5 s to 0.55 s; not yet measured on a Mac). Rules: + +- **Flatten before bundling.** A bundle resource may hold no symbolic links and no `.framework`: `fc_flatten_engine` replaces links with copies and `_internal/Python.framework` with a plain `_internal/Python`. `desktop_check` fails on a folder with either, or without the program. +- **Sign every Mach-O** when `APPLE_SIGNING_IDENTITY` is set (PyInstaller's `--codesign-identity` plus `fc_sign_engine` for what it left); releases are signed by formcompiler. +- **Pipes under pipefail** use `grep ... >/dev/null`, never `grep -q`, because an early exit turns a match into a failure. +- On macOS `cargo check`, `cargo build` and `tauri dev` need `src-tauri/engine`; `desktop_dev` freezes when it is missing. `clean` and `build_app --clean` remove it; `.gitignore` lists it. +- Linux and Windows stay one-file until a real bundle test: Linux packages put resources in `/usr/lib/FormChem/` away from the program, so `engine_folder` would need a third place. +- The splash floor `SPLASH_MIN` (2.6 s, `reveal.rs`) runs alongside the engine start; lower it only together with the bar animation in `public/splash.html`. - Releases are built by formcompiler from `tauri.conf.json`; do not hand-build release artifacts. - Do not run cargo build, tauri build or pyinstaller on a shared or small machine unless the task says so. @@ -35,10 +50,11 @@ Wrap the same window and engine in a native app: a thin Rust shell that starts t `@tauri-apps/cli` is a pinned dev dependency in `frontend/package.json` (2.12.6). The rule: its major.minor equals the `tauri` crate's in `src-tauri/Cargo.lock` (2.12.7), and each `@tauri-apps/plugin-*` package shares major.minor with its `tauri-plugin-*` crate; bump them together in one change, with `package-lock.json`. Tauri refuses to build across minor versions. Until 0.6.0 package.json did not list the CLI, so `npm ci` installed no `tauri` binary and `./build_app` stopped with "the Tauri CLI did not install"; with the pin, the owner's `./build_app` on macOS arm64 (Python 3.14) built the app. -`build_app` checks in order: the system (Xcode Command Line Tools, or WebKitGTK 4.1 on Linux), Python 3.12 or newer, Node 20.19 or newer, one Rust install matching the machine, `THIRD-PARTY-NOTICES.txt`, the engine and window packages (reinstalled when their lock or the toolchain changes), the Tauri CLI binary and the version rule above, then builds the window, freezes the engine with the window, the notices and `backend/app/data/templates` (`--add-data`, the same as `setup/freeze_backend`), runs the frozen engine's `--selfcheck`, and bundles. A data folder the engine reads when frozen must be added to both `build_app` and `setup/freeze_backend` (and its `.bat`), or the desktop app ships without it. +`build_app` checks in order: the system (Xcode Command Line Tools, or WebKitGTK 4.1 on Linux), Python 3.12 or newer, Node 20.19 or newer, one Rust install matching the machine, `THIRD-PARTY-NOTICES.txt`, the engine and window packages (reinstalled when their lock or the toolchain changes), the Tauri CLI binary and the version rule above, then builds the window, freezes the engine with the window, the notices and `backend/app/data/templates` (`--add-data`, the same as `setup/freeze_backend`), runs the frozen engine's `--selfcheck` (on macOS through `fc_engine_folder` in a subshell that sources `setup/lib.sh`), and bundles. A data folder the engine reads when frozen must be added to both `build_app` and `setup/freeze_backend` (and its `.bat`), or the desktop app ships without it. ## Gate - [ ] `./formchem desktop check` passes (rustc and cargo agree, Tauri CLI readable, CLI and crate share major.minor). - [ ] The desktop dev run opens the window without a white flash and the engine answers `/api/health` on its port. - [ ] Quitting the app ends the engine process on every platform touched. +- [ ] On macOS: `src-tauri/engine` has the program, no symbolic link and no `.framework`, and `otool -L` finds nothing linking `Python.framework`. diff --git a/.claude/skills/formchem-skillset/sub-skills/formats-and-export/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/formats-and-export/SUB-SKILL.md new file mode 100644 index 00000000..89c75ae7 --- /dev/null +++ b/.claude/skills/formchem-skillset/sub-skills/formats-and-export/SUB-SKILL.md @@ -0,0 +1,55 @@ +--- +name: formats-and-export +description: "FormChem's exchange layer from 0.7.0: the formats table (formats.py), report items (report.py), the readers (io.py, cdxio.py through Indigo's KET JSON, rdfio.py, cml.py) and writers (writers.py), the export, parse, import and file write routes, picture export (picture.ts offscreen, PNG rasterising, the engine's own PDF and EPS writer with fontTools), the drawing embedded in SVG, PNG, PDF and EPS, the shared save path, print, the import report and File > Import. Use when a file opens wrong or loses something, an export report is missing or wrong, a format is added, a picture export looks different from the canvas, a picture will not reopen as a drawing, saving fails in the desktop app, or File > Import places or limits files wrongly." +--- + +# Formats and export + +## Purpose + +Move drawings in and out of FormChem without losing anything silently. Every reader and writer says what it changed or left out with a report item, every picture carries the drawing so it opens again, and the desktop shell saves through one guarded path. `docs/FORMATS.md` in the repository is the public description; this file is the developer's map. + +## File map + +| Path | Role | +| --- | --- | +| `backend/app/services/chem/formats.py` | `TABLE` (one record per format: id, name, extensions, mime, read, write, binary, multi, reactions, options, `loses`, `loses_v2000`), `FEATURES`, `ALIASES`, `get`, `by_extension`, `loses`, `describe` (served by `GET /api/formats`) | +| `chem/report.py` | `item(code, count, text, severity, atoms, bonds, objects)`, `collect` (merge by code, drop `INTERNAL`, sort error, warn, info, cap 200), `SEVERITY`, `TEXTS` | +| `chem/io.py` | `read_text`, `read_file`, `read_bytes` returning `ParseResult` (fragments, objects, reaction, reactions, warnings, report); `MAX_RECORDS = 1000` for documents; CDX sniffed by `VjCD0100` | +| `chem/writers.py` | `export_document(doc, fmt, scope, page, ids_, options)`, `export_fragments(...)`, `Exported`, `ExportError`; `LOSS_CODES`, `LOSS_TEXTS`, `note_annotations`; molfile V3000 switching | +| `chem/cdxio.py`, `chem/rdfio.py`, `chem/cml.py` | CDXML and CDX through Indigo 1.49 and its KET document; RD files; CML in the dialect the reader accepts | +| `backend/app/services/embedded_source.py` | `extract`, `from_svg`, `from_png`, `from_pdf`, `from_eps`, `open_picture`; `MIME = "application/x-formchem+json"` | +| `backend/app/services/pictures/` | `fonts.py` (fontTools subsets, Arimo instanced to 400 and 700, glyph outlines), `svgdraw.py` (export SVG to a display list), `pdf.py`, `eps.py` | +| `backend/app/services/importers.py` | `import_file` (File > Open) and `read_for_insert`, `grid`, `_left_out` (File > Import) | +| `backend/app/routers/chem.py`, `routers/documents.py`, `routers/files.py`, `routers/pictures.py` | `GET /api/formats`, `POST /api/chem/export`, `POST /api/chem/parse` (text or base64); `GET /api/documents/{id}/export`, `POST /api/documents/import`, open and upload; `POST /api/files/write`; `/api/pictures/capabilities`, `fonts`, `convert` | +| `frontend/src/app/picture.ts` | `pictureSvg` (fresh renderer on a hidden stage, content layers only), `picturePng`, `pngSize` | +| `frontend/src/app/embedded-source.ts` | `subsetDocument`, `sourceText`, `embedInSvg`, `embedInPng`, `extractSource` | +| `frontend/src/app/save-file.ts` | `saveFile`, `saveFiles`: native dialog plus `/api/files/write` in the shell, a Blob download in a browser | +| `frontend/src/app/export-commands.ts`, `ui/export-dialog.ts`, `app/print.ts`, `styles/print.css` | File > Export commands and dialog, Print | +| `frontend/src/ui/import-report.ts`, `app/import-files.ts` | The import report toast and panel; File > Import through the clipboard's paste plan and `freeSpot` | + +## Rules + +- **One table.** A format's capabilities and losses live in `formats.TABLE` only. The window's "will lose" list and the writers' report both read it; never hard-code a format list in the window. +- **Report, never hide.** Every loss or change on reading or writing is a report item with a stable code, a count, a sentence and a severity (`info` routine, `warn` loss, `error` failure). A new code gets a `SEVERITY` entry when it is not `warn`, a row in `docs/FORMATS.md`, and an i18n key for its sentence as the window renders it. +- **Pictures come from the model.** `pictureSvg` renders the document subset with a fresh renderer off screen. Never read the live canvas, its computed style or `data-page-dark`: the dark page filter, the selection, the grid and valence warnings must never reach an export. +- **The embedded drawing is a plain document.json** with one page, the exported objects and `meta.embedded`, under `application/x-formchem+json`, the same payload the clipboard carries. Image bytes are not carried. Readers in both languages must find it: SVG metadata (base64), PNG iTXt (uncompressed), PDF `/EmbeddedFile` stored uncompressed, EPS `%FormChemSource:` lines. +- **Writing files from the shell** goes through `saveFile` and `POST /api/files/write`: window key, absolute path, existing folder, an extension from `SUFFIXES`, atomic write, 200 MB; outside the home folder only with `picked: true` from a dialog. `.fchem` stays on the store's save path. Never add a route that writes where an agent on `/mcp` could point it. +- **Indigo is a bridge, not a source.** CDXML and CDX go through Indigo's KET JSON; FormChem's code, names and samples come from public specifications only (`clean-room`). Do not test against files made by the commercial program unless the owner supplies them. +- **Freeze both paths.** fontTools loads table modules by tag, so `--collect-submodules fontTools` must be in `setup/freeze_backend`, its `.bat` twin and `build_app`'s own freeze. Without fontTools, `/api/pictures/capabilities` says `fonts: false` and PDF and EPS lose their text. +- **Documents read at most 1000 records**, File > Import 50 by default; batch work uses the stream reader (`command-line`). + +## Adding a format + +1. Add its record to `formats.TABLE` (and an alias if people type it), with every feature it cannot hold in `loses`. +2. Write the reader in `io.py` (or its own module) returning a `ParseResult` with report items, and the writer in `writers.py` that counts what it leaves out from the scope. +3. Add the extension to `OPEN_EXTENSIONS` (app/documents.ts), `STRUCTURE_ACCEPT` (ui/home.ts), `importers.FORMATS` and, if the desktop may save it, `files.SUFFIXES`. +4. Round-trip a corpus outside the repository (benzene, Taxol, an AND group, an atom-list query, a Markush scaffold, a two-step scheme, text and a curved arrow): export, read back, compare canonical and isomeric SMILES, CIP labels and CXSMILES; every difference must be named by a report item. +5. Update `docs/FORMATS.md` and the HASHOUT log. + +## Gate + +- [ ] The round trip above names every loss; nothing differs silently. +- [ ] An SVG, PNG, PDF and EPS export of Taxol reopens through File > Open with the same atom ids and coordinates; dark page on and off give byte-identical SVG and PNG. +- [ ] `qpdf --check` (or pypdf) reads the PDF and its attachment; `pdftotext` finds the labels. +- [ ] `backend/venv/bin/python setup/notices.py --check` passes after any dependency change. diff --git a/.claude/skills/formchem-skillset/sub-skills/menus/SUB-SKILL.md b/.claude/skills/formchem-skillset/sub-skills/menus/SUB-SKILL.md index 3756561d..8c82dfc5 100644 --- a/.claude/skills/formchem-skillset/sub-skills/menus/SUB-SKILL.md +++ b/.claude/skills/formchem-skillset/sub-skills/menus/SUB-SKILL.md @@ -14,8 +14,9 @@ One menu definition drives both the in-window menu bar and the native macOS menu | Path | Role | | --- | --- | | `frontend/src/app/menus.ts` | `buildMenus(extensionItems?, recentItems?)`: File, Edit, View, Insert, Structure, Reaction, Arrange, Analysis, 3D, Window, Extensions, Help as command ids | -| `frontend/src/ui/menu.ts` | `MenuBar`, `PopupMenu`, `menuCap` (height cap), `barFloor`, `moreHint` (scroll hint), `modalOpen` | -| `frontend/src/ui/native-menu.ts` | `NativeMenus` (Tauri), `accelerator(combo)`, `menusInWindow`, `setMenusInWindow`, `wantsNativeMenus` (macOS desktop only) | +| `frontend/src/ui/menu.ts` | `MenuBar` (from 0.7.0 with the More menus button, `fold`, `live`, `step`, `reveal`), `PopupMenu`, `menuCap` (height cap), `barFloor`, `moreHint` (scroll hint), `modalOpen`, `menuBarOpen` | +| `frontend/src/ui/titlebar.ts` | `fitMenuRow(bar, menus)`: a ResizeObserver on the title bar that applies `.is-tight` and then folds menus from the right so the row never reaches the document title | +| `frontend/src/ui/native-menu.ts` | `NativeMenus` (Tauri), `accelerator(combo)`, `menusInWindow`, `setMenusInWindow`, `wantsNativeMenus` (macOS desktop only), `ALWAYS_NATIVE` (Cut, Copy, Paste, Select All as system items) | | `frontend/src/ui/context-menu.ts` | Context menus on the same popup | | `frontend/src/canvas/context.ts` | The canvas right-click menus (atom, bond, selection, background); rows are command ids, and atom and bond rows register short-lived `canvas-menu:*` commands while the menu is open. Owned with the `canvas` sub-skill | | `frontend/src/styles/menu.css` | Menu styles from tokens | @@ -28,9 +29,13 @@ One menu definition drives both the in-window menu bar and the native macOS menu - Native menus on macOS desktop unless `formchem.menusInWindow` is set; the pre-paint boot adds `has-native-menus` so the bar never appears and then vanishes. - Menus render into `#overlay-root`, are capped to the space below the bar, and show the scroll hint when cut. They never cover the title bar row (the family menu overlap rules). - Later-phase items are shown disabled rather than hidden, so the menus do not change shape between versions. +- The row never scrolls and never overlaps: menus that do not fit fold into More menus by toggling `.is-folded` on whole buttons (kept in the DOM with their width, never rebuilt), and folded menus open from the keyboard through More. Measure fitting from the title bar only, so the ResizeObserver cannot loop. +- An open bar menu owns Escape and the arrow keys: `canvas/view.ts` `ours()` returns false while `menuBarOpen()`. +- On macOS Cut, Copy, Paste and Select All are predefined system items always; Undo and Redo only while a text field has focus, because WebKit's own undo stack is not the drawing's history (`clipboard`). ## Gate - [ ] The item appears in both the in-window bar and the native menu with the same label and shortcut. - [ ] A long menu at a short window height scrolls with the hint and does not overlap the title bar. - [ ] Keyboard: arrows, Enter and Escape work; focus returns where it was. +- [ ] At 980, 1180, 1280 and 1440 px, in English and German, with the Analysis panel open and closed, no shown menu button intersects the title or the tools, and Alt plus a folded menu's letter opens it inside More. diff --git a/.docs/wiki/Agent-Activity.md b/.docs/wiki/Agent-Activity.md new file mode 100644 index 00000000..76bfd4ad --- /dev/null +++ b/.docs/wiki/Agent-Activity.md @@ -0,0 +1,48 @@ +# Agent Activity + +From 0.8.0 FormChem shows you everything agents do: a panel with every call they made, a chip in the title bar while one is changing your drawing, and a short outline around what each call changed. You can undo an agent's latest call and stop an agent in one click. + +## The panel + +Window > Agent Activity (also the Agent Activity button in the Agents dialog) opens the panel at the bottom right of the canvas. It lists the calls newest first, one row each: + +| Part of a row | What it shows | +| --- | --- | +| Tool and arguments | `draw_from_smiles smiles=CC(=O)Oc1ccccc1C(=O)O name=aspirin`; long text is clipped, a molfile shows as its line count, and anything that looks like a token, password or key shows as `(hidden)` | +| Status | Running, Done, Error or Refused, with the duration (a call that asked you includes the time you took to answer) | +| Agent, drawing and time | the agent's name as its client reports it, the drawing's title, the clock time | +| Tooltip | the first line of the answer the agent got | +| Undo | on the one call per drawing that is still the latest step of that drawing | + +- **Undo** undoes that call's whole change, exactly as Edit > Undo would, and the row shows Undone (struck through). After you or another agent change the drawing, the call is no longer the latest step and Undo leaves the row; use Edit > Undo to step back to it. +- **Click a row** to open its drawing, select what the call changed and outline it. If the drawing is not open in this window, or the objects are gone, a note says so. +- **Show calls from** filters by agent. **Clear** empties the list (the log files stay). +- **Stopped agents** lists the agents you stopped, each with **Allow again**. + +The panel keeps the newest 200 rows on screen of the 400 calls the engine keeps, and says so when there are more. It stays open or closed across reloads. + +## While an agent edits + +When a call changes the drawing you are looking at, the title bar shows a chip beside the document title: "[agent] is editing" while it runs, "[agent] just edited" for three seconds after. At the same time the edge of the canvas lights up and each object the call changed is outlined for about two seconds. With reduced motion turned on in your system, nothing pulses or fades: the outline simply appears and goes. + +- Click the chip's name to open Agent activity on that call. +- **Stop** stops that agent: its next calls are refused, reads included, and Always allow is withdrawn, so every outside agent asks you again before its next change. A call already running finishes. The toast says how to let it back in. + +A drawing an agent makes for you (with `draw_from_smiles` and no drawing open, or `new_document`, `open_document`) opens in the window by itself, and what was drawn into it is outlined once it shows. + +## The call log + +The engine logs every call in one place, whichever way the agent connected (HTTP, stdio, FormChem's own agent tabs or the chat panel). Besides the list in memory (the newest 400), each finished call is appended as one JSON line to `Agent log/-.jsonl` in the data folder (`~/formchem`, or `FORMCHEM_DATA_DIR`). A file rotates at 1 MB, three older parts are kept, and the newest 20 engine sessions are kept. A call that runs a window command (`run_command`, `extension_command`) gets the change the window makes for it during the call or within 1.5 seconds after; if you edit in that moment, your change can be listed under the agent. Read-only calls are listed without a drawing. + +| Route | What it does | +| --- | --- | +| `GET /api/agents/calls?limit=&agent=` | the log, newest first, with `undoable` (drawing id to the call on top of its undo stack), the agent names, the stopped agents and the log file | +| `POST /api/agents/calls/clear` | empties the log in memory | +| `POST /api/agents/calls/{id}/undo` | undoes the call while it is the latest step of its drawing, else `409` | +| `POST /api/agents/stop {agent}` | stops an agent | +| `POST /api/agents/allow {agent}` | lets a stopped agent in again | +| `GET /api/agents/token` | the agent token, for the Agents dialog | + +The POST routes and the token route need the window key, so only the FormChem window can undo, stop or read the token. The live socket sends `agentCall` when a call starts, ends and gets its change, `agentUndoable` when the undoable call of a drawing changes, `agentAccess` when an agent is stopped or allowed and `agentCallsCleared`. + +Code: `backend/app/services/agent_log.py` and `backend/app/routers/agent_activity.py` in the engine; `frontend/src/app/agent-calls.ts`, `app/agent-activity.ts`, `ui/agent-activity.ts`, `ui/agent-chip.ts` and `canvas/agent-marks.ts` in the window. See also [Agents](Agents). diff --git a/.docs/wiki/Agents.md b/.docs/wiki/Agents.md index 8c29b749..8165bbcf 100644 --- a/.docs/wiki/Agents.md +++ b/.docs/wiki/Agents.md @@ -1,68 +1,131 @@ # Agents -FormChem's engine is an MCP server (`backend/app/routers/mcp.py`), over HTTP at `http://127.0.0.1:8220/mcp` and over stdio with `./formchem mcp` (`setup/mcp_stdio.py`, which starts the engine when needed). An agent works in the same window you see. +FormChem's engine is an MCP server (`backend/app/routers/mcp.py`), over HTTP at `http://127.0.0.1:8220/mcp` and over stdio with `./formchem mcp` (`setup/mcp_stdio.py`, which starts the engine when needed). An agent works in the same window you see. From 0.8.0 it draws there directly: it makes and opens drawings, draws structures and reaction schemes from SMILES or molfiles, edits them atom by atom by id, reads them back in machine form and checks its work with a picture drawn by the window's own renderer. Every change is one undo step, every call is listed in [Agent Activity](Agent-Activity), and you can stop an agent from the title bar. + +The full reference, with every tool's arguments and result shape and the recorded examples, is [`docs/AGENTS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/AGENTS.md). ## Setup | Client | How | | --- | --- | -| All at once | `./formchem agents install` writes `.mcp.json`, `.codex/config.toml` and `.cursor/mcp.json`, adds FormChem to Antigravity's `~/.gemini/config/mcp_config.json` and installs the skills | -| Claude Code | `claude mcp add --transport http formchem http://127.0.0.1:8220/mcp` | -| Codex | `[mcp_servers.formchem]` with `url = "http://127.0.0.1:8220/mcp"` in `~/.codex/config.toml` | -| Cursor | `{"mcpServers": {"formchem": {"url": "http://127.0.0.1:8220/mcp"}}}` in `~/.cursor/mcp.json` | +| All at once | `./formchem agents install` writes `.mcp.json` (its HTTP entry carries the agent token), `.codex/config.toml` and `.cursor/mcp.json`, adds FormChem to Antigravity's `~/.gemini/config/mcp_config.json` and installs the skills | +| Claude Code | `claude mcp add --transport http formchem http://127.0.0.1:8220/mcp --header "Authorization: Bearer "` | +| Codex | `[mcp_servers.formchem]` with `url = "http://127.0.0.1:8220/mcp"` and `http_headers = { "Authorization" = "Bearer " }` in `~/.codex/config.toml` | +| Cursor | `{"mcpServers": {"formchem": {"url": "http://127.0.0.1:8220/mcp", "headers": {"Authorization": "Bearer "}}}}` in `~/.cursor/mcp.json` | +| Claude Desktop and any stdio client | `./formchem mcp` (full path to your FormChem folder): no token to set, the transport reads it | + +`` is the agent token (below); the Agents dialog (Window > Agents and MCP) shows these lines with the token filled in. An agent that connected to 0.7.0 over HTTP needs the token from 0.8.0 on: run `./formchem agents install` again, or add the header yourself. -`./formchem agents sync` mirrors `.claude/skills` into `.agents/skills` and writes `agents/manifest.json`; `sync --check` fails on drift. +`./formchem agents sync` regenerates the tools reference of the harness skill from the server, mirrors `.claude/skills` into `.agents/skills` and writes `agents/manifest.json`; `sync --check` fails on drift. ## Tools -Fourteen tools: `get_context` (version, window, agent access, the open drawings, catalogue size, your last handoff), `list_commands`, `run_command`, `extensions_list`, `extension_command`, `handoff` (working, ready or question, with a note), from 0.5.0 four reaction tools and from 0.6.0 four analysis tools: +42 tools. Reading never asks you; a tool that changes something asks you in the window the first time (Consent, below). -| Tool | Kind | What it does | +| Group | Tools | Kind | | --- | --- | --- | -| `perceive_reactions {doc?, page?}` | changes the drawing | reads the reaction arrows and stores each step's reactants, products, agents and conditions (one undo step); steps set by hand are kept; lists reaction and step ids | -| `map_reaction {doc?, reaction?, step?, mode?}` | changes the drawing | maps reactant atoms to product atoms and marks bonds broken, formed and changed (`mode`: `discard`, `keep`, `alter`, or `clear` to remove) | -| `export_reaction {doc?, reaction?, step?, format?}` | reads | a step as reaction SMILES (`smiles`) or RXN (`rxn`, `rxnv3000`) with its map numbers | -| `reaction_stoichiometry {doc?, reaction?, step?}` | reads | moles, equivalents, masses, volumes, the limiting reagent and yields from the amounts in the step, with the balance check | -| `properties {doc?, object?}` | reads | per fragment: formula, MW, exact mass, cLogP, molar refractivity, TPSA (also with S and P), donors and acceptors, rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts and elemental analysis, each with the RDKit method behind it | -| `check_structure {doc?, object?, query?}` | reads | the structure check: issues with a code, a severity (error, warning, info), the atom and bond ids, and the fix the window can run; `query: true` leaves out query-feature notes | -| `stereo {doc?, object?}` | reads | each stereocentre, double bond and axis with its CIP label (R, S, r, s, E, Z, M, P), defined, undefined or unknown, its enhanced stereo group and the CXSMILES | -| `substructure {doc?, smarts or query_object, objects?, chirality?, max_hits?}` | reads | every hit of a SMARTS pattern, or of a fragment of the drawing drawn as the query, with its fragment id and the matched atom and bond ids | - -`doc` may be left out when one drawing is open; `reaction` and `step` default to the first, and `object` (absent) means every fragment. `get_context`, `list_commands`, `extensions_list`, `export_reaction`, `reaction_stoichiometry` and the four analysis tools read; `run_command`, `extension_command`, `perceive_reactions`, `map_reaction` and `handoff` with a state change something and go through the consent question. One command catalogue feeds the menus, Find a Command, the keyboard map, `./formchem cli list|describe|run|batch` and the MCP tools, so anything a person can click an agent can run. - -## Working on drawings - -`get_context` lists every drawing open in the window, oldest first, as text and in `structuredContent.documents`: +| Context | `get_context`, `list_open_documents` | read | +| Documents (0.8.0) | `new_document`, `open_document`, `save_document`, `close_document` | change | +| Drawing (0.8.0) | `draw_from_smiles` (also reaction SMILES), `draw_from_molfile`, `add_reaction` | change | +| Checking (0.8.0) | `render`, `get_structure`, `validate`, `compute_properties` | read | +| Editing by id (0.8.0) | `get_atoms` (read); `add_atom`, `add_bond`, `set_charge`, `set_atom`, `set_stereo`, `replace_substructure`, `delete`, `move`, `scale`, `align`, `clean_layout`, `add_arrow`, `add_text` | change | +| Converting (0.8.0) | `convert`, `batch_convert` | change only when they write outside the temporary folder | +| Window and extensions | `list_commands`, `extensions_list` (read); `run_command`, `extension_command` (change) | | +| Handoff | `handoff` | change with a state | +| Reactions (0.5.0) | `perceive_reactions`, `map_reaction` (change); `export_reaction`, `reaction_stoichiometry` (read) | | +| Analysis (0.6.0) | `properties`, `check_structure`, `stereo`, `substructure` | read | + +| Tool | What it does | +| --- | --- | +| `get_context` | version, window, agent access, the open drawings, catalogue size, your last handoff | +| `list_open_documents` | the open drawings (id, title, path, unsaved changes, revision, fragments, formula) and which one the window shows | +| `new_document {title?}` | an empty drawing, shown in the window | +| `open_document {path}` | a `.fchem`, a chemistry file or a picture with its drawing inside, shown in the window | +| `save_document {doc?, path?}` | saves to the drawing's file, to `path`, or to a new name in the Drawings folder; never over another file | +| `close_document {doc?}` | closes a drawing without unsaved changes | +| `draw_from_smiles {smiles, doc?, x?, y?, name?}` | lays a structure out and places it in free space; reaction SMILES draws a whole scheme | +| `draw_from_molfile {molfile, doc?, x?, y?}` | the same from a V2000 or V3000 molfile or SD text, keeping its coordinates | +| `add_reaction {reaction_smiles, doc?, x?, y?, page?}` | a reaction scheme with its step and roles | +| `render {doc?, scope?, ids?, format?, width?, height?, dpi?}` | a PNG or SVG of objects, your selection or the page, drawn by the window's renderer (by the engine when no window is open) | +| `get_structure {doc?, object?, selection?}` | SMILES, CXSMILES, InChI, InChIKey, a molfile, formula, masses and elemental analysis per fragment | +| `validate {doc?, object?}` | the structure check with `valid` | +| `compute_properties {doc?, object?}` | the Analysis panel's properties with their methods | +| `get_atoms {doc?, object?}` | every atom and bond with its id, position, charge, hydrogens and CIP label | +| `add_atom`, `add_bond`, `set_charge`, `set_atom` | build and change atoms and bonds by id | +| `set_stereo {atom or bond, label}` | R or S on a centre (rewrites its wedges), E or Z on a chain double bond | +| `replace_substructure {smarts, replacement, object?, all?}` | swaps a SMARTS match for a SMILES group, keeping the rest in place | +| `delete`, `move`, `scale`, `align`, `clean_layout` | arrange and tidy by id, without a window | +| `add_arrow`, `add_text` | arrows (anchored to atoms and bonds for electron pushing) and text or captions | +| `convert`, `batch_convert` | files and folders, with the same code and output as `./formchem convert` and `batch` | +| `list_commands`, `run_command` | the window's command catalogue, the same commands as the menus | +| `extensions_list`, `extension_command` | Form extensions and their commands | +| `handoff {state?, note?}` | working, ready or question, with a note the person sees | +| `perceive_reactions`, `map_reaction`, `export_reaction`, `reaction_stoichiometry` | reaction steps, atom mapping, reaction SMILES and RXN, amounts and yields ([Reactions](Reactions)) | +| `properties`, `check_structure`, `stereo`, `substructure` | the 0.6.0 analysis tools ([Analysis](Analysis), [Stereo and Queries](Stereo-and-Queries)) | + +## Drawing directly + +A typical session: `get_context`, then `draw_from_smiles {smiles: "CC(=O)Oc1ccccc1C(=O)O", name: "aspirin"}`. With no drawing open it makes one and shows it in the window. The structure is laid out with the scored 2D layout and placed in free space, right of what is on the page or below it, never on top of it and never after a reaction arrow, where it would read as a product. + +Every change an agent makes is one transaction and one undo step, labelled with the tool's name in Edit > Undo (Undo Draw from SMILES, Undo Add atom). Calls never merge with each other or with your edits. + +Every change answers with the structure it now holds and a picture: a text line per touched object (id, formula, SMILES, InChIKey, atom count, warnings), a PNG drawn by the window, and the same as `structuredContent` (`doc`, `rev`, `changed`, `undo: "one step"`, `objects`, `image`). An agent checks further with `render` (what you see, arrows and text included), `get_structure` (the machine form, with a V2000 molfile, or V3000 when the structure needs it) and `validate`. + +To build or change a structure by id: `get_atoms` lists the ids, `add_atom {element, bond_to}` adds an atom at the bond length in the freest direction (a zigzag for chains), `add_bond {atom1, atom2, order}` bonds two atoms or changes an existing bond, `set_charge`, `set_atom` and `set_stereo` change one atom or bond, and `replace_substructure` swaps a group. `move`, `scale`, `align` and `clean_layout` arrange; `add_arrow`, `add_text` and `add_reaction` build schemes. They all work without a window. + +Which drawing: `doc` when given; else the only open drawing; else the drawing the window shows; else the tool asks for `doc`. Coordinates are points, x right and y down; the default bond length is 14.4 points. + +`get_context` lists every drawing open, oldest first, as text and in `structuredContent.documents`: ``` -Documents: 1 open in the window (change them with run_command and the window's commands, write reactions with perceive_reactions and map_reaction, read them with export_reaction, reaction_stoichiometry, properties, check_structure, stereo and substructure; atom and bond tools arrive in 0.8.0) +Documents: 1 open (draw on them with draw_from_smiles and draw_from_molfile, edit them by id with get_atoms and the edit tools, check them with render, get_structure and validate, write reactions with perceive_reactions and map_reaction, read them with export_reaction, reaction_stoichiometry, compute_properties, stereo and substructure) - d4n2k8q0z "Untitled" (unsaved changes) · rev 1 · 1 fragment · C6H6O · not saved yet ``` -Each entry has `id`, `title`, `path`, `dirty`, `rev`, `fragments` and `formula` (the fragments' formulas from the engine's derived cache, or `null` while the engine is still working out the latest revision). +Each entry has `id`, `title`, `path`, `dirty`, `rev`, `fragments` and `formula` (from the engine's derived cache, or `null` while the engine is still working out the latest revision). -An agent changes drawings with the window's own commands, so every change is one undo step the person sees and can undo: +## The window's commands + +Commands reach what the drawing tools do not, and every change is still one undo step you can see. One command catalogue feeds the menus, Find a Command, the keyboard map, `./formchem cli list|describe|run|batch` and `run_command`, so anything you can click an agent can run. | Goal | Call | | --- | --- | -| Add a structure | `run_command {id: "insert-smiles", params: {smiles: "c1ccccc1O"}}`: into the active drawing (a new one when none is open), centred in view, selected; the answer names the new fragment ids | -| Open a file | `run_command {id: "open-recent", params: {path: "/abs/path/file.mol"}}` (a `.fchem`, or a structure file as a new drawing) | -| Tidy or lay out | `clean-structure` or `layout-structure`: the selection, or every structure on the page | -| Arrange the selection | `select-all`, then `delete`, `duplicate`, `flip-horizontal`, `flip-vertical`, `rotate-90`, `align-*`, `distribute-h`, `distribute-v`, `bring-front`, `send-back`, `group`, `ungroup` | -| Insert a template | `run_command {id: "insert-template", params: {id: "benzene"}}`: one undo step, centred in view at the drawing's bond length; `GET /api/templates` lists the ids | -| Reactions | `perceive-reactions`, `map-atoms`, `clear-mapping`, `balance-reaction` through `run_command`, or the four reaction tools above, which also return the results; `check-reaction` and the Stoichiometry panel (`show-stoichiometry`) open for the person | -| Reaction roles | `set-reaction-roles {role, objects}` gives objects a role in the selected step (reactant, product, agent, condition or none) without the dialog | -| Stereo, hydrogens, abbreviations | `assign-wedges`, `set-stereo-group-abs`, `set-stereo-group-and`, `set-stereo-group-or`, `clear-stereo-group`, `add-hydrogens`, `remove-hydrogens`, `expand-abbreviation`, `contract-abbreviation` on the selection; read the result back with `stereo` | -| Queries and R-groups | `set-atom-list`, the `set-query-bond-` commands, `define-rgroup`, `enumerate-markush`, `copy-smarts`; search with the `substructure` tool | -| Check and properties | the `check_structure` and `properties` tools return the issues and values; `check-structure` and `compute-properties` open the panels for the person | -| Undo, save | `undo`, `redo`, `save` (a drawing without a file asks the person for a name) | +| A structure into the view's centre, selected | `run_command {id: "insert-smiles", params: {smiles}}` (the drawing tools place in free space instead) | +| A template | `run_command {id: "insert-template", params: {id: "benzene"}}`; `GET /api/templates` lists the ids | +| Import a file into the drawing | `run_command {id: "import", params: {path}}`: in free space, selected, one undo step | +| Export and print | `export-png`, `export-svg`, `export-pdf`, `export-eps`, `export-cdxml`, `export-mol`, `export-smiles`, `export-picture`, `print` (you pick where to save in the desktop app; use `convert` or `get_structure` for text the agent reads) | +| Clipboard | `copy`, `cut`, `paste`, the `copy-*` commands, `paste-special` | +| Standardise | `standardise {steps: ["salts", "neutralise"]}` on the selection or the page | +| Stereo, hydrogens, abbreviations, queries, R-groups | `assign-wedges`, the stereo group commands, `add-hydrogens`, `remove-hydrogens`, `expand-abbreviation`, `contract-abbreviation`, `set-atom-list`, the `set-query-bond-` commands, `define-rgroup`, `enumerate-markush` | +| Reaction roles | `set-reaction-roles {role, objects}` | +| Page and grid | `dark-page {on}`, `show-grid {on}`, `snap-to-grid {on}`, `grid-type {type}`, `grid-spacing {value, unit}`, `grid-settings {...}`, each with `scope: "default"` for the default | +| Undo, save | `undo`, `redo`, `save` | + +The window tells the engine within about 120 ms which commands are on after every edit, and a command that is off answers why ("X is not available right now: ..."). Form extensions with the document permission read a drawing (with its derived SMILES, InChIKey and valence errors) and apply transactions to it by id. The engine's HTTP routes for reactions, analysis, templates, formats and media are in [`docs/REACTIONS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/REACTIONS.md), [`docs/ANALYSIS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/ANALYSIS.md), [`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md), [`docs/FORMATS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/FORMATS.md) and [`docs/FORMAT.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/FORMAT.md). -Form extensions with the document permission read a drawing (with its derived SMILES, InChIKey and valence errors) and apply transactions to it by id. Beyond the reaction and analysis tools, dedicated drawing tools for agents (atoms and bonds by id, reading whole structures back, rendering, conversion) arrive in 0.8.0. The engine's HTTP routes for reactions, analysis, templates and media are listed in [`docs/REACTIONS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/REACTIONS.md), [`docs/ANALYSIS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/ANALYSIS.md), [`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md) and [`docs/FORMAT.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/FORMAT.md). +## Consent and Stop + +Agents can always read. When an outside agent first asks to change something, the window asks: Deny, Allow once (that call), or Always allow. The app's own command line counts as an outside agent; FormChem's own Claude Code, Codex, Cursor and Antigravity tabs are trusted and never asked. Only the FormChem window can change the choice, and the engine seals the saved value with a key in the system keychain, so a change made outside the window reads as asking again. `convert` asks only when it writes outside the temporary folder and `batch_convert` unless its output folder is there; neither writes over an existing file. `save_document` never writes over another file and `close_document` never closes a drawing with unsaved changes: those choices stay yours, in the window. + +While an agent changes the drawing you are looking at, the title bar shows "[agent] is editing" and Stop. Stop refuses every further call of that agent, reads included, and withdraws Always allow, so every outside agent asks again on its next change. A call already running finishes. Allow again in [Agent Activity](Agent-Activity) lets the agent back in. + +## The agent token + +From 0.8.0 the HTTP endpoint (`POST /mcp`, also `DELETE /mcp`) answers only a request that carries one of: `Authorization: Bearer `, the token of one of FormChem's own agent tabs (`x-formchem-inapp`), or the window key. Anything else gets `401` with `WWW-Authenticate: Bearer realm="FormChem"` and a JSON-RPC error (code `-32001`) saying where the token is. The engine still listens on loopback only, and the origin check is unchanged. + +The token is one line in `agent-token` in the data folder (`~/formchem`, or `FORMCHEM_DATA_DIR`), created by the engine at start or by `./formchem agents install`, whichever runs first, readable by the owner only. `./formchem agents token` prints it. To change it, delete the file and restart the engine, then run `./formchem agents install` again. The stdio transport (`./formchem mcp`) and `./formchem cli` read the file themselves, so stdio clients need no change. The `.mcp.json` files that install writes hold the token: keep them out of version control (FormChem's own `.gitignore` does). The chat panel's copied prompt tells an outside agent how to send it, without putting the token itself on the clipboard. + +``` +$ curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:8220/mcp -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"ping"}' +401 +$ curl -s -X POST http://127.0.0.1:8220/mcp -H "Authorization: Bearer $(./formchem agents token)" -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"ping"}' +{"jsonrpc": "2.0", "id": 1, "result": {}} +``` -## Consent +## Agent activity -Agents can always read. When an outside agent asks to change something, the window asks: Deny, Allow once, or Always allow for that agent name. The app's own command line counts as an outside agent. Only the FormChem window can change the choice, and the engine seals the saved value with a key in the system keychain, so a change made outside the window reads as asking again. +Every tool call, from any transport or from the window's own chat, is logged by the engine and listed in Window > Agent Activity, with undo for the call that is still the latest step of its drawing. [Agent Activity](Agent-Activity) describes the panel, the editing chip, the call log files and the `/api/agents` routes. ## Skills -`formchem-harness` (using FormChem) and `formchem-skillset` (developing FormChem), in `.claude/skills` and mirrored to `.agents/skills`. +`formchem-harness` (using FormChem: drawing with the tools, checking with render and get_structure, commands, reactions, analysis, handoff) and `formchem-skillset` (developing FormChem), in `.claude/skills` and mirrored to `.agents/skills`. The harness's `references/tools.md` is generated from the server and lists every argument. diff --git a/.docs/wiki/Analysis.md b/.docs/wiki/Analysis.md index ebe59b82..db0b35a2 100644 --- a/.docs/wiki/Analysis.md +++ b/.docs/wiki/Analysis.md @@ -11,7 +11,7 @@ Open it with Analysis > Show Analysis. It follows the selection, or the whole pa | Formula | Hill order with charge, abbreviations expanded | | Molecular weight | standard atomic weights (CIAAW conventional values) | | Exact mass | monoisotopic mass from the most abundant isotope of each element | -| m/z | exact mass over the charge, electron mass corrected (charged species only) | +| m/z | from 0.7.0: [M+H]+ for a neutral molecule, the ion's own m/z for a charged one, from the isotope pattern (electron mass corrected) | | Elemental analysis | mass percent of each element | | cLogP | Wildman and Crippen 1999 atom contributions (typical error 0.5 to 0.7 log units) | | tPSA | topological polar surface area from N and O (Ertl 2000), in Ų | diff --git a/.docs/wiki/Architecture.md b/.docs/wiki/Architecture.md index 9def3f86..a4147a63 100644 --- a/.docs/wiki/Architecture.md +++ b/.docs/wiki/Architecture.md @@ -3,10 +3,12 @@ ``` frontend/ vanilla TypeScript and Vite: engine/ (model, ops, document client, session, reactions-api), chem/ (valence, rings, formula, stoich), canvas/ (view, hit testing, tools, render/ with one module per object kind), app/ (menus, shell, canvas, object and reaction commands, - documents, window tools), ui/ (shell, menus, Home, Preferences, tool rail, Analysis and Stoichiometry panels, template library), dock/, extensions/, styles/ -backend/ FastAPI engine: core/ (config, guard, window key, seal), routers/ (system, live, library, commands, documents, chem, reactions, templates, - terminal, chat, extensions, mcp), services/ (model, ops, store, history, package, importers, templates, chem/ on RDKit and Indigo), data/templates/ -src-tauri/ the desktop shell; the engine runs as a frozen sidecar + documents, window tools, agent-window, agent-calls, agent-activity), ui/ (shell, menus, Home, Preferences, tool rail, Analysis and + Stoichiometry panels, template library, Agent activity panel, agent chip), dock/, extensions/, styles/ +backend/ FastAPI engine: core/ (config, guard, window key, seal, agent token), routers/ (system, live, library, commands, documents, chem, reactions, + templates, terminal, chat, extensions, mcp, agent_activity), services/ (model, ops, store, history, package, importers, templates, + agent_out, agent_draw, agent_edits, agent_convert, agent_log, chem/ on RDKit and Indigo), data/templates/ +src-tauri/ the desktop shell; the frozen engine runs from a folder inside the app on macOS and as a sidecar elsewhere ``` ## The engine owns the document @@ -28,9 +30,19 @@ Undo and redo are engine operations: the engine applies the recorded inverse as Windows and agents talk to the engine over a WebSocket hub. It carries the connection and the engine's state, document transactions and derived caches, the window's command catalogue, the tool calls an agent makes through the engine (`run_command`, the extension tools), consent questions and answers, and handoff notes. Agents reach drawings through the MCP server: `get_context` reads the store's open documents, and `run_command` runs the window's commands, whose changes travel the same flow as the person's. +## Agents draw through the engine + +From 0.8.0 the drawing and edit tools build ops in the engine (`services/agent_draw.py` lays SMILES, molfiles and reaction SMILES out and finds free space; `services/agent_edits.py` holds each edit tool as a pure function from the document and the arguments to ops) and apply them with `STORE.apply` as one transaction with origin `agent` and the agent's name. From there the change travels the document flow above: broadcast to every window, which patches its mirror and its SVG, then derived. So an agent's call is one undo step in the window, and it works with no window open. + +Every write answers with `agent_out.write_result`: the touched structures read back from the derived cache after the transaction, and a picture. Pictures go through the bridge. The engine sends the document and its derived cache to the window as the window tool `render` (`bridge.window_call` over the live channel); the window cuts out the objects asked for and draws them with the same off-screen renderer as File > Export (`app/agent-window.ts`, `app/picture.ts`), in the person's display preferences, and rasterises the PNG itself without waiting on animation frames, so a background window still answers. With no window, a window error or no answer in 25 seconds, the engine draws the structures in the journal style with RDKit (`services/chem/depict.py`) and says so. The window tools `selection` (the person's selection) and `show` (open and activate a drawing the engine made for an agent) travel the same way. `render` and `selection` are read-only window tools, so a window without the drawing does not hold the call. + +## The agent call log + +Every tool call passes through `call_tool` in `routers/mcp.py`, which logs it in `services/agent_log.py` before and after it runs. A context variable set for the call flows through `STORE.apply` into the store's after-change hooks (`store.AFTER_CHANGE`), so each transaction is credited to the call that made it; a window command's transaction, which the window posts itself, is credited to the one writing window-tool call that is running or ended less than 1.5 seconds ago. After every change, undo and redo the hook checks which call owns the top of that drawing's undo stack and tells the windows (`agentUndoable`), so Agent Activity offers Undo on exactly that call. The log is mirrored live to every window (`agentCall`), kept in memory and appended to files in the data folder, and served under `/api/agents` ([Agent Activity](Agent-Activity)). A stopped agent is refused in `call_tool` before any tool runs. + ## Guarding the engine -The engine binds to 127.0.0.1. A local guard refuses requests whose Host or Origin is not local, and a window key made at each start lets only the FormChem window change settings, use the terminal dock or answer an agent's question. Saved agent choices are sealed with a key in the system keychain. +The engine binds to 127.0.0.1. A local guard refuses requests whose Host or Origin is not local, and a window key made at each start lets only the FormChem window change settings, use the terminal dock or answer an agent's question. Saved agent choices are sealed with a key in the system keychain. From 0.8.0 the MCP endpoint also needs the agent token (`core/agent_token.py`, the file `agent-token` in the data folder), which the stdio relay and the agent configs send. ## The window diff --git a/.docs/wiki/Clipboard.md b/.docs/wiki/Clipboard.md new file mode 100644 index 00000000..e6b9e148 --- /dev/null +++ b/.docs/wiki/Clipboard.md @@ -0,0 +1,53 @@ +# Clipboard + +From 0.7.0 Copy, Cut and Paste work on the drawing, between FormChem windows and with other programs, in several forms at once. The engine side of the text formats is in [`docs/FORMATS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/FORMATS.md). + +## Copy, Cut and Paste + +| Command | Keys | What it does | +| --- | --- | --- | +| Copy | `Ctrl+C` (`Cmd+C`) | copies the selection, or the whole page when nothing is selected | +| Cut | `Ctrl+X` (`Cmd+X`) | copies the selection and removes it, as one undo step | +| Paste | `Ctrl+V` (`Cmd+V`) | pastes at the pointer when it is over the canvas, at the right-click point when you use the canvas menu, else in the middle of the view; the pasted items are selected and the paste is one undo step | +| Paste Special... | `Ctrl+Shift+V` (`Cmd+Shift+V`) | lists what the clipboard holds and pastes the one you pick (Enter or a double-click) | + +In a text field (an atom label, a dialog, the find bar) the keys edit text as usual. Pasting the same thing again at the same point steps each copy by 10 pt. With no drawing open, Paste makes a new one. Duplicate (`Ctrl+D`) uses the same machinery, so the copy keeps stereo groups, R-groups and reaction steps. + +## What Copy puts on the clipboard + +One Copy writes several forms, and each program takes the one it understands: + +| Form | Who reads it | +| --- | --- | +| The FormChem drawing | FormChem windows: everything comes back exactly, with its look (a structure copied from a 14.4 pt drawing into a 30 pt one keeps its size and line widths), its abbreviations, R-groups, stereo groups, reaction steps and placed pictures | +| SMILES (reaction SMILES for a reaction) | text editors, notebooks, chat | +| HTML with a PNG picture (the drawing rides along inside it) | word processors and slides; pasting it back into FormChem restores the drawing | +| SVG and PNG pictures | drawing programs, where the platform allows it | + +## Copy As + +Edit > Copy As puts one chosen form on the clipboard: SMILES, CXSMILES, Molfile, InChI, InChIKey, SMARTS, SVG, PNG or CDXML. A reaction becomes reaction SMILES or RXN. Copy as SVG also puts the full SVG on the clipboard as text, which pastes back into FormChem as the drawing; Copy as PNG carries the drawing in its HTML form. The status line says what was copied. + +## What Paste reads + +In this order: a FormChem drawing, a picture that carries a drawing (an SVG or PNG exported or copied by FormChem), structure text in any format FormChem reads (SMILES, CXSMILES, reaction SMILES, molfile, SD, RXN, InChI, CML, CDXML), SMARTS (as a query structure), a plain picture (placed as an image) and plain text (a text object). Structure text takes your drawing's bond length. When the text holds something that could not be read exactly, a note says so. + +Chemical names are not read yet: pasting "aspirin" gives a text object and a note that name to structure arrives in a later version. + +## Platforms + +| | Browser (Chromium) and the Windows app | Linux app | macOS app | +| --- | --- | --- | --- | +| Copy and Cut | every form | drawing, SMILES and HTML | drawing, SMILES, HTML and PNG | +| Paste | everything above | everything above; pictures are read through the clipboard API | everything above, through the system Edit menu | +| Edit menu | in-window | in-window | Cut, Copy, Paste and Select All are the system's own items, so they act on the drawing as well as in text fields | + +- In Chromium (browsers and the Windows app), a PNG that another program put on the clipboard as image data pastes as a plain picture, because Chromium strips the drawing out of clipboard PNGs. Copy the PNG file itself in your file manager, or use FormChem's own Copy, and it pastes back editable. +- Chromium also cleans SVG on the clipboard (the fonts and the drawing are dropped), which is why Copy as SVG adds the text form. +- On macOS, Paste from the canvas right-click menu may show WebKit's small Paste button, which you click once; `Cmd+V` and Edit > Paste do not. +- The macOS app was not tried for this version. +- The desktop windows on Linux and Windows are allowed to read the clipboard from the page, which Edit > Paste and Paste Special need there. + +## For agents + +`copy-smiles`, `copy-cxsmiles`, `copy-molfile`, `copy-inchi`, `copy-inchikey`, `copy-smarts`, `copy-svg`, `copy-png`, `copy-cdxml` and `paste-special` run through `run_command`; `cut`, `copy` and `paste` too. To read a structure as text without touching the clipboard, the export route in `docs/FORMATS.md` is simpler. See [Agents](Agents). diff --git a/.docs/wiki/Command-Line.md b/.docs/wiki/Command-Line.md new file mode 100644 index 00000000..90f45f8c --- /dev/null +++ b/.docs/wiki/Command-Line.md @@ -0,0 +1,44 @@ +# Command Line + +From 0.7.0 four commands work on whole files of structures without the window: convert between formats, convert a folder, write properties to a CSV file and draw every record as a picture. They run from the source tree with the engine's Python; the full reference with timings is [`docs/CLI.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/CLI.md). + +## The four commands + +| Command | What it does | +| --- | --- | +| `./formchem convert IN OUT` | converts one file; the formats come from the extensions (or `--from`, `--to`); `OUT` may be `-` for the terminal | +| `./formchem batch DIR --to FMT` | converts every readable file in a folder (`--recursive` for subfolders) into `DIR/converted` or `--out` | +| `./formchem descriptors IN --csv OUT` | one row per record with the Analysis panel's properties; `--props` picks the columns, `--list` shows them with their methods | +| `./formchem render IN --out DIR` | one SVG or PNG picture per record (`--format`, `--size`, `--transparent`) | + +On Windows use `formchem.bat` with the same arguments. Formats read: SD, molfile, SMILES, CXSMILES, InChI, CML, RXN, reaction SMILES, RD files, CDXML, CDX and FormChem drawings; written: SD, molfile, SMILES, CXSMILES, InChI, InChIKey, CML, RXN, reaction SMILES and FormChem drawings. Any input may be gzip-compressed. `./formchem convert --formats` lists them. + +## Examples + +``` +./formchem convert big.sdf big.smi --errors failed.csv +./formchem convert salts.smi - --to smiles --standardise +./formchem batch ~/mols --to sdf --out ~/mols-sdf --jobs 2 +./formchem descriptors big.sdf --csv props.csv --props mw,clogp,tpsa,hbd,hba,lipinski_violations +./formchem render big.sdf --out pictures --format png --size 600x400 +``` + +## Standardising + +`--standardise` (or `--standardize`) cleans each record first, with the same steps as Structure > Standardise... in the window: clean up, normalise functional groups, remove salts and solvents, reionise, neutralise and remove explicit hydrogens by default, plus keep the largest fragment, the canonical tautomer, remove isotopes and remove stereochemistry when you name them (`--standardise salts,neutralise,tautomer`, `--standardise all`, `--standardise default,tautomer,-strip_h`). Steps always run in the same order. `./formchem convert --steps` lists them with the RDKit method behind each. + +## When records fail + +A record that cannot be read never stops the run. The first 20 failures are printed with the record number, the name and RDKit's own reason; `--errors FILE` writes every failed or warned record to a CSV file instead, and `batch` always writes `formchem-batch-report.csv` when something failed. The command ends with 0 when at least one record was written, 1 when none was, and 2 for a mistake in the arguments. + +## Speed + +On a two-core machine, 10,000 SD records convert to SMILES in about 1.4 seconds, to InChIKey in about 4 seconds, and with standardising in about 22 seconds. `--jobs N` (0 for one per CPU) uses several processes for large files and folders, with the output always in input order. + +## Pictures from the command line + +`render` draws with RDKit, close to the journal style (14.4 pt bonds, 0.6 pt lines, 10 pt Arimo labels, black on white), not with the window's own drawing code, so labels, wedges and double bonds can sit a little differently. For pictures exactly as the window shows them, with the drawing kept inside, use File > Export ([Formats and Export](Formats-and-Export)). + +## Not the same as ./formchem cli + +`./formchem cli list|describe|run|batch` reaches the open window's commands from a terminal ([Getting Started](Getting-Started)); `./formchem batch` converts files. The desktop app does not include the conversion commands yet. diff --git a/.docs/wiki/Desktop.md b/.docs/wiki/Desktop.md index c273566f..799c4cbf 100644 --- a/.docs/wiki/Desktop.md +++ b/.docs/wiki/Desktop.md @@ -1,19 +1,29 @@ # Desktop -The desktop app is a thin Tauri 2 shell around the same window, with the engine frozen by PyInstaller into a sidecar named `formchem-engine`. The shell shows a splash, starts the engine with `FORMCHEM_PORT=0` and `FORMCHEM_PORT_PREFER=8221`, reads the real port from the engine, reveals the window when the page is ready, and stops the engine on exit. +The desktop app is a thin Tauri 2 shell around the same window, with the engine frozen by PyInstaller as `formchem-engine`. On macOS the engine ships as a folder inside the app (`FormChem.app/Contents/Resources/engine`); on Linux and Windows it is a one-file sidecar. The shell shows a splash, starts the engine with `FORMCHEM_PORT=0` and `FORMCHEM_PORT_PREFER=8221`, reads the real port from the engine, reveals the window when the page is ready, and stops the engine on exit. | Source path | What lives there | | --- | --- | -| `src-tauri/src/main.rs` | Sidecar start, splash and reveal, single instance, the Windows job object that ends the engine with the app, the macOS overlay title bar with the traffic lights inset | +| `src-tauri/src/main.rs` | Engine start, splash and reveal, single instance, the Windows job object that ends the engine with the app, the macOS overlay title bar with the traffic lights inset, clipboard access for the windows | +| `src-tauri/src/packaged.rs` | Finds the engine folder: `../Resources/engine/formchem-engine` in the app bundle, or `engine/formchem-engine` beside the program under `tauri dev`; without it the shell starts the sidecar | | `src-tauri/tauri.conf.json` | Identity `ai.nodemode.formchem`, windows, bundle targets, `externalBin`, the updater endpoint | +| `src-tauri/tauri.macos.conf.json` | macOS only: no `externalBin`, and the engine folder `src-tauri/engine` shipped as the resource `engine` | | `src-tauri/capabilities/` | Window permissions | | `src-tauri/flatpak/` | The Flatpak manifest and `ai.nodemode.formchem.metainfo.xml` | -| `setup/freeze_backend` | PyInstaller build of `backend/formchem_engine.py`, named `formchem-engine-` | +| `setup/freeze_backend` | PyInstaller build of `backend/formchem_engine.py`: on macOS a one-folder build copied to `src-tauri/engine`, flattened and checked; elsewhere a one-file sidecar named `formchem-engine-` | +| `setup/lib.sh` | `fc_engine_folder`, `fc_flatten_engine` and `fc_sign_engine`, shared by `freeze_backend` and `build_app` | | `build_app`, `build_app.bat` | Freeze the engine and build the desktop bundle on this machine | +## Startup + +Before 0.7.0 the engine was one file on every system. A one-file engine unpacks itself (RDKit, Indigo, numpy and Python: several hundred megabytes and hundreds of libraries) into a new temporary folder at every launch, and macOS checks every unpacked library again each time, which is why the owner's Mac took about 30 seconds to open the app. On macOS the engine now ships already unpacked, so nothing is unpacked at launch. Measured on Linux, where the same freeze was timed: the engine reaches its address in 0.46 s from source, 1.5 s frozen as one file and 0.55 s frozen as a folder. The splash stays at least 2.6 s from launch (the family value, running alongside the engine start), so the expected open time on a Mac is about 3 seconds. This has not been measured on a Mac yet. + +The one-folder build must be **flattened** before Tauri can carry it as a resource: every symbolic link is replaced by a copy, and `_internal/Python.framework` by a plain `_internal/Python` (the folder grows from about 314 to 426 MB). When `APPLE_SIGNING_IDENTITY` is set, PyInstaller signs with it and `fc_sign_engine` signs every Mach-O file left unsigned. `./formchem desktop check` fails on macOS if `src-tauri/engine` has no program, a symbolic link or a `.framework`, and `./formchem clean` removes the folder. On macOS `cargo check`, `cargo build` and `tauri dev` need the folder to exist; `./formchem desktop dev` freezes first when it is missing. Linux and Windows keep the one-file sidecar for now (Linux packages put resources in another place than the program, and neither could be bundled and tested for this version). + ## Contract -- The sidecar name in `externalBin` and in `main.rs` stays `formchem-engine`. +- The engine is called `formchem-engine` everywhere: the sidecar name in `externalBin` and in `main.rs`, and the program inside the macOS engine folder. +- The macOS engine folder holds no symbolic links and no `.framework`. - The title bar on macOS is the overlay style: the traffic lights sit over the window's own title bar, which carries `data-tauri-drag-region`. - The updater reads `https://dl.formai.studio/formchem/updates/latest.json`; the public key in the repository stays empty, because formcompiler holds the key pair. - Nothing GPL goes into the frozen engine. @@ -35,8 +45,17 @@ Run it from source with `./formchem desktop dev`; `./formchem desktop build` mak | Engine packages | `backend/requirements*.txt` into `backend/venv`, reinstalled when the files or Python change | | Window packages | `npm ci` in `frontend/`, rerun when `package-lock.json` or Node change | | Tauri CLI | `frontend/node_modules/.bin/tauri` must exist, and its major.minor must equal the `tauri` crate's in `src-tauri/Cargo.lock`; each `@tauri-apps/plugin-*` package must share major.minor with its `tauri-plugin-*` crate | -| Build | the window (`npm run build`), the engine frozen by PyInstaller with the window, the notices and the template library, a `--selfcheck` of the frozen engine, then the Tauri bundle (`.app` and `.dmg` on macOS, `.deb`, `.rpm` or AppImage on Linux) | +| Build | the window (`npm run build`), the engine frozen by PyInstaller with the window, the notices and the template library (on macOS as a flattened one-folder in `src-tauri/engine`, signed when `APPLE_SIGNING_IDENTITY` is set; elsewhere as one file), a `--selfcheck` of the frozen engine, then the Tauri bundle (`.app` and `.dmg` on macOS, `.deb`, `.rpm` or AppImage on Linux) | **The Tauri CLI pin.** `@tauri-apps/cli` is a dev dependency in `frontend/package.json`, pinned at 2.12.6 because the `tauri` crate in `Cargo.lock` is 2.12.7: the CLI's major.minor must always equal the crate's, so a crate update to 2.13 needs the CLI at 2.13 in the same change. Before 0.6.0 package.json did not list the CLI at all and the build stopped with "the Tauri CLI did not install"; the message now names package.json. With the pin, the owner's `./build_app` on macOS (Apple silicon, Python 3.14) built the app. `./formchem desktop check` runs the same version comparison without building. -`--reinstall` reinstalls both package sets, `--clean` removes earlier build output, `--bundles` picks the bundle kinds and `--config` merges an extra Tauri config (formcompiler's contract mode). +`--reinstall` reinstalls both package sets, `--clean` removes earlier build output (including `src-tauri/engine`), `--bundles` picks the bundle kinds and `--config` merges an extra Tauri config (formcompiler's contract mode). + +## Desktop-only paths + +- **Saving exports.** The window shows the system's save dialog (a folder dialog for Each structure) and asks the engine to write the file through `POST /api/files/write`, because the webview cannot write files itself; the engine writes outside your home folder only where you chose the place in the dialog. +- **Printing** goes through the shell's `print_window` command, because the macOS webview ignores the page's own print call. +- **Clipboard.** The windows may read and write the clipboard from the page (WebKitGTK on Linux and WebView2 on Windows need this for Edit > Paste). On macOS, Cut, Copy, Paste and Select All in the system Edit menu are the system's own items, so they reach the drawing as well as text fields. +- **Menus.** The macOS menu bar is built from the same menu definitions as the in-window menus, so Scale, Grid, Dark Page, Export, Copy As and Paste Special appear there too. In the window, menus that do not fit beside the title fold into More menus. + +None of these paths, nor the startup time, has been run in a macOS build of 0.7.0 yet. diff --git a/.docs/wiki/Drawing.md b/.docs/wiki/Drawing.md index 1c17ae0e..396aa6b5 100644 --- a/.docs/wiki/Drawing.md +++ b/.docs/wiki/Drawing.md @@ -8,7 +8,7 @@ Press a tool's key with the pointer away from atoms and bonds, or click it on th | Key | Group | Tools | What a click or drag does | | --- | --- | --- | --- | -| `V` | Selection | Select, Lasso (`L`) | Click to select, drag on empty paper for a marquee (the lasso draws a free shape). Drag a selection to move it (`Shift` keeps it level or upright); drag one atom to reshape, dropping it on another atom merges them. The round handle above a selection rotates it in 15 degree steps (`Shift` for free rotation). Arrow keys nudge by 1 pt, `Shift` 10 pt, `Alt` 0.1 pt. | +| `V` | Selection | Select, Lasso (`L`) | Click to select, drag on empty paper for a marquee (the lasso draws a free shape). Drag a selection to move it (`Shift` keeps it level or upright); drag one atom to reshape, dropping it on another atom merges them. The round handle above a selection rotates it in 15 degree steps (`Shift` for free rotation). The four square handles at the corners of a selection that holds a structure scale it on the sheet (`Alt` about the centre, `Shift` in 10 percent steps; see [Grid and Page](Grid-and-Page)). Arrow keys nudge by 1 pt, `Shift` 10 pt, `Alt` 0.1 pt. | | `B` | Bonds | Single, double, triple, wedge, hashed wedge, wavy, bold, dashed, dative, aromatic | Click empty paper for a new bond, click an atom to grow a bond from it at a good angle, drag from an atom to aim it, click a bond to change it to the tool's kind. | | `C` | Chain | Chain | Drag from an atom or empty paper to draw a zig-zag chain; a note shows the carbon count, and typing digits during the drag sets it. | | `R` | Rings | Benzene, cyclopropane to cyclooctane | Click empty paper for a free ring, click a bond to fuse a ring onto it, click an atom for a spiro ring (`Alt`-click attaches the ring through a new bond). | @@ -19,7 +19,15 @@ Press a tool's key with the pointer away from atoms and bonds, or click it on th | `Z` | Zoom | Zoom | Click to zoom in at the point, `Alt`-click to zoom out. `Ctrl` with the wheel zooms anywhere; View has Zoom In (`Ctrl+=`), Zoom Out (`Ctrl+-`), Zoom to Fit (`Ctrl+0`) and Actual Size (`Ctrl+1`). | | `W` `P` `K` `G` `O` | Arrows, Symbols, Brackets, Shapes, Orbitals | and Table, TLC, Image, Caption (in Text) | The annotation tools of 0.5.0; see [Annotations](Annotations). Reaction arrows and plus signs make a scheme FormChem can read; see [Reactions](Reactions). | -Right-click an atom, a bond or the paper for its context menu; from 0.6.0 the atom and bond menus also hold Atom Query, Enhanced Stereo, Query Bond and Define R-Group, and a selection of several atoms Contract Abbreviation. Structure has Clean Up Structure, Lay Out Structure, the abbreviation and explicit hydrogen commands, Assign Wedges, the Enhanced Stereo and Query submenus, Check Structure, Compute Properties and the flips (see [Stereo and Queries](Stereo-and-Queries) and [Analysis](Analysis)); Arrange has the stacking order, align, distribute, Rotate 90 Degrees, Group and Ungroup; Edit has Duplicate (`Ctrl+D`), Delete, Select All (`Ctrl+A`), Find, Find Substructure and Copy as SMARTS. With the selection tool, a selected arrow, line or box shows handles to reshape it. +Right-click an atom, a bond or the paper for its context menu; from 0.6.0 the atom and bond menus also hold Atom Query, Enhanced Stereo, Query Bond and Define R-Group, and a selection of several atoms Contract Abbreviation. Structure has Clean Up Structure, Lay Out Structure, the abbreviation and explicit hydrogen commands, Assign Wedges, the Enhanced Stereo and Query submenus, Check Structure, Standardise... (from 0.7.0: salts, charges, functional groups and tautomers, with a preview), Compute Properties and the flips (see [Stereo and Queries](Stereo-and-Queries) and [Analysis](Analysis)); Arrange has the stacking order, align, distribute, Rotate 90 Degrees, Group and Ungroup, and from 0.7.0 Scale..., Scale Up 10% (`Ctrl+Alt+=`), Scale Down 10% (`Ctrl+Alt+-`) and Scale Labels and Text with Structures; Edit has Cut, Copy and Paste for the drawing (`Ctrl+X`, `Ctrl+C`, `Ctrl+V`), Copy As (SMILES, CXSMILES, Molfile, InChI, InChIKey, SMARTS, SVG, PNG, CDXML), Paste Special... (`Ctrl+Shift+V`), Duplicate (`Ctrl+D`), Delete, Select All (`Ctrl+A`), Find and Find Substructure (see [Clipboard](Clipboard)). With the selection tool, a selected arrow, line or box shows handles to reshape it. + +## Lay out and Clean Up + +Structures inserted from SMILES, files opened without 2D coordinates, Lay Out Structure and Clean Up Structure all go through the engine's 2D layout. From 0.7.0 it tries several layouts, scores each for atoms and labels that touch and bonds that cross, keeps the clearest (the familiar CoordGen layout unless another is clearly better) and then swings crowded substituents apart without changing any stereo or double bond geometry. Taxol, erythromycin and vancomycin now insert with no touching labels. Clean Up keeps the result as close as it can to what you drew. Bridged polycycles such as morphine can still show a bond crossing a ring, because only substituents are moved. + +## Grid, snapping and the page + +View > Grid picks lines, dots, crosses, isometric or hexagonal grids and Grid Settings..., and Snap to Grid puts new bonds, chains, rings and objects on grid points (hold `Alt` to place freely); on an isometric or hexagonal grid at the bond length every atom of a chain or a six-membered ring lands on a point. View > Dark Page shows the page dark, which is the default. Both are on [Grid and Page](Grid-and-Page). ## Hover keys @@ -69,8 +77,8 @@ While the pointer rests on an atom or a bond, its hover keys win over the tool k 5. Every hover key works on the atom or bond under the cursor: `O` for oxygen, `2` for a double bond, `Shift+6` for a ring, `4` for a chain of four, `Enter` then typing for a label. 6. The context-menu key or `Shift+F10` opens the menu of the atom or bond under the cursor. `Escape` leaves the cursor. -Structures can also come in without drawing: Insert > Structure from SMILES, Insert > Template... (206 rings, heterocycles, amino acids, sugars, nucleotides, protecting groups, reagents and glassware), Reaction > Insert Reaction from Clipboard, or File > Open for molfile, SDF, RXN, SMILES, InChI, CML and CDXML files (RXN files and reactions in CML or CDXML open as drawn schemes). +Structures can also come in without drawing: Insert > Structure from SMILES, Insert > Template... (206 rings, heterocycles, amino acids, sugars, nucleotides, protecting groups, reagents and glassware), Reaction > Insert Reaction from Clipboard, Paste of any structure text, File > Open for molfile, SDF, RXN, RD, SMILES, CXSMILES, SMARTS, InChI, CML, CDXML and CDX files and pictures FormChem exported (reactions open as drawn schemes), or File > Import... to add a file's contents to the open drawing. See [Formats and Export](Formats-and-Export). ## Styles -New drawings start from the default style chosen in Preferences > Drawing (Journal standard (1996), Journal variant B, Large screen or New document) with the bond length, line width, bold width and label size set there on top; choosing a style fills those numbers in from it. Preferences > Drawing and Chemistry also switch element colours, carbon labels, aromatic circles, valence warnings and stereo labels for the view. The View menu has Show Stereochemistry (CIP labels), Show Enhanced Stereo Groups (abs, and1, or1 under the labels) and Show Query Features (the purple query tags); the last two are choices of this window, not of the drawing. +New drawings start from the default style chosen in Preferences > Drawing (Journal standard (1996), Journal variant B, Large screen or New document) with the bond length, line width, bold width and label size set there on top; choosing a style fills those numbers in from it. Preferences > Drawing and Chemistry also switch element colours, carbon labels, aromatic circles, valence warnings and stereo labels for the view. The View menu has Show Stereochemistry (CIP labels), Show Enhanced Stereo Groups (abs, and1, or1 under the labels) and Show Query Features (the purple query tags); the last two are choices of this window, not of the drawing, as are View > Dark Page and Show Grid. diff --git a/.docs/wiki/Formats-and-Export.md b/.docs/wiki/Formats-and-Export.md new file mode 100644 index 00000000..bcfeb898 --- /dev/null +++ b/.docs/wiki/Formats-and-Export.md @@ -0,0 +1,66 @@ +# Formats and Export + +From 0.7.0 FormChem opens and saves the common chemistry files, exports pictures that open again as editable drawings, and prints at real size. Every format, what it loses, the report codes and the engine routes are in [`docs/FORMATS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/FORMATS.md). + +## Opening files + +File > Open (or dropping a file on Home) reads: + +| Format | Extensions | Notes | +| --- | --- | --- | +| MDL molfile | `.mol`, `.mdl` | V2000 and V3000, with query features, enhanced stereo and R-group blocks | +| SD file | `.sdf`, `.sd` | up to 1000 records, with their data fields; a record that fails is skipped and counted | +| RXN | `.rxn` | opens as a drawn scheme; the title becomes the step name, the comment line the conditions | +| RD file | `.rdf`, `.rd` | reactions and molecules with their data; every step is kept | +| SMILES, CXSMILES, reaction SMILES | `.smi`, `.smiles`, `.cxsmi`, `.cxsmiles`, `.rsmi` | one structure (or one reaction) per line, with an optional name | +| SMARTS | `.sma`, `.smarts` | opens as query structures | +| InChI | `.inchi` | one per line, with an optional name | +| CML | `.cml` | molecules, data and reaction schemes | +| CDXML, CDX | `.cdxml`, `.cdx` | structures, arrows, plus signs and text | +| Pictures FormChem exported | `.svg`, `.png`, `.pdf`, `.eps` | the drawing kept inside opens again, unchanged | + +A file from another program opens as a new, unsaved drawing at your drawing's bond length. When anything was lost or changed on the way in, a short note appears ("opened with notes", or how many things changed) with **Details**: a panel that lists each item with its count, such as text whose fonts were approximated, a record that could not be read, or stereocentres of unknown configuration. Nothing in the file on disk changes; save the drawing to keep it as a `.fchem` file. + +**File > Import...** brings one or more files into the drawing you have open instead of opening each as a drawing of its own: chemistry files, `.fchem` drawings and pictures that carry a drawing. Each file lands in free space to the right of or below what is already there, at your drawing's bond length, selected, and is one undo step. An SD file brings at most 50 structures, laid out in a table, and the note ("imported with notes") says how many were left out; File > Open reads the whole file. Only the first page of a drawing with several pages comes in. + +## Exporting pictures + +File > Export has Export as PNG..., SVG..., PDF... and EPS..., and **Export Picture...** opens the dialog: + +| Choice | What it does | +| --- | --- | +| Format | PNG, SVG, PDF or EPS | +| Scope | Whole page (cropped to the drawing), Selection, or Each structure (one file per structure, named after it) | +| Resolution | PNG only: 72, 150, 300 (default) or 600 dpi | +| Background | Transparent or White | +| Scale | a percent of real size: at 100 percent one point of the drawing is one point in the file | +| Margin | space around the drawing, in points | +| Keep the editable drawing inside the file | on by default (see below) | + +The dialog remembers your choices. SVG keeps the labels as text and embeds small subsets of the label fonts (Arimo and Tinos), so it looks the same everywhere and stays editable in a vector program; PDF and EPS draw the labels as outlines, and PDF adds a hidden text layer so labels can be searched and copied. PNG files carry their resolution, so they place at the right size in documents. + +Exports are drawn from the drawing itself, never from the screen: the dark page, the grid, the selection and valence warnings never show in them, and line widths are the true ones. + +## The drawing inside the picture + +With "Keep the editable drawing inside the file" on, the picture carries a copy of the drawing: in SVG as metadata, in PNG as a text chunk, in PDF as an attached file (`drawing.fchem.json`) and in EPS as comment lines. Open the picture with File > Open, or paste it, and you get the drawing back with the same structures, wedges, arrows and reaction steps, ready to edit. Pictures placed inside the drawing are drawn into the export but not carried in the copy. + +## Exporting chemistry files + +File > Export also has Export as CDXML..., Export as Molfile... and Export as SMILES...; agents and the engine routes reach every format of the table above (and InChIKey). Each format keeps what it can and the export says what it left out: a warning toast for real losses (such as enhanced stereo groups in SMILES, or text in a molfile), with the full report from the engine. A few rules worth knowing: + +- A molfile is written as V3000 by itself when the drawing needs it (more than 999 atoms or bonds, AND or OR groups, query features, R-groups). Several structures on a page become one molfile; use an SD file to keep them apart. +- RXN holds one reaction step; an RD file or CML keeps a whole scheme. +- Plain SMILES cannot hold query structures; use SMARTS or a V3000 molfile. +- CDXML and CDX keep structures, arrows, plus signs and text, but not colours, fonts, the bond length, line breaks or curved arrows. +- Abbreviations are written as their full structures in every format but `.fchem`. + +In the desktop app each export shows the system's save dialog (Each structure asks for a folder) and remembers the last folder; in a browser the file downloads. + +## Printing + +File > Print... (`Ctrl+P`, `Cmd+P` on macOS) prints the page at real size on paper the size of the page, or with a selection only the selection, in its place on the page. The dark page never prints. + +## For agents + +`export-png`, `export-svg`, `export-pdf`, `export-eps`, `export-picture`, `export-cdxml`, `export-mol`, `export-smiles` and `print` run through `run_command` like any other command; see [Agents](Agents). Large conversions without the window are on [Command Line](Command-Line). diff --git a/.docs/wiki/Getting-Started.md b/.docs/wiki/Getting-Started.md index f6167ea9..0f7d92e8 100644 --- a/.docs/wiki/Getting-Started.md +++ b/.docs/wiki/Getting-Started.md @@ -24,7 +24,20 @@ Aspirin, with the mouse and a few keys: 5. Open the Analysis panel (title bar or View > Analysis Panel): formula C9H8O4, molecular weight 180.16, exact mass 180.0423 and the elemental analysis. The formula also sits in the status bar. 6. Structure > Clean Up Structure tidies bond lengths and angles in one undo step. `Ctrl+S` (`Cmd+S` on macOS) saves; a new drawing asks for a name. -Faster: Insert > Structure from SMILES and paste `CC(=O)Oc1ccccc1C(=O)O`. Molfile, SDF, SMILES, CML and CDXML files open from File > Open or by dropping them on Home. [Drawing](Drawing) lists every tool and hover key, and how to draw with the keyboard alone. +Faster: copy `CC(=O)Oc1ccccc1C(=O)O` and press `Ctrl+V` on the canvas, or use Insert > Structure from SMILES. Molfile, SDF, RXN, SMILES, InChI, CML, CDXML and CDX files open from File > Open or by dropping them on Home, and File > Export saves PNG, SVG, PDF and EPS pictures that open again as the drawing ([Formats and Export](Formats-and-Export)). The page is dark by default; View > Dark Page turns it off ([Grid and Page](Grid-and-Page)). [Drawing](Drawing) lists every tool and hover key, and how to draw with the keyboard alone. + +## Connect an agent + +Claude Code, Codex, Cursor, Antigravity or any MCP client can draw in the window you have open: + +1. Start FormChem (`./formchem`, or the desktop app). +2. In the FormChem folder run `./formchem agents install`. It writes the configs for Claude Code (`.mcp.json`), Codex, Cursor and Antigravity with the agent token, and installs the FormChem skill so the agent knows the tools. For another client, Window > Agents and MCP shows the setup lines with the token filled in, or use `./formchem mcp` as a stdio server, which needs no token. +3. Restart the agent and ask it, for example: "Draw aspirin in FormChem and check it." +4. The first time it changes something, the window asks you: Deny, Allow once or Always allow. + +The agent calls `draw_from_smiles`: the structure appears in a new drawing, the title bar shows "[agent] just edited" with Stop, and what it drew is outlined for a moment. It then checks its work with `render` (a picture drawn by the window) and `get_structure` (SMILES, InChIKey, molfile). `Ctrl+Z` undoes the whole call in one step; Window > Agent Activity lists every call with undo for the latest one. [Agents](Agents) lists the tools and [Agent Activity](Agent-Activity) the panel. + +An agent you connected to 0.7.0 over HTTP needs the token from 0.8.0 on: run `./formchem agents install` again (`./formchem agents token` prints the token). ## Commands @@ -34,12 +47,13 @@ Faster: Insert > Structure from SMILES and paste `CC(=O)Oc1ccccc1C(=O)O`. Molfil | `./formchem backend`, `./formchem frontend` | one half only | | `./formchem build`, `./formchem serve` | build the frontend, serve it from the engine (preview on 5221) | | `./formchem install-desktop`, `./formchem desktop dev`, `./formchem desktop build` | the Tauri desktop app | -| `./formchem freeze` | freeze the engine into the desktop sidecar | +| `./formchem freeze` | freeze the engine for the desktop app (a folder in `src-tauri/engine` on macOS, a one-file sidecar elsewhere) | +| `./formchem convert`, `batch`, `descriptors`, `render` | convert structure files and folders, write properties to CSV, draw every record ([Command Line](Command-Line)) | | `./formchem i18n check`, `scan`, `export`, `import` | the interface languages: gaps, new strings, CSV out and in | | `./formchem counts` | lines of code per language | | `./formchem doctor`, `./formchem clean` | checks, cleanup | | `./formchem mcp` | the MCP server over stdio | -| `./formchem agents install`, `./formchem agents sync` | agent configs and skills | +| `./formchem agents install`, `./formchem agents sync`, `./formchem agents token` | agent configs with the agent token, and skills; print the token | | `./formchem cli list`, `describe`, `run`, `batch` | the window's command catalogue from a terminal; `run` needs the window open | | `./formchem claude` | Claude Code in this terminal with FormChem's MCP tools attached | @@ -47,4 +61,4 @@ Each command has a `formchem.bat` twin on Windows. ## Ports and folders -The engine listens on 127.0.0.1:8220 (`FORMCHEM_PORT`), the Vite app on localhost:5220. The desktop shell starts the engine on a free port and prefers 8221. The data folder is `~/formchem` (`FORMCHEM_DATA_DIR`); it holds `settings.json`, `library.json` (Home's lists), `commands-catalogue.json` and, while the engine runs, `engine.json`. +The engine listens on 127.0.0.1:8220 (`FORMCHEM_PORT`), the Vite app on localhost:5220. The desktop shell starts the engine on a free port and prefers 8221. The data folder is `~/formchem` (`FORMCHEM_DATA_DIR`); it holds `settings.json`, `library.json` (Home's lists), `commands-catalogue.json`, `agent-token` (0.8.0), the `Agent log` folder (0.8.0) and, while the engine runs, `engine.json`. diff --git a/.docs/wiki/Grid-and-Page.md b/.docs/wiki/Grid-and-Page.md new file mode 100644 index 00000000..d09c8adf --- /dev/null +++ b/.docs/wiki/Grid-and-Page.md @@ -0,0 +1,56 @@ +# Grid and Page + +How the page looks and how things line up on it: the dark page, the grid and snapping, rulers, and making structures larger or smaller on the sheet. All of it is from 0.7.0 except the rulers (0.5.0). + +## Dark page + +The drawing page shows dark with light bonds and labels, as in FormTxt, and it is on by default. Element colours stay recognisable (oxygen reads light red, nitrogen light blue), the orange selection and the red warnings keep their real colours, and pictures placed in the drawing are shown close to their real colours. Turn it off with View > Dark Page, the canvas right-click menu or Preferences > Interface > Page; the choice is remembered on this device and other windows follow it. + +The dark page only changes the screen. Exports, printing and copies always have the real colours on a white or transparent background. Under the dark page, very saturated light colours in placed pictures (pure yellow, for example) show beige or brick; that is a limit of the screen filter, not of the picture. + +## Grid + +View > Grid has the grid types, Snap to Grid and Grid Settings...: + +| Type | What it shows | +| --- | --- | +| Lines | square grid lines | +| Dots | dots at the square grid's points | +| Crosses | small plus marks at the square grid's points | +| Isometric | triangle lines at 30, 90 and 150 degrees | +| Isometric dots | dots at the triangle corners | +| Hexagonal | hexagon edges, with vertical sides | +| Hexagonal dots | the hexagon corners | + +Grid Settings... sets the type, the spacing (5 mm, 1/4 in, 10 pt, the bond length, or any value in pt, mm, cm or in, from 1 to 288 pt), a major line every so many cells (0 for none; hexagonal grids have none) and the strength (faint, normal or strong), and shows the result on the page while you choose. **Apply to This Drawing** keeps the grid with the drawing (it is saved in the file and changing it is one undo step); **Make Default for New Drawings** sets the grid every drawing gets until it chooses its own, which Preferences > Drawing > Grid also sets. Square grids start at 7.2 pt, isometric and hexagonal grids at the bond length. + +Show Grid turns the grid off and on for this window. The grid never appears in exports or printing. When you zoom far out, the finest lines are hidden (only the major lines, or a coarser grid, remain), so the grid never becomes a grey wash. + +## Snap to Grid + +With View > Grid > Snap to Grid on (it is off by default, and remembered): + +- A new bond, chain or ring starts on a grid point. On a square grid the bond keeps its length and its 15 degree steps, so only the first atom lands on a point. +- On an isometric or hexagonal grid whose spacing is the bond length, every atom of a chain or a six-membered ring lands on a grid point: bonds follow the grid's directions and rings turn to fit it. That is the quickest way to draw neat zig-zag chains and fused rings. +- Moving a selection snaps the atom or the end you grabbed, and a whole structure stays on the grid. Dragging arrow ends, line points and box corners snaps too, and new arrows, shapes, brackets, tables and TLC plates start and end on points. +- Hold `Alt` (`Option` on macOS) to place freely. `Shift` keeps its usual meaning (level or upright moves, angle steps), and snapping waits while it constrains. +- Rotating and the scale corners do not snap. + +## Rulers + +View > Show Rulers shows rulers along the top and left edges in the drawing's units (click the corner square to switch between pt, mm, cm and in). Drag out of a ruler to place a guide, drag it back to remove it, or use View > Clear Guides. Guides belong to the window, are not saved, and tools do not snap to them. + +## Making structures larger or smaller + +Zoom only changes your view. To make the drawing itself larger on the sheet: + +- **Corner handles.** Select structures with the selection or lasso tool: four square handles appear at the corners of the selection. Drag one to scale; the opposite corner stays put. `Alt` scales about the centre, `Shift` in 10 percent steps, and `Escape` cancels. A label beside the pointer shows the scale and the bond length ("Scale 150%", "Bond 21.6 pt"), and hovering a corner shows the current bond length. +- **Arrange > Scale...** sets a percent or a target bond length, for the selection or, with nothing selected, for every structure on the page, each about its own centre so a scheme keeps its layout. +- **Arrange > Scale Up 10%** and **Scale Down 10%** (`Ctrl+Alt+=` and `Ctrl+Alt+-`, `Cmd+Option` on macOS) step the same way; the two cancel exactly. +- **Arrange > Scale Labels and Text with Structures** (on by default; also in the Scale dialog and in Preferences > Drawing > Scaling): on, line widths, atom labels, arrows and text grow with the drawing; off, they keep the drawing's style and only the geometry changes. + +Each scale is one undo step, the chemistry (SMILES, stereo, wedges) never changes, and the status line says the result, such as "Scaled to 92.6%, bond length 20.0 pt". Scaling and scaling back leaves no trace in the file. + +## For agents + +`dark-page {on?}`, `show-grid {on?}`, `snap-to-grid {on?}`, `grid-type {type, scope?}`, `grid-spacing {value, unit?, scope?}`, `grid-settings {...}`, the radio commands `grid-lines` to `grid-hex-dots`, `scale-selection {percent | bond_length, labels?}`, `scale-up`, `scale-down` and `scale-labels` run through `run_command`; `scope: "default"` changes the default grid instead of the drawing's. See [Agents](Agents). diff --git a/.docs/wiki/Home.md b/.docs/wiki/Home.md index d7371c97..d6d21917 100644 --- a/.docs/wiki/Home.md +++ b/.docs/wiki/Home.md @@ -2,22 +2,27 @@ FormChem is the chemical structure drawing suite of the FormAI family: local-first, no account, on macOS, Windows and Linux. It runs in the browser or as a Tauri desktop app, with a local engine that holds every document, and an MCP server so Claude Code, Codex, Cursor or Antigravity can work in the same window you see. -FormChem is in development. 0.1.0 is the family skeleton (dispatcher, engine, window, desktop shell, CI) and 0.2.0 the family shell (title bar, menus, Home, Preferences, the terminal and agent dock, extensions, Help and updates). 0.3.0 added documents and the RDKit chemistry engine, 0.4.0 the drawing canvas, its tools and hover keys, and the Analysis panel, 0.5.0 reactions and annotations: arrows and the other drawn objects, reaction perception, atom mapping, balance and stoichiometry, the template library, Find and rulers, and 0.6.0 stereo, queries and analysis: CIP labels and enhanced stereo, abbreviations, query structures and R-groups, calculated properties with their methods, the structure check and the isotope pattern. +FormChem is in development. 0.1.0 is the family skeleton (dispatcher, engine, window, desktop shell, CI) and 0.2.0 the family shell (title bar, menus, Home, Preferences, the terminal and agent dock, extensions, Help and updates). 0.3.0 added documents and the RDKit chemistry engine, 0.4.0 the drawing canvas, its tools and hover keys, and the Analysis panel, 0.5.0 reactions and annotations: arrows and the other drawn objects, reaction perception, atom mapping, balance and stoichiometry, the template library, Find and rulers, and 0.6.0 stereo, queries and analysis: CIP labels and enhanced stereo, abbreviations, query structures and R-groups, calculated properties with their methods, the structure check and the isotope pattern. 0.7.0 is formats and exchange: chemistry files in and out with a report of what each format loses, pictures (PNG, SVG, PDF, EPS) that open again as the drawing, printing, the clipboard, Standardise and a command line for whole files, plus what the first desktop test asked for: a fast start on macOS, a clearer 2D layout, the dark page, resizing on the sheet and grids. 0.8.0 is agents: 42 MCP tools with which an agent makes and opens drawings, draws structures and reaction schemes from SMILES or molfiles, edits them atom by atom by id, reads them back and checks its work with a picture from the window's own renderer, each change one undo step, plus Agent Activity with undo and Stop, and an agent token for the HTTP endpoint. | Page | What it covers | | --- | --- | | [Getting Started](Getting-Started) | Install, boot, your first structure, the dispatcher commands, ports and the data folder | | [Drawing](Drawing) | The tools, the hover keys, drawing with the keyboard alone, and styles | +| [Grid and Page](Grid-and-Page) | The dark page, grid types and snapping, rulers, and making structures larger or smaller on the sheet | | [Annotations](Annotations) | Arrows, symbols, brackets, shapes, tables, TLC plates, orbitals, pictures, captions, arranging and grouping, templates, Find and rulers | | [Reactions](Reactions) | Reaction schemes, roles, atom mapping, balance, stoichiometry, RXN and reaction SMILES | | [Stereo and Queries](Stereo-and-Queries) | CIP labels, enhanced stereo groups, wedges, abbreviations, query atoms and bonds, substructure search, SMARTS, R-groups and Markush structures | | [Analysis](Analysis) | Calculated properties with their methods, the isotope pattern, Copy Analysis and Check Structure | -| [Agents](Agents) | The MCP server, agent configs, skills and consent | +| [Formats and Export](Formats-and-Export) | Opening chemistry files and the import report, File > Import, exporting pictures that keep the drawing inside, exporting chemistry files, printing | +| [Clipboard](Clipboard) | Copy, Cut, Paste and Paste Special, Copy As, what goes on the clipboard and what each platform can do | +| [Command Line](Command-Line) | Converting files and folders, properties to CSV and pictures of every record, with standardising and the failure report | +| [Agents](Agents) | The MCP server and its 42 tools, drawing directly, agent configs, the agent token, skills, consent and Stop | +| [Agent Activity](Agent-Activity) | Every call agents made with undo for the latest one, the editing chip with Stop, and the call log | | [Terminal](Terminal) | The terminal and agent dock | | [Extensions](Extensions) | Form extensions in FormChem | | [Project Format](Project-Format) | The `.fchem` document | | [Architecture](Architecture) | The engine, the live channel and the window | -| [Desktop](Desktop) | The Tauri shell and the engine sidecar | +| [Desktop](Desktop) | The Tauri shell, the engine folder on macOS and the sidecar elsewhere, startup | | [Development](Development) | Repo rules, verification and commits | | [Releasing](Releasing) | Version bumps, compile branches and formcompiler | diff --git a/.docs/wiki/Project-Format.md b/.docs/wiki/Project-Format.md index e61a18a7..1a78559b 100644 --- a/.docs/wiki/Project-Format.md +++ b/.docs/wiki/Project-Format.md @@ -28,6 +28,8 @@ The engine writes the package to a temporary file in the same folder and renames - `rgroups` on a scaffold fragment define its R-groups by number: `members` (fragment ids), `occurrence`, `rest_h`, `if_then`, and `attach`, a map of member fragment id to its attachment atom ids. A member without an `attach` entry attaches at its atoms with `data.attach` 1 or 2, else at its `*` stubs (no label, one bond, standing for the R atom), else at its first atom. - `expansions` hold what an abbreviation atom stands for (its atoms, bonds, attachment atoms and reversed label); `source` is `builtin` when the expansion came from the shipped library and `user` otherwise. - `media` maps a media id to `{name, mime, bytes, w, h, sha256}`; an `image` object names the id. The bytes go into the package as `media/[id].[ext]`, and only ids listed in `media` are written. +- From 0.7.0 `style.grid` may hold the drawing's page grid: `{type, spacing, major, strength}`, where `type` is `lines`, `dots`, `crosses`, `isometric`, `isometric-dots`, `hex` or `hex-dots` and `spacing` is points or `"bond"` (the bond length). It is read only from the document's own style, never from presets or an object's style, and it changes only the screen and snapping, never exports or the chemistry. A drawing without it shows the window's default grid and saves unchanged. Whether the grid is shown and whether snapping is on belong to the window, not the file ([Grid and Page](Grid-and-Page)). +- `meta.imported` records a file opened from another format (`name`, `format`, and from 0.7.0 `report`, the import report items). ## What is not in the file @@ -39,4 +41,8 @@ Every change is a transaction: a list of `set`, `ins`, `del` and `move` ops on J ## Other formats -Molfile, SDF, RXN, SMILES and CXSMILES, InChI, CML and CDXML files open as new, unsaved drawings laid out at the drawing's bond length; RXN files and CML or CDXML files with a reaction open as drawn schemes with their roles set. A reaction step exports as reaction SMILES or RXN (V2000 or V3000) from 0.5.0 ([Reactions](Reactions)); exporting whole drawings to the other formats arrives in 0.7.0. From 0.6.0 the engine also writes and reads V3000 molfiles with query features, enhanced stereo and R-group blocks, and SMARTS for query structures ([Stereo and Queries](Stereo-and-Queries)); a molfile with its chiral flag at 0 opens with its centres absolute. Templates use the document format too ([`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md)). +Molfile, SDF, RXN, RD, SMILES and CXSMILES, SMARTS, InChI, CML, CDXML and CDX files open as new, unsaved drawings laid out at the drawing's bond length; files with reactions open as drawn schemes with their roles set. From 0.7.0 a drawing exports to all of them (and InChIKey), each with a report of what the format could not keep, and to SVG, PNG, PDF and EPS pictures ([Formats and Export](Formats-and-Export)). From 0.6.0 the engine also writes and reads V3000 molfiles with query features, enhanced stereo and R-group blocks, and SMARTS for query structures ([Stereo and Queries](Stereo-and-Queries)); a molfile with its chiral flag at 0 opens with its centres absolute. + +## The drawing inside pictures and on the clipboard + +A picture exported with "Keep the editable drawing inside the file" carries a copy of the drawing in the same `document.json` form, holding one page and only the exported objects, with `meta.embedded = {scope, from}` (`scope` is `page`, `selection` or `structure`, `from` the source document's id). It sits in SVG metadata, a PNG iTXt chunk, an attached file `drawing.fchem.json` in PDF, or `%FormChemSource:` comment lines in EPS, always under the MIME type `application/x-formchem+json`. Placed pictures are left out of the copy, because their bytes are not carried. Opening such a picture gives a new document with new document and page ids, the file name as its title and the object ids kept. The FormChem clipboard form is the same document shape with `meta.clipboard`, and pasting gives every object fresh ids. Details are in [`docs/FORMATS.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/FORMATS.md). Templates use the document format too ([`docs/TEMPLATES.md`](https://github.com/nodemode-dev/formchem/blob/main/docs/TEMPLATES.md)). diff --git a/.docs/wiki/_Sidebar.md b/.docs/wiki/_Sidebar.md index b36e1ab9..1536bfd9 100644 --- a/.docs/wiki/_Sidebar.md +++ b/.docs/wiki/_Sidebar.md @@ -3,11 +3,16 @@ - [Home](Home) - [Getting Started](Getting-Started) - [Drawing](Drawing) +- [Grid and Page](Grid-and-Page) - [Annotations](Annotations) - [Reactions](Reactions) - [Stereo and Queries](Stereo-and-Queries) - [Analysis](Analysis) +- [Formats and Export](Formats-and-Export) +- [Clipboard](Clipboard) +- [Command Line](Command-Line) - [Agents](Agents) +- [Agent Activity](Agent-Activity) - [Terminal](Terminal) - [Extensions](Extensions) - [Project Format](Project-Format) 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 diff --git a/AGENTS.md b/AGENTS.md index 5744301a..f08a46fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ FormChem exposes an MCP server at http://127.0.0.1:8220/mcp (stdio: `./formchem mcp`, which runs `setup/mcp_stdio.py`). Configs: .codex/config.toml, .cursor/mcp.json, .mcp.json, and for Antigravity ~/.gemini/config/mcp_config.json. Run `./formchem agents install` to install them and the skills for your home folder too. -Work in the app with six tools: get_context · list_commands · run_command · extensions_list · extension_command · handoff to the person (question when you need their input). Reading is open; changing tools make the window ask the person. FormChem 0.4.0 draws: get_context lists the open drawings (id, title, path, unsaved changes, revision, fragment count, formula), and you change them through run_command with the window's commands (list_commands first): insert-smiles {"smiles": "c1ccccc1O"} adds a structure, open-recent {"path"} opens a file, and select-all, delete, duplicate, flips, rotate-90, align, distribute, clean-structure, layout-structure, check-structure, undo and save act on the active drawing. Form extensions with the document permission read and change drawings by id. Dedicated drawing tools for agents arrive in 0.8.0. The skill packs live in .agents/skills: formchem-harness (using FormChem) and formchem-skillset (developing FormChem). The document contract is docs/FORMAT.md. +HTTP requests need the agent token (`./formchem agents token`; `agents install` writes it into the configs; the stdio transport sends it itself). FormChem has 42 tools. Reading is open; changing tools make the window ask the person the first time, and the person can Stop an agent. Since 0.8.0 agents draw directly: get_context or list_open_documents first; draw_from_smiles and draw_from_molfile place a structure as one undo step and answer with ids, SMILES, InChIKey, formula and a picture; get_atoms names atoms and bonds for the edit tools (add_atom, add_bond, set_charge, set_atom, set_stereo, replace_substructure, delete, move, scale, align, clean_layout, add_arrow, add_text, add_reaction), one undo step each; render, get_structure and validate check the result; convert and batch_convert match the CLI. Reaction and analysis tools, list_commands and run_command for the window's commands, Form extensions and handoff to the person (question when you need their input) are there too. The skill packs live in .agents/skills: formchem-harness (using FormChem) and formchem-skillset (developing FormChem). The document contract is docs/FORMAT.md. Clean room (details in CLAUDE.md): FormChem is written only from the owner's clean-room specifications. Never open, run, decompile or read the private documentation of the commercial suite it replaces, and never copy its names, icons, templates or text. Vendor names appear only to name file formats. diff --git a/CHANGELOG.md b/CHANGELOG.md index 8483ff03..b52c5554 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,132 @@ Versions follow `v*.*.*` with dots. Dates are US Eastern. +## 0.8.0 · 2026-12-03 + +Agents: Claude Code, Codex, Cursor, Antigravity or any MCP client can now draw in FormChem directly. An agent opens and makes drawings, draws structures and reaction schemes from SMILES or molfiles, builds and edits them atom by atom, reads every structure back in machine form, and checks its own work with a picture drawn by the window's own renderer. Every change is one undo step you see as it lands, Agent activity lists every call with undo for the latest one, and Stop in the title bar shuts an agent out. + +### New + +- The MCP server has 42 tools, 28 of them new in this version, listed with every argument in `docs/AGENTS.md`. +- Drawings: `list_open_documents`, `new_document`, `open_document` (FormChem drawings, chemistry files and pictures that carry a drawing), `save_document` and `close_document`. A drawing an agent makes or opens is shown in the window at once. +- Drawing: `draw_from_smiles` and `draw_from_molfile` lay a structure out with FormChem's scored 2D layout and place it in free space beside or below what is on the page, never on top of it and never after a reaction arrow where it would read as a product. A reaction SMILES (`reactants>agents>products`) draws a whole scheme with its arrow and plus signs, as Insert Reaction does. +- Checking: `render` returns a PNG or SVG of objects, the selection or the page, drawn by the window's own renderer when a window is open, so the agent sees what you see, arrows, text and your display preferences included. `get_structure` returns SMILES, CXSMILES, InChI, InChIKey, a molfile, formula, masses and elemental analysis for one object, your selection or every structure. `validate` runs the structure check and `compute_properties` the Analysis panel's properties, each value with its method. +- Converting: `convert` and `batch_convert` convert text, a file or a whole folder with the same code as `./formchem convert` and `./formchem batch`, so the output is identical, with failed records listed and the CSV report written as the command line writes it. +- Editing by id: `get_atoms` lists every atom and bond of a drawing with its id, and 14 edit tools change the drawing by those ids: `add_atom` (in the freest direction, zigzag for chains), `add_bond`, `set_charge`, `set_atom`, `set_stereo` (R or S on a centre, E or Z on a double bond), `replace_substructure`, `delete`, `move`, `scale`, `align`, `clean_layout`, `add_arrow`, `add_text` and `add_reaction`. +- Every change an agent makes is one transaction and one undo step, labelled in Edit > Undo with the tool's name (Undo Draw from SMILES, Undo Add atom), and every answer to a change carries the structure it now holds (ids, SMILES, InChIKey, formula, warnings) and a picture of it. +- Window > Agent Activity opens a panel with every call agents made, newest first: tool, arguments, duration, status, agent and drawing, with a filter by agent and Clear. Undo on a row undoes that call while it is still the latest step of its drawing, and a click on a row opens the drawing and selects what the call changed. +- While an agent changes the drawing you are looking at, the title bar shows which agent is editing, with Stop, the edge of the canvas lights up and what the call changed flashes for a moment (no animation under reduced motion). Stop refuses that agent's next calls and withdraws Always allow, until you allow it again in Agent activity. +- The agent token: HTTP MCP requests now carry a token, kept in `agent-token` in the data folder and readable by you only. `./formchem agents token` prints it, `./formchem agents install` writes it into the agent configs, and the Agents dialog shows the setup lines with the token filled in. + +### Changed + +- The HTTP MCP endpoint (`http://127.0.0.1:8220/mcp`) refuses requests without the agent token (401, with a message that says where the token is). If an agent that worked with 0.7.0 stops connecting, run `./formchem agents install` again in the FormChem folder, which writes the token into `.mcp.json`, Codex's, Cursor's and Antigravity's configs, or add the header `Authorization: Bearer` followed by the output of `./formchem agents token` to the client's FormChem entry. Clients that start FormChem over stdio (`./formchem mcp`) and FormChem's own agent tabs need nothing: they send the token themselves. +- The prompt that the chat panel copies for an outside agent says how to send the token. +- The MCP instructions, the `formchem://guide` resource and `get_context` describe the drawing tools; `get_context` reports `drawingTools: true`. + +### Fixed + +- Water and other lone small molecules were drawn hydrogen last (OH2, SH2, ClH). They are drawn H2O, H2S, HCl, HF and HBr, as chemists write them, and a plus sign next to them no longer lands on their hydrogens. +- A lone `[H+]` (in reaction SMILES such as `CCO.CC(=O)O>[H+]>CC(=O)OCC.O`) got no 2D coordinates and a note that it was drawn as a row of atoms. +- Formula text over a reaction arrow (such as NaOH) was read as an agent; it is read as conditions, as the drawing format says. +- An engine error after a translated "Could not ..." prefix stayed in English; the whole message is translated now, and each Analysis panel warning and each Standardise step detail translates on its own. +- Saving settings from two places at once (Always allow in the agent question while a preference was saved) lost one of the changes. +- An agent call you had undone showed as done again in Agent activity after a later edit. + +### Known issues + +- The 0.5.0 and 0.6.0 tools (`perceive_reactions`, `map_reaction`, `export_reaction`, `reaction_stoichiometry`, `properties`, `check_structure`, `stereo`, `substructure`) still need `doc` when several drawings are open; the 0.8.0 tools use the drawing the window shows. +- Read-only calls show no drawing in Agent activity. +- `draw_from_name` is not there yet: drawing from a chemical name waits for the open decision on how name to structure ships (question Q7 of the plan). Use SMILES. +- `perceive_reactions` lists the conditions text below an arrow before the text above it. +- Lone ions drawn from a SMILES with several lines (NH3 beside HO-) can sit very close, because that row does not allow for label widths. +- The macOS desktop app was not run for this version, and no real Claude Code or Codex client was connected to it: the agent tools were checked with the stdio transport, curl and a browser window. +- Agents cannot type amounts into the Stoichiometry panel, and the export and copy commands still hand their file to you, not to the agent (`convert` returns text to the agent instead). + +### Under the hood + +- New engine modules: `services/agent_out.py` (render through the window, the shared write result, placement in free space), `services/agent_draw.py` (structures and reaction schemes as one set of ops), `services/agent_edits.py` (the edit tools as pure document edits), `services/agent_convert.py` (convert and batch through `services/batch.py`), `services/agent_log.py` (the call log), `core/agent_token.py` and `routers/agent_activity.py`. +- New routes: `GET /api/agents/calls`, `POST /api/agents/calls/clear`, `POST /api/agents/calls/{id}/undo`, `POST /api/agents/stop`, `POST /api/agents/allow` and `GET /api/agents/token`; the live socket adds `agentCall`, `agentUndoable`, `agentAccess` and `agentCallsCleared`. Each finished call is kept as a JSON line in `Agent log` in the data folder. +- The window answers three new window tools for the engine: `render`, `selection` and `show`. When no window is open, or it does not answer in 25 seconds, the engine draws the structures itself in the journal style and says so. +- The engine's store tells its services about every applied change, undo and redo, which is how Agent activity knows which call is on top of each drawing's undo stack. +- `docs/FORMAT.md` says plainly that text with `formula` set in an arrow's band is conditions. +- No new dependency. +- Every new menu item, panel and message is translated into all 25 languages. + +## 0.7.0 · 2026-12-03 + +Formats and exchange: FormChem now reads and writes the common chemistry files, exports pictures that open again as editable drawings, copies and pastes in many forms and converts whole files from the command line. It also fixes everything the first desktop test found: the slow start on macOS, the crowded Taxol layout, the overlapping Analysis panel and the clipped menus, and it adds the dark page, resizing on the sheet and a choice of grids. + +### New + +- File > Export saves pictures as PNG, SVG, PDF or EPS. Export Picture... opens a dialog for the whole page, the selection or each structure as its own file, with the resolution (72 to 600 dpi, 300 by default), a transparent or white background, the scale, the margin and "Keep the editable drawing inside the file". SVG keeps its labels as text with subsets of the label fonts embedded; PDF and EPS draw the labels as outlines, and PDF adds a hidden text layer so the labels can be searched and copied. +- A picture exported with the drawing kept inside opens again as the same drawing through File > Open, with the same structures, wedges, arrows and reaction steps, and pastes back editable. +- File > Print... (`Ctrl+P`, `Cmd+P` on macOS) prints the page, or only the selection in its place on the page, at real size. The dark page never prints. +- Chemistry files in and out: MDL molfile (V2000, and V3000 when the drawing needs it), SD files with their data fields, RXN, RD files, SMILES, CXSMILES, reaction SMILES, SMARTS, InChI, InChIKey (write only), CML, CDXML and CDX. File > Export also has Export as CDXML..., Export as Molfile... and Export as SMILES... +- After a file from another program opens, a short note says what was lost or changed on the way in (such as text that was approximated or a record that could not be read), and Details lists every item with its count. Nothing in the file on disk changes. +- File > Import... brings one or more files (chemistry files, FormChem drawings and pictures that carry a drawing) into the drawing you have open, in free space beside what is there, selected, as one undo step per file. An SD file brings up to 50 structures in a table, and the note says how many were left out. +- The clipboard: Copy (`Ctrl+C`) puts the drawing on the clipboard for FormChem, as SMILES for text editors and as a picture for other programs. Edit > Copy As has SMILES, CXSMILES, Molfile, InChI, InChIKey, SMARTS, SVG, PNG and CDXML. Paste reads FormChem drawings, pictures that carry a drawing, and every text format above, at the pointer, as one undo step. Edit > Paste Special... (`Ctrl+Shift+V`) lists what the clipboard holds and pastes the one you pick. +- Structure > Standardise... cleans up the selected structures, or every structure on the page: normalise functional groups, remove salts and solvents, keep the largest fragment, reionise, neutralise, the canonical tautomer, remove isotopes, stereochemistry or explicit hydrogens. A preview shows the structure before and after, and Apply is one undo step. +- A command line: `./formchem convert` converts a file between formats (10,000 SD records to SMILES in about 1.5 seconds), `./formchem batch` converts a whole folder, `./formchem descriptors` writes the Analysis panel's properties to a CSV file and `./formchem render` draws every record as an SVG or PNG picture. Each one can standardise first, and records that fail are listed with their reason without stopping the run. +- The dark page: the drawing page shows dark with light bonds and labels, on by default, as in FormTxt. View > Dark Page and Preferences > Interface > Page turn it off. Element colours stay recognisable, and exports, printing and copies keep the real colours. +- Resizing on the sheet: drag a corner handle of the selection to make the structures larger or smaller (`Alt` scales about the centre, `Shift` in 10 percent steps). Arrange > Scale... sets a percentage or a bond length, and Scale Up 10% and Scale Down 10% (`Ctrl+Alt+=` and `Ctrl+Alt+-`, `Cmd+Option` on macOS) step it. Line widths, labels and text grow with the structure unless you turn off Arrange > Scale Labels and Text with Structures. Zoom still only changes the view. +- Grids: View > Grid offers lines, dots, crosses, isometric, isometric dots, hexagonal and hexagonal dots, with the spacing (5 mm, 1/4 in, 10 pt, the bond length or any value), a major line every few cells and a faint, normal or strong look. Grid Settings... previews on the page. Each drawing keeps its own grid when saved, and Preferences > Drawing > Grid sets the default for new drawings. +- Snap to Grid puts new bonds, chains, rings, arrows and shapes on grid points, and moves and handle drags follow it. On an isometric or hexagonal grid at the bond length every atom of a chain or a six-membered ring lands on a grid point. Hold `Alt` (`Option`) to place freely. +- Agents can run the new commands through `run_command`: the exports and Print, Copy As and Paste Special, Standardise, Scale, Dark Page, the grid commands and Snap to Grid. + +### Improved + +- 2D layout tries several layouts of a structure, scores each for atoms and labels that touch or bonds that cross, and then swings crowded substituents apart. Clean Up keeps the result close to what you drew, and SMARTS queries are laid out the same way. +- The Analysis panel's rows wrap instead of cutting values off, and the label always keeps its own column. The m/z row shows [M+H]+ for a neutral molecule and the ion's own m/z for a charged one. +- Menus that do not fit beside the document title fold into a More menus button at the end of the menu row, and the keyboard reaches them as before. +- Duplicate keeps stereo groups, R-groups and reaction steps. +- CDXML and CDX drawings bring their arrows, plus signs and text with them, and a scheme of several reaction steps is laid out as a chain. +- Error toasts, the Lipinski verdict, the structure check counts and similar status text are readable in the light themes. +- Every new menu item, dialog, panel and message is translated into all 25 languages. + +### Changed + +- On macOS the engine now ships as a folder inside the app (`Contents/Resources/engine`) instead of one file that unpacked itself at every launch. +- Copy as SMARTS moved into Edit > Copy As. +- `Ctrl+C`, `Ctrl+X` and `Ctrl+V` on the canvas copy, cut and paste the drawing. Copy with nothing selected copies the whole page. +- On macOS, Cut, Copy, Paste and Select All in the system Edit menu are the system's own items, so they act on the drawing as well as in text fields. The Linux and Windows desktop windows may now read and write the clipboard from script, which Edit > Paste needs there. +- The British spelling is used throughout: Standardise, Neutralise, Normalise. + +### Fixed + +- The macOS app took about 30 seconds to open. Its engine was one file that unpacked RDKit, Indigo, numpy and Python, several hundred megabytes and hundreds of libraries, into a new temporary folder at every launch, and macOS checked every unpacked library again each time. On macOS the engine now ships already unpacked as a folder inside the app, so nothing is unpacked at launch. On Linux the same change took the engine's start from 1.5 seconds to 0.55 seconds. This was not yet measured on a Mac: no macOS build was made for this version. +- Text overlapped in the Analysis panel: Elemental analysis and other long values ran into their labels or were cut off at narrow panel widths. +- The Help menu was clipped behind the document title when the window was not wide enough for every menu. +- Escape did not close an open menu while the canvas had the keyboard focus. +- Agents were refused commands right after a keyboard edit (such as Undo after `Ctrl+V`), because the engine still held the state from before the edit. +- Crowded 2D layouts: in Taxol the substituent labels around the taxane core touched each other. Taxol, erythromycin and vancomycin now insert with no touching labels. +- Export SMARTS in the desktop app saves a file instead of copying the SMARTS. +- The m/z row of the Analysis panel showed only a dash. + +### Known issues + +- The macOS paths were not run for this version: the launch time of the one-folder engine, the signed build, the native save and folder dialogs, printing, the clipboard and the system Edit menu in the macOS app. +- Paste from the canvas right-click menu may still show WebKit's small Paste prompt on macOS, which you have to click; `Cmd+V` and Edit > Paste do not. +- Under the dark page, pictures placed in a drawing that use very saturated light colours (pure yellow, for example) show beige or brick on screen. Exports and printing keep the real colours. +- A PNG that another program put on the clipboard as image data pastes as a plain picture in Chromium-based windows (Windows and browsers), because Chromium strips the embedded drawing. Copying the PNG file itself, or FormChem's own Copy as PNG, keeps it editable. +- Chemical names are not read yet: pasting "aspirin" gives a text object with a note. Name to structure is planned for a later version. +- Bridged polycycles such as morphine still have a bond crossing a ring in the 2D layout, because the layout only moves substituents, not ring systems. +- The engine on Linux and Windows still ships as one file, so it unpacks at every launch (about 1.5 seconds on Linux). +- CDXML and CDX are read and written through Indigo, which does not carry colours, fonts, the bond length, line breaks in text, curved arrows (written straight), structure names and data, or R-group members on reading. Query structures cannot be written as CDX. +- EPS files were checked by reopening them, not by drawing them with a PostScript viewer. +- The command line runs from the source tree; the desktop app does not include it yet. +- 3D View and the other 3D commands arrive in 0.10.0. + +### Under the hood + +- New engine routes: `GET /api/formats` (every format with what it loses), `GET /api/documents/{id}/export`, `POST /api/chem/export`, `POST /api/documents/import` (reads a file for File > Import without opening it), `POST /api/files/write` (writes a file the window chose), `/api/pictures/fonts` and `/api/pictures/convert`, `/api/analysis/standardise` and `POST /api/commands/state`. `POST /api/chem/parse` also takes base64 for binary files. They are documented in `docs/FORMATS.md`; the command line is in `docs/CLI.md`. +- Import and export report items share one shape (a stable code, a count, a sentence and a severity), so the list of what a format will lose before saving and the report after saving agree. +- PDF and EPS come from FormChem's own small writer in the engine, with fontTools 4.69.1 (MIT) for the font subsets and label outlines; it is the one new dependency. Pictures are drawn from the document model off screen, never from the live canvas, so the dark page cannot reach them. +- Batch conversion reads files record by record through one stream reader and never builds drawings, which is what keeps 10,000 records near a second. +- The window tells the engine which commands are on within about 120 ms of any edit, and the engine no longer refuses a command from its copy: the window decides. +- The drawing format gains the optional `style.grid`. Documents without it open and save unchanged. +- The selection, hover and warning marks moved into their own SVG layer above the drawing, so the dark page filter leaves their colours alone. + ## 0.6.0 · 2026-12-03 Stereo, queries and analysis: FormChem now reads and edits stereochemistry in depth, draws query structures and R-groups, and computes properties, structure checks and isotope patterns with the method behind every number. diff --git a/CLAUDE.md b/CLAUDE.md index 9ff4ed7a..47b02332 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,9 +4,9 @@ Two jobs happen in this repo: drawing chemistry with FormChem, and developing Fo ## Drawing with FormChem -The FormChem MCP server runs at http://127.0.0.1:8220/mcp, configured in .mcp.json. Start the app with `./formchem` so changes appear live in the window. It has six tools: `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff` (with `question` when you need the person's input). Changing tools (`run_command`, `extension_command`, `handoff`) make the window ask the person unless you were started from FormChem's own dock. +The FormChem MCP server runs at http://127.0.0.1:8220/mcp, configured in .mcp.json; HTTP requests need the agent token (`./formchem agents token`; `./formchem agents install` writes it into the configs, and the stdio transport `./formchem mcp` sends it itself). Start the app with `./formchem` so changes appear live in the window. It has 42 tools. Changing tools make the window ask the person the first time unless you were started from FormChem's own dock, and the person can Stop an agent from the title bar. -FormChem 0.4.0 draws. `get_context` lists the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula). Change them with `run_command` and the window's own commands, after `list_commands`: `insert-smiles {"smiles": "..."}` adds a structure (selected, one undo step), `open-recent {"path": "/abs/file.mol"}` opens a drawing or structure file, and `select-all`, `delete`, `duplicate`, the flips, `rotate-90`, align, distribute, `clean-structure`, `layout-structure`, `check-structure`, zoom, `undo`, `redo` and `save` act on the active drawing and its selection. Form extensions with the document permission read and change drawings by id. Dedicated drawing tools for agents (atoms and bonds by id, reading SMILES and InChIKey, rendering, conversion) arrive in 0.8.0; commands of later versions are listed as off. +Since 0.8.0 agents draw directly: `get_context` or `list_open_documents` first; `draw_from_smiles` (reaction SMILES draws a scheme) and `draw_from_molfile` place a structure in free space as one undo step and answer with ids, SMILES, InChIKey, formula and a picture; `get_atoms` names atoms and bonds by id for the edit tools (`add_atom`, `add_bond`, `set_charge`, `set_atom`, `set_stereo`, `replace_substructure`, `delete`, `move`, `scale`, `align`, `clean_layout`, `add_arrow`, `add_text`, `add_reaction`), each one undo step; check your work with `render`, `get_structure` and `validate`; `convert` and `batch_convert` match `./formchem convert` and `batch`. Reaction tools, analysis tools, the window's own commands (`list_commands`, `run_command`), Form extensions and `handoff` (with `question` when you need the person's input) are there too. Every call shows in the window's Agent activity panel. Load the skill `.claude/skills/formchem-harness` for using the app. For work on the codebase itself, load `.claude/skills/formchem-skillset`. The document format is `docs/FORMAT.md`. diff --git a/NOTICE.md b/NOTICE.md index 5907493e..3fce049c 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -8,7 +8,7 @@ This file is the human list, with the reason each work is there. The full licenc | Work | License | Where | | --- | --- | --- | -| formdeck (https://github.com/nodemode-dev/formdeck, 0.47.0) and formvis (https://github.com/nodemode-dev/formvis, 2.9.0), same owner (NodeAgentc, Inc.): the window shell, the root dispatcher and setup scripts, the PyInstaller sidecar and the Tauri 2 shell, the MCP server and stdio bridge shape, the guard, window key and seal | Apache-2.0 | `frontend/index.html`, `frontend/src/ui/`, `formchem`, `formchem.bat`, `setup/`, `backend/app/`, `backend/formchem_engine.py`, `src-tauri/` | +| formdeck (https://github.com/nodemode-dev/formdeck, 0.47.0) and formvis (https://github.com/nodemode-dev/formvis, 2.9.0), same owner (NodeAgentc, Inc.): the window shell, the root dispatcher and setup scripts, the PyInstaller sidecar, the one-folder macOS engine (`packaged.rs`, `tauri.macos.conf.json`, the flatten and sign steps) and the Tauri 2 shell, the MCP server and stdio bridge shape, the guard, window key and seal | Apache-2.0 | `frontend/index.html`, `frontend/src/ui/`, `formchem`, `formchem.bat`, `setup/`, `backend/app/`, `backend/formchem_engine.py`, `src-tauri/` | | NodeMode stylized design system (through formdeck and formvis): tokens, theme profiles, theme boot, dom-stable helpers, icon subset | MIT | `frontend/src/styles/tokens.css`, `frontend/src/ui/themes.ts`, `frontend/src/ui/dom.ts`, `frontend/src/ui/icons.ts` | | formvis traffic-light placement and overlay title bar, same owner (NodeAgentc, Inc.) | Apache-2.0 | `src-tauri/src/traffic_lights.rs`, `frontend/index.html`, `frontend/src/app.ts` | | Form Extension Contract kit, Apache-2.0, nodemode: the host bridge and the extension resolver and file server, vendored unchanged | Apache-2.0 | `frontend/src/extensions/host-bridge.ts`, `backend/app/services/formext_host.py` | @@ -28,6 +28,7 @@ This file is the human list, with the reason each work is there. The full licenc | starlette, pydantic, pydantic-core | BSD-3-Clause, MIT, MIT | engine, through fastapi | | RDKit 2025.9.3 (`rdkit` Python wheel, with the InChI library and CoordGen it carries) | BSD-3-Clause | engine, the chemistry core: structure model, sanitisation, canonical SMILES, InChI, stereo, coordinates; required from 0.1.0 | | Indigo 1.49.0 (`epam.indigo`) | Apache-2.0 | engine, reading and writing chemical drawing formats; required from 0.1.0 | +| fontTools 4.69.1 (fonttools) | MIT | engine, embeds subsets of the label fonts in exported SVG and draws label outlines in PDF and EPS | | Other Python packages frozen into the engine | listed with their licences in `THIRD-PARTY-NOTICES.txt` | read from the installed metadata of `backend/requirements.txt` | | @tauri-apps/api 2.12.1; tauri, tauri-plugin-shell, tauri-plugin-dialog, tauri-plugin-updater, tauri-plugin-single-instance, serde, serde_json, regex | MIT or Apache-2.0 | desktop shell | | fontdb 0.24 | MIT | desktop shell, lists installed font families | diff --git a/README.md b/README.md index 2792eb7f..5a5f01d3 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ with an MCP server so an agent works in the same window you see. Local-first, no account.

- version 0.6.0 + version 0.8.0 TypeScript and Vite Python and FastAPI macOS, Windows, Linux @@ -28,16 +28,16 @@ ## Features -FormChem draws structures and reactions: draw on the canvas with the mouse or the keyboard, annotate with arrows, brackets, shapes, tables and TLC plates, and the chemistry engine checks every change, reads reaction schemes, maps their atoms, works out the amounts, labels stereochemistry and computes properties with the method behind each number. +FormChem draws structures and reactions: draw on the canvas with the mouse or the keyboard, annotate with arrows, brackets, shapes, tables and TLC plates, and the chemistry engine checks every change, reads reaction schemes, maps their atoms, works out the amounts, labels stereochemistry and computes properties with the method behind each number. Drawings go out as chemistry files and as pictures that open again as the drawing, through the clipboard to other programs, and whole files convert on the command line. Agents draw in the same window: they draw and edit structures and reactions through 42 MCP tools, check their work with a picture of what you see, and every call is one undo step you can review, undo or stop. - + - + @@ -52,30 +52,42 @@ FormChem draws structures and reactions: draw on the canvas with the mouse or th - - + + + + + + + + + + + +

Drawings

.fchem documents kept by the engine, with undo per drawing (one step per gesture, command or agent call), autosave, Save, Save As, Save a Copy and Recent on Home. Molfile, SDF, RXN, SMILES, InChI, CML and CDXML files open as new drawings.

Drawings

.fchem documents kept by the engine, with undo per drawing (one step per gesture, command or agent call), autosave, Save, Save As, Save a Copy and Recent on Home. Files from other programs open as new drawings with a report of anything that changed on the way in, or File > Import adds them to the open drawing.

Canvas and tools

A tool rail with selection and lasso, ten bond kinds, chains, benzene and rings of 3 to 8, atom labels, text, eraser, hand and zoom. Structures render in the 1996 journal style with bundled Arimo, and the canvas patches only what changed.

Hover keys

Point at an atom or a bond and press a key: elements and two-letter symbols, charges, radicals, chains of 1 to 9 carbons, rings, phenyl, bond orders, wedges, hashes and double-bond placement. Arrow keys and Enter draw without the mouse.

Chemistry engine

RDKit in the engine works out canonical SMILES, CXSMILES, InChI, InChIKey, formula and masses after each change, flags valence problems on the canvas, and powers Clean Up, Lay Out and Check Structure.

Chemistry engine

RDKit in the engine works out canonical SMILES, CXSMILES, InChI, InChIKey, formula and masses after each change, flags valence problems on the canvas, and powers Clean Up, Lay Out, Standardise and Check Structure. The 2D layout scores several candidates and swings crowded groups apart, so Taxol's labels no longer touch.

Analysis panel

Formula, masses, m/z and elemental analysis, plus cLogP, TPSA, molar refractivity, donors, acceptors, rotatable bonds and the rule of five, each with its method, and the isotope pattern with adduct m/z. Copy Analysis takes it all as text.

Arrange and style

Duplicate, delete, flip, rotate, align and distribute the selection; Drawing preferences set the default style and its bond length, widths and label size; element colours, carbon labels and stereo labels on request.

Structure check

A panel of errors, warnings and notes with a code each, from valence and charges to wedges, overlaps and R-group gaps. Click a row to select its atoms, or fix wedges and abbreviations in one step.

MCP server

Fourteen tools over HTTP and stdio: agents see the open drawings with their formulas, run the same commands as the menus, perceive, map, export and measure reactions, and read properties, structure checks, stereo and substructure hits.

The family shell

Home, Preferences, twelve menus with full keyboard use, Find a Command, the terminal and agent dock, Help and updates, in 26 interface languages.

Chemistry files

Molfile V2000 and V3000, SD, RXN, RD, SMILES, CXSMILES, reaction SMILES, SMARTS, InChI and InChIKey, CML, CDXML and CDX in and out, each export with a report of exactly what the format could not keep.

Pictures and print

PNG up to 600 dpi, SVG with embedded font subsets, PDF and EPS, for the page, the selection or each structure, with the editable drawing kept inside so the picture opens again as the drawing. Print at real size.

Clipboard

Copy puts the drawing, SMILES and a picture on the clipboard at once; Copy As picks SMILES, CXSMILES, Molfile, InChI, InChIKey, SMARTS, SVG, PNG or CDXML; Paste reads all of them back, and Paste Special lets you choose.

Command line

./formchem convert, batch, descriptors and render work on whole files and folders (10,000 SD records to SMILES in about a second and a half), with optional standardising and a report of every record that failed.

Dark page and grids

A dark drawing page, on by default, that keeps element colours readable and never reaches exports. Line, dot, cross, isometric and hexagonal grids with their own spacing, kept per drawing, and Snap to Grid.

Size on the sheet

Drag a corner handle, or use Arrange > Scale, Scale Up and Scale Down, to make structures larger or smaller on the page by percent or bond length, with their labels and line widths or without.

MCP server

42 tools over HTTP (with an agent token) and stdio: agents open and save drawings, draw from SMILES, reaction SMILES or molfiles, build and edit atom by atom by id, read structures back as SMILES, InChIKey and molfiles, render what you see, validate, convert files as the command line does, and run every menu command. Agent Activity lists each call with undo and Stop.

The family shell

Home, Preferences, twelve menus with full keyboard use (those that do not fit fold into More menus), Find a Command, the terminal and agent dock, Help and updates, in 26 interface languages.

Form extensions

Extensions installed by FormPortal run in a sandboxed frame from the Extensions menu and panel, and ask before they read or change a drawing.
### Coming next -- Reading and writing the common chemical file formats -- Names, predicted spectra and spectrum viewing +- Names (also as an agent tool), predicted spectra and spectrum viewing - 3D models of molecules - A local structure database with search ## Built for agents -The engine's MCP server drives the same command catalogue as the window through `get_context`, `list_commands`, `run_command`, `extensions_list`, `extension_command` and `handoff`, plus four reaction tools (`perceive_reactions`, `map_reaction`, `export_reaction`, `reaction_stoichiometry`) and four analysis tools (`properties`, `check_structure`, `stereo`, `substructure`). Reading is always open; the window asks before an outside agent changes anything. `get_context` lists the open drawings with their formulas, and `run_command insert-smiles {"smiles": "c1ccccc1O"}` puts a structure on the canvas as one undo step. Dedicated drawing tools for agents arrive in 0.8.0. +Claude Code, Codex, Cursor, Antigravity or any MCP client draws in the window you have open. `draw_from_smiles {"smiles": "CC(=O)Oc1ccccc1C(=O)O"}` lays aspirin out in free space on the page and answers with its ids, SMILES, InChIKey, formula and a picture drawn by the window's own renderer; `render`, `get_structure` and `validate` check the work; `get_atoms` and 14 edit tools (`add_atom`, `add_bond`, `set_charge`, `set_stereo`, `replace_substructure`, `move`, `scale`, `add_arrow`, `add_reaction` and more) build and change structures by id; `new_document`, `open_document`, `save_document` and `close_document` handle drawings; `convert` and `batch_convert` give the command line's exact output. The window's commands (`list_commands`, `run_command`), Form extensions, handoffs and the reaction and analysis tools are there as before. + +Every change is one undo step, labelled with the tool in Edit > Undo. Reading is always open; the window asks before an outside agent changes anything, the title bar shows which agent is editing with a Stop button, and Window > Agent Activity lists every call with undo for the latest one. The HTTP endpoint needs the agent token, which `./formchem agents install` writes into the agent configs; stdio clients send it themselves. An agent set up for 0.7.0 over HTTP needs `./formchem agents install` once more. ```sh -./formchem agents install # writes .mcp.json, .codex/config.toml, .cursor/mcp.json and Antigravity's ~/.gemini/config/mcp_config.json, installs the skills +./formchem agents install # writes .mcp.json (with the agent token), .codex/config.toml, .cursor/mcp.json and Antigravity's ~/.gemini/config/mcp_config.json, installs the skills +./formchem agents token # prints the agent token for HTTP MCP (Authorization: Bearer ) +./formchem mcp # MCP server on stdio for Claude Code, Codex, Cursor, Antigravity and Claude Desktop ./formchem cli list # the window's command catalogue; run needs the window open and counts as an outside agent (it asks there) -./formchem mcp # MCP server on stdio for Claude Code, Codex, Cursor and Antigravity ``` -See [`AGENTS.md`](AGENTS.md). +Every tool, its arguments and its result: [`docs/AGENTS.md`](docs/AGENTS.md). Instructions for coding agents in this repository: [`AGENTS.md`](AGENTS.md). ## Extensions @@ -85,7 +97,9 @@ FormChem hosts Form extensions (Form Extension Contract, API 1): FormPortal inst - **Engine:** a FastAPI service holds every document; each change is a JSON op with an inverse, broadcast to every window and agent. RDKit and Indigo are the chemistry core. - **Window:** vanilla TypeScript and Vite, with an inline-SVG icon set and no UI framework. -- **Desktop:** a Tauri 2 shell around the same window, with the engine frozen as a sidecar. +- **Desktop:** a Tauri 2 shell around the same window, with the engine frozen by PyInstaller. On macOS it ships as a folder inside the app, so nothing is unpacked at launch (the one-file engine it replaces made the app take about 30 seconds to open); on Linux and Windows it is still a one-file sidecar. +- **Pictures:** built from the drawing off screen, never from the canvas; PDF and EPS come from FormChem's own writer, with fontTools for the label fonts. +- **Agents:** the drawing and edit tools build JSON ops in the engine and apply them as one transaction, so they work with or without a window; pictures for agents come from the window's own renderer over the live channel, with an RDKit fallback when no window is open. One function logs every call for Agent Activity. - **Format:** `.fchem` is a zip package around `document.json`, specified in [`docs/FORMAT.md`](docs/FORMAT.md), which both the engine and the window implement. ## Run it from source @@ -104,7 +118,7 @@ cd formchem `./formchem desktop dev` opens the desktop window instead. On Windows use `formchem.bat install` and `formchem.bat`. The engine listens on `127.0.0.1:8220` (MCP at `/mcp`); `FORMCHEM_DATA_DIR` moves the data folder from `~/formchem`. > [!IMPORTANT] -> **Status:** in development, and the repository is private until the first release. This version draws, checks and analyses structures and reactions, with stereochemistry, query structures and calculated properties; file export, names, spectra and 3D come in later versions. Nothing is built or released for download yet. +> **Status:** in development, and the repository is private until the first release. This version draws, checks and analyses structures and reactions, with stereochemistry, query structures and calculated properties, from 0.7.0 reads and writes the common chemistry files, exports pictures, prints, copies and pastes, and converts files on the command line, and from 0.8.0 lets agents draw, edit, check and convert directly; names, spectra and 3D come in later versions. The 0.7.0 and 0.8.0 desktop apps have not been run on a Mac yet, and 0.8.0's agent tools were checked over stdio and HTTP, not yet with a real Claude Code or Codex client. Nothing is built or released for download yet. **Contributing:** branch from `main`, keep changes to source here, and leave packaging and releases to FormCompiler. See [`CONTRIBUTING.md`](CONTRIBUTING.md), [`CODE_OF_CONDUCT.md`](CODE_OF_CONDUCT.md), [`.docs/BRANCHING.md`](.docs/BRANCHING.md) and [`AGENTS.md`](AGENTS.md). Report security issues privately as [`SECURITY.md`](SECURITY.md) describes. @@ -112,12 +126,12 @@ cd formchem | Path | What it is | |---|---| -| `backend/` | FastAPI engine: documents, chemistry, reactions and analysis, templates, live channel, terminal dock, extensions, MCP | -| `frontend/` | Vanilla TypeScript and Vite window: the drawing canvas and tools, shell, menus, Home, Preferences, dock | -| `setup/` | Install, boot, build, freeze and agent setup scripts | -| `src-tauri/` | Desktop shell and the engine sidecar | +| `backend/` | FastAPI engine: documents, chemistry, reactions and analysis, file formats and pictures, the conversion command line, templates, live channel, terminal dock, extensions, MCP and the agent tools, the agent call log | +| `frontend/` | Vanilla TypeScript and Vite window: the drawing canvas and tools, export, print and clipboard, shell, menus, Home, Preferences, dock | +| `setup/` | Install, boot, build, freeze, convert and agent setup scripts | +| `src-tauri/` | Desktop shell; it starts the engine folder on macOS and the engine sidecar elsewhere | -Docs: [`.docs/wiki`](.docs/wiki) · Agents: [`CLAUDE.md`](CLAUDE.md), [`AGENTS.md`](AGENTS.md) · Contributing: [`.docs/BRANCHING.md`](.docs/BRANCHING.md) +Docs: [`.docs/wiki`](.docs/wiki) · Formats: [`docs/FORMATS.md`](docs/FORMATS.md) · Command line: [`docs/CLI.md`](docs/CLI.md) · Agent tools: [`docs/AGENTS.md`](docs/AGENTS.md) · Agents: [`CLAUDE.md`](CLAUDE.md), [`AGENTS.md`](AGENTS.md) · Contributing: [`.docs/BRANCHING.md`](.docs/BRANCHING.md)
diff --git a/SECURITY.md b/SECURITY.md index 926a8a37..7b944daf 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -7,7 +7,7 @@ check whether the problem is still there. | Version | Supported | | --- | --- | -| 0.2.x (in development, not yet released) | Yes | +| 0.8.x (in development, not yet released) | Yes | | Anything older | No | ## Reporting a vulnerability @@ -38,6 +38,30 @@ something outside it could get in: engine seals that saved value with a key in the system keychain, so a change made outside the window puts the choice back to asking. Anything that lets another program change it without the window counts. +- **The agent token** (from 0.8.0): the MCP endpoint over HTTP answers only + requests that carry `Authorization: Bearer `, the token of one of + FormChem's own agent tabs, or the window key; everything else gets 401. The + token is one line in `agent-token` in the data folder (`~/formchem`, or + `FORMCHEM_DATA_DIR`), created with owner-only permissions, compared in + constant time, and written by `./formchem agents install` into the agent + configs. Treat it like a password: the `.mcp.json` files that install writes + hold it, so keep them out of version control, and delete the file and restart + the engine to change it. The engine still listens on loopback only, so the + token protects against other programs and other users on the same machine, + not against the network. Anything that lets a request without the token + reach a tool, or that leaks the token to a page, an extension or another + user, counts. +- **Agent edits, Stop and the call log** (from 0.8.0): agents change drawings + only through the consent question above, one undo step per call. Agent + tools never write over an existing file and never close a drawing with + unsaved changes. Stop in the title bar refuses every further call of that + agent and withdraws Always allow; only the FormChem window (it holds the + window key) can stop, allow again, undo an agent call from Agent Activity or + read the token. Every call is logged in memory and in `Agent log` in the data + folder, with secret-looking arguments shown as `(hidden)`; the log does hold + SMILES, file paths and tool names. Anything that lets an agent act after + Stop, undo or change someone else's work through the call log, or skip the + log, counts. - **Files**: opening or importing documents, structure files, media or archives in a way that writes outside where it should. diff --git a/THIRD-PARTY-NOTICES.txt b/THIRD-PARTY-NOTICES.txt index 84f2c986..544df01d 100644 --- a/THIRD-PARTY-NOTICES.txt +++ b/THIRD-PARTY-NOTICES.txt @@ -752,6 +752,424 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [[ end file fastapi-0.141.1.dist-info/licenses/LICENSE ]] +============================================================================== +python: fonttools 4.69.1 +Licence: MIT +Source: http://github.com/fonttools/fonttools +[[ begin file fonttools-4.69.1.dist-info/licenses/LICENSE ]] +MIT License + +Copyright (c) 2017 Just van Rossum + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +[[ end file fonttools-4.69.1.dist-info/licenses/LICENSE ]] +[[ begin file fonttools-4.69.1.dist-info/licenses/LICENSE.external ]] +FontTools includes the following font projects for testing purposes, which are +under SIL Open Font License, Version 1.1: + +Lobster + Copyright (c) 2010, Pablo Impallari (www.impallari.com|impallari@gmail.com), + with Reserved Font Name Lobster. + This Font Software is licensed under the SIL Open Font License, Version 1.1. + +Noto Fonts + This Font Software is licensed under the SIL Open Font License, Version 1.1. + +XITS font project + Copyright (c) 2001-2010 by the STI Pub Companies, consisting of the American + Institute of Physics, the American Chemical Society, the American + Mathematical Society, the American Physical Society, Elsevier, Inc., and The + Institute of Electrical and Electronic Engineers, Inc. (www.stixfonts.org), + with Reserved Font Name STIX Fonts, STIX Fonts (TM) is a trademark of The + Institute of Electrical and Electronics Engineers, Inc. + + Portions copyright (c) 1998-2003 by MicroPress, Inc. + (www.micropress-inc.com), with Reserved Font Name TM Math. To obtain + additional mathematical fonts, please contact MicroPress, Inc., 68-30 Harrow + Street, Forest Hills, NY 11375, USA, Phone: (718) 575-1816. + + Portions copyright (c) 1990 by Elsevier, Inc. + + This Font Software is licensed under the SIL Open Font License, Version 1.1. + +Iosevka + Copyright (c) 2015-2020 Belleve Invis (belleve@typeof.net). + This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +===== + +FontTools includes Adobe AGL & AGLFN, which is under 3-clauses BSD license: + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +Neither the name of Adobe Systems Incorporated nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +===== + +FontTools includes cu2qu, which is Copyright 2016 Google Inc. All Rights Reserved. +Licensed under the Apache License, Version 2.0, a copy of which is reproduced below: + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +===== + +FontTools includes code in `fontTools.misc.filesystem` which is derived from: + +PyFilesystem2 (i.e. the `fs` package) by Will McGugan +Licensed under the MIT License +https://github.com/PyFilesystem/pyfilesystem2 + +Copyright (c) 2017-2021 The PyFilesystem2 contributors +Copyright (c) 2016-2019 Will McGugan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +[[ end file fonttools-4.69.1.dist-info/licenses/LICENSE.external ]] + ============================================================================== python: h11 0.16.0 Licence: MIT diff --git a/agents/manifest.json b/agents/manifest.json index 3ff9a4a9..d9001d35 100644 --- a/agents/manifest.json +++ b/agents/manifest.json @@ -5,6 +5,19 @@ "mcp": { "tools": [ "get_context", + "render", + "draw_from_smiles", + "draw_from_molfile", + "get_structure", + "validate", + "compute_properties", + "convert", + "batch_convert", + "list_open_documents", + "new_document", + "open_document", + "save_document", + "close_document", "list_commands", "run_command", "extensions_list", @@ -17,10 +30,30 @@ "properties", "check_structure", "stereo", - "substructure" + "substructure", + "get_atoms", + "add_atom", + "add_bond", + "set_charge", + "set_atom", + "set_stereo", + "replace_substructure", + "delete", + "move", + "scale", + "align", + "clean_layout", + "add_arrow", + "add_text", + "add_reaction" ], "read_only": [ "get_context", + "render", + "get_structure", + "validate", + "compute_properties", + "list_open_documents", "list_commands", "extensions_list", "export_reaction", @@ -28,14 +61,37 @@ "properties", "check_structure", "stereo", - "substructure" + "substructure", + "get_atoms" ], "approval_gated": [ + "draw_from_smiles", + "draw_from_molfile", + "convert", + "batch_convert", + "new_document", + "open_document", + "save_document", + "close_document", "run_command", "extension_command", "handoff", "perceive_reactions", - "map_reaction" + "map_reaction", + "add_atom", + "add_bond", + "set_charge", + "set_atom", + "set_stereo", + "replace_substructure", + "delete", + "move", + "scale", + "align", + "clean_layout", + "add_arrow", + "add_text", + "add_reaction" ], "transports": [ "stdio", @@ -46,6 +102,8 @@ { "name": "formchem-harness", "sub_skills": [ + "drawing", + "edit-by-id", "extension-drawings", "handoff", "reactions", @@ -63,11 +121,14 @@ "canvas", "chemistry-engine", "clean-room", + "clipboard", + "command-line", "desktop", "dock", "document-format", "engine", "extensions", + "formats-and-export", "menus", "reactions", "release", diff --git a/backend/HASHOUT_LOG.md b/backend/HASHOUT_LOG.md index 7dc23de5..64a2ef21 100644 --- a/backend/HASHOUT_LOG.md +++ b/backend/HASHOUT_LOG.md @@ -1,6 +1,6 @@ # backend HASHOUT_LOG -Living log for the FormChem engine and its setup scripts, _v0.1.0 to _v0.6.0. It follows the family template (formdeck's engine) for 0.1.0 and 0.2.0, from 0.3.0 it records the chemistry engine, the document store and the file format, from 0.5.0 the reaction services (perception, mapping, balance, stoichiometry, reaction exchange), the template library and media, and from 0.6.0 the analysis services (stereo and enhanced stereo, wedges, abbreviations, hydrogens, queries and SMARTS, V3000 query molfiles, Markush, properties, the structure check, the isotope pattern), the analysis router and tools, and the desktop build fixes, so many reasons here are about what was kept, what was dropped, and why. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. +Living log for the FormChem engine and its setup scripts, _v0.1.0 to _v0.8.0. It follows the family template (formdeck's engine) for 0.1.0 and 0.2.0, from 0.3.0 it records the chemistry engine, the document store and the file format, from 0.5.0 the reaction services (perception, mapping, balance, stoichiometry, reaction exchange), the template library and media, and from 0.6.0 the analysis services (stereo and enhanced stereo, wedges, abbreviations, hydrogens, queries and SMARTS, V3000 query molfiles, Markush, properties, the structure check, the isotope pattern), the analysis router and tools, and the desktop build fixes, and from 0.7.0 the one-folder macOS engine, the scored 2D layout, the formats table with its readers, writers and report items, the stream reader, picture export with its own PDF and EPS writer, the embedded source, the file write route, standardisation, the batch command line and the quick command state mirror, and from 0.8.0 the agent tools (drawing, checking, documents, conversion and edits by id), the shared write result and the render bridge, the agent call log with its undo and Stop, and the agent token, so many reasons here are about what was kept, what was dropped, and why. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. ## Org navi map @@ -22,6 +22,21 @@ backend/app/services/ hub.py (client and agent table), bridge.py (window backend/app/services/chem/ abbrev, convert, perceive, ids, mass, layout, io, derive (RDKit and Indigo, 0.3.0) geometry, reactions, rxnio, scheme, mapping, balance, stoich (reactions, 0.5.0) stereo, superatom, hydrogens, query, search, v3000, markush, props, check, isotopes (analysis, 0.6.0) + layout_score, layout_refine (scored 2D layout, 0.7.0) + formats, report, writers, cdxio, rdfio, cml, stream, records, standardise, depict (formats, 0.7.0) +backend/app/services/importers.py also reads files for File > Import without opening them (read_for_insert, 0.7.0) +backend/app/services/ also embedded_source.py (the drawing inside pictures), batch.py (convert, batch, descriptors, + render runners), pictures/ (fonts, svgdraw, pdf, eps: the picture writers), 0.7.0 +backend/app/routers/ also files (POST /api/files/write) and pictures (font subsets, PDF and EPS), 0.7.0 +backend/app/cli.py the command line behind ./formchem convert, batch, descriptors and render (0.7.0) +backend/app/services/ agent_out.py (write result, render bridge, free space), agent_draw.py (structures and schemes as ops), + agent_edits.py (the edit tools as pure builders), agent_convert.py (convert and batch for agents), + agent_log.py (the agent call log), 0.8.0 +backend/app/core/agent_token.py the agent token for HTTP MCP (0.8.0) +backend/app/routers/agent_activity.py /api/agents: calls, undo, stop, allow, token (0.8.0) +docs/AGENTS.md every agent tool with arguments and results, consent, Stop, the token and the call log (0.8.0) +docs/FORMATS.md every format, what it loses, the report codes and the exchange routes (0.7.0) +docs/CLI.md the conversion command line with examples and timings (0.7.0) backend/app/data/templates/ 206 original templates in nine category files (0.5.0) docs/FORMAT.md the document format, the single source for both languages (0.3.0) docs/REACTIONS.md reaction perception, mapping, balance, stoichiometry and their routes (0.5.0) @@ -29,7 +44,8 @@ docs/ANALYSIS.md stereo, queries, R-groups, properties, the structur docs/TEMPLATES.md the template file format and API (0.5.0) backend/requirements*.txt pins for the engine and for the desktop freeze formchem, formchem.bat one dispatcher for install, boot, serve, build, desktop, doctor, clean -setup/ the commands behind the dispatcher, plus notices.py, i18n_tool.py, catalogue.py +setup/ the commands behind the dispatcher, plus notices.py, i18n_tool.py, catalogue.py; + lib.sh holds fc_flatten_engine, fc_sign_engine and fc_engine_folder (0.7.0), convert launches the CLI build_app, build_app.bat desktop bundle build, teed to build_app.log ``` @@ -133,6 +149,72 @@ build_app, build_app.bat desktop bundle build, teed to build_app.log 96. Four analysis tools on the MCP server · routers/mcp.py 97. build_app names package.json when the Tauri CLI is missing · build_app 98. build_app bundles the template library when it freezes the engine · build_app +99. The macOS engine is a flattened one-folder, unpacked once at install · setup/freeze_backend, setup/lib.sh, build_app +100. The dev, check and clean scripts know the engine folder · setup/desktop_dev, setup/desktop_check, setup/clean +101. Nothing in the engine's own start was deferred · formchem_engine.py, app/main.py +102. A 2D layout gets a score for crowding, crossings and labels · services/chem/layout_score.py +103. Several layout candidates, CoordGen first among equals · services/chem/layout.py depict +104. Crowded substituents swing on their hinge bond · services/chem/layout_refine.py +105. Clean Up picks the candidate nearest the drawing · services/chem/layout.py clean +106. One table of formats drives menus, warnings and reports · services/chem/formats.py +107. Report items share one shape everywhere · services/chem/report.py +108. One writer per format, with a report of what was left out · services/chem/writers.py +109. CDXML and CDX go through Indigo's document JSON · services/chem/cdxio.py +110. RD files and CML are FormChem's own readers and writers · services/chem/rdfio.py, services/chem/cml.py +111. The readers keep annotations and every reaction step · services/chem/io.py, services/importers.py +112. What the round-trip corpus found and fixed · services/chem/cdxio.py, query.py, io.py, scheme.py +113. The export and format routes · routers/documents.py, routers/chem.py +114. One stream reader for batch work · services/chem/stream.py +115. The file write route trusts the window key and an extension list · routers/files.py +116. The engine reads the drawing kept inside pictures · services/embedded_source.py, services/store.py +117. fontTools subsets and outlines the label fonts · services/pictures/fonts.py, requirements.txt +118. The export SVG becomes a display list · services/pictures/svgdraw.py +119. FormChem writes its own PDF · services/pictures/pdf.py +120. And its own EPS · services/pictures/eps.py +121. The pictures router · routers/pictures.py, app/main.py +122. Standardise is one pipeline in a fixed order · services/chem/standardise.py run +123. Standardised structures are written back as one transaction · services/chem/standardise.py _fragment_ops +124. The standardise route · routers/analysis.py standardise_steps, standardise_structures +125. The engine draws in the journal style for the command line · services/chem/depict.py +126. Properties run on a molecule as well as a fragment · services/chem/props.py measure +127. Batch runners and the record adapter · services/batch.py, services/chem/records.py +128. The command line · app/cli.py, setup/convert, formchem, formchem.bat +129. The engine takes quick command state and lets the window decide · routers/commands.py state, execute +130. Preferences, model and guide additions of 0.7.0 · routers/system.py PREF_SHAPES, services/model.py Grid, routers/mcp.py GUIDE +131. The i18n scanner reads template placeholders and t() wrappers · setup/i18n_tool.py +132. Import reads a file for insertion without opening it · routers/documents.py import_for_insert, services/importers.py read_for_insert +133. Every agent write answers with the structure and a picture · services/agent_out.py write_result +134. render asks the window, which draws what the person sees · services/agent_out.py render_image, services/bridge.py READ_ONLY +135. Without a window the engine draws the structures · services/agent_out.py engine_picture +136. Which drawing a tool acts on · routers/mcp.py _doc_id, _show, _edit_doc +137. New things go into free space, never after an arrow · services/agent_out.py free_spot, services/agent_draw.py _where +138. Drawing from text is one set of ops through the Insert Reaction path · services/agent_draw.py, routers/mcp.py _draw +139. get_structure writes V3000 only when the structure needs it · services/agent_out.py full_structures +140. validate and compute_properties are the spec's names for the 0.6.0 tools · routers/mcp.py _same_as +141. convert and batch_convert run the command line's own runners · services/agent_convert.py, services/batch.py +142. Save and close never lose the person's work · routers/mcp.py t_save_document, t_close_document +143. Every writing tool goes through the consent gate · routers/mcp.py MUTATING, _mutating +144. The edit tools are pure builders · services/agent_edits.py, routers/mcp.py _edit +145. add_atom picks the freest direction · services/agent_edits.py add_atom, free_angle +146. add_bond sets an existing bond and merges fragments with care · services/agent_edits.py add_bond +147. set_stereo rewrites wedges for R and S and mirrors for E and Z · services/agent_edits.py set_stereo +148. replace_substructure matches like search and is checked against RDKit · services/agent_edits.py replace_substructure +149. move, scale and align run in the engine · services/agent_edits.py move, scale, align, map_ops +150. clean_layout, delete, add_arrow, add_text and add_reaction · services/agent_edits.py +151. One call log, hooked where every call passes · services/agent_log.py, routers/mcp.py call_tool +152. A call owns its transactions through a context variable and a 1.5 s window · services/agent_log.py _owner +153. The store tells services about every change, undo and redo · services/store.py AFTER_CHANGE, services/agent_log.py after_change +154. The call log on disk · services/agent_log.py _persist, _rotate +155. The agent activity routes · routers/agent_activity.py +156. Stop refuses an agent by name and withdraws Always allow · services/consent.py stop, routers/mcp.py call_tool +157. The agent token lives in the data folder · core/agent_token.py +158. HTTP MCP needs the token; the stdio relay and the cli send it · routers/mcp.py _authorised, setup/mcp_stdio.py, setup/catalogue.py +159. agents install writes the token, agents token prints it · setup/agents.py +160. The instructions, guide and get_context of 0.8.0 · routers/mcp.py INSTRUCTIONS, GUIDE, t_get_context +161. A lone hydrogen gets real coordinates · services/chem/layout.py _candidates +162. A lone atom's box covers its hydrogens on the side they are written · services/chem/geometry.py fragment_box +163. Formula text in an arrow's band is conditions · services/chem/reactions.py infer_step, docs/FORMAT.md +164. Settings are written under one lock · core/config.py write_settings ## 1. Ports and the data folder are FormChem's own · _v0.1.0 (app/core/config.py) @@ -525,3 +607,275 @@ Every POST takes its structure either stateless (`fragment`, optional `expansion ## 98. build_app bundles the template library when it freezes the engine · _v0.6.0 (build_app freeze) Entry 76 added `backend/app/data/templates` as `templates` data to `setup/freeze_backend` and its `.bat` twin, but `build_app` runs PyInstaller itself and missed it, so a desktop app built with `./build_app` had an empty template library (`templates.builtin_dir()` reads `config.resource_dir() / "templates"` when frozen). It now passes the same `--add-data`. `build_app.bat` goes through `setup/desktop_build.bat` and `freeze_backend.bat`, so Windows already had it. Not run here (no pyinstaller or Tauri on this machine). The owner ran `./build_app` on macOS arm64 (Python 3.14.6, Node 24.16, Rust 1.97.1) after the CLI pin, and the desktop app built; the frozen engine at runtime (the template library in particular) and the native macOS menu were not reported on. + +## 99. The macOS engine is a flattened one-folder, unpacked once at install · _v0.7.0 (setup/freeze_backend, setup/lib.sh fc_flatten_engine, fc_sign_engine, fc_engine_folder; build_app freeze) + +The owner's macOS app took about 30 seconds to open. The engine was a PyInstaller `--onefile` sidecar, which unpacks everything (314 MB, 1280 files, 417 shared libraries: RDKit, Indigo, numpy, Python) into a new `_MEIxxxxxx` folder at every launch, and macOS scans every new unsigned library each time. Python itself is not slow: from source the engine prints its address in about 0.46 s, frozen one-file in 1.51 s, frozen one-folder in 0.54 s (medians on this Linux machine). The fix is FormVis 2.9.0's layout (Apache-2.0, same owner): on macOS `freeze_backend` and `build_app` freeze `--onedir` (with `--codesign-identity` and the entitlements when `APPLE_SIGNING_IDENTITY` is set), and `fc_engine_folder` copies the result to `src-tauri/engine`, flattens it and runs `--selfcheck`. Flattening (`fc_flatten_engine`) replaces every symbolic link with a copy and `_internal/Python.framework` with a plain `_internal/Python`, because a bundle resource may hold neither; on Linux it grows the folder from 314 to 426 MB. `fc_sign_engine` signs every Mach-O file that PyInstaller left unsigned. The pipes use `grep ... >/dev/null` rather than `grep -q`, because build_app runs with `pipefail` and an early grep exit would turn a match into a failure. Linux and Windows keep the one-file sidecar: deb, rpm and AppImage put resources in `/usr/lib/FormChem/` while the binary sits in `/usr/bin`, so the shell would need a third place to look, and none of it can be bundled and tested here. On Linux the one-folder would save about 1 s. + +## 100. The dev, check and clean scripts know the engine folder · _v0.7.0 (setup/desktop_dev, setup/desktop_check, setup/clean, setup/clean.bat, formchem, .gitignore) + +On macOS tauri-build checks resources, so `cargo check`, `cargo build` and `tauri dev` need `src-tauri/engine` to exist, just as Linux needs the sidecar file. `desktop_dev` freezes when `src-tauri/engine/formchem-engine` is missing (a stale one-file binary no longer counts). `desktop_check` fails on macOS when the folder exists but has no program, a symbolic link or a `.framework`, the three things a bundle cannot carry. `clean` and `clean.bat` remove the folder, `.gitignore` lists it and the `freeze` help line of `./formchem` says where it goes. + +## 101. Nothing in the engine's own start was deferred · _v0.7.0 (formchem_engine.py, app/main.py) + +`python -X importtime` up to the address line: about 0.42 s of imports (fastapi and uvicorn 0.19 s, `rdkit.Chem` 0.06 to 0.10 s, the rest of `app.*` 0.14 s), then the lifespan (discovery file, one glob, terminal binding, a history task that sleeps first). Indigo, templates, the command catalogue, agent lookup and notices already load lazily. RDKit is imported at module level by twenty chem modules and through them by three routers; deferring it would save about 0.1 s and restructure those routers, and the first drawing needs RDKit anyway, so it stays. `serve()` calls `runtime.start_logging` twice; harmless and left. + +## 102. A 2D layout gets a score for crowding, crossings and labels · _v0.7.0 (services/chem/layout_score.py shape, evaluate, score_mol, Score) + +The Taxol test showed substituent labels touching around the taxane core. `shape(mol)` and `evaluate(shape, pts)` score coordinates scaled so the median bond is 1. Hard terms: non-bonded pairs closer than 0.5 (`close`, weight 10), proper crossings of bonds that share no atom (`cross`, 10), atoms within 0.35 of a non-incident bond (`near`, 5) and label conflicts (`label`, 3). The soft term, a tie-breaker, sums (1 - d)^2 over non-bonded pairs closer than 1 and 2 x (0.4 - gap)^2 over label boxes less than 0.4 apart. The label model follows the window's renderer with the default journal-1996 style (10 pt Arimo on a 14.4 pt bond, hetero hydrogens shown, terminal carbons as line ends): every non-carbon is labelled, plus isolated, isotopic or radical carbons; a box is 0.5 per capital and 0.38 per lower-case letter wide, plus the H and its count on the side `labelSide()` would choose, plus 0.3 for a charge, half height 0.25, so a one-letter label takes about 0.62 x 0.62 bond lengths. `Score.crowded` lists the atoms involved for the refinement. numpy is imported directly here for the first time; it was already bundled through RDKit and listed in THIRD-PARTY-NOTICES.txt. `score_fragment` returns null above 600 atoms, where the pairwise arrays grow too large. + +## 103. Several layout candidates, CoordGen first among equals · _v0.7.0 (services/chem/layout.py depict, _candidates) + +The candidates are CoordGen, RDKit's native layout with and without ring templates, the native layout with sampled rotatable-bond flips (seeds 1 and 2, ten samples, up to 150 atoms), each also straightened when no atoms are fixed. The winner is the first candidate, in that order, whose total is within 0.5 of the lowest, so CoordGen stays the house style unless another is clearly better. CoordGen has no seed: twelve random atom renumberings and all four precision presets gave the same Taxol and vancomycin layouts, so the variety comes from RDKit's flips. RDKit runs with `bondLength=1.0` so a coordinate map of fixed atoms matches CoordGen's unit bond. Above 300 atoms `depict` is plain CoordGen as before. `depict` now returns the chosen Score and takes an optional `reference`; the old callers ignore both. When every score is not a number (H2 in a reaction SMILES did that), it falls back to the first candidate. `query.from_smarts` uses `depict` too, so SMARTS inserts look like SMILES inserts, and the layout route adds `score` to its answer (the window ignores it). + +## 104. Crowded substituents swing on their hinge bond · _v0.7.0 (services/chem/layout_refine.py refine) + +No candidate avoids Taxol's clashes (the C1 OH touching the C2 ester O, the C4 acetate O touching that same O), so `refine` moves branches. For every acyclic bond the smaller side is a branch hinged on the other atom; only branches that hold or hinge on a crowded atom are tried. Moves rotate by plus or minus 12, 24 or 36 degrees (cost 0.1, 0.25, 0.4) or mirror the branch across its hinge bond (single bonds, two atoms or more, cost 0.05), plus 0.01 per branch atom; a move is kept when the total drops by more than its cost and the hard part does not rise. Guards: the smallest angle at the hinge stays at least 60 degrees (45 at a four-connected hinge) or no smaller than it was, every double bond keeps its substituents on the same side (E/Z never changes), and atoms fixed by a partial Lay Out never move. At most six greedy passes, and work is capped at max(40, 6000 / atoms) evaluations: a count, not a clock, so the result is the same on every machine and hash seed. Results (total, then close/cross/near/label): Taxol 10.14 (0/0/0/3) to 0.68 (0/0/0/0) in 98 ms, erythromycin 3.26 to 0.07, vancomycin 7.31 to 0.76 in about 180 ms; benzene, aspirin, cholesterol and the cyclophane give byte-identical fragments to 0.6.0. Every CIP label and the canonical SMILES were unchanged in all ten test molecules. Morphine stays at 40.68: every candidate crosses the bridge over a ring bond, and the moves only touch acyclic branches. + +## 105. Clean Up picks the candidate nearest the drawing · _v0.7.0 (services/chem/layout.py clean, depict reference) + +Clean Up re-lays out each component and fits it back over the drawing, so its contract is to stay close to what was drawn. `depict(mol, reference=drawn)` picks, among the candidates with the lowest hard penalty, the one nearest the drawn coordinates (rigid fit with reflection), and refines only when that one still has a hard problem. On jittered drawings of six molecules the new Clean Up never moved atoms further than the old one. Wedges are untouched by the layout: insert and import derive them from the final coordinates, and the layout route still flips them through `restereo`. + +## 106. One table of formats drives menus, warnings and reports · _v0.7.0 (services/chem/formats.py TABLE, FEATURES, ALIASES, get, by_extension, loses, describe) + +Each format is one record: id, name, extensions, mime, read and write, binary, multi, reactions, options and `loses` (feature codes from `FEATURES`, plus `loses_v2000` for the molfile family). `GET /api/formats` serves `describe()`, so the window's "this will lose" list before saving and the writers' report after saving read the same table and cannot disagree. Ids: molfile (auto V2000 or V3000), molfile3000, sdf, rxn, rdf, smiles, cxsmiles (option `coords`), rsmiles, smarts, inchi, inchikey (write only), cml, cdxml and cdx (binary). Aliases (`mol`, `sd`, `smi`, `v3000`, `reaction_smiles` and the rest) resolve through `get`. `fchem` is not in the table: it has its own save path. + +## 107. Report items share one shape everywhere · _v0.7.0 (services/chem/report.py item, collect, SEVERITY, TEXTS, INTERNAL) + +An import or export report item is `{code, count, text, severity, atoms?, bonds?, objects?}`. Codes are stable, so the window can key translations on them later; `text` is a short English sentence. Severity is `info` for routine changes (coordinates generated, abbreviations expanded, written as V3000), `warn` for real loss and `error` for a record or structure that failed. `collect` merges items by code (adding counts and ids), drops internal notes (`INTERNAL`: reaction_arrow, query_ignored, conditions_comment) that earlier readers used for their own bookkeeping, sorts error, warn, info and caps the list at 200. Strings become `note` items, so old readers that return plain warnings still fit. + +## 108. One writer per format, with a report of what was left out · _v0.7.0 (services/chem/writers.py export_document, export_fragments, Exported, ExportError, _Writer, LOSS_CODES, LOSS_TEXTS) + +`export_document(doc, fmt, scope, page, ids_, options)` builds a scope (a page, the selection with groups expanded, or every page; atom ids are refused) and `export_fragments` does the same from loose fragments, objects and reaction records, so the routes, the CLI and the MCP tools of 0.8.0 share one path. `Exported` carries the body, the mime, a suggested filename (the single named structure's name, else the document title, made safe) and the report. The writer counts what the format cannot hold (enhanced stereo, queries, R-groups, data, names, maps, styles) from the scope itself and words it with the format's name; `note_annotations` reports text and graphics that no written reaction step used. Molfile switches to V3000 by itself past 999 atoms or bonds, or for AND/OR groups, queries, R-groups, dative or hydrogen bonds; forcing V2000 strips stereo groups first, because RDKit would otherwise switch to V3000 silently. Several structures on a page become one molfile with an info item; RXN writes the first step only; queries refuse plain SMILES with `query_refused`. The molfile chiral flag is written only when the fragment says `chiral: "absolute"`, as FORMAT says. + +## 109. CDXML and CDX go through Indigo's document JSON · _v0.7.0 (services/chem/cdxio.py read, write, _Frame) + +Indigo 1.49 reads CDXML and CDX with `loadMolecule` (then `loadReaction`) and can describe the result as KET JSON with structures, arrows, plus signs and styled text, so the reader walks the KET document rather than the XML, and the clean-room rule (no vendor code, text or sample files) holds. KET arrow modes map to FormChem arrow types, text keeps bold, italic, underline, sub, sup and size, and reaction steps are perceived from the geometry with `reactions.perceive_page`. The writer builds one KET document (structures as V3000 through Indigo, arrows, plus, text) and saves it with `cdxml()` or `b64cdx()`. What Indigo cannot carry is reported, not faked: colours and fonts (it writes Arial and Times), the bond length (it writes 30), line breaks in text (read back as spaces), curved arrows (written straight, `arrow_straightened`), shapes, brackets, tables, TLC plates, images, fragment names and data, R-group members on reading, and query structures in CDX ("Unsupported type 17"). Indigo's `loadKetDocument` handles macromolecules only and is not used. + +## 110. RD files and CML are FormChem's own readers and writers · _v0.7.0 (services/chem/rdfio.py, services/chem/cml.py) + +RD files hold `$RFMT` and `$MFMT` records with `$DTYPE`/`$DATUM` fields (with `+` continuation lines); a field whose name ends in CONDITIONS is read as the step's conditions, and each written step carries `RXN:CONDITIONS`. Every other structure becomes an `$MFMT` record with its data, and R-group members stay inside their scaffold's V3000 record instead of also being written as records of their own. CML writes the dialect the reader accepts: each molecule once, a `reactionScheme` or `reactionList` that refers to molecules by `ref`, `propertyList` as data, `label` for R and pseudo atoms, and a `conditionList`. Enhanced stereo, queries, R-group definitions and map numbers are not written to CML. + +## 111. The readers keep annotations and every reaction step · _v0.7.0 (services/chem/io.py read_text, read_file, read_bytes, ParseResult; services/importers.py import_file; services/chem/scheme.py) + +`ParseResult` gained `objects` (arrows, plus signs and text from CDXML and CDX), `reactions` (every step when a file holds more than one) and `report`. New inputs: RD files, `.sma` files of SMARTS lines with optional names (chirality drawn as wedges), InChI lines with a name, and reaction lines (a line with two `>`) in SMILES files. `importers.import_file` keeps the annotations and lays several steps out as chains (`scheme.layout`), continuing a row when a step starts from the last products, and stores the report in `meta.imported.report`; `warnings` stays as the report texts for older callers. Documents read at most `MAX_RECORDS = 1000` records (about 1.1 s); batch work must use the stream reader (entry 114). The old `io.split_components`, `_indigo` and the `cdx_dropped` and `cdxml_dropped` codes are gone. + +## 112. What the round-trip corpus found and fixed · _v0.7.0 (services/chem/cdxio.py, query.py, io.py, scheme.py) + +Fourteen documents (benzene, aspirin, caffeine, L-alanine, Taxol, sodium acetate, tetramethylammonium, chloroform-d, an AND pair, an atom-list query, a Markush scaffold, an esterification with conditions, a two-step scheme, a drawing with text and a curved arrow) were exported to every format and read back, comparing canonical and isomeric SMILES, CIP labels, CXSMILES, charges, isotopes, queries, R-groups, names, data, text, arrows and steps; the corpus lives outside the repository and takes about 3 s. Fixed on the way: `loadReaction` turned every single molecule into a reaction, so `loadMolecule` goes first; structures without a chiral flag came back as racemic AND groups, so the writer sets the flag for absolute stereo and an ABS-only group read back becomes `chiral: "absolute"`; element lists came back as a pseudo atom "C,N,O"; a salt was split into one KET molecule per ion on writing; forward arrows came back open-headed; text sizes were written on every run. RDKit wrote some three-coordinate centres of a SMARTS query with inverted parity (Taxol lost three), so `to_smarts` checks its text against the query and inverts those centres. InChI read Taxol's amide back as an iminol, so acyclic iminols from InChI become amides again. A two-step scheme read from RD or SMILES had its intermediate twice, so consecutive steps whose reactant matches the previous product (canonical SMILES) share it. Every loss left is named by a report item; the table is in `docs/FORMATS.md`. + +## 113. The export and format routes · _v0.7.0 (routers/documents.py export_document; routers/chem.py formats, export_fragments, export_options, parse) + +`GET /api/documents/{id}/export?format=&scope=&page=&ids=&options=&as=` answers the file body by default, with `Content-Disposition` (both `filename` and `filename*`), `X-FormChem-Filename`, `X-FormChem-Format` (the format actually written, so a molfile that switched says `molfile3000`) and `X-FormChem-Report` (URL-encoded JSON, at most 8 KB, halved and then replaced by one `report_truncated` item), all listed in `Access-Control-Expose-Headers`; `as=json` answers `{format, filename, mime, binary, text | base64, report}`. Failures are 422 with `{detail: {message, report}}`. `POST /api/chem/export` takes fragments, objects, reactions and expansions validated like `/api/chem/convert`. `POST /api/chem/parse` takes `base64` for binary data and sniffs CDX by its `VjCD0100` signature when no format is given. GETs need no window key; POSTs do, like every other POST. + +## 114. One stream reader for batch work · _v0.7.0 (services/chem/stream.py iter_records, Record, convert, explain) + +Building drawable fragments costs about 1 ms a record (10,000 SD records took 11.1 s through `io.read_file`), so batch work never builds them. `iter_records(path | text | file, fmt)` yields `Record(index, mol | None, name, block, error)` for SD, molfile, SMILES, CXSMILES, InChI and RD files, with SD data parsed lazily (`.data`), gzip read transparently and `#` comment lines skipped. `convert(source, to, out, fmt, limit)` writes SMILES, CXSMILES, InChI, InChIKey, SD or molfile and returns `{records, written, failed, seconds, to}`; 10,000 records to SMILES take 0.73 s. A failed record keeps its index and name, and `explain` gives RDKit's own reason ("Explicit valence for atom # 0 C, 5, is greater than permitted") by routing RDKit's error log to a captured `sys.stderr` while it parses that record again. That swap is process-wide for a moment: fine in the CLI and a single call, but in the engine's thread pool another thread's stderr could land in the capture. + +## 115. The file write route trusts the window key and an extension list · _v0.7.0 (routers/files.py write_file, _target, SUFFIXES, WRITE_LIMIT) + +In the desktop shell the window shows the native save dialog and asks the engine to write, because the webview cannot. `POST /api/files/write {path, text | base64, picked}` needs the window key, an absolute path, an existing parent folder, a target that is not a folder and an extension from `SUFFIXES` (pictures, chemistry and data text formats; `.fchem` stays on the store's save path); it writes atomically through `core/files.write_atomic`, up to 200 MB. Paths outside the home folder are refused unless `picked` is true. The engine cannot prove a native dialog produced the path: `picked` is the window's word, and the real boundary is the window key (agents on `/mcp` do not hold it) plus the extension list (no dotfiles, scripts or binaries). A stronger design, a Rust command that shows the dialog and registers the grant with the engine, is left for later. + +## 116. The engine reads the drawing kept inside pictures · _v0.7.0 (services/embedded_source.py extract, from_svg, from_png, from_pdf, from_eps, open_picture; services/store.py open; routers/documents.py upload_document) + +Exported pictures can carry the drawing as a plain document.json (one page, the exported objects, `meta.embedded`), under the mime `application/x-formchem+json`: SVG in `` as base64, PNG in an uncompressed iTXt chunk with that keyword (the compressed flag is also accepted), PDF as an uncompressed `/EmbeddedFile` named `drawing.fchem.json` (so both readers find it by a byte search; its length is found past the nested Params dictionary), and EPS in `%FormChemSource:` comment lines. `open_picture` validates the payload with `model.validate`, gives the document and page new ids and the file stem as title, and keeps object ids; a picture without a drawing is refused with a sentence that says so. Store.open and the upload route call it for `.svg`, `.png`, `.pdf` and `.eps`. + +## 117. fontTools subsets and outlines the label fonts · _v0.7.0 (services/pictures/fonts.py subset_woff, outline, advance, face, pdf_base; requirements.txt, requirements_macos.txt, setup/freeze_backend) + +SVG export embeds WOFF subsets of Arimo and Tinos as `@font-face` data URIs, keeping `kern` and `liga`, with timestamps not recalculated so the same drawing gives the same bytes; text stays text and the family list falls back to Arial, Helvetica or Times in programs that ignore `@font-face`. The OFL 1.1 allows embedding subsets. Arimo is a variable font, so it is instanced to static 400 and 700 with `fontTools.varLib.instancer`, cached per process; weight 500 maps to regular and 600 or more to bold, the same rule in SVG, PDF and EPS. PDF and EPS draw labels from the glyph outlines (`outline`, `advance`), without kerning pairs, a sub-pixel difference on short labels. fontTools 4.69.1 (MIT) is pinned in both engine requirement files and is the one new dependency of 0.7.0; `freeze_backend` and its `.bat` twin pass `--collect-submodules fontTools`, because fontTools loads its table modules by tag at run time. Without fontTools `/api/pictures/capabilities` says `fonts: false`, SVG embeds the full TTF faces, PNG still works and PDF and EPS draw everything except text, with a warning. svglib and cairosvg (LGPL-3.0, native cairo) and reportlab (large, and its PostScript backend cannot embed TrueType) were rejected. + +## 118. The export SVG becomes a display list · _v0.7.0 (services/pictures/svgdraw.py Reader, read, Drawing, Item, parse_transform, path_segments) + +The PDF and EPS writers do not interpret SVG themselves. `read` turns the export SVG, which the window built from its own renderer, into a display list of filled and stroked paths, text runs and images in page coordinates. It covers exactly what that SVG uses: paths with arcs, line, polyline, polygon, rect with rx, circle, ellipse, text and tspan with absolute positions and text-anchor chunks, image data URIs, transforms, clip-path rectangles, opacity, dashes, caps and joins. Gradients become their mean colour with a warning. Anything else is skipped with a warning rather than guessed. + +## 119. FormChem writes its own PDF · _v0.7.0 (services/pictures/pdf.py write, path_ops, _Images) + +PDF 1.7 with Flate content streams, an ExtGState per opacity, images as Flate RGB with an SMask (or DCT for JPEG, through Pillow when it is present), labels as glyph outlines and an invisible text layer (render mode 3, base-14 Helvetica or Times, metric twins of Arimo and Tinos) so pdftotext, search and copy work. The source goes in as an `/EmbeddedFile` with `/AFRelationship /Source`, listed in `/Names /EmbeddedFiles` and `/AF`. Checked with pdfinfo, pdftotext, pdfdetach, pypdf and `qpdf --check` (no errors), and pdftoppm renders match the PNG. Pillow comes with RDKit and is not pinned; without it a placed picture is left out of PDF and EPS with a warning. + +## 120. And its own EPS · _v0.7.0 (services/pictures/eps.py write, PROLOG) + +Level 2 EPSF-3.0 with a tight `%%BoundingBox`, the same path operators as the PDF from the same display list, outlined labels, ASCII85 images composited on white (EPS has no transparency; a warning says so) and the source in `%FormChemSource:` comment lines. No Ghostscript was available, so EPS was checked by reopening its source, not by rendering it. + +## 121. The pictures router · _v0.7.0 (routers/pictures.py capabilities, subset_fonts, convert; app/main.py) + +`GET /api/pictures/capabilities` answers `{formats: ["eps", "pdf"], fonts}`. `POST /api/pictures/fonts {faces: [{family, bold, italic, text}]}` answers WOFF subsets as base64 and lists the faces it could not find. `POST /api/pictures/convert {format, svg, source, title}` answers `{base64, mime, warnings}`. Both POSTs need the window key. main.py includes `files` (imported as `file_writes`, because `app.core.files` is already in scope) and `pictures` on their own lines after the existing routers. + +## 122. Standardise is one pipeline in a fixed order · _v0.7.0 (services/chem/standardise.py run, STEPS, ALIASES) + +Steps always run as cleanup, normalise, salts, largest, reionise, neutralise, tautomer, isotopes, stereo, strip_h, whatever order they are given in, so the same choice gives the same result in the window, the route and the CLI. The default set is cleanup, normalise, salts, reionise, neutralise and strip_h; `largest` is off because on a page it would keep one molecule of a whole scheme. Each step reports whether it changed anything (by canonical SMILES before and after, about 2 ms a record and most of the cost), a short detail ("removed Na+", "charged atoms 1 to 0") or its error; a failing step is skipped, never fatal. The fragments in scope are standardised together as one molecule, so a drawn Na+ beside a benzoate is a salt. The tautomer step keeps sp3 and double-bond stereo (`tautomerRemoveSp3Stereo` and `tautomerRemoveBondStereo` false), because with RDKit's defaults alanine lost its stereocentre. The window path skips perceive.prepare's sanitising (`SANITIZE_ALL` minus `SANITIZE_CLEANUP`), because RDKit's clean-up would rewrite N(=O)=O as the charge-separated nitro before the cleanup and normalise steps could report it. The UI says Standardise, as the rest of the app is British; the CLI also accepts `--standardize` and the -ize step names. + +## 123. Standardised structures are written back as one transaction · _v0.7.0 (services/chem/standardise.py _fragment_ops) + +Each RDKit atom carries an int property (`fc_std`) indexing a table of fragment, owner atom id and drawn flag. The Normalizer's reactions drop atom properties, so after each step any atom without it gets it back from a graph match of the skeletons, preferring the match that agrees with the atoms that kept theirs. Write-back deletes removed atoms and their bonds; sets charge, isotope (clearing D and T labels) and radical changes; rewrites bond orders only where the aromatic-model bond type changed, plus every bond of an aromatic system that holds a changed atom, from a fresh Kekule structure (that is how 2-hydroxypyridine becomes a correctly drawn 2-pyridone without touching an untouched benzene); pins hydrogens only where the window's valence model would read the new atom wrong; and clears element-like labels (OH, NH3+) on changed atoms so the renderer redraws them. A fragment that loses every atom leaves its page or group (an emptied group goes too) and the reaction roles. Wedges are cleared by the stereo step or when their bond stops being single. Changes inside an abbreviation are computed but not drawn, with an `abbreviation_kept` warning. + +## 124. The standardise route · _v0.7.0 (routers/analysis.py standardise_steps, standardise_structures) + +`GET /api/analysis/standardise` lists the steps with labels and methods. `POST /api/analysis/standardise` takes a fragment or a document with objects (the selection or the page, groups walked) and `steps`, and answers the per-step report, the SMILES before and after and `tx: {label, ops}` for the window to commit as one undo step, following entry 95's rules. The dialog previews by calling it without applying and commits on Apply after checking that no fragment changed meanwhile. + +## 125. The engine draws in the journal style for the command line · _v0.7.0 (services/chem/depict.py svg, png, Style, font_file) + +The window's renderer is TypeScript and not available in-process, so `./formchem render` draws with RDKit's MolDraw2DSVG and MolDraw2DCairo set close to the journal style: coordinates rescaled so the median bond is 1.5 A, then 14.4 pt bonds, 0.6 pt lines (`scaleBondWidth` off), an 18 percent double-bond offset, 10 pt Arimo labels when `frontend/public/fonts`, `FORMCHEM_DIST/fonts` or `FORMCHEM_FONTS` holds the font (RDKit's own font otherwise), black and white, a white background unless `--transparent`. SVG is sized in pt; PNG is 300 dpi with a pHYs chunk. It differs from the window: RDKit places labels and hydrogens itself, draws its own wedge and hash shapes, picks double-bond sides, has no aromatic circles or charge circles, and draws no FormChem text, arrows or styles. The Cairo library inside the RDKit wheel is covered by RDKit's row. + +## 126. Properties run on a molecule as well as a fragment · _v0.7.0 (services/chem/props.py measure, compute) + +`measure(mol)` holds what `compute(frag)` did after building the molecule, so `./formchem descriptors` reports exactly the Analysis panel's values and rounding without building drawings. The window's answers were checked unchanged on five structures. + +## 127. Batch runners and the record adapter · _v0.7.0 (services/batch.py convert_file, batch, descriptors_file, render_file, Options, Summary; services/chem/records.py parse_chunk, document, write_document) + +The runners are a library so the MCP `convert` and `batch_convert` tools of 0.8.0 give the same output as the CLI. Inputs that split into records (SD, SMILES, CXSMILES, InChI) are cut into chunks of 1000 and use a process pool (`--jobs`) only when there are at least two chunks; batch spreads files over the pool and gives a lone file the whole pool; output order always equals input order. The worker functions are module-level and picklable for the spawn start method of macOS and Windows. records.py reads through `stream.iter_records` only: the converter's own SD, SMILES and InChI readers were removed at integration, so there is one reader and no fallback path, and the 10,000-record outputs and failure CSVs were byte-identical before and after. Whole-document formats (CML, RXN, fchem) go through records.py's document writers; CDXML, CDX, RD and SMARTS output are not offered by the CLI yet and would go through `writers.export_fragments`. No empty output file is left when every record failed. + +## 128. The command line · _v0.7.0 (app/cli.py main, USAGE; setup/convert, setup/convert.bat; formchem, formchem.bat) + +`./formchem convert | batch | descriptors | render` run `python -m app.cli` from backend/ in the engine's venv, in-process, with no server or window. Paths are relative to the folder the person ran `./formchem` from (`FORMCHEM_CALLER_DIR`). Exit codes: 0 when at least one record was written, 1 when none was, 2 for bad arguments, 130 on Ctrl+C. Failures never stop a run; without `--errors` the first 20 are printed, with it every failed or warned record goes to a CSV (file, record, name, status, message), and `batch` always writes `formchem-batch-report.csv` when anything failed. `formchem.bat` passes `%*` untouched so comma lists survive cmd's argument splitting. `./formchem cli batch` (the window's command catalogue) and `./formchem batch` (files) are different commands; the usage text keeps them apart. The frozen desktop engine does not expose the CLI. Reference and timings: `docs/CLI.md`. + +## 129. The engine takes quick command state and lets the window decide · _v0.7.0 (routers/commands.py state, execute) + +The mirrored catalogue's `enabled` flags lagged behind keyboard edits (the window mirrored on registry changes and every two minutes), so agents were refused `undo` and `duplicate` right after a keyboard paste. `POST /api/commands/state {enabled, checked}` patches the mirror in memory (the file is rewritten by the next full mirror), and `execute` no longer refuses a command because the mirror says it is off: with a window connected the call goes to the window, which checks its registry and answers "X is not available right now: ". Without a window it answers NO_WINDOW as before. The mirror stays for `list_commands`. + +## 130. Preferences, model and guide additions of 0.7.0 · _v0.7.0 (routers/system.py PREF_SHAPES; services/model.py Grid, Style.grid; routers/mcp.py GUIDE) + +`scaleLabels` (bool) joins the settings store's shapes, so the Scale Labels and Text with Structures choice persists. The model gains the optional `Grid` TypedDict and `Style.grid` (FORMAT's Grid subsection); `_overlay` is unchanged and drops it from resolved styles, because a grid is only ever read from the document's own style. The agent guide names `scale-selection`, `scale-up` and `scale-down` and says zoom is only the view, so agents asked to make a structure larger do not zoom. + +## 131. The i18n scanner reads template placeholders and t() wrappers · _v0.7.0 (setup/i18n_tool.py EXPR, T_CALL, keep) + +The scanner skipped every string inside `${...}` of a template literal (how every HTML template passes text), lone lowercase words passed to `t()` and strings ending in a `{N}` placeholder, and it did not know the escaping wrappers `h()` and `x()`. It now visits placeholder expressions recursively, keeps every argument of `t()`, `h()` and `x()`, and no longer treats a closing `{N}` as code. The scan grew from 220 to 502 strings, 243 of them older than this version (Home, Help, About, Agents, Preferences, the stoichiometry and check panels, the find count). Some scanned strings are not UI text (MIME types, PNG chunk names, font keys, CSS font shorthands, report lines), so `NOT_TEXT` and three narrow `NOT_TEXT_RE` rules drop them; the bare word "in" stays out because keying it would translate the inch unit in the unit menus. `KEYED_WHOLE` keeps the pieces of toasts built from parts out of the scan, because their whole sentences are keyed instead (frontend log 186). + +## 132. Import reads a file for insertion without opening it · _v0.7.0 (routers/documents.py import_for_insert, _read_for_insert, _insert_number; services/importers.py read_for_insert, can_insert, grid, _left_out, INSERT_LIMIT, INSERT_MAX; services/chem/io.py) + +File > Import puts a file's contents into the drawing that is open, so the engine must read it without adding a document to the store, the recent list or the Imports folder. `POST /api/documents/import` takes JSON `{path, bond_length?, limit?}` (an absolute path, from the desktop dialog or an agent) or a multipart `file` with `?bond_length=&limit=` (the browser; the upload lives in a temporary folder), needs the window key, and answers `{name, format, document, media, keep_style, structures, report, warnings}`. It refuses relative or missing paths, kinds outside the import list plus `.fchem` and the four picture kinds, and files over 50 MB. `read_for_insert` sends chemistry files to `import_file` with the target drawing's bond length and at most `limit` records (default 50, at most 1000), `.fchem` files to `package.read` (media come back as data URLs up to 16 MB, the same carrier the clipboard uses) and pictures to `embedded_source.open_picture`. Only the first page with content is inserted (`pages_left_out`), and pictures inside an embedded drawing cannot come along (`pictures_left_out`), both warn. Inserted structures are laid out by `grid()` as a table (column widths and row heights from what they hold, as many columns as fit the page width), while File > Open keeps the old row flow. `_left_out` replaces io's `truncated` item with `left_out` (warn, count = records left out): "Inserted 50 of 120 structures; 70 were left out. Use File > Open to open the whole file as a drawing of its own."; io's SD reader now gives that count. `keep_style` is false for chemistry files (they take the target's style, as pasted SMILES does) and true for drawings and pictures. A plain picture without a drawing is refused; Insert > Image places pictures. + +## 133. Every agent write answers with the structure and a picture · _v0.8.0 (services/agent_out.py write_result, structure_of, row_line, _row, RESULT_SIZE) + +Spec 9.1 asks that every write return the resulting structure plus a rendered image, so the agent can check its work without a second call. `write_result(doc_id, tx, ids, text, extra)` is the one place that shapes it for the draw tools, the document tools and all 14 edit tools: content is a text block (the tool's sentence, "(rev N, one undo step)" when a transaction landed, one `row_line` per touched object, and a "Picture:" line naming the renderer) and an image block; `structuredContent` holds `doc`, `rev`, `changed`, `undo` ("one step" or null), `objects` (per fragment id, kind, atom and bond counts, SMILES, CXSMILES, InChIKey, formula, MW, warnings and valence errors; a group lists its fragments; a deleted id says `gone`), `image` and the tool's own `extra`. Rows come from the derived cache after the transaction (`STORE.derive_now`, which derives at once when the cache is stale), so the SMILES is the engine's, not the agent's input echoed back. The picture is a PNG of the touched objects fitted into 640 x 480 at 144 dpi; a render failure never fails the write: the image is left out and the text says why. The sentence ending is added once (`rstrip(". ")`), after an early version doubled it. + +## 134. render asks the window, which draws what the person sees · _v0.8.0 (services/agent_out.py render_image, selection, WINDOW_WAIT, SCOPES; services/bridge.py READ_ONLY) + +The engine has no renderer of FormChem's own (it is TypeScript), and a picture an agent checks must be the one the person sees, arrows, plus signs, text, brackets and display preferences included. So `render_image` sends the whole document, its derived cache, the page and the ids to the window as the window tool `render` (`bridge.window_call`), and the window draws it with the export renderer (frontend entry 187). Scopes: `object` (ids, checked against the drawing first), `selection` (the window tool `selection`, which must name this drawing) and `page` (every visible object in the page's order; an empty page is an error that names draw_from_smiles). Width, height and dpi are checked against 16 to 8192 px and 18 to 1200 dpi before anything is sent. `render` and `selection` joined `bridge.READ_ONLY`, so a background window that holds no drawing does not hold the call; `show` did not, because it opens a drawing. The wait is 25 s, long enough for a first PNG with font subsets on a throttled machine. + +## 135. Without a window the engine draws the structures · _v0.8.0 (services/agent_out.py engine_picture, _fragment_mol, ENGINE_DPI; services/chem/depict.py) + +With no window, a window error, or no answer in 25 s, the engine draws with `depict.svg` or `depict.png` (entry 125): the fragments in scope are combined with `Chem.CombineMols` from `perceive.prepare` molecules (falling back to `convert.to_mol`) so they keep their page positions. Arrows, plus signs and text cannot be drawn there; the result counts what was left out and says that an open window draws them. A requested width or height without dpi sizes the box directly; otherwise the natural size is drawn and shrunk to fit. Every answer names its renderer (`window` or `engine`), in the text and in `structuredContent.renderer`, so an agent never mistakes the journal-style fallback for the person's view. + +## 136. Which drawing a tool acts on · _v0.8.0 (routers/mcp.py _doc_id, _active_doc, _show, _shown_text, _edit_doc, _DOC) + +`doc` when given (an unknown id names list_open_documents); else the only open drawing; else the drawing the window shows (the `selection` window tool returns the active doc); else a ToolError asking for doc. The draw tools, `add_atom` and `add_reaction` make a new drawing when none is open and close it again when their input cannot be read, so a failed first call leaves nothing behind. The engine does not know which drawings a window has attached (a client's doc list fills only on transactions), so the window tool `show` is idempotent: it attaches and activates a drawing the window does not have yet, or any drawing when `focus` is true, and leaves Home. `_edit_doc` is `_doc_id` then `_drawing({"doc": id})`, which made the edit tools pick the shown drawing too (integration commit e2749ad); the 0.5.0 and 0.6.0 tools still use `_drawing` and `_analysis_source`, which need doc when several are open, a known issue left for a later change because it changes their behaviour. + +## 137. New things go into free space, never after an arrow · _v0.8.0 (services/agent_out.py free_spot, GAP_BONDS, FIRST_BONDS; services/agent_draw.py _where, _overlaps, _box) + +A structure dropped on top of others, or just after a reaction arrow where perception would read it as a product, is a silent error the agent cannot see. The text is parsed at the origin with the scored layout, its box measured with `geometry.object_box`, and `free_spot` puts it right of the page content, top aligned, two bond lengths clear, when that fits within the page width less its margin; otherwise below the content at its left edge. A page that holds any arrow always grows downwards (fix 7c86a6a). An empty page starts at the margin plus two bond lengths. When the agent gives x and y they are used as given, and an `overlap` note says the drawing covers objects already there. Bond length is the drawing's resolved style, so a drawing scaled on the sheet gets structures at its own size. + +## 138. Drawing from text is one set of ops through the Insert Reaction path · _v0.8.0 (services/agent_draw.py structure_ops, reaction_ops, is_reaction, STRUCTURE_FORMATS, QUIET; routers/mcp.py _draw, t_draw_from_smiles, t_draw_from_molfile) + +`structure_ops` reads SMILES, CXSMILES, molfile or SD text with `io.read_text` at the drawing's bond length (a molfile keeps its own coordinates, scaled; one without them is laid out), claims fresh ids against `reactions.used_ids` with `scheme._claim`, names the structure (numbered when the text held several), moves it to its spot and returns `set` and `ins` ops. A first word with exactly two `>` is reaction SMILES: `reaction_ops` parses it once with `scheme.parse` to measure the box, then calls `scheme.insert_ops` at the computed origin, exactly the Insert Reaction layout, so the scheme has its arrow, plus signs, agents over the arrow and the reaction step with roles. The `coordinates_generated` note is dropped as routine. `_draw` applies the ops as one transaction with the undo label Draw from SMILES, Draw from Molfile or Draw Reaction from SMILES, shows the drawing, and words the result through entry 133. + +## 139. get_structure writes V3000 only when the structure needs it · _v0.8.0 (services/agent_out.py full_structures, FULL_FIELDS; routers/mcp.py t_get_structure, MOLFILES_IN_TEXT, STRUCTURE_ROWS) + +One object (a fragment or a group, whose fragments are listed), the person's selection (`selection: true`) or every fragment, each with SMILES, CXSMILES, InChI, InChIKey, formula, average and monoisotopic mass, m/z for charged structures, elemental analysis, warnings and a molfile. The molfile goes through `writers.export_document(doc, "molfile", "selection", None, [fid])`, the same writer as File > Export, so it switches to V3000 by itself only for what V2000 cannot hold (entry 108: more than 999 atoms or bonds, AND and OR groups, queries, R-groups, dative or hydrogen bonds), and `molfile_version` says which. Loss items of warn severity from the writer join the fragment's warnings. The text shows at most three molfiles; `structuredContent` carries them all, up to 200 rows, with `more` for the rest. + +## 140. validate and compute_properties are the spec's names for the 0.6.0 tools · _v0.8.0 (routers/mcp.py t_validate, t_compute_properties, _same_as) + +Spec 9.1 names them validate and compute_properties; agents written against 0.6.0 call check_structure and properties. Both pairs stay: `_same_as` resolves the drawing the 0.8.0 way (entry 136) and then calls the 0.6.0 handler, so the answers are the same JSON. `validate` adds `valid`, true when no fragment has an error-severity issue and every fragment could be read. + +## 141. convert and batch_convert run the command line's own runners · _v0.8.0 (services/agent_convert.py convert, batch_convert, steps_of, in_temp, _fresh, is_path, REPORT, TEXT_LIMIT, ROWS; services/batch.py) + +Spec 9.2 asks that an agent's conversion equal the CLI's. Both tools call `services/batch.py` `convert_file` and `batch` with the same `Options` as `setup/cli.py` builds, in a worker thread, and `batch_convert` writes `formchem-batch-report.csv` in the output folder when any row failed, as `./formchem batch` does; `./formchem batch DIR --to sdf --out A` and `batch_convert` into B gave `diff -r` identical trees. `convert` input is text, or an absolute path when it looks like one and exists; text output is returned up to 2 MB, failures per record up to 50 rows. `standardise` takes true, `default` or step names through `standardise.parse_steps`. Neither tool writes over an existing file or into a folder that already holds files, the temporary folder included (fix 4f09649), so an agent cannot clobber anything even where consent is not asked. There is no progress channel (the HTTP server answers JSON, no SSE), so a long batch answers at the end; the stdio relay waits up to 900 s. + +## 142. Save and close never lose the person's work · _v0.8.0 (routers/mcp.py t_new_document, t_open_document, t_save_document, t_close_document, t_list_open_documents; services/store.py default_target) + +`save_document` writes to the drawing's own file, to an absolute `path` (`.fchem` added), or, with neither, to a free name in the Drawings folder. It refuses a path that exists and is not the drawing's own file, naming File > Save As in the window as the way to overwrite: the refusal is the consent path, so no overwrite dialog was needed. `close_document` refuses a drawing with unsaved changes, because only the person may throw changes away. `open_document` reads FormChem drawings, chemistry files and pictures with a drawing inside, does not open a file twice, and shows the drawing; `new_document` shows an empty one. + +## 143. Every writing tool goes through the consent gate · _v0.8.0 (routers/mcp.py MUTATING, _mutating, _temporary) + +new_document, open_document, save_document, close_document, draw_from_smiles, draw_from_molfile and the 14 edit tools are in `MUTATING`, so an outside agent's first change asks the person (Deny, Allow once, Always allow), and FormChem's own agent tabs are never asked, as before. `convert` asks only when `output` is outside `tempfile.gettempdir()`, `batch_convert` unless its output folder is there, which the generated tools reference shows as "approval-gated when it changes something". render, get_structure, validate, compute_properties, list_open_documents and get_atoms carry `readOnlyHint` and never ask. In the aspirin exit run the only question was the first draw_from_smiles. + +## 144. The edit tools are pure builders · _v0.8.0 (services/agent_edits.py, EditError, merge_ops, Target, locate_atom, locate_bond; routers/mcp.py _edit, _touched) + +Each tool is `fn(doc, args) -> (ops, info)` on a deep copy of the document, with no store, no window and no I/O, raising `EditError` with the next step in its text. `_edit` runs the builder in a thread, applies the ops through `_apply` (`STORE.apply` with origin `agent` and the agent's name, no coalescing key, so two calls never merge into one undo step), shows a drawing the call created, and answers through `write_result` with `edit` (what the builder reports) and `label`. A builder that changes nothing still answers, and says there is nothing to undo. `Target` turns a mix of atom and object ids into atoms per fragment plus whole objects, with their box and median bond length, so move, scale, align and clean_layout accept either. On 21 edit calls of the mcpedit run the revision rose by exactly one each time and the top of the undo stack carried the call's label. + +## 145. add_atom picks the freest direction · _v0.8.0 (services/agent_edits.py add_atom, free_angle, _room_ops) + +No neighbour: 30 degrees. One neighbour: the two 120 degree candidates (180 when the new or the existing bond is triple, or both are double). Two or more: the bisector of the widest gap. Candidates rank by distance to every other atom on the page (rounded to 0.01 bond length), ties by the more horizontal one, which gives the chemist's zigzag; when the best is within 0.75 bond length of another atom a 15 degree sweep picks the freest. The bond length is the fragment's median, else the style's. An atom with an explicit `hydrogens` count gives up as many as the bond order it gains, and a plain element-plus-H label (OH, NH2) is dropped when it gains a bond (`_room_ops`), so the label on the canvas and the chemistry agree. Without `bond_to` the atom starts a new fragment in free space, or at x and y. + +## 146. add_bond sets an existing bond and merges fragments with care · _v0.8.0 (services/agent_edits.py add_bond) + +The spec has no set_bond, so add_bond on two atoms already bonded sets that bond's order and wedge. Atoms of two fragments merge (atoms, bonds and stereo groups) into the one a reaction step, caption, arrow anchor or stoichiometry row refers to; when both are referred to, it refuses with the reason rather than break a scheme, and a fragment with R-groups is never merged away. A wedge or hash has its narrow end at atom1. + +## 147. set_stereo rewrites wedges for R and S and mirrors for E and Z · _v0.8.0 (services/agent_edits.py set_stereo; services/chem/stereo.py rewedge) + +R or S goes through `stereo.rewedge(frag, expansions, centres=[atom], cip={atom: label})`, the 0.6.0 wedge assignment, touching only that centre's wedges; when no wedge choice reaches the label, it refuses with the reason. E or Z is geometry: the smaller side of a chain double bond is mirrored across the bond's line with its wedges inverted (as Flip does), `either` is cleared, and the result is read back with perception before the ops are returned. Ring double bonds are refused. Checked on (R)-2-butanol: one wedge written, the derived cache read R and the stereo tool `CC[C@@H](C)O`. + +## 148. replace_substructure matches like search and is checked against RDKit · _v0.8.0 (services/agent_edits.py replace_substructure, fragment_diff_ops; services/chem/search.py query_from; services/chem/layout.py compute_coords) + +Matching is search.py's (`search.query_from`, matches on `perceive.prepare` molecules), skipping hits inside abbreviations and taking non-overlapping matches, the first only unless `all`. It follows `Chem.ReplaceSubstructs` semantics: the replacement's first atom, or the atom next to a single `*`, takes every bond from the matched atoms to the rest. The fragment is edited as a copy and written back as a diff, so untouched atoms keep their ids and places; the connecting atom sits where the first bonded matched atom was and only the new atoms are laid out (`compute_coords` with every other atom fixed). The replacement is built with `convert.from_mol`, so charges, isotopes and pinned hydrogens come with it. Every result is compared with `Chem.ReplaceSubstructs` on the same fragment, and a difference is reported in the text, never hidden. + +## 149. move, scale and align run in the engine · _v0.8.0 (services/agent_edits.py move, scale, align, map_ops) + +The window's arrange code is TypeScript, and the tools must work with no window open, so the engine mirrors it. `map_ops` is the engine's mapObject: it moves or scales every object kind, and captions anchored to a structure follow it. `scale` mirrors canvas/tools/scale.ts: with ids the chosen objects scale together about their centre; without ids every unlocked, visible top-level structure on every page scales about its own centre (the window does the current page only; the engine has no current page). The style gets `bond_length` always and line and label sizes when `labels` is true; shapes, images, brackets and TLC plates resize, plus signs and orbitals scale, text scales only with labels. Percent is 5 to 2000 and the factor is clamped to 0.05 to 20 as in the window. `align` lines up edges or centres and spaces three or more evenly. + +## 150. clean_layout, delete, add_arrow, add_text and add_reaction · _v0.8.0 (services/agent_edits.py clean_layout, delete, remove_objects_ops, add_arrow, add_text, add_reaction) + +`clean_layout` uses each fragment's resolved bond length (so a scaled structure keeps its size), `layout.clean` with the atom ids for mode clean and `layout.compute_coords` for mode layout, flips wedges with the same `layout.restereo` as `/api/chem/layout`, and reports `layout.score_fragment` before and after. `delete` mirrors the window's deleteSelectionOps and removeObjectsOps (an atom takes its bonds, an emptied fragment goes, a group whose members all go is removed) and, like the window, leaves reaction steps that name a deleted object for perceive_reactions to redo. `add_arrow` stops object ends half a bond length outside the object's box on the line between the ends, anchors atom and bond ends and stops them 0.15 bond lengths short (curved.ts ANCHOR_GAP), defaults curved and fishhook arrows to a 90 degree bend, and writes head and tail only when given. `add_text` with `below` makes a centred caption anchored half a bond length under its target. `add_reaction` calls `agent_draw.reaction_ops`, the same function as reaction SMILES in draw_from_smiles. + +## 151. One call log, hooked where every call passes · _v0.8.0 (services/agent_log.py begin, end, summary, _value, SECRET, NOTE_LIMIT; routers/mcp.py call_tool, _dispatch) + +`call_tool` wraps the old body (now `_dispatch`), so every tool, present and future, from HTTP, stdio or the window's own chat (chat/tools.py calls `call_tool`) is logged without the tools knowing. An entry holds id, agent, inapp, tool, an argument summary, start time, duration, status (running, ok, error, refused), whether the call writes, the drawing, the transaction, how many transactions, the revision, up to 60 touched top-level object ids and the first line of the answer (200 characters). The summary is `key=value`: strings clipped at 48 characters with their length, anything with a line break (a molfile) as "(n lines)", values of keys that look like tokens, secrets, passwords, API keys, authorisation, cookies or credentials as "(hidden)", nested dicts one level, short lists of up to four scalars, the whole line at 240 characters. The gate's refusals are tagged `_refused` in `_dispatch` and popped before the answer leaves, so the log tells a refusal from an error. + +## 152. A call owns its transactions through a context variable and a 1.5 s window · _v0.8.0 (services/agent_log.py _current, _owner, _running, _settling, _settled, SETTLE_SECONDS, WINDOW_TOOLS) + +`begin` sets a contextvar that flows through `_apply`, `STORE.apply` and the after-change hooks, so direct writers (the draw and edit tools, perceive_reactions, map_reaction) are attributed exactly. `run_command` and `extension_command` make the window post a `user` transaction, possibly after the tool has answered; such a transaction goes to the single writing window-tool call that is running or ended less than 1.5 s ago. With two such calls at once nothing is attributed, and a person editing in those 1.5 s could be attributed to the agent: rare, and named here rather than hidden. History transactions are never attributed. + +## 153. The store tells services about every change, undo and redo · _v0.8.0 (services/store.py AFTER_CHANGE, _applied; services/agent_log.py after_change, _stacks, undoable, _owners) + +`AFTER_CHANGE` is a list of async hooks the store awaits after it broadcasts each applied transaction, before derive and autosave; a failing hook is logged and never breaks the change. agent_log's hook records the owner of each transaction and, after every change, undo or redo, looks at the top of that drawing's undo stack and broadcasts `agentUndoable {doc, call}` when the call that owns it changes, which is what puts Undo on exactly one row per drawing. `undone` is recomputed on history transactions as "in the redo stack, or was undone and is not back on the undo stack" (fix 93ba9e4): reading the redo stack alone turned an undone row back to done once a later edit cleared redo. + +## 154. The call log on disk · _v0.8.0 (services/agent_log.py _persist, _rotate, _session_file, log_path, CAP, FOLDER, FILE_LIMIT, ROTATIONS, SESSIONS_KEPT) + +The newest 400 calls stay in memory. Each finished call (a window-tool write after its 1.5 s settle) is appended as one JSON line to `Agent log/-.jsonl` in the data folder; a file rotates at 1 MB to `.1`, `.2` and `.3`, and the newest 20 engine sessions are kept. The argument summaries are what is written, so secrets never reach disk, but tool names, SMILES and paths do: the folder lives in the person's data folder with the drawings. + +## 155. The agent activity routes · _v0.8.0 (routers/agent_activity.py calls, clear, undo, stop, allow, token, _guard, _announce; app/main.py) + +`GET /api/agents/calls?limit=&agent=` answers the log newest first with `undoable` (drawing to call), the agent names, the stopped agents, the cap and the log file; it is open like the other GETs. `POST /calls/clear` empties the memory (the files stay) and keeps running calls. `POST /calls/{id}/undo` undoes the call's transaction only while it is the top of its drawing's undo stack, else 409 with a sentence that says to use Edit, Undo; a call that changed nothing or a closed drawing is 404 or 409 with its reason. `POST /stop` and `/allow` take `{agent}`. `GET /token` returns the agent token for the Agents dialog. Every route but the calls listing needs the window key, so an agent cannot undo itself into someone else's work or read the token. Live messages: `agentCall` (start, end, each attributed transaction), `agentUndoable`, `agentAccess {agent, state, stopped}`, `agentCallsCleared {kept}`. + +## 156. Stop refuses an agent by name and withdraws Always allow · _v0.8.0 (services/consent.py STOPPED, stop, resume, stopped; routers/mcp.py call_tool) + +`STOPPED` is in memory for the engine run. `stop(agent)` also writes `agentsAllowed: false`, so a standing Always allow is withdrawn for every outside agent and the next change of any of them asks again; Allow once was already per call. `call_tool` refuses every call of a stopped agent, reads included, with status refused and a sentence telling it to ask the person to allow it again in Agent activity. Identity is the MCP clientInfo name (or the in-app tab's name), so two sessions with one name stop together, and in-app tabs can be stopped too. A call already running when Stop is pressed finishes; Stop is about the next call, not an interrupt. `resume` clears the stop; the next change asks first. + +## 157. The agent token lives in the data folder · _v0.8.0 (core/agent_token.py value, valid, given, path, _create, FILE, SCHEME; app/main.py lifespan; core/config.py) + +Before 0.8.0 any local process could drive the tools: LocalGuard checks the Host and Origin, not who is asking. The token is 32 random bytes (`secrets.token_urlsafe`) on one line in `/agent-token`, created with `O_EXCL` and mode 0600 by the engine at start or by `./formchem agents install`, whichever runs first (both use O_EXCL, so they cannot write two). `value()` caches by mtime, so a replaced file is picked up without a restart, and a deleted one is made again on next use. `valid` compares with `hmac.compare_digest`. A file beside the settings, rather than a keychain entry, because stdio relays, the CLI and agent configs must read it without a prompt; it is a local bearer token, not a secret against the person's own account. + +## 158. HTTP MCP needs the token; the stdio relay and the cli send it · _v0.8.0 (routers/mcp.py _authorised, _unauthorised, mcp, mcp_delete; setup/mcp_stdio.py agent_token, post; setup/catalogue.py) + +`POST /mcp` and `DELETE /mcp` accept `Authorization: Bearer `, a live in-app tab token (`x-formchem-inapp`, claude_code.TOKENS) or the window key; anything else is 401 with `WWW-Authenticate: Bearer realm="FormChem"` and JSON-RPC error -32001 saying where the token is and that `./formchem agents install` or the stdio transport fixes it. `/mcp` stays in window_key.OPEN because the token, not the window key, is its credential. `mcp_stdio.py` reads the file on each request (an in-app tab sends its own token instead), retries once when a 401 comes back and the file changed (the engine made it at start), and turns a final 401 into a JSON-RPC error carrying the request's id, so the client shows the sentence. `./formchem cli run|batch|extension` send it too. + +## 159. agents install writes the token, agents token prints it · _v0.8.0 (setup/agents.py agent_token, data_dir, entries, configure, show_token, TOKEN_FILE; formchem, formchem.bat) + +The Claude Code HTTP entry of each `.mcp.json` install writes gets `headers.Authorization`; Codex, Cursor and Antigravity entries are stdio and read the file themselves. A caller folder's `.mcp.json` (FORMCHEM_CALLER_DIR) gets it too, and install says that such a folder may be under version control; FormChem's own `.gitignore` already ignores `.mcp.json`. `--dry-run` never creates a token. `./formchem agents token` prints it, for setup lines and `curl`. The token is deliberately not put in the chat panel's copied prompt (frontend entry 196), where it would sit in the clipboard and in transcripts. + +## 160. The instructions, guide and get_context of 0.8.0 · _v0.8.0 (routers/mcp.py INSTRUCTIONS, WORKFLOW, GUIDE, DRAWING_FROM, t_get_context; agents/manifest.json; .claude/skills/formchem-harness/references/tools.md) + +The server's instructions say to draw directly and check with render, get_structure and validate; WORKFLOW gains the draw-check and edit-by-id lines; GUIDE lists the drawing, checking, document, file and edit tools with "since 0.8.0" and the asking rules; `get_context` reports `drawingTools: true` and its Documents line names the tools. Tool descriptions say what each tool does now and nothing about later versions. `./formchem agents sync` regenerated the tools reference (42 sections with a contents list) and the manifest at each tool change. + +## 161. A lone hydrogen gets real coordinates · _v0.8.0 (services/chem/layout.py _candidates, depict) + +CoordGen returns NaN positions for a molecule made only of hydrogen, so `[H+]` in `CCO.CC(=O)O>[H+]>CC(=O)OCC.O` had no place and `scheme._repair` reported a row of atoms. Candidates with any non-finite coordinate are now skipped. That reached a fallback no input had hit: `Compute2DCoords(mol, coordMap=None)`, which RDKit's Boost signature rejects; both fallback calls now pass the dict, empty or not. `[H+]`, `[H][H]` and the reaction above get coordinates and the misleading note is gone. + +## 162. A lone atom's box covers its hydrogens on the side they are written · _v0.8.0 (services/chem/geometry.py fragment_box, HYDRIDE_FIRST) + +Once the window wrote water as H2O (frontend entry 197), the engine still measured a lone atom as its symbol only, so Insert Reaction put the plus sign on the H2. A lone atom without a label (not H, `*` or R#) now reaches two characters further on the side its hydrogens are written: left for O, S, Se, Te and the halogens (the same `HYDRIDE_FIRST` set as chem/valence.ts), right for the rest. + +## 163. Formula text in an arrow's band is conditions · _v0.8.0 (services/chem/reactions.py infer_step; docs/FORMAT.md) + +FORMAT.md (the contract) says that in the arrow's band above or below, structures are agents and text is conditions, and the 0.5.0 notes say text takes a role only as conditions in the band, or as a reactant or product on the row with `formula` true. The code put formula text in the band into agents. `infer_step` now puts only structures into agents. The step model has no text reagent with an amount, so conditions is the role that holds the meaning. FORMAT.md gained two clauses: band text with `formula` is conditions, and on the row the nearest structure, or text with `formula` true, takes the role, which is what the code always did. + +## 164. Settings are written under one lock · _v0.8.0 (core/config.py write_settings, _write_settings, _SETTINGS_LOCK) + +Always allow in the consent box (consent.py writes settings) and a window preference save ran in two threadpool workers; both wrote `settings.tmp`, the second `replace` failed with FileNotFoundError and a 500, and one change was lost. `write_settings` now holds a `threading.Lock` across read, merge, seal, write and replace. One engine process writes the settings, so a process lock is enough. + +## Not verified at 0.7.0 + +No macOS build was made: the one-folder freeze with Python 3.14 (in particular that `fc_flatten_engine` finds and replaces `Python.framework` and that `otool` finds nothing still linking it), the signed and notarized build, the launch time against the old 30 seconds, and multiprocessing under the frozen engine. At a2c81f6 `build_app`'s own freeze step does not pass `--collect-submodules fontTools`, which `setup/freeze_backend` does; a desktop app built with `./build_app` may lack fontTools' table modules, which would turn the font subsets off. EPS was not rendered (no Ghostscript). CDXML and CDX files made by the reference suite itself were never read; only Indigo-written files were. `formchem.bat` and `setup/convert.bat` were not run (no Windows here). + +## Not verified at 0.8.0 + +No real Claude Code, Codex, Cursor or Antigravity client was connected: the tools ran through `setup/mcp_stdio.py`, raw HTTP and curl, with the window in headless Chromium. Clients that cannot show image content were not tried; they still get the text and `structuredContent`. The desktop window (Tauri, WKWebView on macOS) never answered a `render` call; the PNG path avoids requestAnimationFrame, so a minimised window should still answer, untried. `formchem.bat agents token` was not run. `batch_convert` on 10,000 records was not timed through MCP (it runs the CLI's code in a worker thread). E and Z on bonds with large or crossing substituent trees were tried only on small chains. The 1.5 s attribution window can credit an agent with a person's edit made in that moment; it was reasoned about, not provoked. diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 906d362f..777f190d 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -1 +1 @@ -__version__ = "0.6.0" +__version__ = "0.8.0" diff --git a/backend/app/cli.py b/backend/app/cli.py new file mode 100644 index 00000000..3a3c1673 --- /dev/null +++ b/backend/app/cli.py @@ -0,0 +1,220 @@ +import argparse +import os +import signal +import sys +from pathlib import Path + +USAGE = """./formchem convert IN OUT [--from FMT] [--to FMT] [--standardise [STEPS]] [--errors report.csv] [--jobs N] [--v3000] +./formchem batch DIR --to FMT [--out DIR] [--jobs N] [--standardise [STEPS]] [--recursive] [--errors report.csv] +./formchem descriptors IN --csv OUT [--props LIST] [--standardise [STEPS]] [--jobs N] [--errors report.csv] +./formchem render IN --out DIR [--format svg|png] [--size W[xH]] [--transparent] [--standardise [STEPS]] [--jobs N] +./formchem convert --formats | --steps ./formchem descriptors --list""" +SHOWN = 20 + + +def _path(p: str) -> str: + if p == "-": + return p + q = Path(p).expanduser() + if not q.is_absolute(): + q = Path(os.environ.get("FORMCHEM_CALLER_DIR") or os.getcwd()) / q + return str(q) + + +def _jobs(v: str) -> int: + try: + n = int(v) + except ValueError: + raise argparse.ArgumentTypeError("jobs must be a whole number (0 means one per CPU)") + if n < 0: + raise argparse.ArgumentTypeError("jobs must be 0 or more") + return n or (os.cpu_count() or 1) + + +def _common(p: argparse.ArgumentParser) -> None: + p.add_argument("--from", dest="source", metavar="FMT", help="input format when the extension does not say it") + p.add_argument("--standardise", "--standardize", dest="steps", nargs="?", const="default", metavar="STEPS", + help="standardise each record first: default, all, or steps such as salts,neutralise,tautomer (see convert --steps)") + p.add_argument("--errors", metavar="FILE", help="write every failed record (record number, name, error) to this CSV file") + p.add_argument("--jobs", type=_jobs, default=1, metavar="N", help="worker processes for large inputs (0: one per CPU)") + p.add_argument("-q", "--quiet", action="store_true", help="print nothing but errors") + + +def parser() -> argparse.ArgumentParser: + top = argparse.ArgumentParser(prog="./formchem", usage=USAGE, description="FormChem's chemistry from a terminal, without the window or the engine server.") + sub = top.add_subparsers(dest="command", required=True) + c = sub.add_parser("convert", usage=USAGE.splitlines()[0], help="convert one structure file to another format") + c.add_argument("input", nargs="?") + c.add_argument("output", nargs="?", help="the output file, or - for the terminal") + c.add_argument("--to", metavar="FMT", help="output format when the extension does not say it") + c.add_argument("--v3000", action="store_true", help="write molfiles and SD files as V3000") + c.add_argument("--formats", action="store_true", help="list the formats") + c.add_argument("--steps", dest="list_steps", action="store_true", help="list the standardise steps") + _common(c) + b = sub.add_parser("batch", usage=USAGE.splitlines()[1], help="convert every structure file in a folder") + b.add_argument("folder") + b.add_argument("--to", metavar="FMT", required=True) + b.add_argument("--out", metavar="DIR", help="where the converted files go (default: DIR/converted)") + b.add_argument("--recursive", action="store_true", help="also convert files in subfolders") + b.add_argument("--v3000", action="store_true") + _common(b) + d = sub.add_parser("descriptors", usage=USAGE.splitlines()[2], help="calculated properties of every record as CSV") + d.add_argument("input", nargs="?") + d.add_argument("--csv", metavar="OUT", help="the CSV file, or - for the terminal") + d.add_argument("--props", metavar="LIST", help="comma-separated columns (default: every 0.6.0 property; all adds InChI, InChIKey and rule counts)") + d.add_argument("--list", action="store_true", help="list the columns with their methods") + _common(d) + r = sub.add_parser("render", usage=USAGE.splitlines()[3], help="one image per record in a folder") + r.add_argument("input") + r.add_argument("--out", metavar="DIR", required=True) + r.add_argument("--format", choices=("svg", "png"), default="svg") + r.add_argument("--size", metavar="W[xH]", help="fit each drawing into this many pixels (default: the journal scale, 14.4 pt bonds; PNG at 300 dpi)") + r.add_argument("--transparent", action="store_true", help="no white background") + _common(r) + return top + + +def _say(quiet: bool, text: str) -> None: + if not quiet: + print(text, file=sys.stderr) + + +def _report(args, summaries: list, default: str | None = None) -> None: + from app.services import batch + rows = [r for s in summaries for r in s.rows] + target = _path(args.errors) if args.errors else default + if target and (rows or args.errors): + batch.write_report(target, rows) + _say(args.quiet, f"report: {target} ({len(rows)} rows)") + return + failed = [r for r in rows if r["status"] == "failed"] + for r in failed[:SHOWN]: + where = f"record {r['record']}" if r["record"] != "" else "file" + print(f" {r['file']} {where}" + (f" ({r['name']})" if r["name"] else "") + f": {r['message']}", file=sys.stderr) + if len(failed) > SHOWN: + print(f" ... {len(failed) - SHOWN} more; give --errors FILE to list them all", file=sys.stderr) + + +def _line(s, verb: str) -> str: + from app.services.chem import records + rate = f", {s.records / s.seconds:,.0f} per second" if s.seconds > 0 and s.records > 99 else "" + jobs = f" with {s.jobs} processes" if s.jobs > 1 else "" + out = (f"{verb} {s.written:,} of {s.records:,} records from {records.NAMES.get(s.format_in, s.format_in)} to " + f"{records.NAMES.get(s.format_out, s.format_out.upper())} in {s.seconds:.2f} s{jobs}{rate}") + if s.failed: + out += f"; {s.failed:,} failed" + if s.changed: + out += "; standardise changed " + ", ".join(f"{n:,} by {k}" for k, n in sorted(s.changed.items())) + return out + + +def _steps(args) -> list[str]: + from app.services.batch import BadArguments + from app.services.chem import standardise + if not args.steps: + return [] + try: + steps = standardise.parse_steps(args.steps) + except ValueError as exc: + raise BadArguments(str(exc)) + if not steps: + raise BadArguments("--standardise chose no steps") + return steps + + +def _list_formats() -> int: + from app.services.batch import EXT + from app.services.chem import records + for f in sorted(set(records.READ) | set(records.WRITE)): + mode = ("read" if f in records.READ else " ") + (" write" if f in records.WRITE else "") + exts = ", ".join(sorted(e for e, k in records.EXTENSIONS.items() if k == f)) or EXT.get(f, "") + print(f"{f:<10} {mode:<11} {records.NAMES.get(f, f):<26} {exts}") + print("\nAny input may also be gzip-compressed (.sdf.gz, .smi.gz).") + return 0 + + +def _list_steps() -> int: + from app.services.chem import standardise + for k, label, method in standardise.STEPS: + print(f"{k:<11}{'*' if k in standardise.DEFAULT else ' '} {label}: {method}") + print("\n* in the default set. Steps always run in this order. Examples: --standardise (the default set)," + " --standardise all, --standardise default,tautomer,-strip_h") + return 0 + + +def _list_columns() -> int: + from app.services import batch + for k, label, unit, method in batch.descriptor_columns(): + print(f"{k:<24} {label + (f' ({unit})' if unit else ''):<34} {method}") + print("\nrecord, name and smiles are always written. --props all adds every column above.") + return 0 + + +def run(args) -> int: + from app.services import batch + from app.services.chem import depict + quiet = args.quiet + steps = _steps(args) + if args.command == "convert": + if args.formats: + return _list_formats() + if args.list_steps: + return _list_steps() + if not args.input or not args.output: + raise batch.BadArguments("give an input and an output file: ./formchem convert IN OUT") + s = batch.convert_file(_path(args.input), _path(args.output), + batch.Options(args.to or "", args.source, steps, args.v3000, args.jobs)) + _say(quiet, _line(s, "converted")) + if len(s.outputs) > 1: + _say(quiet, f"wrote {len(s.outputs)} files: {s.outputs[0]} ... {s.outputs[-1]}") + _report(args, [s]) + return 0 if s.written else 1 + if args.command == "batch": + out = _path(args.out) if args.out else None + target, _files = batch.batch_files(_path(args.folder), out, args.recursive) + found = batch.batch(_path(args.folder), batch.Options(args.to, None, steps, args.v3000, args.jobs), out, args.recursive) + if not found: + raise batch.BadArguments(f"no structure files in {args.folder}") + for s in found: + _say(quiet, f"{Path(s.source).name} -> {s.target}: {s.written:,} of {s.records:,}" + (f", {s.failed:,} failed" if s.failed else "")) + total = sum(s.written for s in found) + _say(quiet, f"batch: {len(found)} files, {total:,} of {sum(s.records for s in found):,} records written to {target} " + f"({sum(s.seconds for s in found):.2f} s of work" + (f", {args.jobs} processes)" if args.jobs > 1 else ")")) + _report(args, found, str(target / "formchem-batch-report.csv") if any(s.rows for s in found) else None) + return 0 if total else 1 + if args.command == "descriptors": + if args.list: + return _list_columns() + if not args.input or not args.csv: + raise batch.BadArguments("give an input and --csv OUT: ./formchem descriptors IN --csv OUT") + s = batch.descriptors_file(_path(args.input), _path(args.csv), batch.Options("csv", args.source, steps, jobs=args.jobs, keys=batch.parse_props(args.props))) + _say(quiet, _line(s, "described")) + _report(args, [s]) + return 0 if s.written else 1 + try: + size = depict.parse_size(args.size) + except ValueError as exc: + raise batch.BadArguments(str(exc)) + s = batch.render_file(_path(args.input), _path(args.out), batch.Options(args.format, args.source, steps, jobs=args.jobs, size=size, transparent=args.transparent)) + _say(quiet, _line(s, "rendered") + f"; images in {_path(args.out)}") + _report(args, [s]) + return 0 if s.written else 1 + + +def main(argv: list[str] | None = None) -> int: + if hasattr(signal, "SIGPIPE"): + signal.signal(signal.SIGPIPE, signal.SIG_DFL) + args = parser().parse_args(sys.argv[1:] if argv is None else argv) + from app.services.batch import BadArguments + try: + return run(args) + except BadArguments as exc: + print(f"formchem {args.command}: {exc}", file=sys.stderr) + return 2 + except KeyboardInterrupt: + print(f"formchem {args.command}: stopped", file=sys.stderr) + return 130 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/backend/app/core/agent_token.py b/backend/app/core/agent_token.py new file mode 100644 index 00000000..13389467 --- /dev/null +++ b/backend/app/core/agent_token.py @@ -0,0 +1,65 @@ +import hmac +import os +import secrets +from pathlib import Path + +from app.core import config + +FILE = "agent-token" +SCHEME = "bearer" +_cache: dict[str, object] = {} + + +def path() -> Path: + return config.data_dir() / FILE + + +def _read(p: Path) -> str: + try: + return p.read_text(encoding="utf-8").strip() + except OSError: + return "" + + +def _create(p: Path) -> str: + fresh = secrets.token_urlsafe(32) + try: + fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + except FileExistsError: + return _read(p) or fresh + except OSError: + return fresh + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(fresh + "\n") + return fresh + + +def value() -> str: + p = path() + try: + stamp = p.stat().st_mtime_ns + except OSError: + stamp = None + if stamp is not None and _cache.get("stamp") == stamp and _cache.get("value"): + return str(_cache["value"]) + found = _read(p) if stamp is not None else "" + if not found: + found = _create(p) + try: + stamp = p.stat().st_mtime_ns + except OSError: + stamp = None + _cache.update(stamp=stamp, value=found) + return found + + +def given(header: str | None) -> str: + if not isinstance(header, str): + return "" + scheme, _, rest = header.strip().partition(" ") + return rest.strip() if scheme.lower() == SCHEME else "" + + +def valid(header: str | None) -> bool: + token = given(header) + return bool(token) and hmac.compare_digest(token.encode("utf-8"), value().encode("utf-8")) diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 07923cec..7102ecfd 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -1,10 +1,13 @@ import json import os import sys +import threading from pathlib import Path from app import __version__ +_SETTINGS_LOCK = threading.Lock() + APP_NAME = "formchem" APP_TITLE = "FormChem" VERSION = __version__ @@ -104,6 +107,11 @@ def read_settings() -> dict: def write_settings(patch: dict) -> dict: + with _SETTINGS_LOCK: + return _write_settings(patch) + + +def _write_settings(patch: dict) -> dict: from app.core import seal stored = stored_settings() diff --git a/backend/app/main.py b/backend/app/main.py index 9eb5b571..e0cc9fae 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -10,13 +10,16 @@ from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles -from app.core import config +from app.core import agent_token, config from app.core.local_guard import LocalGuard from app.core.window_key import WindowKeyGuard from app.routers import analysis, chat, chem, commands, documents, extensions, library, live, mcp, reactions, system, templates, terminal 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 +from app.routers import pictures +from app.routers import agent_activity mimetypes.add_type("text/javascript", ".js") mimetypes.add_type("text/javascript", ".mjs") @@ -43,6 +46,7 @@ def _clear_discovery() -> None: @asynccontextmanager async def lifespan(this: FastAPI): _write_discovery() + agent_token.value() claude_code.sweep() terminals.bind(asyncio.get_running_loop()) history.start() @@ -71,6 +75,9 @@ async def lifespan(this: FastAPI): app.include_router(terminal.router) app.include_router(live.router) app.include_router(mcp.router) +app.include_router(agent_activity.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/agent_activity.py b/backend/app/routers/agent_activity.py new file mode 100644 index 00000000..37336a4b --- /dev/null +++ b/backend/app/routers/agent_activity.py @@ -0,0 +1,75 @@ +from fastapi import APIRouter, Body, Depends, HTTPException, Request + +from app.core import agent_token, window_key +from app.services import agent_log, consent +from app.services.hub import HUB +from app.services.store import STORE + +router = APIRouter(prefix="/api/agents") + + +def _guard(request: Request) -> None: + window_key.require(request) + + +GUARD = [Depends(_guard)] + + +def _stopped() -> list[str]: + return sorted(consent.STOPPED) + + +@router.get("/calls") +def calls(limit: int = agent_log.CAP, agent: str = "") -> dict: + return {**agent_log.listing(limit, agent), "stopped": _stopped()} + + +@router.post("/calls/clear", dependencies=GUARD) +async def clear() -> dict: + return {"cleared": await agent_log.clear()} + + +@router.post("/calls/{cid}/undo", dependencies=GUARD) +async def undo(cid: str) -> dict: + entry = agent_log.find(cid) + if entry is None or not entry.get("doc"): + raise HTTPException(404, "That agent call changed no drawing, or the log no longer holds it.") + doc_id = entry["doc"] + if doc_id not in STORE.sessions: + raise HTTPException(404, "The drawing that call changed is closed.") + if agent_log.undoable(doc_id) != cid: + raise HTTPException(409, "Something changed the drawing after this call, so it is no longer the latest step. Use Edit, Undo to step back to it.") + result = await STORE.undo(doc_id) + if result is None: + raise HTTPException(409, "There is nothing to undo in that drawing.") + return {"undone": cid, "doc": doc_id, "rev": result["rev"]} + + +async def _announce(agent: str, state: str) -> None: + await HUB.broadcast_all({"t": "agentAccess", "agent": agent, "state": state, "stopped": _stopped()}) + + +@router.post("/stop", dependencies=GUARD) +async def stop(body: dict = Body(...)) -> dict: + agent = str(body.get("agent") or "").strip() + if not agent: + raise HTTPException(400, "Name the agent to stop.") + consent.stop(agent) + await _announce(agent, "stopped") + return {"stopped": _stopped()} + + +@router.post("/allow", dependencies=GUARD) +async def allow(body: dict = Body(...)) -> dict: + agent = str(body.get("agent") or "").strip() + if not agent: + raise HTTPException(400, "Name the agent to allow again.") + consent.resume(agent) + await _announce(agent, "allowed") + return {"stopped": _stopped()} + + +@router.get("/token", dependencies=GUARD) +def token() -> dict: + value = agent_token.value() + return {"token": value, "header": "Authorization", "value": f"Bearer {value}", "file": str(agent_token.path())} diff --git a/backend/app/routers/analysis.py b/backend/app/routers/analysis.py index e7d0f64c..48dc437f 100644 --- a/backend/app/routers/analysis.py +++ b/backend/app/routers/analysis.py @@ -6,7 +6,7 @@ from app.routers.chem import MAX_TEXT, _bond_length, _expansions, _fragment, _num from app.services import ops as opsmod -from app.services.chem import ENGINE, abbrev, check, convert, hydrogens, isotopes, markush, props, query, search, stereo, superatom, v3000 +from app.services.chem import ENGINE, abbrev, check, convert, hydrogens, isotopes, markush, props, query, search, standardise, stereo, superatom, v3000 from app.services.store import STORE router = APIRouter() @@ -293,6 +293,32 @@ async def substructure(body: dict) -> dict: return await run(search.substructure, targets, pattern, smarts, expansions, _limit(body, "max_hits", search.MAX_HITS, 100_000), body.get("chirality") is True) +@router.get("/api/analysis/standardise") +def standardise_steps() -> dict: + return {"steps": [{"step": k, "label": label, "method": method, "default": k in standardise.DEFAULT} for k, label, method in standardise.STEPS], "engine": ENGINE} + + +@router.post("/api/analysis/standardise") +async def standardise_structures(body: dict) -> dict: + src = source(body) + try: + steps = standardise.parse_steps(body.get("steps")) + except ValueError as exc: + raise _unprocessable(exc) + if not steps: + raise HTTPException(422, "choose at least one standardise step") + doc = None + if src.doc is not None: + try: + s = STORE.get(src.doc) + except KeyError: + raise HTTPException(404, f"No open drawing has the id {src.doc}.") + with s.lock: + doc = copy.deepcopy(s.doc) + out = await run(standardise.standardise_fragments, src.fragments, steps, src.expansions, doc) + return await finish(body, src, out) + + @router.post("/api/analysis/molfile") async def molfile(body: dict) -> dict: src = source(body, single=True) diff --git a/backend/app/routers/chem.py b/backend/app/routers/chem.py index 8ce5ece4..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) @@ -93,7 +161,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/routers/commands.py b/backend/app/routers/commands.py index 26c9ef60..3bcf7910 100644 --- a/backend/app/routers/commands.py +++ b/backend/app/routers/commands.py @@ -88,8 +88,6 @@ async def execute(cid: str, params: dict) -> dict: found = find(cid) if _state["commands"] and found is None: return {"ok": False, "error": unknown(cid)} - if found and found.get("enabled") is False: - return {"ok": False, "error": f"{cid} is off in the window right now: it arrives in a later version of FormChem, or there is nothing for it to act on."} if not bridge.window_connected(): return {"ok": False, "error": NO_WINDOW} out = await bridge.window_call("run_command", {"id": cid, "params": params or {}}, None, 120) @@ -116,6 +114,24 @@ def mirror(body: Mirror, request: Request) -> dict: return {"ok": True, "size": _state["size"]} +class State(BaseModel): + enabled: dict[str, bool] = Field(default_factory=dict) + checked: dict[str, bool] = Field(default_factory=dict) + + +@router.post("/state") +def state(body: State, request: Request) -> dict: + require_local(request) + with _lock: + for c in _state["commands"]: + cid = c.get("id") + if cid in body.enabled: + c["enabled"] = body.enabled[cid] + if cid in body.checked: + c["checked"] = body.checked[cid] + return {"ok": True, "changed": len(body.enabled)} + + @router.get("") def catalogue(group: str = "", text: str = "") -> dict: rows = search(group, text) diff --git a/backend/app/routers/documents.py b/backend/app/routers/documents.py index e8f0d444..8e10dda2 100644 --- a/backend/app/routers/documents.py +++ b/backend/app/routers/documents.py @@ -1,12 +1,20 @@ import asyncio +import copy +import json +import tempfile 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 @@ -86,7 +94,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: @@ -102,6 +110,68 @@ async def upload_document(request: Request) -> dict: return {**info, "uploaded": str(target)} +def _insert_number(value: object, low: float, high: float, what: str) -> float | None: + if value is None or value == "": + return None + try: + number = float(value) + except (TypeError, ValueError): + raise HTTPException(422, f"{what} must be a number from {low:g} to {high:g}.") + if not low <= number <= high: + raise HTTPException(422, f"{what} must be a number from {low:g} to {high:g}.") + return number + + +async def _read_for_insert(path: Path, bond_length: float | None, limit: float | None) -> dict: + try: + return await asyncio.to_thread(importers.read_for_insert, path, bond_length, int(limit or importers.INSERT_LIMIT)) + except (importers.ImportFailed, ValueError, OSError) as exc: + raise HTTPException(400, str(exc)) + + +@router.post("/api/documents/import", dependencies=GUARD) +async def import_for_insert(request: Request) -> dict: + query = request.query_params + if request.headers.get("content-type", "").startswith("multipart/"): + bond_length = _insert_number(query.get("bond_length"), 1, 500, "bond_length") + limit = _insert_number(query.get("limit"), 1, importers.INSERT_MAX, "limit") + form = await request.form() + found = [v for key in ("file", "files") for v in form.getlist(key) if isinstance(v, StarletteUpload)] + if not found: + raise HTTPException(400, "Send the file as a multipart field named file, or its path as JSON.") + name = files.safe_name(Path(found[0].filename or "").name, "Imported") + if not importers.can_insert(name): + raise HTTPException(400, f"FormChem cannot import {Path(name).suffix or 'this kind of'} files.") + data = await found[0].read(UPLOAD_LIMIT + 1) + if len(data) > UPLOAD_LIMIT: + raise HTTPException(413, f"{name} is larger than {UPLOAD_LIMIT // (1024 * 1024)} MB.") + with tempfile.TemporaryDirectory(prefix="formchem-import-") as folder: + target = Path(folder) / name + await asyncio.to_thread(target.write_bytes, data) + return await _read_for_insert(target, bond_length, limit) + try: + body = await request.json() + except ValueError: + raise HTTPException(400, "Send the file as a multipart field named file, or its path as JSON.") + if not isinstance(body, dict): + raise HTTPException(400, "Send the path of the file as JSON: {\"path\": \"...\"}.") + bond_length = _insert_number(body.get("bond_length", query.get("bond_length")), 1, 500, "bond_length") + limit = _insert_number(body.get("limit", query.get("limit")), 1, importers.INSERT_MAX, "limit") + raw = body.get("path") + if not isinstance(raw, str) or not raw.strip(): + raise HTTPException(400, "Give the absolute path of the file to import.") + p = Path(raw.strip()).expanduser() + if not p.is_absolute(): + raise HTTPException(400, "Give the absolute path of the file to import.") + if not importers.can_insert(p): + raise HTTPException(400, f"FormChem cannot import {p.suffix or 'this kind of'} files.") + if not p.is_file(): + raise HTTPException(400, f"{p} does not exist.") + if p.stat().st_size > UPLOAD_LIMIT: + raise HTTPException(413, f"{p.name} is larger than {UPLOAD_LIMIT // (1024 * 1024)} MB.") + return await _read_for_insert(p.resolve(), bond_length, limit) + + @router.get("/api/documents/{doc_id}") async def get_document(doc_id: str) -> dict: _session(doc_id) @@ -192,6 +262,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) 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)} diff --git a/backend/app/routers/mcp.py b/backend/app/routers/mcp.py index 8fe1f043..fa88f45a 100644 --- a/backend/app/routers/mcp.py +++ b/backend/app/routers/mcp.py @@ -1,8 +1,10 @@ import asyncio +import base64 import copy import json import time import uuid +from pathlib import Path from fastapi import APIRouter, Request, Response @@ -17,24 +19,32 @@ LEGACY = ["2025-06-18", "2025-03-26", "2024-11-05"] DRAWING_FROM = "0.8.0" HANDOFF_STATES = ("working", "ready", "question", "clear") +OPEN_ROWS = 40 +STRUCTURE_ROWS = 200 +MOLFILES_IN_TEXT = 3 SERVER = {"name": "formchem", "title": "FormChem", "version": config.VERSION} CAPS = {"tools": {}, "resources": {}} LIST_CACHE = {"ttlMs": 60_000, "cacheScope": "private"} INSTRUCTIONS = ("FormChem is the structure drawing suite of the FormAI family, running on this computer; the person watches it in the FormChem window. " - "Drawings exist: get_context lists the documents open in the window (id, title, path, unsaved changes, revision, fragments, formula). " - f"Change them through run_command with the window's own commands (list_commands first; insert-smiles {{smiles}} adds a structure, clean-structure, align and the rest act on the person's selection) " - "and through Form extensions. Reaction tools work on a drawing directly: perceive_reactions and map_reaction write the reaction steps and the atom mapping (one undo step each); " - "export_reaction and reaction_stoichiometry read them. Analysis tools read a drawing: properties, check_structure, stereo (CIP labels and enhanced stereo groups) and substructure (SMARTS or a drawn query). " - f"Tools that add atoms and bonds by id arrive in {DRAWING_FROM}. " - "Workflow: get_context first; list_commands and run_command reach the window's menu commands; extensions_list and extension_command reach Form extensions; " - "handoff {state: ready or question, note} tells the person where your work stands in the window. Commands, extensions and a handoff change what the person sees, " - "so the first one asks the person in the window to allow agents. Details: resource formchem://guide.") + "get_context (or list_open_documents) lists the drawings open (id, title, path, unsaved changes, revision, fragments, formula). " + "Draw directly: draw_from_smiles {smiles} (reaction SMILES draws a scheme) and draw_from_molfile {molfile} lay a structure out and place it clear of the page content as one undo step, " + "and answer with the new ids, SMILES, InChIKey, formula, warnings and a picture. Check your work with render (a PNG or SVG of objects, the selection or the page, drawn by the window's own renderer when it is open), " + "get_structure (SMILES, CXSMILES, InChI, InChIKey, molfile, formula, masses) and validate (the structure check). new_document, open_document, save_document and close_document handle drawings; " + "convert and batch_convert convert files with the same code as ./formchem convert and batch. " + "The window's own commands stay reachable through list_commands and run_command; reaction tools (perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry) and analysis tools " + "(compute_properties, stereo, substructure) work on a drawing directly; extensions_list and extension_command reach Form extensions; handoff {state: ready or question, note} tells the person where your work stands. " + "Edit tools change a drawing by id, one undo step per call, and answer with the structure and a picture: get_atoms lists the atom and bond ids; add_atom, add_bond, set_charge, set_atom, " + "set_stereo, replace_substructure, delete, move, scale, align, clean_layout, add_arrow, add_text and add_reaction. " + "Tools that change what the person sees ask the person in the window to allow agents the first time. Details: resource formchem://guide.") WORKFLOW = [ "1. get_context -> window open or not, agents allowed or not, open drawings, catalogue size, your last handoff", - "2. list_commands {text} -> command ids; run_command {id} runs one in the window as the person's click would", - "3. reactions: perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry; analysis: properties, check_structure, stereo, substructure", - "4. extensions_list -> Form extensions and their commands; extension_command {id, command} runs one in the window", - "5. handoff {state: ready, note} when you are done; state question when you need the person's input", + "2. draw_from_smiles {smiles} or draw_from_molfile {molfile} -> new object ids, structure and a picture (one undo step); new_document, open_document {path}, save_document, close_document", + "3. edit by id: get_atoms -> atom and bond ids; add_atom, add_bond, set_charge, set_atom, set_stereo, replace_substructure, delete, move, scale, align, clean_layout, " + "add_arrow, add_text, add_reaction (one undo step each)", + "4. check: render {ids | scope} -> picture; get_structure {object} -> SMILES, InChIKey, molfile; validate -> issues by atom and bond id", + "5. reactions: perceive_reactions, map_reaction, export_reaction, reaction_stoichiometry; analysis: compute_properties, stereo, substructure; files: convert, batch_convert", + "6. list_commands {text} and run_command {id} for the window's own menu commands; extensions_list and extension_command for Form extensions", + "7. handoff {state: ready, note} when you are done; state question when you need the person's input", ] GUIDE = f"""# FormChem agent guide @@ -43,15 +53,29 @@ ## What exists in this version 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. +How an agent works on drawings: +- Drawing tools (since {DRAWING_FROM}): draw_from_smiles and draw_from_molfile put a structure or a reaction scheme on a drawing as one undo step, in free space right of or below what is there, and answer with the new object ids, the structure in machine form and a picture. With no drawing open they make one and show it in the window. +- Checking tools: render draws objects, the person's selection or the page as PNG or SVG (the window's own renderer when a window is open, so it is what the person sees; otherwise the engine's drawing of the structures). get_structure gives SMILES, CXSMILES, InChI, InChIKey, a molfile, formula and masses. validate runs the structure check. None of them change anything. +- Document tools: list_open_documents, new_document, open_document, save_document (never over another existing file) and close_document (never a drawing with unsaved changes). +- File tools: convert and batch_convert run the same conversion code as ./formchem convert and ./formchem batch, so their output is identical. +- 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. -Tools that add atoms and bonds by id and read the whole document arrive in {DRAWING_FROM}. Until then, say plainly what you can do with the commands and tools above. +- Edit tools (since {DRAWING_FROM}) change a drawing by id without a window: get_atoms names the atoms and bonds, the edit tools below each apply one transaction (one undo step) and answer with the structure in machine form and a picture. +Every change an agent makes is one undo step, so the person undoes a whole call with one Undo in the window. Ids of objects, atoms and bonds are stable: use the ids a tool returned, never positions. ## Tools - get_context: app, version, whether a window is open, whether agents are allowed, the documents open in the window (id, title, path, unsaved changes, revision, fragment count, formula), the size of the command catalogue and your last handoff. Call it first. +- draw_from_smiles {{smiles, doc?, x?, y?, name?}}: draws SMILES, CXSMILES or reaction SMILES (a scheme with arrow and plus signs) with the scored 2D layout, as one undo step. x and y place the top-left corner in points; left out, FormChem finds free space. Returns ids, structure and a picture. +- draw_from_molfile {{molfile, doc?, x?, y?}}: draws a V2000 or V3000 molfile (or SD records), keeping its coordinates, as one undo step. Returns ids, structure and a picture. +- render {{doc?, scope?, ids?, format?, width?, height?, dpi?}}: a PNG (image) or SVG (text) of objects, the selection or the page, and which renderer drew it. Read only. +- get_structure {{doc?, object? | selection?}}: SMILES, CXSMILES, InChI, InChIKey, molfile (V3000 only when needed), formula, average and monoisotopic mass, m/z and elemental analysis per fragment. Read only. +- validate {{doc?, object?}}: the structure check (valence, charges, undefined stereo, overlaps, wedges, isotopes, query features, R-groups) with a valid verdict; check_structure is the same check under its older name. Read only. +- compute_properties {{doc?, object?}}: the calculated properties with their methods; properties is the same list under its older name. Read only. +- list_open_documents: the open drawings and which one the window shows. Read only. +- new_document {{title?}}, open_document {{path}}, save_document {{doc?, path?}}, close_document {{doc?}}: make, open, save and close drawings; new and opened drawings show in the window. +- convert {{input, from?, to, output?, v3000?, standardise?}}: converts structure text or a file; the result comes back as text or goes to output. batch_convert {{input_dir, to, output_dir?, standardise?, recursive?, v3000?}}: converts a folder with a failure report, as ./formchem batch does. - list_commands {{text?, group?, id?, limit?}}: the window's command catalogue (the same commands as the menus, the title bar and the palette): id, label, group, what it does. Commands that arrive in a later version are listed as off. - run_command {{id, params?, confirm?}}: runs one command in the open window, exactly as the person's click would. A command marked risky needs confirm true. - extensions_list: the Form extensions FormChem found (installed by FormPortal or run from a folder by form.ext), their state and their commands. @@ -65,9 +89,18 @@ - check_structure {{doc?, object?, query?}}: the structure check: issues with a code, a severity and the atom and bond ids. Read only. - stereo {{doc?, object?}}: stereocentres, double bonds and axes with CIP labels, defined or not, and their enhanced stereo groups. Read only. - substructure {{doc?, smarts | query_object, objects?, chirality?, max_hits?}}: substructure hits across the drawing's fragments by atom and bond id. Read only. +- get_atoms {{doc?, object?}}: every atom (element, x, y, charge, isotope, label, implicit H, CIP, bond ids) and bond (atoms, order, wedge, E or Z) by id, per fragment with formula, SMILES and InChIKey. Read only. +- add_atom {{element, bond_to?, order?, fragment?, x?, y?, doc?}}: one atom; with bond_to it sits at bond length in the freest direction (a zigzag for chains); without, it starts a new fragment. Makes a drawing when none is open. +- add_bond {{atom1, atom2, order?, stereo?}}: bonds two atoms (joining their fragments), or sets the order and wedge of the bond already between them; a wedge's narrow end is at atom1. +- set_charge {{atom, charge}} and set_atom {{atom, element?, isotope?, label?, radical?}}: change one atom. +- set_stereo {{atom, label R|S}} rewrites that centre's wedges to the wanted CIP label; {{bond, label E|Z}} mirrors the smaller side of a chain double bond. It refuses, with the reason, an atom that is not a stereocentre or a ring double bond. +- replace_substructure {{smarts, replacement, object?, all?}}: replaces the first match (all: every match) with a SMILES group, as RDKit ReplaceSubstructs does; the replacement's first atom, or the atom next to its *, takes the outside bonds. Untouched atoms keep ids and places. +- delete {{ids}}, move {{ids, dx, dy}}, scale {{ids?, percent | bond_length, labels?}}, align {{ids, mode}}: arrange atoms and objects; scale changes the drawing, not the zoom. +- clean_layout {{objects?, mode clean|layout}}: Clean Up or Lay Out through the scored layout, with the score before and after. +- add_arrow {{kind?, from, to?, bend?, head?, tail?}}: from and to are [x, y] or an object, atom or bond id. add_text {{text, x?, y?, style?, size?, align?, below?}}: free text, or a caption under a structure. add_reaction {{reaction_smiles, x?, y?}}: a whole scheme from reaction SMILES with its step recorded. ## Asking the person -run_command, extension_command and handoff with a state change what the person sees, so the first such call from an agent asks the person in the FormChem window: Deny, Allow once or Always allow. With no window open there is nobody to ask, and the call is refused with a sentence saying so. Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are already trusted and are never asked. +Tools that change a drawing or what the person sees (the drawing, document and edit tools, run_command, extension_command, the reaction writers and handoff with a state), and convert or batch_convert writing outside the temporary folder, ask the person in the FormChem window the first time: Deny, Allow once or Always allow. Read-only tools never ask. With no window open there is nobody to ask, and the call is refused with a sentence saying so, unless the person chose Always allow earlier. Agents started from FormChem's own Claude Code, Codex, Cursor or Antigravity tabs are already trusted and are never asked. ## Errors Every error names the next step. Read it, do that, retry once. If get_context itself fails, the problem is the connection or the engine: ask the person to run ./formchem (or open the app). @@ -96,10 +129,68 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None = _S = {"type": "string"} +_DOC = {"type": "string", "description": "Drawing id from list_open_documents; may be left out when one drawing is open or the window shows one"} +_IDS = {"type": "array", "items": {"type": "string"}, "description": "Object ids: fragments, arrows, plus signs, text or groups"} TOOLS = [ _tool("get_context", "FormChem's version, whether a window is open, whether agents are allowed, the drawings open in the window (id, title, path, unsaved changes, revision, fragment count, formula), " - f"the command catalogue size and your last handoff. Change drawings with run_command and the window's commands; perceive_reactions and map_reaction write reactions; " - f"properties, check_structure, stereo and substructure read chemistry; tools that add atoms and bonds by id arrive in {DRAWING_FROM}.", {}, read=True), + "the command catalogue size and your last handoff. Draw with draw_from_smiles and draw_from_molfile and check with render, get_structure and validate; " + "get_atoms names atoms and bonds by id for the edit tools (add_atom, add_bond and the rest); " + "run_command reaches the window's own commands; perceive_reactions and map_reaction write reactions; compute_properties, stereo and substructure read chemistry.", {}, read=True), + _tool("render", "A picture of what the person sees: objects by id, the person's selection in the window or the whole page, as PNG (an image) or SVG (text). With a FormChem window open, the window's own " + "renderer draws it, arrows, plus signs and text included; with none open the engine draws the structures in the journal style. The answer says which renderer drew it.", + {"doc": _DOC, "scope": {"type": "string", "enum": ["object", "selection", "page"], "description": "object (the ids given), selection (what the person selected in the window) or page; default object when ids are given, else page"}, + "ids": _IDS, "format": {"type": "string", "enum": ["png", "svg"], "description": "png (default) or svg"}, + "width": {"type": "integer", "description": "Fit into this many pixels across (16 to 8192)"}, "height": {"type": "integer", "description": "Fit into this many pixels down (16 to 8192)"}, + "dpi": {"type": "integer", "description": "PNG resolution at 72 points to the inch (default 144; 18 to 1200)"}}, read=True), + _tool("draw_from_smiles", "Draws a structure from SMILES or CXSMILES in a drawing with FormChem's scored 2D layout, placed in free space right of or below what is on the page, as one undo step. " + "A reaction SMILES (reactants>agents>products) draws a scheme with an arrow and plus signs, as Insert Reaction does. With no drawing open it makes one and shows it in the window. " + "Returns the new object ids with SMILES, CXSMILES, InChIKey, formula and warnings, and a picture to check.", + {"smiles": {"type": "string", "description": "SMILES, CXSMILES or reaction SMILES, such as CC(=O)Oc1ccccc1C(=O)O; one structure per line"}, "doc": _DOC, + "x": {"type": "number", "description": "Left edge in points (x to the right); left out: free space"}, "y": {"type": "number", "description": "Top edge in points (y down); left out: free space"}, + "name": {"type": "string", "description": "Name given to the new structure"}}, ["smiles"]), + _tool("draw_from_molfile", "Draws the structure of an MDL molfile (V2000 or V3000) or the first records of SD text in a drawing, keeping the file's own 2D coordinates at the drawing's bond length " + "(laid out when it has none), placed in free space right of or below what is on the page, as one undo step. With no drawing open it makes one. Returns ids, SMILES, InChIKey, formula, warnings and a picture.", + {"molfile": {"type": "string", "description": "Molfile or SD text, with its line breaks"}, "doc": _DOC, + "x": {"type": "number", "description": "Left edge in points; left out: free space"}, "y": {"type": "number", "description": "Top edge in points; left out: free space"}}, ["molfile"]), + _tool("get_structure", "The structures of a drawing in machine form: SMILES, CXSMILES, InChI, InChIKey, a molfile (V2000, or V3000 when the structure needs it), formula, average and monoisotopic mass, m/z of " + "charged structures and elemental analysis, per fragment. For one object (a fragment or a group), the person's selection in the window (selection true) or every fragment. Does not change the drawing.", + {"doc": _DOC, "object": {"type": "string", "description": "A fragment or group id; left out: every fragment"}, + "selection": {"type": "boolean", "description": "True: the fragments the person has selected in the FormChem window"}}, read=True), + _tool("validate", "Checks the structures of a drawing (spec 9.1 name for check_structure, the same check): valence errors, unusual charges, undefined stereocentres and double bonds, wedge problems, " + "overlapping or crossing atoms and bonds, uncommon isotopes, query features in a plain drawing and R-group gaps. Each issue has a code, a severity (error, warning, info) and the atom and bond ids; " + "valid is true when no fragment has an error. Does not change the drawing.", + {"doc": _DOC, "object": {"type": "string", "description": "One fragment id; left out: every fragment"}}, read=True), + _tool("compute_properties", "The calculated properties of a drawing's structures per fragment, each with the RDKit method behind it (spec 9.1 name for properties, the same list): formula, MW, exact mass, " + "cLogP and molar refractivity (Crippen), TPSA, H-bond donors and acceptors, rotatable bonds, rings, aromatic rings, fraction Csp3, charge, stereocentres, Lipinski and Veber verdicts and elemental analysis. " + "Does not change the drawing.", + {"doc": _DOC, "object": {"type": "string", "description": "One fragment id; left out: every fragment"}}, read=True), + _tool("convert", "Converts structures between file formats with the same code as ./formchem convert: input is structure text or the absolute path of a file; the result comes back as text, " + "or is written to output (an absolute path; writing outside the temporary folder asks the person the first time, and an existing file is never written over). " + "Reads SD, SMILES, CXSMILES, InChI, molfile, RXN, reaction SMILES, RD, CML, CDXML, CDX and .fchem; writes smiles, cxsmiles, sdf, molfile, inchi, inchikey, cml, rxn, rsmiles and fchem. " + "Failures are reported per record.", + {"input": {"type": "string", "description": "Structure text, or the absolute path of a structure file"}, "from": {"type": "string", "description": "Input format when it cannot be told from the text or the extension"}, + "to": {"type": "string", "description": "Output format: smiles, cxsmiles, sdf, molfile, inchi, inchikey, cml, rxn, rsmiles or fchem"}, + "output": {"type": "string", "description": "Absolute path to write; left out: the result comes back as text"}, + "v3000": {"type": "boolean", "description": "Write molfiles and SD records as V3000"}, + "standardise": {"type": "string", "description": "default (strip salts, neutralise, canonical tautomer, largest fragment) or step names, comma separated; left out: none"}}, ["input", "to"]), + _tool("batch_convert", "Converts every structure file in a folder with the same code and output as ./formchem batch, into output_dir (default: a converted folder inside input_dir), " + "with a CSV report of failed records there. Writing outside the temporary folder asks the person the first time; a folder that already holds files is never written into. Returns a summary per file.", + {"input_dir": {"type": "string", "description": "Absolute path of the folder to convert"}, "to": {"type": "string", "description": "Output format, as for convert"}, + "output_dir": {"type": "string", "description": "Absolute path of a new or empty folder for the results"}, + "standardise": {"type": "string", "description": "default or step names, comma separated; left out: none"}, + "recursive": {"type": "boolean", "description": "Also convert files in subfolders"}, "v3000": {"type": "boolean"}}, ["input_dir", "to"]), + _tool("list_open_documents", "The drawings open in FormChem: id, title, path, unsaved changes, revision, fragment count and formula, and which one the window shows. get_context gives the same list with the rest of the context.", + {}, read=True), + _tool("new_document", "Makes a new empty drawing and shows it in the FormChem window. Returns its id for the drawing tools.", + {"title": {"type": "string", "description": "Title of the drawing (default Untitled)"}}), + _tool("open_document", "Opens a file as a drawing and shows it in the window: a FormChem drawing (.fchem), a structure file (molfile, SDF, RXN, RD, SMILES, CXSMILES, CML, CDXML, CDX, InChI) or a picture " + "FormChem exported with its drawing inside. A file already open is not opened twice. Returns the drawing's structures and a picture.", + {"path": {"type": "string", "description": "Absolute path of the file"}}, ["path"]), + _tool("save_document", "Saves a drawing as a .fchem file: to its own file, to path, or, when it has none yet and no path is given, to a new file in FormChem's Drawings folder. " + "It never writes over another file that exists: choose a new path, or ask the person to save over it in the window (File > Save As).", + {"doc": _DOC, "path": {"type": "string", "description": "Absolute path to save to; .fchem is added when missing"}}), + _tool("close_document", "Closes a drawing that has no unsaved changes, in the engine and in the window. A drawing with unsaved changes is not closed: save_document first, or ask the person to close it in the window.", + {"doc": _DOC}), _tool("list_commands", "The window's command catalogue, the same commands as the menus, title bar and palette: id, label, group and what it does; commands of a later version are listed as off. " "text narrows by words (all must match), group by one group; id returns one command in full.", {"text": _S, "group": _S, "id": _S, "limit": {"type": "integer", "description": "Most rows to return (default 60)"}}, read=True), @@ -144,9 +235,82 @@ def _tool(name: str, description: str, props: dict, required: list[str] | None = "query_object": {"type": "string", "description": "A fragment of the drawing to use as the query instead of smarts"}, "objects": {"type": "array", "items": {"type": "string"}, "description": "Fragment ids to search; absent: all"}, "chirality": {"type": "boolean"}, "max_hits": {"type": "integer", "description": "Most hits to return (default 1000)"}}, read=True), + _tool("get_atoms", "The atoms and bonds of a drawing's fragments by id, so edit tools can address them: per fragment its formula, SMILES and InChIKey; per atom the element, x and y in points " + "(y down), charge, isotope, label, implicit hydrogens, CIP label and bond ids; per bond the two atom ids, order, wedge and E or Z. Does not change the drawing.", + {"doc": _DOC, "object": {"type": "string", "description": "A fragment or group id; absent: every fragment of the drawing"}}, read=True), + _tool("add_atom", "Adds one atom as one undo step. With bond_to it bonds to that atom and sits at the drawing's bond length in the freest direction (zigzag for chains, the widest gap at branches) " + "unless x and y are given; without bond_to it starts a new fragment (or joins fragment, unbonded) in free space or at x, y. Returns the new atom and bond ids, the structure and a picture.", + {"doc": _DOC, "element": {"type": "string", "description": "Element symbol such as C, N, O, Cl, or * for any atom"}, + "bond_to": {"type": "string", "description": "Atom id to bond the new atom to (get_atoms lists them)"}, + "order": {"description": "Bond order for bond_to: 1, 2, 3, 1.5 (aromatic) or single, double, triple, aromatic; default 1"}, + "fragment": {"type": "string", "description": "Fragment id to add to; absent: bond_to's fragment, or a new fragment"}, + "x": {"type": "number", "description": "Page x in points (right); give with y"}, "y": {"type": "number", "description": "Page y in points (down); give with x"}}, + ["element"]), + _tool("add_bond", "Bonds two atoms by id as one undo step; when they are already bonded it sets that bond's order and wedge instead. Atoms of two fragments are joined into one fragment. " + "A wedge or hash has its narrow end at atom1.", + {"doc": _DOC, "atom1": {"type": "string", "description": "First atom id (the narrow end of a wedge)"}, "atom2": {"type": "string", "description": "Second atom id"}, + "order": {"description": "1, 2, 3, 4, 1.5 (aromatic), single, double, triple, aromatic, dative, zero, hydrogen or ionic; default 1"}, + "stereo": {"type": "string", "enum": ["none", "wedge", "hash", "hollow", "wavy", "either"], "description": "Wedge drawn on the bond; default none"}}, + ["atom1", "atom2"]), + _tool("set_charge", "Sets the formal charge of one atom by id as one undo step; hydrogens follow from the valence.", + {"doc": _DOC, "atom": {"type": "string", "description": "Atom id"}, "charge": {"type": "integer", "description": "Formal charge from -15 to 15; 0 removes it"}}, ["atom", "charge"]), + _tool("set_atom", "Changes one atom by id as one undo step: its element (dropping a label, hydrogen count and isotope, as the window's element menu does), isotope, label text or radical.", + {"doc": _DOC, "atom": {"type": "string", "description": "Atom id"}, "element": {"type": "string", "description": "New element symbol"}, + "isotope": {"type": "integer", "description": "Mass number; 0 for natural abundance"}, "label": {"type": "string", "description": "Text shown for the atom such as OH or D; empty shows the element"}, + "radical": {"type": "string", "enum": ["none", "doublet", "singlet", "triplet"]}}, ["atom"]), + _tool("set_stereo", "Sets a CIP label as one undo step: atom with R or S rewrites that centre's wedges so it reads as asked; bond with E or Z mirrors the smaller side of a chain double bond " + "across the bond's line. Fails with the reason when the atom is not a stereocentre or the bond cannot be E or Z.", + {"doc": _DOC, "atom": {"type": "string", "description": "Stereocentre atom id (label R or S)"}, "bond": {"type": "string", "description": "Double bond id (label E or Z)"}, + "label": {"type": "string", "enum": ["R", "S", "E", "Z"]}}, ["label"]), + _tool("replace_substructure", "Replaces what a SMARTS pattern matches with a SMILES group as one undo step, the way RDKit ReplaceSubstructs does: the matched atoms go and the replacement's first atom " + "(or the atom bonded to its *) takes their bonds to the rest. Untouched atoms keep their ids and places; only the new part is laid out.", + {"doc": _DOC, "smarts": {"type": "string", "description": "What to find, such as Cl, [OH] or C(=O)[OH]"}, + "replacement": {"type": "string", "description": "SMILES of what to put in, such as O, OC or *N(C)C"}, + "object": {"type": "string", "description": "Fragment or group to change; absent: every structure"}, + "all": {"type": "boolean", "description": "Replace every match (default: the first only)"}}, ["smarts", "replacement"]), + _tool("delete", "Deletes atoms, bonds and objects by id as one undo step, as the window's Delete does: an atom takes its bonds, a fragment left without atoms goes, and a group whose members all go is removed.", + {"doc": _DOC, "ids": {"type": "array", "items": {"type": "string"}, "description": "Atom, bond and object ids (get_atoms, get_structure)"}}, ["ids"], destructive=True), + _tool("move", "Moves atoms and objects by dx, dy points as one undo step (x right, y down); captions anchored to a moved structure follow it.", + {"doc": _DOC, "ids": {"type": "array", "items": {"type": "string"}, "description": "Object ids (fragments, arrows, text) or atom ids"}, + "dx": {"type": "number", "description": "Points to the right (negative: left)"}, "dy": {"type": "number", "description": "Points down (negative: up)"}}, ["ids"]), + _tool("scale", "Makes structures larger or smaller on the sheet as one undo step, without a window: by percent or to a median bond length, each about its own centre; with ids the chosen objects " + "scale together, without them every structure of the drawing. labels true scales line widths, labels and text too. Zoom only changes the view; this changes the drawing.", + {"doc": _DOC, "ids": {"type": "array", "items": {"type": "string"}, "description": "Object or atom ids; absent: every structure"}, + "percent": {"type": "number", "description": "New size in percent of the current size, 5 to 2000, such as 150"}, + "bond_length": {"type": "number", "description": "Wanted median bond length in points, such as 14.4 or 20"}, + "labels": {"type": "boolean", "description": "Scale line widths, atom labels and text too (default false)"}}), + _tool("align", "Lines up two or more objects (or groups of atoms of different fragments) as one undo step: left, centre or right edges, top, middle or bottom, " + "or spaces three or more evenly with distribute_h or distribute_v.", + {"doc": _DOC, "ids": {"type": "array", "items": {"type": "string"}, "description": "Object or atom ids"}, + "mode": {"type": "string", "enum": ["left", "centre", "right", "top", "middle", "bottom", "distribute_h", "distribute_v"]}}, ["ids", "mode"]), + _tool("clean_layout", "Tidies structures as one undo step with the window's scored layout: mode clean (Clean Up: even bond lengths and angles, keeping place and shape; atom ids clean only those atoms) " + "or layout (Lay Out: fresh 2D coordinates). Wedges the new geometry would invert are flipped; returns the layout score before and after (0 is best).", + {"doc": _DOC, "objects": {"type": "array", "items": {"type": "string"}, "description": "Fragment, group or atom ids; absent: every structure"}, + "mode": {"type": "string", "enum": ["clean", "layout"], "description": "Default clean"}}), + _tool("add_arrow", "Adds an arrow as one undo step. from and to are [x, y] in points or ids: an object (the arrow starts and stops half a bond length outside it, on the line between the two), " + "an atom or a bond (the end is anchored to it, for electron pushing). Without to, a straight arrow four bond lengths long points right. Reaction arrows become steps with perceive_reactions.", + {"doc": _DOC, "kind": {"type": "string", "enum": ["forward", "equilibrium", "equilibrium_unbalanced", "reversible", "resonance", "retro", "nogo_cross", "nogo_slash", "dashed", + "curved", "fishhook", "arc", "plain", "fragmentation", "dissociation"], "description": "Default forward"}, + "from": {"description": "Tail: [x, y] in points, or an object, atom or bond id"}, "to": {"description": "Head: [x, y] in points, or an object, atom or bond id"}, + "bend": {"type": "number", "description": "Arc sweep in degrees, positive bulges left of tail to head; curved and fishhook default 90"}, + "head": {"type": "string", "enum": ["full", "half_left", "half_right", "open", "hollow", "none"]}, "tail": {"type": "string", "enum": ["full", "half_left", "half_right", "open", "hollow", "none"]}, + "page": {"type": "string", "description": "Page id for an arrow between points; default the first page"}}, ["from"]), + _tool("add_text", "Adds text as one undo step: at x, y (top-left, points), as a caption under a structure with below, or in free space. style formula writes chemical subscripts " + "(H2SO4) automatically; \\n breaks a line. Text above or below a reaction arrow becomes its conditions with perceive_reactions.", + {"doc": _DOC, "text": {"type": "string", "description": "The words to place"}, "x": {"type": "number", "description": "Left in points"}, "y": {"type": "number", "description": "Top in points"}, + "style": {"type": "string", "enum": ["plain", "formula", "bold", "italic"]}, "size": {"type": "number", "description": "Font size in points (default the caption font)"}, + "align": {"type": "string", "enum": ["left", "centre", "right"]}, "below": {"type": "string", "description": "Fragment or object id to caption; the caption moves with it"}, + "page": {"type": "string", "description": "Page id; default the first page"}}, ["text"]), + _tool("add_reaction", "Draws a reaction scheme from reaction SMILES (reactants>agents>products) as one undo step: structures, plus signs, the arrow with agents above it, " + "and the reaction step recorded with its roles. Placed in free space, or with its top-left at x, y. Makes a drawing when none is open.", + {"doc": _DOC, "reaction_smiles": {"type": "string", "description": "Such as CCO.CC(=O)O>[H+]>CC(=O)OCC.O"}, + "x": {"type": "number", "description": "Left in points"}, "y": {"type": "number", "description": "Top in points"}, "page": {"type": "string", "description": "Page id; default the first page"}}, + ["reaction_smiles"]), ] NAMES = {t["name"] for t in TOOLS} -MUTATING = {"run_command", "extension_command", "perceive_reactions", "map_reaction"} +MUTATING = {"run_command", "extension_command", "perceive_reactions", "map_reaction", "new_document", "open_document", "save_document", "close_document", + "draw_from_smiles", "draw_from_molfile", "add_atom", "add_bond", "set_charge", "set_atom", "set_stereo", "replace_substructure", + "delete", "move", "scale", "align", "clean_layout", "add_arrow", "add_text", "add_reaction"} def _ok(text: str, data: dict | None = None) -> dict: @@ -170,9 +334,18 @@ def _mutating(name: str, args: dict) -> bool: return True if name == "handoff": return bool(args.get("state")) + if name == "convert": + return bool(args.get("output")) and not _temporary(args.get("output")) + if name == "batch_convert": + return not _temporary(args.get("output_dir") or f"{args.get('input_dir') or ''}/converted") return False +def _temporary(path: object) -> bool: + from app.services import agent_convert + return isinstance(path, str) and bool(path.strip()) and agent_convert.in_temp(path.strip()) + + def _inapp(request: Request) -> tuple[bool, str]: try: from app.services import claude_code @@ -266,11 +439,11 @@ async def t_get_context(a: Agent, args: dict) -> dict: lines.append("Agents: " + ("blocked by the person (Preferences)" if blocked else "allowed" if allowed else "not yet allowed (your first change asks the person in the window)")) docs = _documents() if docs: - lines.append(f"Documents: {len(docs)} open in the window (change them with run_command and the window's commands, write reactions with perceive_reactions and map_reaction, " - f"read them with export_reaction, reaction_stoichiometry, properties, check_structure, stereo and substructure; atom and bond tools arrive in {DRAWING_FROM})") + lines.append(f"Documents: {len(docs)} open (draw on them with draw_from_smiles and draw_from_molfile, edit them by id with get_atoms and the edit tools, check them with render, get_structure and validate, " + "write reactions with perceive_reactions and map_reaction, read them with export_reaction, reaction_stoichiometry, compute_properties, stereo and substructure)") lines.extend(_document_line(d) for d in docs) else: - lines.append("Documents: none open (run_command new-document, insert-smiles {smiles} or open-recent {path} opens one)") + lines.append("Documents: none open (draw_from_smiles makes one as it draws; new_document makes an empty one; open_document {path} opens a file)") count = cat.size() lines.append(f"Commands: {count} in the catalogue (list_commands)" if count else "Commands: the catalogue is empty until a window has opened (list_commands)") mine = HANDOFFS.get(a.name) @@ -279,7 +452,296 @@ async def t_get_context(a: Agent, args: dict) -> dict: lines.append("Workflow:") lines.extend(WORKFLOW) return _ok("\n".join(lines), {"app": config.APP_NAME, "version": config.VERSION, "window": bool(wins), "windows": len(wins), "agentsAllowed": allowed, "agentsBlocked": blocked, - "inapp": a.inapp, "documents": docs, "drawingTools": False, "drawingFrom": DRAWING_FROM, "commands": count, "handoff": mine}) + "inapp": a.inapp, "documents": docs, "drawingTools": True, "drawingFrom": DRAWING_FROM, "commands": count, "handoff": mine}) + + +async def _active_doc() -> str | None: + from app.services import agent_out + if not bridge.window_connected(): + return None + try: + return (await agent_out.selection()).get("doc") + except agent_out.RenderError: + return None + + +async def _doc_id(args: dict, create: bool = False) -> tuple[str, bool]: + from app.services.store import STORE + wanted = str(args.get("doc") or "").strip() + if wanted: + if wanted not in STORE.sessions: + raise ToolError(f"No open drawing has the id {wanted}. list_open_documents lists the open drawings.") + return wanted, False + open_ids = list(STORE.sessions) + if len(open_ids) == 1: + return open_ids[0], False + if open_ids: + active = await _active_doc() + if active in STORE.sessions: + return active, False + raise ToolError("Several drawings are open and no window shows one of them; give doc, an id from list_open_documents.") + if not create: + raise ToolError("No drawing is open. draw_from_smiles or new_document makes one; open_document {path} opens a file.") + info = await STORE.new() + return info["id"], True + + +def _id_list(value: object) -> list[str]: + return [v for v in value if isinstance(v, str) and v] if isinstance(value, list) else [] + + +async def t_render(a: Agent, args: dict) -> dict: + from app.services import agent_out + doc_id, _ = await _doc_id(args) + ids = _id_list(args.get("ids")) + scope = str(args.get("scope") or ("object" if ids else "page")) + fmt = str(args.get("format") or "png") + try: + pic = await agent_out.render_image(doc_id, scope, ids, fmt, {k: args[k] for k in ("width", "height", "dpi") if args.get(k) is not None}) + except agent_out.RenderError as exc: + raise ToolError(str(exc)) from None + who = "the FormChem window's own renderer, as the person sees it" if pic["renderer"] == "window" else "the engine (RDKit in the journal style, structures only)" + shown = ", ".join(pic["ids"][:8]) + (f" and {len(pic['ids']) - 8} more" if len(pic["ids"]) > 8 else "") + text = f"{fmt.upper()} of the {scope} ({shown}) of {doc_id}, {pic['width']} x {pic['height']}, drawn by {who}." + "".join(f" {w}" for w in pic["warnings"]) + data = {"doc": doc_id, "scope": scope, "ids": pic["ids"], "format": fmt, "renderer": pic["renderer"], "width": pic["width"], "height": pic["height"], "warnings": pic["warnings"]} + if fmt == "svg": + svg = pic["bytes"].decode("utf-8") + return {"content": [{"type": "text", "text": text}, {"type": "text", "text": svg}], "structuredContent": {**data, "svg": svg}} + return {"content": [{"type": "text", "text": text}, {"type": "image", "data": base64.b64encode(pic["bytes"]).decode("ascii"), "mimeType": pic["mime"]}], "structuredContent": data} + + +async def _show(doc_id: str, focus: bool) -> bool: + if not bridge.window_connected(): + return False + out = await bridge.window_call("show", {"doc": doc_id, "focus": focus}, None, 20) + return bool(out) and not out.get("isError") + + +def _shown_text(shown: bool) -> str: + return "It shows in the FormChem window." if shown else "No FormChem window is open; the person sees it when they open one (Recent)." if not bridge.window_connected() else "The window did not show it; it is listed in the window's open drawings." + + +async def t_list_open_documents(a: Agent, args: dict) -> dict: + docs = _documents() + active = await _active_doc() + if not docs: + return _ok("No drawing is open. new_document or draw_from_smiles makes one; open_document {path} opens a file.", {"documents": [], "active": None, "window": bridge.window_connected()}) + lines = [f"{len(docs)} drawing{'' if len(docs) == 1 else 's'} open" + (f"; the window shows {active}" if active else "") + ":"] + lines.extend(_document_line(d) + (" · shown in the window" if d["id"] == active else "") for d in docs) + return _ok("\n".join(lines), {"documents": docs, "active": active, "window": bridge.window_connected()}) + + +async def t_new_document(a: Agent, args: dict) -> dict: + from app.services.store import STORE + title = str(args.get("title") or "").strip()[:120] or None + info = await STORE.new(title) + shown = await _show(info["id"], True) + return _ok(f"Made the drawing {info['id']} \"{info['title']}\". {_shown_text(shown)} Draw on it with draw_from_smiles {{doc: \"{info['id']}\"}}.", + {"doc": info["id"], "title": info["title"], "shown": shown}) + + +async def t_open_document(a: Agent, args: dict) -> dict: + from app.services import agent_out + from app.services.store import STORE, StoreError + raw = str(args.get("path") or "").strip() + if not raw: + raise ToolError("Give path, the absolute path of the file to open.") + try: + info = await STORE.open(raw) + except StoreError as exc: + raise ToolError(f"{exc} Give the absolute path of a file that exists.") from None + doc_id = info["id"] + shown = await _show(doc_id, True) + s = STORE.get(doc_id) + with s.lock: + pages = s.doc.get("pages") or [] + ids = [i for i in (pages[0].get("order") or []) if isinstance(i, str)] if pages else [] + notes = [w.get("text") for w in info.get("warnings") or [] if isinstance(w, dict) and w.get("text")] + text = (f"Opened {raw} as {doc_id} \"{info['title']}\" ({len(ids)} object{'' if len(ids) == 1 else 's'} on the first page). {_shown_text(shown)}" + + (f" Notes from reading it: {'; '.join(notes[:5])}" + (f" (+{len(notes) - 5} more)." if len(notes) > 5 else ".") if notes else "")) + return await agent_out.write_result(doc_id, None, ids[:OPEN_ROWS], text, {"opened": raw, "title": info["title"], "shown": shown, "objectsOnPage": len(ids), "warnings": info.get("warnings") or []}) + + +async def t_save_document(a: Agent, args: dict) -> dict: + from app.core import files + from app.services import package + from app.services.store import STORE, StoreError + doc_id, _ = await _doc_id(args) + s = STORE.get(doc_id) + raw = str(args.get("path") or "").strip() + target = None + if raw: + p = Path(raw).expanduser() + if not p.is_absolute(): + raise ToolError("Give path as an absolute path, such as /Users/name/Documents/aspirin.fchem.") + p = files.with_suffix(p, package.EXT) + if p.exists() and (s.path is None or p.resolve() != s.path): + raise ToolError(f"{p} already exists. FormChem does not write over another file for an agent: choose a new path, or ask the person to save over it in the window (File > Save As).") + target = str(p) + try: + out = await STORE.save(doc_id, target) + except StoreError as exc: + raise ToolError(f"{exc} Choose another path and retry.") from None + return _ok(f"Saved {doc_id} to {out['saved']} (rev {out['rev']}, {out['bytes']:,} bytes).", {"doc": doc_id, **out}) + + +async def t_close_document(a: Agent, args: dict) -> dict: + from app.services.store import STORE + doc_id, _ = await _doc_id(args) + if STORE.get(doc_id).dirty: + raise ToolError(f"{doc_id} has unsaved changes. Save it first (save_document), or ask the person to close it in the window, where they choose whether to keep the changes.") + await STORE.close(doc_id) + return _ok(f"Closed {doc_id}.", {"doc": doc_id, "closed": True}) + + +def _coord(args: dict, key: str) -> float | None: + v = args.get(key) + if v is None: + return None + if isinstance(v, bool) or not isinstance(v, (int, float)) or not -100_000 <= v <= 100_000: + raise ToolError(f"{key} is a number of points from -100000 to 100000, or left out for free space.") + return float(v) + + +async def _draw(a: Agent, args: dict, text: str, fmt: str, label: str, what: str) -> dict: + from app.services import agent_draw, agent_out + from app.services.store import STORE + x, y = _coord(args, "x"), _coord(args, "y") + name = str(args.get("name") or "").strip()[:200] or None + reaction = fmt == "smiles" and agent_draw.is_reaction(text) + doc_id, created = await _doc_id(args, create=True) + s = STORE.get(doc_id) + with s.lock: + doc = copy.deepcopy(s.doc) + try: + if reaction: + ops, ids, record, notes = await asyncio.to_thread(agent_draw.reaction_ops, doc, text, "smiles", None, x, y) + else: + ops, ids, notes = await asyncio.to_thread(agent_draw.structure_ops, doc, text, fmt, None, x, y, name) + except agent_draw.DrawError as exc: + if created: + await STORE.close(doc_id) + raise ToolError(f"Could not read the {what}: {str(exc).rstrip('. ')}. Check it and retry.") from None + done = await _apply(a, doc_id, "Draw Reaction from SMILES" if reaction else label, ops) + shown = await _show(doc_id, created) + head = (f"Drew {'a reaction scheme' if reaction else 'the ' + what} in {doc_id}" + (" (a new drawing)" if created else "") + f": {len(ids)} new object{'' if len(ids) == 1 else 's'}. " + + ("" if shown or not bridge.window_connected() else "The window did not show the drawing. ") + "".join(f"Note: {n['text']} " for n in notes[:5] if n.get("text"))) + extra = {"created": created, "shown": shown, "notes": notes, "new": ids} + if reaction: + extra["reaction"] = record["id"] + return await agent_out.write_result(doc_id, done, ids, head, extra) + + +async def t_draw_from_smiles(a: Agent, args: dict) -> dict: + text = str(args.get("smiles") or "").strip() + if not text: + raise ToolError("Give smiles, such as CC(=O)Oc1ccccc1C(=O)O.") + return await _draw(a, args, text, "smiles", "Draw from SMILES", "SMILES") + + +async def t_get_structure(a: Agent, args: dict) -> dict: + from app.services import agent_out + from app.services.store import STORE + doc_id, _ = await _doc_id(args) + with STORE.get(doc_id).lock: + doc = copy.deepcopy(STORE.get(doc_id).doc) + objects = doc.get("objects") or {} + wanted = str(args.get("object") or "").strip() + if args.get("selection") is True: + try: + found = await agent_out.selection(doc_id) + except agent_out.RenderError as exc: + raise ToolError(str(exc)) from None + if found.get("doc") != doc_id or not found.get("ids"): + raise ToolError("Nothing of this drawing is selected in the FormChem window. Ask the person to select the structure, or give object.") + frags = agent_out.fragments_in(doc, list(found["ids"])) + elif wanted: + if wanted not in objects: + raise ToolError(f"{wanted} is not an object of {doc_id}; give a fragment or group id (list_open_documents, or the ids a drawing tool returned), not an atom id.") + frags = agent_out.fragments_in(doc, [wanted]) + else: + frags = [k for k, o in objects.items() if isinstance(o, dict) and o.get("kind") == "fragment"] + frags = [f for f in frags if objects[f].get("atoms")] + if not frags: + raise ToolError("There is no structure there. draw_from_smiles draws one.") + rows = await asyncio.to_thread(agent_out.full_structures, doc_id, frags[:STRUCTURE_ROWS]) + lines = [] + for r in rows: + lines += [f"{r['id']}" + (f" \"{r['name']}\"" if r.get("name") else "") + f": {r['formula']} · {r['atoms']} atoms", + f" SMILES {r['smiles']}", f" CXSMILES {r['cxsmiles']}", f" InChI {r['inchi']}", f" InChIKey {r['inchikey']}", + f" MW {r['mw']} · monoisotopic {r['exact_mass']}" + (f" · m/z {r['mz']}" if r.get("mz") is not None else "")] + lines += [f" Note: {w['text']}" for w in r["warnings"][:6] if isinstance(w, dict) and w.get("text")] + if len(rows) <= MOLFILES_IN_TEXT and r.get("molfile"): + lines += [f" Molfile ({r['molfile_version']}):", r["molfile"].rstrip("\n")] + if len(rows) > MOLFILES_IN_TEXT: + lines.append("Molfiles are in structuredContent (fragments[].molfile).") + if len(frags) > STRUCTURE_ROWS: + lines.append(f"{len(frags) - STRUCTURE_ROWS} more fragments left out; ask for one object at a time.") + return _ok("\n".join(lines), {"doc": doc_id, "fragments": rows, "more": max(0, len(frags) - STRUCTURE_ROWS)}) + + +async def _same_as(a: Agent, args: dict, fn) -> dict: + doc_id, _ = await _doc_id(args) + out = await fn(a, {"doc": doc_id, **({"object": args["object"]} if args.get("object") else {})}) + return {**out, "structuredContent": {"doc": doc_id, **(out.get("structuredContent") or {})}} + + +async def t_validate(a: Agent, args: dict) -> dict: + out = await _same_as(a, args, t_check_structure) + frags = out["structuredContent"].get("fragments") or {} + errors = sum((r.get("counts") or {}).get("error", 0) for r in frags.values() if isinstance(r, dict)) + unread = [k for k, r in frags.items() if isinstance(r, dict) and "error" in r] + valid = not errors and not unread + head = "Valid: no errors." if valid else f"Not valid: {errors} error{'' if errors == 1 else 's'}" + (f", {len(unread)} fragment(s) could not be read" if unread else "") + "." + out["content"] = [{"type": "text", "text": head + "\n" + out["content"][0]["text"]}] + out["structuredContent"]["valid"] = valid + return out + + +async def t_compute_properties(a: Agent, args: dict) -> dict: + return await _same_as(a, args, t_properties) + + +def _failures(rows: list[dict]) -> list[str]: + return [f" {r['file']} " + (f"record {r['record']}" if r.get("record") != "" else "file") + (f" ({r['name']})" if r.get("name") else "") + f": {r['message']}" + for r in rows if r.get("status") == "failed"][:12] + + +async def t_convert(a: Agent, args: dict) -> dict: + from app.services import agent_convert + try: + out = await asyncio.to_thread(agent_convert.convert, str(args.get("input") or ""), str(args.get("from") or "") or None, str(args.get("to") or ""), + str(args.get("output") or "").strip() or None, args.get("v3000") is True, agent_convert.steps_of(args.get("standardise"))) + except agent_convert.ConvertError as exc: + raise ToolError(str(exc)) from None + head = (f"Converted {out['written']:,} of {out['records']:,} record{'' if out['records'] == 1 else 's'} from {out['format_in']} to {out['format_out']}" + + (f"; {out['failed']:,} failed" if out["failed"] else "") + (f"; standardise changed {', '.join(f'{n} by {k}' for k, n in out['standardised'].items())}" if out["standardised"] else "") + + (f"; wrote {', '.join(out['written_to'][:3])}" + (f" and {len(out['written_to']) - 3} more" if len(out["written_to"]) > 3 else "") if out["written_to"] else "") + ".") + lines = [head, *_failures(out["rows"])] + if out["text"] is not None: + lines.append(out["text"].rstrip("\n")) + return _ok("\n".join(lines), out) + + +async def t_batch_convert(a: Agent, args: dict) -> dict: + from app.services import agent_convert + try: + out = await asyncio.to_thread(agent_convert.batch_convert, str(args.get("input_dir") or ""), str(args.get("to") or ""), str(args.get("output_dir") or "").strip() or None, + agent_convert.steps_of(args.get("standardise")), args.get("recursive") is True, args.get("v3000") is True) + except agent_convert.ConvertError as exc: + raise ToolError(str(exc)) from None + lines = [f"{len(out['files'])} file{'' if len(out['files']) == 1 else 's'}, {out['written']:,} of {out['records']:,} records written to {out['output_dir']} in {out['seconds']:.2f} s" + + (f"; {out['failed']:,} failed, listed in {out['report']}" if out["report"] else "") + "."] + lines += [f"- {Path(f['source']).name} -> {f['target']}: {f['written']:,} of {f['records']:,}" + (f", {f['failed']:,} failed" if f["failed"] else "") for f in out["files"][:40]] + lines += _failures([r for f in out["files"] for r in f["rows"]]) + return _ok("\n".join(lines), out) + + +async def t_draw_from_molfile(a: Agent, args: dict) -> dict: + text = str(args.get("molfile") or "") + if "M END" not in text and "M END" not in text: + raise ToolError("Give molfile, the whole text of a V2000 or V3000 molfile (or SD record) ending in M END, with its line breaks.") + return await _draw(a, args, text, "sdf" if "$$$$" in text else "molfile", "Draw from Molfile", "molfile") def _param_line(c: dict) -> str: @@ -592,6 +1054,198 @@ async def t_substructure(a: Agent, args: dict) -> dict: return _ok("\n".join(lines), out) +LISTED_ATOMS = 400 + + +def _atom_line(r: dict) -> str: + extra = [f"{'+' if r['charge'] > 0 else ''}{r['charge']}" if r.get("charge") else "", f"isotope {r['isotope']}" if r.get("isotope") else "", + f"label {r['label']}" if r.get("label") else "", f"H{r['h']}" if r.get("h") else "", f"CIP {r['cip']}" if r.get("cip") else ""] + return f" {r['id']} {r['element']} ({r['x']:.1f}, {r['y']:.1f})" + "".join(f" {e}" for e in extra if e) + (f" · bonds {', '.join(r['bonds'])}" if r["bonds"] else "") + + +def _bond_line(r: dict) -> str: + return f" {r['id']} {r['a']}-{r['b']} order {r['order']}" + (f" {r['stereo']}" if r.get("stereo") else "") + (f" {r['cip']}" if r.get("cip") else "") + + +async def t_get_atoms(a: Agent, args: dict) -> dict: + from app.services import agent_edits + from app.services.store import STORE + doc_id, doc, _ = await _edit_doc(args) + derived = await asyncio.to_thread(STORE.derive_now, doc_id) + try: + rows = agent_edits.listing(doc, derived, str(args.get("object") or "").strip() or None) + except agent_edits.EditError as exc: + raise ToolError(str(exc)) from None + if not rows: + return _ok(f"{doc_id} has no structures yet. add_atom, draw_from_smiles or add_reaction draws one.", {"doc": doc_id, "fragments": []}) + lines, shown = [], 0 + for f in rows: + lines.append(f"{f['id']} on page {f['page']}: {f['formula'] or 'formula still being worked out'} · {f['smiles'] or ''} · {f['inchikey'] or ''}".rstrip(" ·")) + lines.append(f" atoms ({len(f['atoms'])}):") + for r in f["atoms"]: + if shown < LISTED_ATOMS: + lines.append(_atom_line(r)) + shown += 1 + lines.append(f" bonds ({len(f['bonds'])}):") + lines.extend(_bond_line(r) for r in f["bonds"][:LISTED_ATOMS]) + if shown > LISTED_ATOMS: + lines.append(f"{shown - LISTED_ATOMS} more atoms are in structuredContent; give object to list one fragment.") + return _ok("\n".join(lines), {"doc": doc_id, "rev": (derived or {}).get("rev"), "fragments": rows}) + + +async def _edit_doc(args: dict, create: bool = False) -> tuple[str, dict, bool]: + doc_id, created = await _doc_id(args, create) + wanted, doc = _drawing({"doc": doc_id}) + return wanted, doc, created + + +def _touched(info: dict) -> list[str]: + out = [] + for key in ("fragment", "object", "fragments", "objects"): + v = info.get(key) + out += [v] if isinstance(v, str) else [i for i in v if isinstance(i, str)] if isinstance(v, list) else [] + return list(dict.fromkeys(out)) + + +async def _edit(a: Agent, args: dict, fn, label: str, say, create: bool = False) -> dict: + from app.services import agent_edits, agent_out + from app.services.store import STORE + doc_id, doc, created = await _edit_doc(args, create) + try: + ops, info = await asyncio.to_thread(fn, doc, args) + except agent_edits.EditError as exc: + if created: + await STORE.close(doc_id) + raise ToolError(str(exc)) from None + done = await _apply(a, doc_id, label, ops) + shown = await _show(doc_id, created) if done or created else False + s = STORE.get(doc_id) + with s.lock: + ids = [i for i in _touched(info) if i in (s.doc.get("objects") or {})] + text = say(info) if done else f"{say(info).rstrip('. ')}; nothing changed, so there is nothing to undo" + return await agent_out.write_result(doc_id, done, ids, text, {"edit": info, "label": label, "created": created, "shown": shown}) + + +def _order_text(order: object) -> str: + return {1: "single", 2: "double", 3: "triple", 4: "quadruple", 1.5: "aromatic"}.get(order, str(order)) + + +async def t_add_atom(a: Agent, args: dict) -> dict: + from app.services import agent_edits + + def say(i: dict) -> str: + where = f"bonded to {i['bond_to']} by {_order_text(i['order'])} bond {i['bond']}" if i.get("bond") else "as a new fragment" if i.get("new_fragment") else "unbonded" + return f"Added {i['element']} atom {i['atom']} to fragment {i['fragment']}, {where}." + return await _edit(a, args, agent_edits.add_atom, "Add atom", say, create=True) + + +async def t_add_bond(a: Agent, args: dict) -> dict: + from app.services import agent_edits + + def say(i: dict) -> str: + wedge = f", {i['stereo']}" if i.get("stereo") != "none" else "" + if i.get("existing"): + return f"{i['atom1']} and {i['atom2']} were already bonded by {i['bond']}; it is now {_order_text(i['order'])}{wedge}." + return f"Bonded {i['atom1']} to {i['atom2']} with {_order_text(i['order'])} bond {i['bond']}{wedge}" + (f"; fragment {i['merged']} joined {i['fragment']}." if i.get("merged") else ".") + return await _edit(a, args, agent_edits.add_bond, "Add bond", say) + + +async def t_set_charge(a: Agent, args: dict) -> dict: + from app.services import agent_edits + return await _edit(a, args, agent_edits.set_charge, "Set charge", lambda i: f"Charge of {i['atom']}: {i['was']} -> {i['charge']}.") + + +async def t_set_atom(a: Agent, args: dict) -> dict: + from app.services import agent_edits + return await _edit(a, args, agent_edits.set_atom, "Set atom", + lambda i: f"Changed {', '.join(i['changed'])} of {i['atom']}." if i["changed"] else f"{i['atom']} already reads so.") + + +async def t_set_stereo(a: Agent, args: dict) -> dict: + from app.services import agent_edits + + def say(i: dict) -> str: + if i.get("atom"): + return f"{i['atom']} reads {i['label']}" + (f" (wedges set on {', '.join(i['wedges'])})." if i["wedges"] else " already.") + moved = len(i.get("moved") or []) + return f"Bond {i['bond']} reads {i['label']}" + (f" (was {i['was']}; {moved} atom{'' if moved == 1 else 's'} mirrored across it)." if moved else f" (was {i['was'] or 'undefined'}).") + return await _edit(a, args, agent_edits.set_stereo, "Set stereo", say) + + +async def t_replace_substructure(a: Agent, args: dict) -> dict: + from app.services import agent_edits + + def say(i: dict) -> str: + parts = [f"Replaced {i['replaced']} match{'' if i['replaced'] == 1 else 'es'} of {i['smarts']} with {i['replacement']}:"] + for fid, d in i["detail"].items(): + parts.append(f"{fid} lost {', '.join(d['removed'])} and gained {', '.join(d['added'])}, now {d['smiles'] or '?'}" + + (f" (RDKit ReplaceSubstructs reads {d['rdkit']})" if d.get("rdkit") else "") + ";") + return " ".join(parts).rstrip(";") + "." + return await _edit(a, args, agent_edits.replace_substructure, "Replace substructure", say) + + +def _plural(n: int, word: str) -> str: + return f"{n} {word}{'' if n == 1 else 's'}" + + +async def t_delete(a: Agent, args: dict) -> dict: + from app.services import agent_edits + def say(i: dict) -> str: + parts = ([_plural(i["atoms"], "atom")] if i["atoms"] else []) + ([_plural(i["bonds"], "bond")] if i["bonds"] else []) + \ + ([f"the object{'' if len(i['objects']) == 1 else 's'} {', '.join(i['objects'])}"] if i["objects"] else []) + return "Deleted " + (", ".join(parts[:-1]) + " and " + parts[-1] if len(parts) > 1 else parts[0]) + "." + return await _edit(a, args, agent_edits.delete, "Delete", say) + + +async def t_move(a: Agent, args: dict) -> dict: + from app.services import agent_edits + return await _edit(a, args, agent_edits.move, "Move", lambda i: f"Moved {', '.join(i['moved'][:12])}{' and more' if len(i['moved']) > 12 else ''} by ({i['dx']:g}, {i['dy']:g}) pt.") + + +async def t_scale(a: Agent, args: dict) -> dict: + from app.services import agent_edits + return await _edit(a, args, agent_edits.scale, "Scale", + lambda i: f"Scaled {_plural(i['targets'], 'structure')} to {i['percent']:g}%" + (f", median bond length now {i['bond_length']:.2f} pt." if i.get("bond_length") else ".")) + + +async def t_align(a: Agent, args: dict) -> dict: + from app.services import agent_edits + return await _edit(a, args, agent_edits.align, "Align", lambda i: f"{i['mode'].replace('_', ' ').capitalize()}: {_plural(i['units'], 'object')} lined up.") + + +async def t_clean_layout(a: Agent, args: dict) -> dict: + from app.services import agent_edits + + def say(i: dict) -> str: + scores = "; ".join(f"{fid} score {s['before']:g} -> {s['after']:g}" for fid, s in i["scores"].items()) + return (f"{'Cleaned up' if i['mode'] == 'clean' else 'Laid out'} {', '.join(i['fragments'])}" + (f" ({scores})" if scores else "") + "." + + "".join(f" Note: {n}" for n in i["notes"])) + label = "Lay Out Structure" if str(args.get("mode") or "clean").strip().lower() == "layout" else "Clean Up Structure" + return await _edit(a, args, agent_edits.clean_layout, label, say) + + +async def t_add_arrow(a: Agent, args: dict) -> dict: + from app.services import agent_edits + return await _edit(a, args, agent_edits.add_arrow, "Add arrow", + lambda i: f"Added {i['kind']} arrow {i['object']} from ({i['tail'][0]:.1f}, {i['tail'][1]:.1f}) to ({i['head'][0]:.1f}, {i['head'][1]:.1f}) on page {i['page']}.") + + +async def t_add_text(a: Agent, args: dict) -> dict: + from app.services import agent_edits + return await _edit(a, args, agent_edits.add_text, "Add text", lambda i: f"Added {i['kind']} {i['object']} at ({i['x']:.1f}, {i['y']:.1f}) on page {i['page']}.") + + +async def t_add_reaction(a: Agent, args: dict) -> dict: + from app.services import agent_edits + + def say(i: dict) -> str: + r = i["reaction"] or {} + step = (r.get("steps") or [{}])[0] + roles = "; ".join(f"{k} {', '.join(step[k])}" for k in ("reactants", "agents", "products") if step.get(k)) + return (f"Drew reaction {r.get('id')} (step {step.get('id')}, arrow {step.get('arrow')}): {roles}." + "".join(f" Note: {n}" for n in i["notes"][:3])) + return await _edit(a, args, agent_edits.add_reaction, "Add reaction", say, create=True) + + async def _send_handoffs(client: Client, msg: dict) -> None: await client.send({"t": "handoffs", "items": _handoff_list()}) @@ -601,10 +1255,24 @@ async def _send_handoffs(client: Client, msg: dict) -> None: async def call_tool(a: Agent, name: str, args: dict) -> dict: + from app.services import agent_log, consent + entry = await agent_log.begin(a.name, a.inapp, name, args, _mutating(name, args) and name != "handoff") + stopped = consent.stopped(a.name) + result = None + try: + result = _fail(f"The person stopped {a.name}'s access to FormChem from the window. Tell them what you were about to do and ask them to allow you again " + "(Agent Activity, in the Window menu), then retry.") if stopped else await _dispatch(a, name, args) + return result + finally: + said = result if result is not None else _fail("The call ended before it finished.") + await agent_log.end(entry, said, stopped or bool(said.pop("_refused", False))) + + +async def _dispatch(a: Agent, name: str, args: dict) -> dict: if _mutating(name, args): refused = await _gate(a, name, args) if refused: - return _fail(refused) + return {**_fail(refused), "_refused": True} try: return await HANDLERS[name](a, args) except ToolError as exc: @@ -615,10 +1283,25 @@ async def call_tool(a: Agent, name: str, args: dict) -> dict: return _fail(f"{name} failed: {type(exc).__name__}: {_clip(str(exc), 300)}") +def _authorised(request: Request) -> bool: + from app.core import agent_token, window_key + if agent_token.valid(request.headers.get("authorization")) or window_key.valid(request.headers.get(window_key.HEADER)): + return True + return _inapp(request)[0] + + +def _unauthorised() -> Response: + text = ("FormChem's MCP endpoint needs the agent token: send the header Authorization: Bearer , the token being the one line in agent-token in FormChem's data folder. " + "Run ./formchem agents install in the FormChem folder to write it into your agent's config, or use the stdio transport (./formchem mcp), which sends it itself.") + return Response(status_code=401, content=json.dumps(_err(None, -32001, text)), media_type="application/json", headers={"WWW-Authenticate": 'Bearer realm="FormChem"'}) + + @router.post("/mcp") async def mcp(request: Request) -> Response: if not local_origin(request.headers.get("origin")): return Response(status_code=403, content=json.dumps(_err(None, -32600, "Origin not allowed")), media_type="application/json") + if not _authorised(request): + return _unauthorised() try: msg = json.loads(await request.body()) except ValueError: @@ -682,6 +1365,8 @@ def mcp_get() -> Response: @router.delete("/mcp") def mcp_delete(request: Request) -> Response: + if not _authorised(request): + return _unauthorised() SESSIONS.pop(request.headers.get("mcp-session-id") or "", None) return Response(status_code=204) 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} 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",), diff --git a/backend/app/services/agent_convert.py b/backend/app/services/agent_convert.py new file mode 100644 index 00000000..1e1d5835 --- /dev/null +++ b/backend/app/services/agent_convert.py @@ -0,0 +1,121 @@ +import tempfile +from pathlib import Path + +from app.services import batch +from app.services.chem import io, records, standardise + +TEXT_LIMIT = 2_000_000 +ROWS = 50 +PATH_LIMIT = 4096 +REPORT = "formchem-batch-report.csv" + + +class ConvertError(ValueError): + pass + + +def temp_root() -> Path: + return Path(tempfile.gettempdir()).resolve() + + +def in_temp(path: str | Path) -> bool: + try: + return Path(path).expanduser().resolve().is_relative_to(temp_root()) + except (OSError, ValueError): + return False + + +def steps_of(value: object) -> list[str]: + if value is None or value is False or value == "": + return [] + try: + steps = standardise.parse_steps("default" if value is True else value) + except ValueError as exc: + raise ConvertError(f"standardise: {exc}") from None + if not steps: + raise ConvertError("standardise chose no steps; give true, default or step names such as salts,neutralise.") + return steps + + +def summary_of(s: batch.Summary) -> dict: + return {"source": s.source, "target": s.target, "format_in": s.format_in, "format_out": s.format_out, "records": s.records, "written": s.written, + "failed": s.failed, "warned": s.warned, "seconds": round(s.seconds, 3), "outputs": s.outputs[:ROWS], "standardised": dict(s.changed), + "rows": s.rows[:ROWS], "more_rows": max(0, len(s.rows) - ROWS)} + + +def _absolute(raw: str, what: str) -> Path: + p = Path(raw).expanduser() + if not p.is_absolute(): + raise ConvertError(f"Give {what} as an absolute path.") + return p + + +def is_path(text: str) -> bool: + one = text.strip() + if not one or "\n" in one or len(one) > PATH_LIMIT: + return False + try: + p = Path(one).expanduser() + return p.is_absolute() and p.is_file() + except (OSError, ValueError): + return False + + +def _fresh(dst: Path) -> None: + if dst.exists(): + raise ConvertError(f"{dst} already exists. FormChem does not write over another file for an agent: choose a new output path.") + + +def convert(text: str, source: str | None, to: str, output: str | None, v3000: bool, steps: list[str]) -> dict: + fout = records.format_of("", to) if to else None + if fout not in records.WRITE: + raise ConvertError(f"to is one of {', '.join(records.WRITE)}.") + with tempfile.TemporaryDirectory(prefix="formchem-convert-") as tmp: + if is_path(text): + src = Path(text.strip()).expanduser() + else: + if not text.strip(): + raise ConvertError("Give input: structure text (SMILES, a molfile, SD records, InChI, CML and so on) or the absolute path of a file.") + source = source or io.detect(text) + src = Path(tmp) / "input.txt" + src.write_text(text, encoding="utf-8") + if output: + dst = _absolute(output, "output") + _fresh(dst) + else: + if fout == "fchem": + raise ConvertError("A FormChem document is a file; give output, an absolute path ending in .fchem.") + dst = Path(tmp) / f"output{batch.EXT[fout]}" + try: + s = batch.convert_file(src, str(dst), batch.Options(fout, source, steps, v3000)) + except batch.BadArguments as exc: + raise ConvertError(str(exc).replace("--from", "from").replace("--to", "to")) from None + out = summary_of(s) + if output: + return {**out, "text": None, "written_to": s.outputs} + parts = [Path(p).read_text(encoding="utf-8") for p in s.outputs if Path(p).is_file()] + body = "".join(parts) if len(parts) == 1 or fout not in batch.ONE_PER_FILE else "\n".join(parts) + if len(body) > TEXT_LIMIT: + raise ConvertError(f"The result is {len(body):,} characters, too long to return as text; give output, an absolute path to write it to.") + return {**out, "text": body, "written_to": [], "outputs": []} + + +def batch_convert(input_dir: str, to: str, output_dir: str | None, steps: list[str], recursive: bool, v3000: bool) -> dict: + folder = _absolute(input_dir, "input_dir") + out = _absolute(output_dir, "output_dir") if output_dir else None + try: + target, files = batch.batch_files(folder, out, recursive) + if not files: + raise ConvertError(f"No structure files in {folder} ({', '.join(records.READ)}).") + if target.exists() and any(target.iterdir()): + raise ConvertError(f"{target} already holds files. FormChem does not write over files for an agent: give output_dir, a new or empty folder.") + found = batch.batch(folder, batch.Options(to, None, steps, v3000, 1), out, recursive) + except batch.BadArguments as exc: + raise ConvertError(str(exc).replace("--to", "to")) from None + rows = [r for s in found for r in s.rows] + report = target / REPORT if rows else None + if report: + batch.write_report(report, rows) + return {"input_dir": str(folder), "output_dir": str(target), "files": [summary_of(s) for s in found], "records": sum(s.records for s in found), + "written": sum(s.written for s in found), "failed": sum(s.failed for s in found), "seconds": round(sum(s.seconds for s in found), 3), + "report": str(report) if report else None} diff --git a/backend/app/services/agent_draw.py b/backend/app/services/agent_draw.py new file mode 100644 index 00000000..f684a60e --- /dev/null +++ b/backend/app/services/agent_draw.py @@ -0,0 +1,103 @@ +import math + +from app.services import model +from app.services.agent_out import free_spot, page_of +from app.services.chem import DEFAULT_BOND_LENGTH, geometry, io, scheme +from app.services.chem.reactions import ReactionError, used_ids + +STRUCTURE_FORMATS = ("smiles", "cxsmiles", "molfile", "sdf") +QUIET = ("coordinates_generated",) + + +class DrawError(ValueError): + pass + + +def bond_length(doc: dict) -> float: + return float(model.resolve_style(doc).get("bond_length") or DEFAULT_BOND_LENGTH) + + +def is_reaction(text: str) -> bool: + words = text.strip().split() + return bool(words) and words[0].count(">") == 2 + + +def _box(objects: list[dict], style: dict) -> geometry.Box | None: + tmp = {"objects": {o["id"]: o for o in objects}} + return geometry.union([geometry.object_box(tmp, o["id"], style) for o in objects]) + + +def _overlaps(doc: dict, page: dict, box: geometry.Box, style: dict) -> bool: + for oid in page.get("order") or []: + b = geometry.object_box(doc, oid, style) if isinstance(oid, str) else None + if b and b[0] < box[2] and box[0] < b[2] and b[1] < box[3] and box[1] < b[3]: + return True + return False + + +def _where(doc: dict, page: dict, box: geometry.Box, x: float | None, y: float | None, notes: list[dict], style: dict) -> tuple[float, float]: + w, h = box[2] - box[0], box[3] - box[1] + if x is None or y is None: + fx, fy = free_spot(doc, page.get("id"), w, h) + x, y = (fx if x is None else x), (fy if y is None else y) + placed = (x, y, x + w, y + h) + if _overlaps(doc, page, placed, style): + notes.append({"code": "overlap", "text": "The drawing overlaps objects already on the page at the x and y given; leave them out to let FormChem find free space."}) + return x, y + + +def structure_ops(doc: dict, text: str, fmt: str | None, page_id: str | None = None, x: float | None = None, y: float | None = None, + name: str | None = None) -> tuple[list[dict], list[str], list[dict]]: + page = page_of(doc, None, page_id) + if page is None: + raise DrawError("The drawing has no page to draw on.") + try: + parsed = io.read_text(text, fmt, bond_length(doc), (0.0, 0.0)) + except ValueError as exc: + raise DrawError(str(exc)) from None + if parsed.format not in STRUCTURE_FORMATS: + raise DrawError(f"The text reads as {parsed.format}, not as {fmt or 'a structure'}.") + frags = [f for f in parsed.fragments if f.get("atoms")] + notes = [w for w in parsed.warnings if isinstance(w, dict) and w.get("code") not in QUIET] + if not frags: + raise DrawError(next((w.get("text") for w in notes if w.get("text")), "it holds no structure")) + used = used_ids(doc) + frags = [scheme._claim(f, used) for f in frags] + if name: + for n, f in enumerate(frags): + f["name"] = name if len(frags) == 1 else f"{name} {n + 1}" + style = model.resolve_style(doc) + box = _box(frags, style) + if box is None or not all(math.isfinite(v) for v in box): + raise DrawError("The structure has no usable coordinates.") + left, top = _where(doc, page, box, x, y, notes, style) + dx, dy = left - box[0], top - box[1] + ops: list[dict] = [] + order = ["pages", {"id": page["id"]}, "order"] + for f in frags: + for a in f["atoms"].values(): + a["x"], a["y"] = round(a["x"] + dx, 3), round(a["y"] + dy, 3) + ops.append({"op": "set", "path": ["objects", f["id"]], "value": f}) + ops.append({"op": "ins", "path": order, "value": f["id"]}) + return ops, [f["id"] for f in frags], notes + + +def reaction_ops(doc: dict, text: str, fmt: str | None = "smiles", page_id: str | None = None, x: float | None = None, + y: float | None = None) -> tuple[list[dict], list[str], dict, list[dict]]: + page = page_of(doc, None, page_id) + if page is None: + raise DrawError("The drawing has no page to draw on.") + style = model.resolve_style(doc) + bl = bond_length(doc) + try: + trial = scheme.parse(text, fmt, bl, (0.0, 0.0), used_ids(doc)) + box = _box(trial["objects"], style) + if box is None: + raise DrawError("The reaction has nothing to draw.") + notes: list[dict] = [] + left, top = _where(doc, page, box, x, y, notes, style) + ops, found = scheme.insert_ops(doc, page, text, fmt, (round(left - box[0], 3), round(top - box[1], 3))) + except ReactionError as exc: + raise DrawError(str(exc)) from None + notes.extend(w for w in found.get("warnings") or [] if isinstance(w, dict) and w.get("code") not in QUIET) + return ops, [o["id"] for o in found["objects"]], found["reaction"], notes diff --git a/backend/app/services/agent_edits.py b/backend/app/services/agent_edits.py new file mode 100644 index 00000000..cc4eaa08 --- /dev/null +++ b/backend/app/services/agent_edits.py @@ -0,0 +1,1338 @@ +import copy +import math +import re +import statistics + +from app.services import model +from app.services.chem import DEFAULT_BOND_LENGTH, geometry +from app.services.chem.reactions import fresh_id, used_ids +from app.services.ops import atom_path, bond_path, object_path, page_path + +LIST_ATOMS = "get_atoms lists the atoms and bonds with their ids" +ORDER_NAMES = {"single": 1, "double": 2, "triple": 3, "quadruple": 4, "aromatic": 1.5} +BOND_STEREO = ("none", "wedge", "hash", "hollow", "wavy", "either") +WEDGES = ("wedge", "hash", "hollow") +CHAIN_ANGLE = 120.0 +START_ANGLE = 30.0 +SWEEP_STEP = 15.0 +CROWDED = 0.75 +LABEL_H = re.compile(r"^([A-Z][a-z]?)(H\d*)?$") +Point = tuple[float, float] + + +class EditError(ValueError): + pass + + +def _num(v: object) -> bool: + return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) + + +def _r(v: float) -> float: + return round(float(v), 3) + + +def fragments(doc: dict) -> dict[str, dict]: + return {k: o for k, o in (doc.get("objects") or {}).items() if isinstance(o, dict) and o.get("kind") == "fragment"} + + +def fragment(doc: dict, fid: str) -> dict: + obj = (doc.get("objects") or {}).get(fid) + if not isinstance(obj, dict): + raise EditError(f"The drawing has no object {fid}; {LIST_ATOMS} and their fragments.") + if obj.get("kind") != "fragment": + raise EditError(f"{fid} is a {obj.get('kind')} object, not a fragment of atoms; {LIST_ATOMS} and their fragments.") + return obj + + +def locate_atom(doc: dict, aid: str, fid: str | None = None) -> tuple[dict, dict]: + aid = str(aid or "").strip() + if not aid: + raise EditError(f"Give an atom id; {LIST_ATOMS}.") + if fid: + frag = fragment(doc, fid) + atom = (frag.get("atoms") or {}).get(aid) + if atom is None: + raise EditError(f"Atom {aid} is not in fragment {fid}; {LIST_ATOMS}.") + return frag, atom + for frag in fragments(doc).values(): + if aid in (frag.get("atoms") or {}): + return frag, frag["atoms"][aid] + raise EditError(f"The drawing has no atom {aid}; {LIST_ATOMS}.") + + +def locate_bond(doc: dict, bid: str) -> tuple[dict, dict]: + bid = str(bid or "").strip() + for frag in fragments(doc).values(): + if bid in (frag.get("bonds") or {}): + return frag, frag["bonds"][bid] + raise EditError(f"The drawing has no bond {bid}; {LIST_ATOMS}.") + + +def parents(doc: dict) -> dict[str, str]: + out: dict[str, str] = {} + for oid, o in (doc.get("objects") or {}).items(): + if isinstance(o, dict) and o.get("kind") == "group": + for c in o.get("children") or []: + if isinstance(c, str): + out[c] = oid + return out + + +def page_of(doc: dict, oid: str) -> dict: + up = parents(doc) + seen = 0 + while oid in up and seen < 64: + oid, seen = up[oid], seen + 1 + for p in doc.get("pages") or []: + if isinstance(p, dict) and oid in (p.get("order") or []): + return p + raise EditError(f"{oid} is not on any page of the drawing; get_context lists the drawings.") + + +def first_page(doc: dict, page_id: str | None = None) -> dict: + pages = [p for p in doc.get("pages") or [] if isinstance(p, dict)] + if not pages: + raise EditError("The drawing has no page. Open another drawing (get_context lists them).") + if not page_id: + return pages[0] + for p in pages: + if p.get("id") == page_id: + return p + raise EditError(f"The drawing has no page {page_id}; get_context lists the drawings, get_structure their pages.") + + +def bond_length(doc: dict, frag: dict | None = None) -> float: + atoms = (frag or {}).get("atoms") or {} + lengths = [] + for b in ((frag or {}).get("bonds") or {}).values(): + p, q = atoms.get(b.get("a")), atoms.get(b.get("b")) + if p and q: + d = math.hypot(p["x"] - q["x"], p["y"] - q["y"]) + if d > 1e-6: + lengths.append(d) + if lengths: + return statistics.median(lengths) + return float(model.resolve_style(doc, frag).get("bond_length") or DEFAULT_BOND_LENGTH) + + +def element_of(value: object) -> str: + text = str(value or "").strip() + if text in model.SPECIAL_ELEMENTS: + return text + sym = text[:1].upper() + text[1:].lower() + if sym not in model.ELEMENTS: + raise EditError(f"{text or 'element'} is not an element symbol; give one such as C, N, O, Cl or Br (or * for any atom).") + return sym + + +def order_of(value: object) -> object: + if value is None: + return 1 + if isinstance(value, str): + key = value.strip().lower() + if key in ORDER_NAMES: + return ORDER_NAMES[key] + if key in model.BOND_ORDERS: + return key + try: + value = float(key) + except ValueError: + pass + if _num(value): + v = int(value) if float(value).is_integer() else float(value) + if v in model.BOND_ORDERS: + return v + raise EditError("order is 1, 2, 3, 4 or 1.5 (aromatic), a name (single, double, triple, aromatic), or dative, zero, hydrogen or ionic.") + + +def valence_of(order: object) -> int: + return int(order) if _num(order) else 0 + + +def stereo_of(value: object) -> str: + text = str(value or "none").strip().lower() + if text not in BOND_STEREO: + raise EditError("stereo is none, wedge (solid, narrow end at atom1), hash (hashed, narrow end at atom1), hollow, wavy or either.") + return text + + +def charge_of(value: object) -> int: + if isinstance(value, str): + text = value.strip() + if text in ("+", "-"): + text += "1" + if text.endswith(("+", "-")) and text[:-1].isdigit(): + text = text[-1] + text[:-1] + try: + value = int(text) + except ValueError: + pass + if not _num(value) or not float(value).is_integer() or not -15 <= value <= 15: + raise EditError("charge is a whole number from -15 to 15, such as -1, 0 or 1.") + return int(value) + + +def page_atoms(doc: dict, page: dict) -> list[tuple[str, Point]]: + out = [] + up = parents(doc) + for fid, frag in fragments(doc).items(): + top, seen = fid, 0 + while top in up and seen < 64: + top, seen = up[top], seen + 1 + if top not in (page.get("order") or []): + continue + out.extend((aid, (a["x"], a["y"])) for aid, a in (frag.get("atoms") or {}).items() if _num(a.get("x")) and _num(a.get("y"))) + return out + + +def _angle(dx: float, dy: float) -> float: + return math.degrees(math.atan2(-dy, dx)) % 360.0 + + +def _at(p: Point, angle: float, length: float) -> Point: + t = math.radians(angle) + return (p[0] + length * math.cos(t), p[1] - length * math.sin(t)) + + +def _linear(frag: dict, aid: str, order: object) -> bool: + bonds = [b for b in (frag.get("bonds") or {}).values() if aid in (b.get("a"), b.get("b"))] + if len(bonds) != 1: + return False + other = bonds[0].get("order", 1) + return order == 3 or other == 3 or (order == 2 and other == 2) + + +def free_angle(doc: dict, frag: dict, aid: str, order: object, length: float) -> float: + atoms = frag.get("atoms") or {} + atom = atoms[aid] + here = (atom["x"], atom["y"]) + nbrs = [b["b"] if b.get("a") == aid else b["a"] for b in (frag.get("bonds") or {}).values() if aid in (b.get("a"), b.get("b"))] + angles = sorted(_angle(atoms[n]["x"] - here[0], atoms[n]["y"] - here[1]) for n in nbrs if n in atoms) + if not angles: + ideal = [START_ANGLE] + elif len(angles) == 1: + ideal = [angles[0] + 180.0] if _linear(frag, aid, order) else [angles[0] + CHAIN_ANGLE, angles[0] - CHAIN_ANGLE] + else: + gaps = [((angles[(i + 1) % len(angles)] - a) % 360.0 or 360.0, a) for i, a in enumerate(angles)] + widest = max(g for g, _ in gaps) + ideal = [a + g / 2 for g, a in gaps if g >= widest - 1e-6] + others = [p for k, p in page_atoms(doc, page_of(doc, frag["id"])) if k != aid] + + def room(angle: float) -> tuple[float, float]: + p = _at(here, angle, length) + near = min((math.hypot(p[0] - q[0], p[1] - q[1]) for q in others), default=math.inf) + return (round(min(near, 3 * length) / length, 2), round(abs(math.cos(math.radians(angle))), 3)) + + best = max((a % 360.0 for a in ideal), key=room) + if room(best)[0] >= CROWDED: + return best + sweep = [i * SWEEP_STEP for i in range(int(360 / SWEEP_STEP))] + return max([best] + sweep, key=room) + + +def _room_ops(frag: dict, aid: str, gained: int) -> list[dict]: + atom = frag["atoms"][aid] + ops: list[dict] = [] + if gained <= 0: + return ops + h = atom.get("hydrogens") + if isinstance(h, int) and not isinstance(h, bool): + left = h - gained + ops.append({"op": "set", "path": atom_path(frag["id"], aid, "hydrogens"), **({"value": left} if left > 0 else {})}) + label = atom.get("label") + found = LABEL_H.match(label) if isinstance(label, str) else None + if found and found.group(1) == atom.get("element") and not atom.get("expansion"): + ops.append({"op": "set", "path": atom_path(frag["id"], aid, "label")}) + return ops + + +def _bond_record(bid: str, a: str, b: str, order: object, stereo: str) -> dict: + rec = {"id": bid, "a": a, "b": b, "order": order} + if stereo != "none": + rec["stereo"] = stereo + return rec + + +def _new_fragment_ops(doc: dict, page: dict, fid: str, atom: dict) -> list[dict]: + frag = {"id": fid, "kind": "fragment", "atoms": {atom["id"]: atom}, "bonds": {}} + return [{"op": "set", "path": object_path(fid), "value": frag}, {"op": "ins", "path": page_path(page["id"], "order"), "value": fid}] + + +def _spot(doc: dict, page: dict, frag: dict | None, length: float) -> Point: + style = model.resolve_style(doc) + if frag is not None: + box = geometry.fragment_box(frag, style) + if box is not None: + return (box[2] + length, (box[1] + box[3]) / 2) + from app.services.chem import scheme + x, y = scheme.free_origin(doc, page) + return (x + length, y + length) + + +def add_atom(doc: dict, args: dict) -> tuple[list[dict], dict]: + element = element_of(args.get("element")) + order = order_of(args.get("order")) + fid = str(args.get("fragment") or "").strip() or None + target = str(args.get("bond_to") or "").strip() or None + has_xy = _num(args.get("x")) and _num(args.get("y")) + if (args.get("x") is None) != (args.get("y") is None) or (args.get("x") is not None and not has_xy): + raise EditError("Give both x and y in points (page coordinates, y down), or neither to let FormChem place the atom.") + used = used_ids(doc) + aid = fresh_id(used, "a") + ops: list[dict] = [] + info: dict = {"atom": aid, "element": element} + if target: + frag, other = locate_atom(doc, target, fid) + length = bond_length(doc, frag) + if has_xy: + x, y = float(args["x"]), float(args["y"]) + else: + x, y = _at((other["x"], other["y"]), free_angle(doc, frag, target, order, length), length) + bid = fresh_id(used, "b") + ops.append({"op": "set", "path": atom_path(frag["id"], aid), "value": {"id": aid, "element": element, "x": _r(x), "y": _r(y)}}) + ops.append({"op": "set", "path": bond_path(frag["id"], bid), "value": _bond_record(bid, target, aid, order, "none")}) + ops.extend(_room_ops(frag, target, valence_of(order))) + info.update({"fragment": frag["id"], "bond": bid, "bond_to": target, "order": order, "new_fragment": False}) + return ops, info + frag = fragment(doc, fid) if fid else None + page = page_of(doc, fid) if fid else first_page(doc, str(args.get("page") or "") or None) + length = bond_length(doc, frag) + x, y = (float(args["x"]), float(args["y"])) if has_xy else _spot(doc, page, frag, length) + atom = {"id": aid, "element": element, "x": _r(x), "y": _r(y)} + if frag is not None: + ops.append({"op": "set", "path": atom_path(frag["id"], aid), "value": atom}) + info.update({"fragment": frag["id"], "new_fragment": False}) + else: + fid = fresh_id(used, "f") + ops.extend(_new_fragment_ops(doc, page, fid, atom)) + info.update({"fragment": fid, "new_fragment": True, "page": page["id"]}) + return ops, info + + +def _referenced(doc: dict, oid: str) -> bool: + stack: list = [(k, v) for k, v in doc.items() if k not in ("objects", "pages")] + for p in doc.get("pages") or []: + if isinstance(p, dict): + stack.extend((k, v) for k, v in p.items() if k not in ("order", "id")) + for k, o in (doc.get("objects") or {}).items(): + if k != oid and isinstance(o, dict): + stack.extend((kk, v) for kk, v in o.items() if not (o.get("kind") == "group" and kk == "children")) + while stack: + key, node = stack.pop() + if node == oid or key == oid: + return True + if isinstance(node, dict): + stack.extend(node.items()) + elif isinstance(node, list): + stack.extend((None, v) for v in node) + return False + + +def merge_ops(doc: dict, keep: dict, gone: dict) -> list[dict]: + if gone.get("rgroups"): + raise EditError(f"{gone['id']} holds R-group definitions, so it cannot be joined to {keep['id']}; bond atoms that are already in one fragment.") + ops: list[dict] = [] + for aid, atom in (gone.get("atoms") or {}).items(): + ops.append({"op": "set", "path": atom_path(keep["id"], aid), "value": atom}) + for bid, bond in (gone.get("bonds") or {}).items(): + ops.append({"op": "set", "path": bond_path(keep["id"], bid), "value": bond}) + if gone.get("stereo_groups"): + ops.append({"op": "set", "path": object_path(keep["id"], "stereo_groups"), "value": list(keep.get("stereo_groups") or []) + list(gone["stereo_groups"])}) + return ops + remove_objects_ops(doc, [gone["id"]]) + + +def add_bond(doc: dict, args: dict) -> tuple[list[dict], dict]: + a1 = str(args.get("atom1") or "").strip() + a2 = str(args.get("atom2") or "").strip() + if not a1 or not a2: + raise EditError(f"Give atom1 and atom2, two atom ids; {LIST_ATOMS}.") + if a1 == a2: + raise EditError("atom1 and atom2 are the same atom; a bond joins two different atoms.") + order = order_of(args.get("order")) + stereo = stereo_of(args.get("stereo")) + f1, _ = locate_atom(doc, a1) + f2, _ = locate_atom(doc, a2) + ops: list[dict] = [] + info: dict = {"atom1": a1, "atom2": a2, "order": order, "stereo": stereo} + if f1["id"] == f2["id"]: + for b in (f1.get("bonds") or {}).values(): + if {b.get("a"), b.get("b")} != {a1, a2}: + continue + path = lambda *k: bond_path(f1["id"], b["id"], *k) + if stereo in WEDGES and b["a"] != a1: + ops += [{"op": "set", "path": path("a"), "value": a1}, {"op": "set", "path": path("b"), "value": a2}] + if b.get("order", 1) != order: + ops.append({"op": "set", "path": path("order"), "value": order}) + ops.extend(_room_ops(f1, a1, valence_of(order) - valence_of(b.get("order", 1)))) + ops.extend(_room_ops(f1, a2, valence_of(order) - valence_of(b.get("order", 1)))) + if (b.get("stereo") or "none") != stereo: + ops.append({"op": "set", "path": path("stereo"), **({"value": stereo} if stereo != "none" else {})}) + info.update({"fragment": f1["id"], "bond": b["id"], "existing": True}) + return ops, info + keep = f1 + else: + one, two = _referenced(doc, f1["id"]), _referenced(doc, f2["id"]) + if one and two: + raise EditError(f"{a1} and {a2} sit in fragments {f1['id']} and {f2['id']}, which both take part in a scheme (a reaction step, caption or arrow names them), " + "so they cannot be joined; bond atoms of one fragment, or delete and redraw one side.") + keep, gone = (f2, f1) if two and not one else (f1, f2) + ops.extend(merge_ops(doc, keep, gone)) + info["merged"] = gone["id"] + bid = fresh_id(used_ids(doc), "b") + ops.append({"op": "set", "path": bond_path(keep["id"], bid), "value": _bond_record(bid, a1, a2, order, stereo)}) + for aid in (a1, a2): + owner = f1 if aid in (f1.get("atoms") or {}) else f2 + ops.extend({**op, "path": atom_path(keep["id"], aid, *op["path"][4:])} for op in _room_ops(owner, aid, valence_of(order))) + info.update({"fragment": keep["id"], "bond": bid, "existing": False}) + return ops, info + + +def _field_ops(frag: dict, atom: dict, change: dict) -> list[dict]: + ops = [] + for key, value in change.items(): + if atom.get(key) == value or (value is None and key not in atom): + continue + ops.append({"op": "set", "path": atom_path(frag["id"], atom["id"], key), **({"value": value} if value is not None else {})}) + return ops + + +def set_charge(doc: dict, args: dict) -> tuple[list[dict], dict]: + frag, atom = locate_atom(doc, args.get("atom"), str(args.get("fragment") or "") or None) + charge = charge_of(args.get("charge")) + ops = _field_ops(frag, atom, {"charge": charge or None}) + return ops, {"fragment": frag["id"], "atom": atom["id"], "charge": charge, "was": atom.get("charge", 0)} + + +def isotope_of(value: object) -> int | None: + if value in (None, 0, "", "natural"): + return None + if not _num(value) or not float(value).is_integer() or not 1 <= value <= 300: + raise EditError("isotope is a mass number from 1 to 300, or 0 for natural abundance.") + return int(value) + + +def set_atom(doc: dict, args: dict) -> tuple[list[dict], dict]: + frag, atom = locate_atom(doc, args.get("atom"), str(args.get("fragment") or "") or None) + change: dict = {} + if args.get("element") is not None: + element = element_of(args.get("element")) + if element == "R#": + raise EditError("Set an R-group with the window's define-rgroup command; set_atom takes element symbols and * only.") + if element != atom.get("element"): + change.update({"element": element, "label": None, "hydrogens": None, "isotope": None, "expansion": None, "generic": None}) + if "isotope" in args: + change["isotope"] = isotope_of(args.get("isotope")) + if "label" in args: + label = str(args.get("label") or "").strip() + if len(label) > 40: + raise EditError("label is short text shown for the atom, at most 40 characters, such as OH, D or CO2Me; an empty label shows the element.") + change["label"] = label or None + if args.get("radical") is not None: + radical = str(args.get("radical")).strip().lower() + if radical not in model.RADICALS: + raise EditError("radical is none, doublet (one dot), singlet or triplet.") + change["radical"] = None if radical == "none" else radical + if not change: + raise EditError("Give at least one of element, isotope, label or radical to change; set_charge changes the charge.") + ops = _field_ops(frag, atom, change) + return ops, {"fragment": frag["id"], "atom": atom["id"], "changed": [op["path"][-1] for op in ops]} + + +def id_list(value: object, name: str = "ids") -> list[str]: + if isinstance(value, str): + value = [value] + if not isinstance(value, list) or not value or not all(isinstance(v, str) and v.strip() for v in value): + raise EditError(f"{name} is a list of ids (atoms, bonds or objects); {LIST_ATOMS}, get_context the drawings.") + return list(dict.fromkeys(v.strip() for v in value)) + + +def sort_ids(doc: dict, ids: list[str]) -> tuple[dict[str, list[str]], dict[str, list[str]], list[str]]: + objects = doc.get("objects") or {} + atoms: dict[str, list[str]] = {} + bonds: dict[str, list[str]] = {} + whole: list[str] = [] + frags = fragments(doc) + missing = [] + for i in ids: + if i in objects: + whole.append(i) + continue + found = next((("a", fid) for fid, f in frags.items() if i in (f.get("atoms") or {})), None) or \ + next((("b", fid) for fid, f in frags.items() if i in (f.get("bonds") or {})), None) + if found is None: + missing.append(i) + elif found[0] == "a": + atoms.setdefault(found[1], []).append(i) + else: + bonds.setdefault(found[1], []).append(i) + if missing: + raise EditError(f"The drawing has no atom, bond or object {', '.join(missing[:6])}; {LIST_ATOMS}, get_structure the objects.") + return atoms, bonds, whole + + +def remove_objects_ops(doc: dict, ids: list[str]) -> list[dict]: + objects = doc.get("objects") or {} + up = parents(doc) + gone: set[str] = set() + + def down(oid: str, depth: int = 0) -> None: + if oid in gone or oid not in objects or depth > 64: + return + gone.add(oid) + o = objects[oid] + if isinstance(o, dict) and o.get("kind") == "group": + for c in o.get("children") or []: + down(c, depth + 1) + + for oid in ids: + down(oid) + grew = True + while grew: + grew = False + for oid, o in objects.items(): + if oid not in gone and isinstance(o, dict) and o.get("kind") == "group" and all(c in gone for c in o.get("children") or []): + gone.add(oid) + grew = True + ops: list[dict] = [] + for oid in sorted(gone): + if oid in up: + if up[oid] not in gone: + ops.append({"op": "del", "path": object_path(up[oid], "children"), "id": oid}) + continue + page = next((p for p in doc.get("pages") or [] if isinstance(p, dict) and oid in (p.get("order") or [])), None) + if page is not None: + ops.append({"op": "del", "path": page_path(page["id"], "order"), "id": oid}) + ops.extend({"op": "set", "path": object_path(oid)} for oid in sorted(gone)) + return ops + + +def delete(doc: dict, args: dict) -> tuple[list[dict], dict]: + atoms, bonds, whole = sort_ids(doc, id_list(args.get("ids"))) + ops: list[dict] = [] + emptied: list[str] = [] + for fid in sorted(set(atoms) | set(bonds)): + if fid in whole: + continue + frag = fragment(doc, fid) + drop = [a for a in atoms.get(fid, []) if a in frag["atoms"]] + if drop and len(drop) == len(frag["atoms"]): + emptied.append(fid) + continue + gone = set(drop) + for bid in bonds.get(fid, []): + b = frag["bonds"][bid] + if b["a"] not in gone and b["b"] not in gone: + ops.append({"op": "set", "path": bond_path(fid, bid)}) + ops.extend({"op": "set", "path": bond_path(fid, b["id"])} for b in frag["bonds"].values() if b["a"] in gone or b["b"] in gone) + ops.extend({"op": "set", "path": atom_path(fid, a)} for a in drop) + ops.extend(remove_objects_ops(doc, whole + emptied)) + touched = sorted((set(atoms) | set(bonds)) - set(whole) - set(emptied)) + return ops, {"atoms": sum(len(v) for v in atoms.values()), "bonds": sum(len(v) for v in bonds.values()), "objects": whole + emptied, "fragments": touched} + + +class Target: + def __init__(self, doc: dict, ids: list[str]): + atoms, bonds, whole = sort_ids(doc, ids) + for fid, bids in bonds.items(): + frag = fragment(doc, fid) + for bid in bids: + atoms.setdefault(fid, []).extend((frag["bonds"][bid]["a"], frag["bonds"][bid]["b"])) + self.doc = doc + self.objects = [o for o in whole] + self.atoms = {fid: list(dict.fromkeys(a)) for fid, a in atoms.items() if fid not in whole} + self.style = model.resolve_style(doc) + + def box(self) -> geometry.Box | None: + boxes = [geometry.object_box(self.doc, oid, self.style) for oid in self.objects] + for fid, aids in self.atoms.items(): + pts = [(fragment(self.doc, fid)["atoms"][a]["x"], fragment(self.doc, fid)["atoms"][a]["y"]) for a in aids] + boxes.append((min(p[0] for p in pts), min(p[1] for p in pts), max(p[0] for p in pts), max(p[1] for p in pts))) + return geometry.union(boxes) + + def fragment_ids(self) -> list[str]: + out = list(self.atoms) + + def walk(oid: str, depth: int = 0) -> None: + o = (self.doc.get("objects") or {}).get(oid) + if not isinstance(o, dict) or depth > 64: + return + if o.get("kind") == "fragment": + out.append(oid) + elif o.get("kind") == "group": + for c in o.get("children") or []: + walk(c, depth + 1) + + for oid in self.objects: + walk(oid) + return list(dict.fromkeys(out)) + + def median_bond(self) -> float | None: + lengths = [] + for fid in self.fragment_ids(): + frag = fragment(self.doc, fid) + chosen = set(self.atoms.get(fid) or frag["atoms"]) + for b in frag["bonds"].values(): + if b["a"] in chosen and b["b"] in chosen: + p, q = frag["atoms"][b["a"]], frag["atoms"][b["b"]] + lengths.append(math.hypot(p["x"] - q["x"], p["y"] - q["y"])) + return statistics.median(lengths) if lengths else None + + +LABEL_KEYS = ("line_width", "bold_width", "hash_spacing", "margin_width", "bond_spacing_abs") + + +def _restyle(doc: dict, obj: dict, k: float, labels: bool) -> list[dict]: + own = model.resolve_style(doc, obj) + plain = model.resolve_style(doc) + keys = (["bond_length"] if obj.get("kind") == "fragment" else []) + (list(LABEL_KEYS) if labels and obj.get("kind") == "fragment" else []) + font = "label_font" if obj.get("kind") == "fragment" else "caption_font" if obj.get("kind") in ("text", "caption") else None + nxt = dict(obj.get("style") or {}) + for key in keys: + if not _num(own.get(key)): + continue + v = round(own[key] * k, 2) + if _num(plain.get(key)) and abs(v - plain[key]) < 0.006: + nxt.pop(key, None) + else: + nxt[key] = v + if labels and font and isinstance(own.get(font), dict): + size = round(float(own[font].get("size") or 10) * k, 2) + if abs(size - float((plain.get(font) or {}).get("size") or 10)) < 0.006 and own[font].get("family") == (plain.get(font) or {}).get("family"): + nxt.pop(font, None) + else: + nxt[font] = {**own[font], "size": size} + if nxt == (obj.get("style") or {}): + return [] + return [{"op": "set", "path": object_path(obj["id"], "style"), **({"value": nxt} if nxt else {})}] + + +def _object_ops(doc: dict, oid: str, f, k: float, labels: bool, ops: list[dict], depth: int = 0) -> None: + obj = (doc.get("objects") or {}).get(oid) + if not isinstance(obj, dict) or depth > 64: + return + kind = obj.get("kind") + put = lambda key, value: ops.append({"op": "set", "path": object_path(oid, key), "value": value}) + if kind == "fragment": + for aid, a in (obj.get("atoms") or {}).items(): + x, y = f((a["x"], a["y"])) + ops += [{"op": "set", "path": atom_path(oid, aid, "x"), "value": _r(x)}, {"op": "set", "path": atom_path(oid, aid, "y"), "value": _r(y)}] + elif kind == "group": + for c in obj.get("children") or []: + _object_ops(doc, c, f, k, labels, ops, depth + 1) + return + elif kind == "arrow" and geometry.arrow_points(obj): + for xk, yk in (("x1", "y1"), ("x2", "y2")): + x, y = f((obj[xk], obj[yk])) + put(xk, _r(x)) + put(yk, _r(y)) + if labels and k != 1: + for key in ("head_length", "head_width", "line_width"): + if _num(obj.get(key)): + put(key, round(obj[key] * k, 2)) + elif kind in ("plus", "orbital") and _num(obj.get("x")) and _num(obj.get("y")): + x, y = f((obj["x"], obj["y"])) + put("x", _r(x)) + put("y", _r(y)) + if k != 1: + size = obj.get("size") if _num(obj.get("size")) else 0.6 * float(model.resolve_style(doc, obj).get("bond_length") or DEFAULT_BOND_LENGTH) + put("size", round(size * k, 2)) + elif kind == "line": + put("points", [[_r(v) for v in f((p[0], p[1]))] for p in obj.get("points") or [] if isinstance(p, list) and len(p) == 2]) + elif kind in ("shape", "image", "bracket", "tlc") and all(_num(obj.get(key)) for key in ("x", "y", "w", "h")): + cx, cy = obj["x"] + obj["w"] / 2, obj["y"] + obj["h"] / 2 + nx, ny = f((cx, cy)) + w, h = obj["w"] * k, obj["h"] * k + put("x", _r(nx - w / 2)) + put("y", _r(ny - h / 2)) + if k != 1: + put("w", _r(w)) + put("h", _r(h)) + elif _num(obj.get("x")) and _num(obj.get("y")): + box = geometry.object_box(doc, oid, model.resolve_style(doc, obj)) + c = geometry.centre(box) if box else (obj["x"], obj["y"]) + n = f(c) + grow = k if labels and kind in ("text", "caption") else 1.0 + put("x", _r(n[0] + (obj["x"] - c[0]) * grow)) + put("y", _r(n[1] + (obj["y"] - c[1]) * grow)) + if grow != 1: + if _num(obj.get("w")): + put("w", _r(obj["w"] * grow)) + if any(isinstance(r, dict) and _num(r.get("size")) for r in obj.get("runs") or []): + put("runs", [{**r, "size": round(r["size"] * grow, 2)} if isinstance(r, dict) and _num(r.get("size")) else r for r in obj["runs"]]) + if k != 1: + ops.extend(_restyle(doc, obj, k, labels)) + + +def _captions(before: dict, after: dict, mapped: set[str], f) -> list[dict]: + ops: list[dict] = [] + style = model.resolve_style(before) + for oid, c in (before.get("objects") or {}).items(): + if not isinstance(c, dict) or c.get("kind") != "caption" or not c.get("target") or not isinstance(c.get("offset"), list) or len(c["offset"]) != 2: + continue + target = c["target"] + was = geometry.object_box(before, target, style) + now = geometry.object_box(after, target, style) + own = geometry.object_box(after, oid, style) + if was is None or now is None or own is None or (oid not in mapped and was == now): + continue + top = (was[0] + was[2]) / 2 + c["offset"][0], was[3] + c["offset"][1] + if oid in mapped: + top = f(top) + else: + top = ((now[0] + now[2]) / 2 + c["offset"][0], now[3] + c["offset"][1]) + width = own[2] - own[0] + anchor = 0.0 if c.get("align") == "c" and not _num(c.get("w")) else width / 2 if c.get("align") == "r" and not _num(c.get("w")) else -width / 2 + ops += [{"op": "set", "path": object_path(oid, "offset"), "value": [_r(top[0] - (now[0] + now[2]) / 2), _r(top[1] - now[3])]}, + {"op": "set", "path": object_path(oid, "x"), "value": _r(top[0] + anchor)}, + {"op": "set", "path": object_path(oid, "y"), "value": _r(top[1])}] + return ops + + +def map_ops(doc: dict, target: Target, f, k: float = 1.0, labels: bool = False) -> list[dict]: + from app.services import ops as opsmod + ops: list[dict] = [] + mapped: set[str] = set() + for fid, aids in target.atoms.items(): + frag = fragment(doc, fid) + for aid in aids: + x, y = f((frag["atoms"][aid]["x"], frag["atoms"][aid]["y"])) + ops += [{"op": "set", "path": atom_path(fid, aid, "x"), "value": _r(x)}, {"op": "set", "path": atom_path(fid, aid, "y"), "value": _r(y)}] + if k != 1 and len(aids) == len(frag["atoms"]): + ops.extend(_restyle(doc, frag, k, labels)) + for oid in target.objects: + obj = (doc.get("objects") or {}).get(oid) + if isinstance(obj, dict) and obj.get("kind") == "caption" and obj.get("target") and obj.get("offset"): + mapped.add(oid) + continue + _object_ops(doc, oid, f, k, labels, ops) + after = copy.deepcopy(doc) + opsmod.apply_ops(after, copy.deepcopy(ops)) + return ops + _captions(doc, after, mapped, f) + + +def _clean(ops: list[dict], doc: dict) -> list[dict]: + from app.services import ops as opsmod + out = [] + for op in ops: + try: + current = opsmod.resolve(doc, op["path"]) + except Exception: + out.append(op) + continue + if "value" in op and opsmod.same_value(current, op["value"]): + continue + out.append(op) + return out + + +def move(doc: dict, args: dict) -> tuple[list[dict], dict]: + if not _num(args.get("dx", 0)) or not _num(args.get("dy", 0)): + raise EditError("dx and dy are numbers of points (x right, y down), such as dx 50, dy 0.") + dx, dy = float(args.get("dx") or 0), float(args.get("dy") or 0) + target = Target(doc, id_list(args.get("ids"))) + ops = _clean(map_ops(doc, target, lambda p: (p[0] + dx, p[1] + dy)), doc) + return ops, {"moved": target.objects + [a for v in target.atoms.values() for a in v], "dx": dx, "dy": dy, "fragments": target.fragment_ids()} + + +SCALE_MIN, SCALE_MAX = 0.05, 20.0 + + +def _structures(doc: dict) -> list[str]: + out = [] + for p in doc.get("pages") or []: + for oid in (p.get("order") or []) if isinstance(p, dict) else []: + o = (doc.get("objects") or {}).get(oid) + if isinstance(o, dict) and not o.get("locked") and not o.get("hidden") and geometry.has_fragment(doc, oid): + out.append(oid) + return out + + +def scale(doc: dict, args: dict) -> tuple[list[dict], dict]: + percent, wanted = args.get("percent"), args.get("bond_length") + if (percent is None) == (wanted is None): + raise EditError("Give percent (100 keeps the size, 150 makes it half again as large) or bond_length (the wanted median bond length in points), not both.") + if percent is not None and (not _num(percent) or not 5 <= percent <= 2000): + raise EditError("percent is a number from 5 to 2000.") + if wanted is not None and (not _num(wanted) or not 1 <= wanted <= 500): + raise EditError("bond_length is a number of points from 1 to 500, such as 14.4 (the journal style) or 20.") + labels = args.get("labels") is True + given = args.get("ids") + groups = [Target(doc, id_list(given))] if given else [Target(doc, [oid]) for oid in _structures(doc)] + if not groups: + raise EditError("The drawing has no structures to scale; draw one first (draw_from_smiles or add_atom).") + was = Target(doc, [i for t in groups for i in t.objects + [a for v in t.atoms.values() for a in v]]).median_bond() + if wanted is not None and not was: + raise EditError("The chosen objects have no bonds to measure; scale them by percent instead.") + k = float(percent) / 100 if percent is not None else float(wanted) / was + k = min(SCALE_MAX, max(SCALE_MIN, k)) + ops: list[dict] = [] + for t in groups: + box = t.box() + if box is None: + continue + c = geometry.centre(box) + ops.extend(map_ops(doc, t, lambda p, c=c: (c[0] + (p[0] - c[0]) * k, c[1] + (p[1] - c[1]) * k), k, labels)) + frags = [fid for t in groups for fid in t.fragment_ids()] + return _clean(ops, doc), {"k": round(k, 4), "percent": round(k * 100, 2), "bond_length": round(was * k, 3) if was else None, "fragments": list(dict.fromkeys(frags)), + "targets": len(groups)} + + +ALIGN_MODES = {"left": "left", "centre": "centre", "center": "centre", "right": "right", "top": "top", "middle": "middle", "bottom": "bottom", + "distribute_h": "distribute_h", "distribute-h": "distribute_h", "distribute_v": "distribute_v", "distribute-v": "distribute_v"} + + +def align(doc: dict, args: dict) -> tuple[list[dict], dict]: + how = ALIGN_MODES.get(str(args.get("mode") or "").strip().lower()) + if how is None: + raise EditError("mode is left, centre, right, top, middle or bottom (edges or centres line up), or distribute_h or distribute_v (even spacing of three or more).") + whole = Target(doc, id_list(args.get("ids"))) + units = [Target(doc, [oid]) for oid in whole.objects] + [Target(doc, aids) for aids in whole.atoms.values()] + boxed = [(u, u.box()) for u in units] + boxed = [(u, b) for u, b in boxed if b is not None] + need = 3 if how.startswith("distribute") else 2 + if len(boxed) < need: + raise EditError(f"{how.replace('_', ' ')} needs {need} or more objects (or groups of atoms of different fragments); give more ids.") + allx = geometry.union([b for _, b in boxed]) + ops: list[dict] = [] + if how.startswith("distribute"): + i = 0 if how == "distribute_h" else 1 + ranked = sorted(boxed, key=lambda ub: geometry.centre(ub[1])[i]) + first, last = geometry.centre(ranked[0][1])[i], geometry.centre(ranked[-1][1])[i] + step = (last - first) / (len(ranked) - 1) + moves = [(u, (first + step * n - geometry.centre(b)[i]) * (i == 0), (first + step * n - geometry.centre(b)[i]) * (i == 1)) for n, (u, b) in enumerate(ranked)] + else: + moves = [] + for u, b in boxed: + c = geometry.centre(b) + dx = {"left": allx[0] - b[0], "right": allx[2] - b[2], "centre": (allx[0] + allx[2]) / 2 - c[0]}.get(how, 0.0) + dy = {"top": allx[1] - b[1], "bottom": allx[3] - b[3], "middle": (allx[1] + allx[3]) / 2 - c[1]}.get(how, 0.0) + moves.append((u, dx, dy)) + for u, dx, dy in moves: + if abs(dx) > 1e-6 or abs(dy) > 1e-6: + ops.extend(map_ops(doc, u, lambda p, dx=dx, dy=dy: (p[0] + dx, p[1] + dy))) + return _clean(ops, doc), {"mode": how, "units": len(boxed), "fragments": whole.fragment_ids()} + + +def clean_layout(doc: dict, args: dict) -> tuple[list[dict], dict]: + from app.services.chem import layout + how = str(args.get("mode") or "clean").strip().lower() + if how not in ("clean", "layout"): + raise EditError("mode is clean (tidy bond lengths and angles, keeping the structure's place and shape) or layout (fresh 2D coordinates).") + given = args.get("objects") + if given: + target = Target(doc, id_list(given, "objects")) + jobs = {fid: (target.atoms.get(fid) if how == "clean" else None) for fid in target.fragment_ids()} + else: + jobs = {fid: None for oid in _structures(doc) for fid in Target(doc, [oid]).fragment_ids()} + jobs = {fid: ids for fid, ids in jobs.items() if fragment(doc, fid).get("atoms")} + if not jobs: + raise EditError("There is no structure to lay out; give fragment or atom ids (get_atoms lists them) or draw one first.") + ops: list[dict] = [] + notes: list[str] = [] + scores: dict[str, dict] = {} + for fid, ids in jobs.items(): + frag = fragment(doc, fid) + length = float(model.resolve_style(doc, frag).get("bond_length") or DEFAULT_BOND_LENGTH) + try: + coords = layout.clean(frag, ids, length) if how == "clean" else layout.compute_coords(frag, None, length) + except Exception as exc: + raise EditError(f"{fid} could not be laid out ({exc}); check_structure shows what is wrong with it.") from None + flips, warnings = layout.restereo(frag, coords) + for aid, (x, y) in coords.items(): + atom = frag["atoms"][aid] + if abs(atom["x"] - x) > 1e-3: + ops.append({"op": "set", "path": atom_path(fid, aid, "x"), "value": x}) + if abs(atom["y"] - y) > 1e-3: + ops.append({"op": "set", "path": atom_path(fid, aid, "y"), "value": y}) + ops.extend({"op": "set", "path": bond_path(fid, bid, "stereo"), "value": s} for bid, s in flips.items() if bid in frag["bonds"]) + notes.extend(w["text"] for w in warnings if w.get("text")) + before, after = layout.score_fragment(frag), layout.score_fragment(frag, coords) + if before and after: + scores[fid] = {"before": round(before.get("total", 0.0), 3), "after": round(after.get("total", 0.0), 3)} + return ops, {"mode": how, "fragments": list(jobs), "scores": scores, "notes": notes} + + +STEREO_NEXT = "the stereo tool lists the stereocentres and stereogenic double bonds with their labels" + + +def _side(frag: dict, start: str, cut: tuple[str, str]) -> set[str]: + adj: dict[str, list[str]] = {} + for b in (frag.get("bonds") or {}).values(): + if {b["a"], b["b"]} == set(cut): + continue + adj.setdefault(b["a"], []).append(b["b"]) + adj.setdefault(b["b"], []).append(b["a"]) + seen, stack = {start}, [start] + while stack: + for n in adj.get(stack.pop(), []): + if n not in seen: + seen.add(n) + stack.append(n) + return seen + + +def _reflect(p: Point, a: Point, b: Point) -> Point: + dx, dy = b[0] - a[0], b[1] - a[1] + n = dx * dx + dy * dy or 1.0 + t = ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / n + fx, fy = a[0] + t * dx, a[1] + t * dy + return (2 * fx - p[0], 2 * fy - p[1]) + + +def _centre_stereo(doc: dict, aid: str, label: str) -> tuple[list[dict], dict]: + from app.services.chem import stereo + frag, _ = locate_atom(doc, aid) + try: + out = stereo.rewedge(frag, doc.get("expansions"), centres=[aid], cip={aid: label}) + except ValueError as exc: + raise EditError(f"Wedges for {aid} could not be placed ({exc}); clean_layout the structure, then retry.") from None + if out["cip"].get(aid) != label: + codes = {w["code"] for w in out["warnings"]} + why = "it is not a stereocentre, or its label depends on another undefined centre" if "cip_unreachable" in codes else "the wedges could not express it" + raise EditError(f"{aid} cannot be set to {label}: {why}; {STEREO_NEXT}, so set the other centres first.") + return out["tx"]["ops"], {"fragment": frag["id"], "atom": aid, "label": label, "wedges": out["changed"], "cip": out["cip"]} + + +def _bond_stereo(doc: dict, bid: str, label: str) -> tuple[list[dict], dict]: + from app.services.chem import perceive + frag, bond = locate_bond(doc, bid) + if bond.get("order", 1) != 2: + raise EditError(f"{bid} is not a double bond, so it has no E or Z; {STEREO_NEXT}.") + expansions = doc.get("expansions") + now = perceive.perceive(frag, expansions).cip.get(bid) + info = {"fragment": frag["id"], "bond": bid, "label": label, "was": now} + either = (bond.get("stereo") or "none") == "either" + ops: list[dict] = [{"op": "set", "path": bond_path(frag["id"], bid, "stereo")}] if either else [] + if now == label and not either: + return [], {**info, "moved": []} + a, b = bond["a"], bond["b"] + side_b, side_a = _side(frag, b, (a, b)), _side(frag, a, (a, b)) + if a in side_b: + raise EditError(f"{bid} lies in a ring, so its geometry cannot be flipped to {label}; redraw the ring (draw_from_smiles with / and \\ bonds) instead.") + moving = (side_b - {b}) if len(side_b) <= len(side_a) else (side_a - {a}) + atoms = frag["atoms"] + pa, pb = (atoms[a]["x"], atoms[a]["y"]), (atoms[b]["x"], atoms[b]["y"]) + moved = {k: dict(v) for k, v in atoms.items()} + bonds = {k: dict(v) for k, v in (frag.get("bonds") or {}).items()} + if either: + bonds[bid].pop("stereo", None) + trial = {**frag, "atoms": moved, "bonds": bonds} + if perceive.perceive(trial, expansions).cip.get(bid) != label: + for k in moving: + moved[k]["x"], moved[k]["y"] = (_r(v) for v in _reflect((atoms[k]["x"], atoms[k]["y"]), pa, pb)) + for k, rec in bonds.items(): + if rec["a"] in moving and rec["b"] in moving and rec.get("stereo") in ("wedge", "hash"): + rec["stereo"] = "hash" if rec["stereo"] == "wedge" else "wedge" + else: + moving = set() + got = perceive.perceive(trial, expansions).cip.get(bid) + if got != label: + raise EditError(f"{bid} cannot be made {label}: one end carries two equal groups (not stereogenic) or a substituent lies on the bond's line; " + f"clean_layout the structure, then retry ({STEREO_NEXT}).") + for k in sorted(moving): + ops += [{"op": "set", "path": atom_path(frag["id"], k, "x"), "value": moved[k]["x"]}, {"op": "set", "path": atom_path(frag["id"], k, "y"), "value": moved[k]["y"]}] + for k, rec in bonds.items(): + if (rec.get("stereo") or "none") != ((frag["bonds"][k].get("stereo") or "none") if k != bid or not either else "none"): + ops.append({"op": "set", "path": bond_path(frag["id"], k, "stereo"), "value": rec["stereo"]}) + return ops, {**info, "moved": sorted(moving)} + + +def set_stereo(doc: dict, args: dict) -> tuple[list[dict], dict]: + label = str(args.get("label") or "").strip() + aid, bid = str(args.get("atom") or "").strip(), str(args.get("bond") or "").strip() + if bool(aid) == bool(bid): + raise EditError(f"Give atom (a stereocentre, with label R or S) or bond (a double bond, with label E or Z), not both; {STEREO_NEXT}.") + if aid: + if label.upper() not in ("R", "S"): + raise EditError("A stereocentre takes label R or S.") + return _centre_stereo(doc, aid, label.upper()) + if label.upper() not in ("E", "Z"): + raise EditError("A double bond takes label E or Z.") + return _bond_stereo(doc, bid, label.upper()) + + +MAX_MATCHES = 1000 + + +def fragment_diff_ops(old: dict, new: dict) -> list[dict]: + fid = old["id"] + ops: list[dict] = [] + for kind, path in (("bonds", bond_path), ("atoms", atom_path)): + before, after = old.get(kind) or {}, new.get(kind) or {} + ops.extend({"op": "set", "path": path(fid, k)} for k in before if k not in after) + for kind, path in (("atoms", atom_path), ("bonds", bond_path)): + before, after = old.get(kind) or {}, new.get(kind) or {} + ops.extend({"op": "set", "path": path(fid, k), "value": v} for k, v in after.items() if before.get(k) != v) + return ops + + +def _replacement(text: str): + from rdkit import Chem + from app.services.chem import convert + rm = Chem.MolFromSmiles(text) + if rm is None or not rm.GetNumAtoms(): + raise EditError(f"replacement {text} is not valid SMILES; give the group to put in, such as O, OC, C(=O)O or *N(C)C (a * marks the atom that takes the bond).") + stubs = [a for a in rm.GetAtoms() if a.GetAtomicNum() == 0 and a.GetDegree() == 1 and not a.GetIsotope()] + if len(stubs) > 1: + raise EditError("replacement has more than one * attachment; give one * (or none, and the first atom takes the bond).") + stub = stubs[0].GetIdx() if stubs else None + connect = stubs[0].GetNeighbors()[0].GetIdx() if stubs else 0 + return rm, stub, connect, convert + + +def _apply_match(work: dict, match_ids: list[str], rm, stub, connect, convert, used: set[str], length: float) -> tuple[list[str], str, list[str]]: + rf = convert.from_mol(rm, length, (0.0, 0.0), used=used) + ids = list(rf["atoms"]) + if stub is not None: + sid = ids[stub] + rf["bonds"] = {k: b for k, b in rf["bonds"].items() if sid not in (b["a"], b["b"])} + del rf["atoms"][sid] + cid = ids[connect] + gone = set(match_ids) + external = [b for b in work["bonds"].values() if (b["a"] in gone) != (b["b"] in gone)] + first = next((a for a in match_ids if any(a in (b["a"], b["b"]) for b in external)), match_ids[0]) + anchor = (work["atoms"][first]["x"], work["atoms"][first]["y"]) + centre = (statistics.fmean(work["atoms"][a]["x"] for a in match_ids), statistics.fmean(work["atoms"][a]["y"] for a in match_ids)) + work["bonds"] = {k: b for k, b in work["bonds"].items() if b["a"] not in gone and b["b"] not in gone} + for a in match_ids: + del work["atoms"][a] + rx = statistics.fmean(a["x"] for a in rf["atoms"].values()) + ry = statistics.fmean(a["y"] for a in rf["atoms"].values()) + shift = (anchor[0] - rf["atoms"][cid]["x"], anchor[1] - rf["atoms"][cid]["y"]) if external else (centre[0] - rx, centre[1] - ry) + for a in rf["atoms"].values(): + a["x"], a["y"] = _r(a["x"] + shift[0]), _r(a["y"] + shift[1]) + work["atoms"].update(rf["atoms"]) + work["bonds"].update(rf["bonds"]) + joined: set[str] = set() + gained = 0 + for b in external: + out = b["b"] if b["a"] in gone else b["a"] + if out in joined: + continue + joined.add(out) + bid = fresh_id(used, "b") + keep = b.get("stereo") if b.get("stereo") in WEDGES and b["a"] == out else None + rec = {"id": bid, "a": out, "b": cid, "order": b.get("order", 1)} + if keep: + rec["stereo"] = keep + work["bonds"][bid] = rec + gained += valence_of(b.get("order", 1)) + h = work["atoms"][cid].get("hydrogens") + if stub is None and isinstance(h, int) and gained: + if h - gained > 0: + work["atoms"][cid]["hydrogens"] = h - gained + else: + work["atoms"][cid].pop("hydrogens", None) + free = [a for a in rf["atoms"] if a != cid] if external else [] + return list(rf["atoms"]), cid, free + + +def _cross_check(frag: dict, expansions: dict | None, qm, rm, stub, connect, every: bool) -> str | None: + from rdkit import Chem + from app.services.chem import ids as chem_ids, perceive + try: + repl = Chem.RWMol(rm) + if stub is not None: + repl.RemoveAtom(stub) + connect -= 1 if stub < connect else 0 + base = perceive.prepare(frag, expansions).mol + out = Chem.ReplaceSubstructs(base, qm, repl.GetMol(), replaceAll=every, replacementConnectionPoint=connect)[0] + Chem.SanitizeMol(out) + return chem_ids.smiles(out) + except Exception: + return None + + +def replace_substructure(doc: dict, args: dict) -> tuple[list[dict], dict]: + from app.services.chem import ids as chem_ids, layout, perceive, search + smarts = str(args.get("smarts") or "").strip() + text = str(args.get("replacement") or "").strip() + if not smarts or not text: + raise EditError("Give smarts (what to find, such as Cl or [OH]) and replacement (SMILES of what to put in, such as O).") + try: + qm, _, _ = search.query_from(None, smarts) + except ValueError: + raise EditError(f"{smarts} is not valid SMARTS; give a pattern such as Cl, [OH], C(=O)O or c1ccccc1.") from None + rm, stub, connect, convert = _replacement(text) + every = args.get("all") is True + given = str(args.get("object") or "").strip() + targets = Target(doc, [given]).fragment_ids() if given else [fid for oid in _structures(doc) for fid in Target(doc, [oid]).fragment_ids()] + if not targets: + raise EditError(f"{given} holds no structure; get_atoms lists the fragments." if given else "The drawing has no structures to search; draw one first.") + expansions = doc.get("expansions") + used = used_ids(doc) + ops: list[dict] = [] + done: dict[str, dict] = {} + skipped = count = 0 + for fid in targets: + frag = fragment(doc, fid) + if not frag.get("atoms"): + continue + conv = perceive.prepare(frag, expansions) + matches = conv.mol.GetSubstructMatches(qm, uniquify=True, maxMatches=MAX_MATCHES) + work = copy.deepcopy(frag) + taken: set[str] = set() + added: list[str] = [] + free: list[str] = [] + removed: list[str] = [] + for m in matches: + if any(not conv.drawn[i] for i in m): + skipped += 1 + continue + ids = list(dict.fromkeys(conv.owner[i] for i in m)) + if taken & set(ids): + continue + taken |= set(ids) + new, _, loose = _apply_match(work, ids, rm, stub, connect, convert, used, bond_length(doc, frag)) + added += new + free += loose + removed += ids + count += 1 + if not every: + break + if not removed: + continue + if free: + coords = layout.compute_coords(work, free, bond_length(doc, frag)) + for aid, (x, y) in coords.items(): + work["atoms"][aid]["x"], work["atoms"][aid]["y"] = x, y + ops.extend(fragment_diff_ops(frag, work)) + try: + got = chem_ids.smiles(perceive.prepare(work, expansions).mol) + except Exception: + got = None + rd = _cross_check(frag, expansions, qm, rm, stub, connect, every) + done[fid] = {"removed": removed, "added": added, "smiles": got, **({"rdkit": rd} if rd and got and rd != got else {})} + if not every: + break + if not done: + why = f" ({skipped} hit(s) fall inside abbreviations; expand them first with run_command expand-abbreviation)" if skipped else "" + raise EditError(f"Nothing in {given or 'the drawing'} matches {smarts}{why}; the substructure tool shows what a pattern finds.") + return ops, {"smarts": smarts, "replacement": text, "replaced": count, "fragments": list(done), "detail": done} + + +ARROW_TYPES = ("forward", "equilibrium", "equilibrium_unbalanced", "reversible", "resonance", "retro", "nogo_cross", "nogo_slash", "dashed", + "curved", "fishhook", "arc", "plain", "fragmentation", "dissociation") +ARROW_HEADS = ("full", "half_left", "half_right", "open", "hollow", "none") +CURVED = ("curved", "fishhook") +CURVED_BEND = 90.0 +ANCHOR_GAP = 0.15 +END_GAP = 0.5 +ARROW_BONDS = 4.0 + + +def _end(doc: dict, value: object, name: str) -> tuple[Point | None, geometry.Box | None, dict | None]: + if isinstance(value, (list, tuple)) and len(value) == 2 and all(_num(v) for v in value): + return (float(value[0]), float(value[1])), None, None + ref = str(value or "").strip() + if not ref: + return None, None, None + objects = doc.get("objects") or {} + if ref in objects: + box = geometry.object_box(doc, ref, model.resolve_style(doc)) + if box is None: + raise EditError(f"{name} {ref} has no extent on the page to point at; give [x, y] instead.") + return None, box, None + for fid, frag in fragments(doc).items(): + if ref in (frag.get("atoms") or {}): + a = frag["atoms"][ref] + return (a["x"], a["y"]), None, {"object": fid, "atom": ref} + if ref in (frag.get("bonds") or {}): + b = frag["bonds"][ref] + p, q = frag["atoms"][b["a"]], frag["atoms"][b["b"]] + return ((p["x"] + q["x"]) / 2, (p["y"] + q["y"]) / 2), None, {"object": fid, "bond": ref} + raise EditError(f"{name} is [x, y] in points, or the id of an object, atom or bond; {ref} is none of these ({LIST_ATOMS}).") + + +def _exit(box: geometry.Box, towards: Point, gap: float) -> Point: + c = geometry.centre(box) + dx, dy = towards[0] - c[0], towards[1] - c[1] + n = math.hypot(dx, dy) + if n < 1e-9: + return c + ux, uy = dx / n, dy / n + hw, hh = (box[2] - box[0]) / 2, (box[3] - box[1]) / 2 + t = min(hw / abs(ux) if abs(ux) > 1e-9 else math.inf, hh / abs(uy) if abs(uy) > 1e-9 else math.inf) + return (c[0] + ux * (t + gap), c[1] + uy * (t + gap)) + + +def add_arrow(doc: dict, args: dict) -> tuple[list[dict], dict]: + kind = str(args.get("kind") or args.get("type") or "forward").strip().lower() + if kind not in ARROW_TYPES: + raise EditError(f"kind is one of {', '.join(ARROW_TYPES)}.") + length = float(model.resolve_style(doc).get("bond_length") or DEFAULT_BOND_LENGTH) + tail, tail_box, tail_anchor = _end(doc, args.get("from"), "from") + head, head_box, head_anchor = _end(doc, args.get("to"), "to") + if tail is None and tail_box is None: + raise EditError("Give from: [x, y] in points, or the id of the object, atom or bond the arrow starts at.") + if head is None and head_box is None: + if tail is None: + tail = (tail_box[2] + END_GAP * length, geometry.centre(tail_box)[1]) + head = (tail[0] + ARROW_BONDS * length, tail[1]) + if tail is None: + tail = _exit(tail_box, head if head is not None else geometry.centre(head_box), END_GAP * length) + if head is None: + head = _exit(head_box, tail, END_GAP * length) + if tail_anchor or head_anchor: + span = math.hypot(head[0] - tail[0], head[1] - tail[1]) + k = ANCHOR_GAP * length / span if span > 3 * ANCHOR_GAP * length else 0.0 + t0, h0 = tail, head + if tail_anchor: + tail = (t0[0] + (h0[0] - t0[0]) * k, t0[1] + (h0[1] - t0[1]) * k) + if head_anchor: + head = (h0[0] + (t0[0] - h0[0]) * k, h0[1] + (t0[1] - h0[1]) * k) + if math.hypot(head[0] - tail[0], head[1] - tail[1]) < 1.0: + raise EditError("from and to are at the same place; give two different points or objects.") + obj: dict = {"id": fresh_id(used_ids(doc), "o"), "kind": "arrow", "type": kind, "x1": _r(tail[0]), "y1": _r(tail[1]), "x2": _r(head[0]), "y2": _r(head[1])} + bend = args.get("bend") + if bend is not None and (not _num(bend) or not -345 <= bend <= 345): + raise EditError("bend is the arc sweep in degrees from -345 to 345 (0 is straight; positive bulges to the left of tail to head).") + if bend is None and kind in CURVED: + bend = CURVED_BEND + if bend: + obj["bend"] = float(bend) + for key in ("head", "tail"): + if args.get(key) is not None: + if args[key] not in ARROW_HEADS: + raise EditError(f"{key} is one of {', '.join(ARROW_HEADS)}.") + obj[key] = args[key] + if tail_anchor or head_anchor: + obj["anchors"] = {k: v for k, v in (("tail", tail_anchor), ("head", head_anchor)) if v} + page = first_page(doc, str(args.get("page") or "") or None) + for ref in (args.get("from"), args.get("to")): + if isinstance(ref, str) and ref.strip() in (doc.get("objects") or {}): + page = page_of(doc, ref.strip()) + break + if tail_anchor: + page = page_of(doc, tail_anchor["object"]) + ops = [{"op": "set", "path": object_path(obj["id"]), "value": obj}, {"op": "ins", "path": page_path(page["id"], "order"), "value": obj["id"]}] + return ops, {"object": obj["id"], "kind": kind, "tail": [obj["x1"], obj["y1"]], "head": [obj["x2"], obj["y2"]], "page": page["id"]} + + +TEXT_STYLES = ("plain", "formula", "bold", "italic") + + +def add_text(doc: dict, args: dict) -> tuple[list[dict], dict]: + text = str(args.get("text") or "") + if not text.strip(): + raise EditError("Give text, the words to place (\\n breaks a line).") + if len(text) > 4000: + raise EditError("text is at most 4000 characters.") + style = str(args.get("style") or "plain").strip().lower() + if style not in TEXT_STYLES: + raise EditError("style is plain, formula (chemical subscripts such as H2SO4 written automatically), bold or italic.") + align = str(args.get("align") or "l").strip().lower()[:1] + if align not in ("l", "c", "r"): + raise EditError("align is left, centre or right.") + size = args.get("size") + if size is not None and (not _num(size) or not 4 <= size <= 72): + raise EditError("size is the font size in points, from 4 to 72.") + run: dict = {"t": text} + if style == "bold": + run["b"] = True + if style == "italic": + run["i"] = True + if size is not None: + run["size"] = float(size) + used = used_ids(doc) + obj: dict = {"id": fresh_id(used, "o"), "kind": "text", "x": 0.0, "y": 0.0, "runs": [run]} + if align != "l": + obj["align"] = align + if style == "formula": + obj["formula"] = True + target = str(args.get("below") or "").strip() + has_xy = _num(args.get("x")) and _num(args.get("y")) + length = float(model.resolve_style(doc).get("bond_length") or DEFAULT_BOND_LENGTH) + if target: + box = geometry.object_box(doc, target, model.resolve_style(doc)) if target in (doc.get("objects") or {}) else None + if box is None: + raise EditError(f"below is the id of an object on the page to caption, such as a fragment; {target} is not one ({LIST_ATOMS}).") + page = page_of(doc, target) + obj.update({"kind": "caption", "target": target, "offset": [0.0, _r(END_GAP * length)], "align": "c"}) + obj["x"], obj["y"] = _r((box[0] + box[2]) / 2), _r(box[3] + END_GAP * length) + else: + page = first_page(doc, str(args.get("page") or "") or None) + if has_xy: + obj["x"], obj["y"] = _r(args["x"]), _r(args["y"]) + else: + from app.services.chem import scheme + obj["x"], obj["y"] = scheme.free_origin(doc, page) + ops = [{"op": "set", "path": object_path(obj["id"]), "value": obj}, {"op": "ins", "path": page_path(page["id"], "order"), "value": obj["id"]}] + return ops, {"object": obj["id"], "kind": obj["kind"], "x": obj["x"], "y": obj["y"], "page": page["id"]} + + +def add_reaction(doc: dict, args: dict) -> tuple[list[dict], dict]: + text = str(args.get("reaction_smiles") or "").strip() + if not text: + raise EditError("Give reaction_smiles, such as CCO.CC(=O)O>[H+]>CC(=O)OCC.O (reactants>agents>products).") + if text.split()[0].count(">") != 2: + raise EditError(f"{text} is not reaction SMILES: it needs reactants>agents>products, such as CCO.CC(=O)O>>CC(=O)OCC.O; draw_from_smiles draws one structure.") + x, y = args.get("x"), args.get("y") + if (x is not None and not _num(x)) or (y is not None and not _num(y)): + raise EditError("x and y are the top-left of the scheme in points; leave them out to place it in free space.") + page_id = str(args.get("page") or "").strip() or None + first_page(doc, page_id) + try: + from app.services import agent_draw + except ImportError: + agent_draw = None + if agent_draw is not None: + try: + ops, objects, reaction, notes = agent_draw.reaction_ops(doc, text, "smiles", page_id, x, y) + except agent_draw.DrawError as exc: + raise EditError(f"{exc} Check the reaction SMILES (reactants>agents>products).") from None + else: + from app.services.chem import scheme + from app.services.chem.reactions import ReactionError + page = first_page(doc, page_id) + try: + ops, found = scheme.insert_ops(doc, page, text, "smiles", (float(x), float(y)) if x is not None and y is not None else None) + except ReactionError as exc: + raise EditError(f"{exc} Check the reaction SMILES (reactants>agents>products).") from None + objects, reaction, notes = [o["id"] for o in found["objects"]], found["reaction"], found.get("warnings") or [] + frags = [o for o in objects if (doc.get("objects") or {}).get(o) is None and any(op.get("value", {}).get("kind") == "fragment" for op in ops + if isinstance(op.get("value"), dict) and op["value"].get("id") == o)] + return ops, {"objects": objects, "fragments": frags, "reaction": reaction, "notes": [n.get("text") for n in notes if isinstance(n, dict) and n.get("text")]} + + +ATOM_KEYS = ("charge", "isotope", "label", "radical", "map", "hydrogens", "expansion", "generic", "rgroup") + + +def listing(doc: dict, derived: dict | None, oid: str | None = None) -> list[dict]: + if oid: + if oid not in (doc.get("objects") or {}): + raise EditError(f"The drawing has no object {oid}; get_atoms without object lists every fragment.") + chosen = Target(doc, [oid]).fragment_ids() + if not chosen: + raise EditError(f"{oid} is a {(doc['objects'][oid] or {}).get('kind')} object and holds no atoms; get_atoms without object lists every fragment.") + else: + chosen = [fid for p in doc.get("pages") or [] if isinstance(p, dict) for top in p.get("order") or [] for fid in Target(doc, [top]).fragment_ids()] + found = (derived or {}).get("fragments") or {} + out = [] + for fid in chosen: + frag = fragment(doc, fid) + d = found.get(fid) if isinstance(found.get(fid), dict) else {} + cip = d.get("cip") or {} + hs = d.get("implicit_h") or {} + atoms = [] + for aid, a in (frag.get("atoms") or {}).items(): + row = {"id": aid, "element": a.get("element"), "x": a.get("x"), "y": a.get("y"), "charge": a.get("charge", 0)} + row.update({k: a[k] for k in ATOM_KEYS[1:] if a.get(k) not in (None, "none")}) + if aid in hs: + row["h"] = hs[aid] + if aid in cip: + row["cip"] = cip[aid] + row["bonds"] = [b["id"] for b in (frag.get("bonds") or {}).values() if aid in (b.get("a"), b.get("b"))] + atoms.append(row) + bonds = [] + for bid, b in (frag.get("bonds") or {}).items(): + row = {"id": bid, "a": b.get("a"), "b": b.get("b"), "order": b.get("order", 1)} + if (b.get("stereo") or "none") != "none": + row["stereo"] = b["stereo"] + if bid in cip: + row["cip"] = cip[bid] + bonds.append(row) + out.append({"id": fid, "page": page_of(doc, fid)["id"], "formula": d.get("formula"), "smiles": d.get("smiles"), "inchikey": d.get("inchikey"), + "atoms": atoms, "bonds": bonds}) + return out diff --git a/backend/app/services/agent_log.py b/backend/app/services/agent_log.py new file mode 100644 index 00000000..5cb261de --- /dev/null +++ b/backend/app/services/agent_log.py @@ -0,0 +1,258 @@ +import asyncio +import contextvars +import json +import logging +import os +import re +import threading +import time +from collections import deque +from pathlib import Path + +from app.core import config, ids +from app.services.hub import HUB +from app.services.store import AFTER_CHANGE, STORE + +CAP = 400 +FOLDER = "Agent log" +FILE_LIMIT = 1_000_000 +ROTATIONS = 3 +SESSIONS_KEPT = 20 +SUMMARY_LIMIT = 240 +VALUE_LIMIT = 48 +NOTE_LIMIT = 200 +OBJECT_LIMIT = 60 +SETTLE_SECONDS = 1.5 +WINDOW_TOOLS = ("run_command", "extension_command") +SECRET = re.compile(r"token|secret|passw|api[_-]?key|authori[sz]ation|cookie|credential", re.I) +log = logging.getLogger("formchem.agent_log") + +_calls: deque = deque(maxlen=CAP) +_running: dict[str, dict] = {} +_settling: dict[str, dict] = {} +_owners: dict[tuple[str, str], str] = {} +_undoable: dict[str, str | None] = {} +_current: contextvars.ContextVar = contextvars.ContextVar("formchem_agent_call", default=None) +_write = threading.Lock() +_file: dict[str, Path | None] = {"path": None} + + +def _clip(text: str, n: int) -> str: + text = " ".join(str(text).split()) + return text if len(text) <= n else text[: n - 1] + "…" + + +def _value(key: str, v, top: bool) -> str: + if SECRET.search(str(key)): + return "(hidden)" + if isinstance(v, str): + if "\n" in v.strip(): + return f"({v.strip().count(chr(10)) + 1} lines)" + flat = " ".join(v.split()) + return json.dumps(flat if len(flat) <= VALUE_LIMIT else flat[: VALUE_LIMIT - 1] + "…", ensure_ascii=False) + ("" if len(flat) <= VALUE_LIMIT else f" ({len(flat)} chars)") + if v is None or isinstance(v, (bool, int, float)): + return json.dumps(v) + if isinstance(v, (list, tuple)): + if len(v) <= 4 and all(isinstance(x, (str, int, float, bool)) and len(str(x)) <= 24 for x in v): + return "[" + ", ".join(_value(key, x, False) for x in v) + "]" + return f"[{len(v)} items]" + if isinstance(v, dict): + if not top: + return f"{{{len(v)} keys}}" + return "{" + ", ".join(f"{k}={_value(str(k), x, False)}" for k, x in v.items()) + "}" + return type(v).__name__ + + +def summary(args: dict) -> str: + if not isinstance(args, dict) or not args: + return "" + return _clip(" ".join(f"{k}={_value(str(k), v, True)}" for k, v in args.items()), SUMMARY_LIMIT) + + +def _first_line(result: dict) -> str: + for block in result.get("content") or []: + if isinstance(block, dict) and block.get("type") == "text" and block.get("text"): + return _clip(str(block["text"]).strip().splitlines()[0], NOTE_LIMIT) + return "" + + +def _public(entry: dict) -> dict: + return {k: v for k, v in entry.items() if not k.startswith("_")} + + +async def _send(entry: dict) -> None: + await HUB.broadcast_all({"t": "agentCall", "call": _public(entry)}) + + +def _folder() -> Path: + path = config.data_dir() / FOLDER + path.mkdir(parents=True, exist_ok=True) + return path + + +def _session_file() -> Path: + if _file["path"] is None: + folder = _folder() + _file["path"] = folder / f"{time.strftime('%Y%m%d-%H%M%S')}-{os.getpid()}.jsonl" + stems = sorted({p.name.split(".", 1)[0] for p in folder.glob("*.jsonl")}) + for old in stems[: max(0, len(stems) - SESSIONS_KEPT + 1)]: + for p in folder.glob(f"{old}*.jsonl"): + try: + p.unlink() + except OSError: + pass + return _file["path"] + + +def _rotate(path: Path) -> None: + stem = path.name[: -len(".jsonl")] + for n in range(ROTATIONS - 1, 0, -1): + older = path.with_name(f"{stem}.{n}.jsonl") + if older.exists(): + older.replace(path.with_name(f"{stem}.{n + 1}.jsonl")) + path.replace(path.with_name(f"{stem}.1.jsonl")) + + +def _persist(entry: dict) -> None: + line = json.dumps(_public(entry), ensure_ascii=False) + "\n" + try: + with _write: + path = _session_file() + if path.exists() and path.stat().st_size + len(line) > FILE_LIMIT: + _rotate(path) + with open(path, "a", encoding="utf-8") as f: + f.write(line) + except OSError as exc: + log.warning("could not write the agent call log: %s", exc) + + +def log_path() -> str | None: + return str(_file["path"]) if _file["path"] is not None else None + + +async def begin(agent: str, inapp: bool, tool: str, args: dict, writes: bool) -> dict: + doc = args.get("doc") if isinstance(args, dict) and isinstance(args.get("doc"), str) else None + entry = {"id": ids.short("k", 10), "agent": agent or "agent", "inapp": bool(inapp), "tool": tool, "args": summary(args), "started": int(time.time() * 1000), "ms": None, + "status": "running", "writes": bool(writes), "doc": doc, "tx": None, "txs": 0, "rev": None, "objects": [], "note": "", "undone": False, "_t0": time.monotonic()} + _calls.append(entry) + _running[entry["id"]] = entry + entry["_token"] = _current.set(entry) + await _send(entry) + return entry + + +async def end(entry: dict, result: dict, refused: bool = False) -> None: + token = entry.pop("_token", None) + if token is not None: + try: + _current.reset(token) + except ValueError: + pass + entry["ms"] = int((time.monotonic() - entry.pop("_t0", time.monotonic())) * 1000) + entry["status"] = "refused" if refused else "error" if result.get("isError") else "ok" + entry["note"] = _first_line(result) + _running.pop(entry["id"], None) + await _send(entry) + if entry["status"] == "ok" and entry["writes"] and entry["tool"] in WINDOW_TOOLS and not entry["txs"]: + _settling[entry["id"]] = entry + asyncio.get_running_loop().call_later(SETTLE_SECONDS, _settled, entry["id"]) + else: + await asyncio.to_thread(_persist, entry) + + +def _settled(cid: str) -> None: + entry = _settling.pop(cid, None) + if entry is not None: + threading.Thread(target=_persist, args=(entry,), daemon=True).start() + + +def _touched(ops: list) -> list[str]: + out: list[str] = [] + for op in ops or []: + if not isinstance(op, dict): + continue + path = op.get("path") or [] + found = None + if len(path) >= 2 and path[0] == "objects" and isinstance(path[1], str): + found = path[1] + elif op.get("op") in ("ins", "del") and len(path) >= 3 and path[0] == "pages" and path[-1] == "order" and isinstance(op.get("value"), str): + found = op["value"] + if found and found not in out: + out.append(found) + return out + + +def _owner(tx: dict) -> dict | None: + current = _current.get() + if isinstance(current, dict) and current.get("status") == "running": + return current + if tx.get("origin") == "history": + return None + waiting = [e for e in list(_running.values()) + list(_settling.values()) if e["writes"] and e["tool"] in WINDOW_TOOLS] + return waiting[-1] if len(waiting) == 1 else None + + +def _stacks(doc_id: str) -> tuple[str | None, set[str], set[str]]: + s = STORE.sessions.get(doc_id) + if s is None: + return None, set(), set() + with s.lock: + return (s.undo[-1].get("id") if s.undo else None), {e.get("id") for e in s.redo}, {e.get("id") for e in s.undo} + + +async def after_change(doc_id: str, result: dict) -> None: + tx = result.get("tx") or {} + entry = _owner(tx) + if entry is not None: + key = result.get("merged") or tx.get("id") + entry["doc"] = doc_id + entry["tx"] = key + entry["txs"] += 1 + entry["rev"] = result.get("rev") + entry["undone"] = False + entry["objects"] = (entry["objects"] + [o for o in _touched(tx.get("ops")) if o not in entry["objects"]])[:OBJECT_LIMIT] + if key: + if len(_owners) > CAP * 4: + _owners.pop(next(iter(_owners))) + _owners[(doc_id, key)] = entry["id"] + await _send(entry) + if entry["id"] in _settling: + _settled(entry["id"]) + top, redo, done = _stacks(doc_id) + if tx.get("origin") == "history": + for e in list(_calls): + now = e["tx"] in redo or (e["undone"] and e["tx"] not in done) + if e["doc"] == doc_id and e["tx"] and e["undone"] != now: + e["undone"] = now + await _send(e) + owner = _owners.get((doc_id, top)) if top else None + if _undoable.get(doc_id) != owner: + _undoable[doc_id] = owner + await HUB.broadcast_all({"t": "agentUndoable", "doc": doc_id, "call": owner}) + + +def find(cid: str) -> dict | None: + return next((e for e in _calls if e["id"] == cid), None) + + +def undoable(doc_id: str) -> str | None: + top, _, _ = _stacks(doc_id) + return _owners.get((doc_id, top)) if top else None + + +def listing(limit: int = CAP, agent: str = "") -> dict: + rows = [_public(e) for e in reversed(_calls) if not agent or e["agent"] == agent][: max(1, min(CAP, limit))] + docs = {e["doc"] for e in _calls if e["doc"]} + return {"calls": rows, "undoable": {d: undoable(d) for d in docs if undoable(d)}, "agents": sorted({e["agent"] for e in _calls}), "cap": CAP, "file": log_path()} + + +async def clear() -> int: + gone = [e for e in _calls if e["status"] != "running"] + keep = [e for e in _calls if e["status"] == "running"] + _calls.clear() + _calls.extend(keep) + await HUB.broadcast_all({"t": "agentCallsCleared", "kept": [e["id"] for e in keep]}) + return len(gone) + + +AFTER_CHANGE.append(after_change) diff --git a/backend/app/services/agent_out.py b/backend/app/services/agent_out.py new file mode 100644 index 00000000..7798fe20 --- /dev/null +++ b/backend/app/services/agent_out.py @@ -0,0 +1,313 @@ +import asyncio +import base64 +import copy +import re +import struct + +from app.services import bridge, model +from app.services.chem import DEFAULT_BOND_LENGTH, geometry +from app.services.store import STORE + +GAP_BONDS = 2.0 +FIRST_BONDS = 2.0 +MAX_DEPTH = 32 +SCOPES = ("object", "selection", "page") +FORMATS = ("png", "svg") +MIME = {"png": "image/png", "svg": "image/svg+xml"} +WINDOW_WAIT = 25.0 +ENGINE_DPI = 144 +RESULT_SIZE = {"width": 640, "height": 480, "dpi": 144} +FULL_FIELDS = ("smiles", "cxsmiles", "inchi", "inchikey", "formula", "mw", "exact_mass", "mz", "elemental_analysis") + + +class RenderError(Exception): + pass + + +def page_of(doc: dict, ids: list[str] | None = None, page_id: str | None = None) -> dict | None: + pages = [p for p in doc.get("pages") or [] if isinstance(p, dict)] + if page_id: + return next((p for p in pages if p.get("id") == page_id), None) + wanted = set(ids or []) + if wanted: + for p in pages: + if wanted & set(_flat(doc, p.get("order") or [])) or wanted & set(p.get("order") or []): + return p + return pages[0] if pages else None + + +def _flat(doc: dict, ids: list, depth: int = 0) -> list[str]: + out: list[str] = [] + objects = doc.get("objects") or {} + for oid in ids: + obj = objects.get(oid) if isinstance(oid, str) else None + if not isinstance(obj, dict): + continue + out.append(oid) + if obj.get("kind") == "group" and depth < MAX_DEPTH: + out.extend(_flat(doc, obj.get("children") or [], depth + 1)) + return out + + +def fragments_in(doc: dict, ids: list[str]) -> list[str]: + objects = doc.get("objects") or {} + seen: list[str] = [] + for oid in _flat(doc, ids): + if objects[oid].get("kind") == "fragment" and oid not in seen: + seen.append(oid) + return seen + + +def _row(doc: dict, oid: str, derived: dict | None) -> dict: + obj = (doc.get("objects") or {}).get(oid) + if not isinstance(obj, dict): + return {"id": oid, "kind": None, "gone": True} + kind = obj.get("kind") + if kind == "group": + return {"id": oid, "kind": "group", "fragments": fragments_in(doc, [oid])} + if kind != "fragment": + return {"id": oid, "kind": kind} + found = ((derived or {}).get("fragments") or {}).get(oid) or {} + atoms = obj.get("atoms") or {} + out = {"id": oid, "kind": "fragment", "atoms": len(atoms), "bonds": len(obj.get("bonds") or {}), + "smiles": found.get("smiles"), "cxsmiles": found.get("cxsmiles"), "inchikey": found.get("inchikey"), + "formula": found.get("formula"), "mw": found.get("mw"), "warnings": list(found.get("warnings") or [])} + if obj.get("name"): + out["name"] = obj["name"] + errors = found.get("valence_errors") or [] + if errors: + out["valence_errors"] = errors + if not found: + out["warnings"].append({"code": "not_derived", "text": "The chemistry engine has not worked this fragment out yet."}) + return out + + +def structure_of(doc_id: str, ids: list[str]) -> list[dict]: + s = STORE.get(doc_id) + derived = STORE.derive_now(doc_id) + with s.lock: + doc = copy.deepcopy(s.doc) + rows = [] + for oid in ids: + row = _row(doc, oid, derived) + rows.append(row) + if row.get("kind") == "group": + rows.extend(_row(doc, f, derived) for f in row["fragments"] if f not in ids) + return rows + + +def full_structures(doc_id: str, fragment_ids: list[str]) -> list[dict]: + from app.services.chem import writers + s = STORE.get(doc_id) + derived = STORE.derive_now(doc_id) + with s.lock: + doc = copy.deepcopy(s.doc) + found = (derived or {}).get("fragments") or {} + out = [] + for fid in fragment_ids: + obj = (doc.get("objects") or {}).get(fid) or {} + d = found.get(fid) or {} + row = {"id": fid, "name": obj.get("name"), "atoms": len(obj.get("atoms") or {}), "bonds": len(obj.get("bonds") or {}), + **{k: d.get(k) for k in FULL_FIELDS}, "warnings": list(d.get("warnings") or [])} + try: + mol = writers.export_document(doc, "molfile", "selection", None, [fid]) + row["molfile"], row["molfile_version"] = mol.text, "V3000" if mol.format == "molfile3000" else "V2000" + row["warnings"].extend({"code": r.get("code"), "text": r.get("text")} for r in mol.report if r.get("severity") != "info") + except writers.ExportError as exc: + row["molfile"], row["molfile_version"] = None, None + row["warnings"].append({"code": "molfile", "text": f"No molfile: {exc}"}) + out.append(row) + return out + + +def row_line(r: dict) -> str: + if r.get("gone"): + return f"- {r['id']}: no longer in the drawing" + if r.get("kind") != "fragment": + return f"- {r['id']}: {r.get('kind')}" + (f" holding {', '.join(r['fragments'])}" if r.get("fragments") else "") + parts = [r.get("formula") or "no formula", r.get("smiles") or "no SMILES", r.get("inchikey") or "no InChIKey", f"{r['atoms']} atom{'' if r['atoms'] == 1 else 's'}"] + line = f"- {r['id']}" + (f" \"{r['name']}\"" if r.get("name") else "") + ": " + " · ".join(parts) + notes = [w.get("text", "") for w in r.get("warnings") or [] if isinstance(w, dict) and w.get("text")] + if notes: + line += " · " + "; ".join(notes[:4]) + (f" (+{len(notes) - 4} more)" if len(notes) > 4 else "") + return line + + +def _fragment_mol(frag: dict, expansions: dict | None): + from app.services.chem import convert, perceive + try: + return perceive.prepare(frag, expansions).mol + except Exception: + return convert.to_mol(frag, expansions).mol + + +def engine_picture(doc: dict, ids: list[str], fmt: str, size: dict | None = None) -> dict: + from rdkit import Chem + from app.services.chem import depict + size = size or {} + objects = doc.get("objects") or {} + frags = [f for f in fragments_in(doc, ids) if objects[f].get("atoms")] + if not frags: + raise RenderError("There is no structure to draw there; the engine draws structures only. Open the FormChem window to draw arrows and text, or pick fragment ids.") + expansions = doc.get("expansions") or {} + mol = None + for fid in frags: + part = _fragment_mol(objects[fid], expansions) + mol = Chem.Mol(part) if mol is None else Chem.CombineMols(mol, part) + w, h = size.get("width"), size.get("height") + dpi = int(size.get("dpi") or depict.PNG_DPI) + mime = MIME[fmt] + + def draw(box: tuple[int, int]) -> bytes: + return depict.svg(mol, box).encode("utf-8") if fmt == "svg" else depict.png(mol, box, dpi=dpi) + + if (w or h) and not size.get("dpi"): + data = draw((int(w or h), int(h or w))) + else: + data = draw((-1, -1)) + dims = _dimensions(data, mime) + k = min(w / dims["width"] if w and dims["width"] else 1.0, h / dims["height"] if h and dims["height"] else 1.0) + if k < 1: + data = draw((max(16, int(dims["width"] * k)), max(16, int(dims["height"] * k)))) + left = [i for i in _flat(doc, ids) if objects[i].get("kind") not in ("fragment", "group")] + warnings = [f"The engine draws structures only; {len(left)} other object{'' if len(left) == 1 else 's'} (arrows, plus signs, text) " + "were left out. With the FormChem window open, render draws them too."] if left else [] + return {"bytes": data, "mime": mime, "renderer": "engine", "warnings": warnings, "ids": frags, **_dimensions(data, mime)} + + +def _dimensions(data: bytes, mime: str) -> dict: + if mime == "image/png" and data[:8] == b"\x89PNG\r\n\x1a\n": + w, h = struct.unpack(">II", data[16:24]) + return {"width": w, "height": h} + m = re.search(rb"]*?\bwidth=['\"]([\d.]+)[a-z]*['\"][^>]*?\bheight=['\"]([\d.]+)", data[:2000]) + return {"width": round(float(m.group(1))), "height": round(float(m.group(2)))} if m else {"width": None, "height": None} + + +def _snapshot(doc_id: str) -> tuple[dict, dict | None]: + try: + s = STORE.get(doc_id) + except KeyError: + raise RenderError(f"No open drawing has the id {doc_id}. list_open_documents lists them.") from None + derived = STORE.derive_now(doc_id) + with s.lock: + return copy.deepcopy(s.doc), derived + + +def _size(size: dict | None) -> dict: + out = {} + for key, low, high in (("width", 16, 8192), ("height", 16, 8192), ("dpi", 18, 1200)): + v = (size or {}).get(key) + if v is None: + continue + if isinstance(v, bool) or not isinstance(v, (int, float)) or not low <= v <= high: + raise RenderError(f"{key} must be a number from {low} to {high}.") + out[key] = int(v) + return out + + +async def selection(doc_id: str | None = None) -> dict: + if not bridge.window_connected(): + raise RenderError("The selection lives in the FormChem window and none is open. Give object ids instead, or ask the person to open FormChem.") + out = await bridge.window_call("selection", {}, doc_id, WINDOW_WAIT) + if not out or out.get("isError"): + raise RenderError(_text(out) or "No FormChem window answered with its selection. Retry, or give object ids.") + return out.get("structuredContent") or {} + + +def _text(out: dict | None) -> str: + return " ".join(c.get("text", "") for c in (out or {}).get("content") or [] if isinstance(c, dict)).strip() + + +async def render_image(doc_id: str, scope: str = "object", ids: list[str] | None = None, fmt: str = "png", size: dict | None = None) -> dict: + if scope not in SCOPES: + raise RenderError(f"scope is {', '.join(SCOPES)}.") + if fmt not in FORMATS: + raise RenderError(f"format is {' or '.join(FORMATS)}.") + size = _size(size) + doc, derived = await asyncio.to_thread(_snapshot, doc_id) + objects = doc.get("objects") or {} + ids = [i for i in ids or [] if isinstance(i, str)] + if scope == "object": + if not ids: + raise RenderError("Give ids (object ids from get_structure or list_open_documents), or scope page or selection.") + missing = [i for i in ids if i not in objects] + if missing: + raise RenderError(f"{', '.join(missing[:6])} {'is' if len(missing) == 1 else 'are'} not in the drawing {doc_id}. get_structure lists its objects.") + page = page_of(doc, ids if scope == "object" else None) + if page is None: + raise RenderError(f"The drawing {doc_id} has no page.") + if scope == "page": + ids = [i for i in page.get("order") or [] if i in objects and not objects[i].get("hidden")] + if not ids: + raise RenderError("The page is empty; draw something first (draw_from_smiles).") + if scope == "selection": + found = await selection(doc_id) + if found.get("doc") != doc_id or not found.get("ids"): + raise RenderError("Nothing of this drawing is selected in the FormChem window. Ask the person to select it, or give ids.") + ids = list(found["ids"]) + warnings: list[str] = [] + if bridge.window_connected(): + args = {"doc": doc, "derived": derived, "page": page.get("id"), "ids": None if scope == "page" else ids, "format": fmt, **size} + out = await bridge.window_call("render", args, doc_id, WINDOW_WAIT) + data = (out or {}).get("structuredContent") or {} + if out and not out.get("isError") and (data.get("base64") or data.get("svg")): + raw = data["svg"].encode("utf-8") if fmt == "svg" else base64.b64decode(data["base64"]) + return {"bytes": raw, "mime": MIME[fmt], "renderer": "window", "width": data.get("width"), "height": data.get("height"), + "warnings": list(data.get("warnings") or []), "ids": list(data.get("ids") or ids)} + warnings.append(f"The window did not draw it ({_text(out) or 'no answer'}); the engine drew it instead.") + fallback = {**size} + if "dpi" not in fallback and "width" not in fallback and "height" not in fallback: + fallback["dpi"] = ENGINE_DPI + pic = await asyncio.to_thread(engine_picture, doc, ids, fmt, fallback) + pic["warnings"] = warnings + pic["warnings"] + return pic + + +async def write_result(doc_id: str, tx: dict | None, ids: list[str], text: str = "", extra: dict | None = None) -> dict: + rows = await asyncio.to_thread(structure_of, doc_id, ids) + live = [r["id"] for r in rows if not r.get("gone") and r["id"] in ids] + picture, note = None, "" + if live: + try: + picture = await render_image(doc_id, "object", live, "png", RESULT_SIZE) + except RenderError as exc: + note = f"No picture: {exc}" + rev = tx["rev"] if tx else STORE.get(doc_id).rev + head = text or (f"Changed {doc_id}" if tx else f"No change to {doc_id}") + lines = [head.rstrip(". ") + (f" (rev {rev}, one undo step)." if tx else ".")] + lines.extend(row_line(r) for r in rows) + if picture: + lines.append(f"Picture: {picture['width']} x {picture['height']} PNG drawn by the {picture['renderer']}." + "".join(f" {w}" for w in picture["warnings"])) + elif note: + lines.append(note) + content = [{"type": "text", "text": "\n".join(lines)}] + if picture: + content.append({"type": "image", "data": base64.b64encode(picture["bytes"]).decode("ascii"), "mimeType": picture["mime"]}) + data = {"doc": doc_id, "rev": rev, "changed": bool(tx), "undo": "one step" if tx else None, "objects": rows, + "image": {k: picture[k] for k in ("renderer", "mime", "width", "height", "warnings")} if picture else None, **(extra or {})} + return {"content": content, "structuredContent": data} + + +def _page_size(page: dict) -> tuple[float, float] | None: + size = page.get("size") + if isinstance(size, dict) and isinstance(size.get("w"), (int, float)) and isinstance(size.get("h"), (int, float)): + return float(size["w"]), float(size["h"]) + return None + + +def free_spot(doc: dict, page_id: str | None, w: float, h: float) -> tuple[float, float]: + page = page_of(doc, None, page_id) or {} + style = model.resolve_style(doc) + bond = float(style.get("bond_length") or DEFAULT_BOND_LENGTH) + margin = float(page.get("margins", 36) or 0) + gap = GAP_BONDS * bond + box = geometry.union([geometry.object_box(doc, oid, style) for oid in page.get("order") or [] if isinstance(oid, str)]) + if box is None: + return round(margin + FIRST_BONDS * bond, 3), round(margin + FIRST_BONDS * bond, 3) + size = _page_size(page) + right = box[2] + gap + objects = doc.get("objects") or {} + arrows = any((objects.get(oid) or {}).get("kind") == "arrow" for oid in _flat(doc, page.get("order") or [])) + if not arrows and (size is None or right + w <= size[0] - margin): + return round(right, 3), round(box[1], 3) + return round(max(margin, box[0]), 3), round(box[3] + gap, 3) diff --git a/backend/app/services/batch.py b/backend/app/services/batch.py new file mode 100644 index 00000000..25b440f6 --- /dev/null +++ b/backend/app/services/batch.py @@ -0,0 +1,444 @@ +import csv +import multiprocessing +import re +import sys +import time +from collections import Counter +from dataclasses import dataclass, field, replace +from itertools import chain, islice +from pathlib import Path +from typing import Iterable, Iterator + +from rdkit import Chem + +from app.services.chem import depict, ids, props, records, standardise +from app.services.chem.records import Record + +CHUNK = 1000 +MAX_DOCUMENT = 1000 +EXT = { + "smiles": ".smi", "cxsmiles": ".cxsmi", "sdf": ".sdf", "molfile": ".mol", "inchi": ".inchi", "inchikey": ".inchikey", + "cml": ".cml", "rxn": ".rxn", "rsmiles": ".rsmi", "fchem": ".fchem", +} +ONE_PER_FILE = ("molfile", "cml", "rxn") +REPORT_FIELDS = ("file", "record", "name", "status", "message") +EXTRA_COLUMNS = ( + ("inchi", "InChI", "rdinchi.MolToInchi (InChI 1.07 standard)"), + ("inchikey", "InChIKey", "Chem.InchiToInchiKey"), + ("lipinski_violations", "Lipinski violations", "MW <= 500, cLogP <= 5, HBD <= 5, HBA <= 10; one allowed"), + ("veber_violations", "Veber violations", "rotatable bonds <= 10, TPSA <= 140"), +) + + +class BadArguments(ValueError): + pass + + +@dataclass +class Options: + to: str + source: str | None = None + steps: list[str] = field(default_factory=list) + v3000: bool = False + jobs: int = 1 + task: str = "convert" + keys: list[str] = field(default_factory=list) + out_dir: str = "" + size: tuple[int, int] = (-1, -1) + transparent: bool = False + + +@dataclass +class Summary: + source: str + target: str + format_in: str = "" + format_out: str = "" + records: int = 0 + written: int = 0 + failed: int = 0 + warned: int = 0 + seconds: float = 0.0 + jobs: int = 1 + rows: list[dict] = field(default_factory=list) + outputs: list[str] = field(default_factory=list) + changed: Counter = field(default_factory=Counter) + + def add(self, rows: list[dict], n: int, ok: int, changed: Counter) -> None: + self.records += n + self.written += ok + self.rows.extend(rows) + self.failed += sum(1 for r in rows if r["status"] == "failed") + self.warned += sum(1 for r in rows if r["status"] == "warning") + self.changed.update(changed) + + +def row(file: str, index: int | None, name: str, status: str, message: str) -> dict: + return {"file": file, "record": "" if index is None else index + 1, "name": name, "status": status, "message": message} + + +def _standard(rec: Record, opts: Options, file: str) -> tuple[Chem.Mol | None, list[dict], list[str]]: + mol, rows, changed = rec.mol, [], [] + if not opts.steps: + return mol, rows, changed + try: + mol, report = standardise.standardise_mol(mol, opts.steps) + except Exception as exc: + return None, [row(file, rec.index, rec.name, "failed", f"standardise: {exc}")], [] + for r in report: + if r.get("error"): + rows.append(row(file, rec.index, rec.name, "warning", f"{r['label']}: {r['error']}")) + elif r["changed"]: + changed.append(r["step"]) + return mol, rows, changed + + +def descriptor_columns() -> list[tuple[str, str, str, str]]: + out = [(k, label, unit, method) for k, label, unit, method, _note in props.ROWS] + return out + [(k, label, "", method) for k, label, method in EXTRA_COLUMNS] + + +def parse_props(text: str | None) -> list[str]: + known = [k for k, *_ in descriptor_columns()] + if not text or text.strip().lower() == "default": + return [k for k, *_ in props.ROWS] + words = [w.strip().lower() for w in text.replace(";", ",").split(",") if w.strip()] + if words == ["all"]: + return known + bad = [w for w in words if w not in known] + if bad: + raise BadArguments(f"unknown descriptor {bad[0]}; run ./formchem descriptors --list for the names") + return [w for w in dict.fromkeys(words) if w != "smiles"] + + +def _describe(rec: Record, opts: Options, file: str) -> tuple[dict | None, list[dict], list[str]]: + if rec.error: + return None, [row(file, rec.index, rec.name, "failed", rec.error)], [] + if rec.mol is None: + return None, [row(file, rec.index, rec.name, "failed", "a reaction has no descriptors; give single structures")], [] + mol, rows, changed = _standard(rec, opts, file) + if mol is None: + return None, rows, changed + try: + values, notes = props.measure(mol) + except Exception as exc: + return None, rows + [row(file, rec.index, rec.name, "failed", f"{type(exc).__name__}: {exc}")], changed + rows.extend(row(file, rec.index, rec.name, "warning", n["text"]) for n in notes) + out = {"record": rec.index + 1, "name": rec.name, "smiles": ids.smiles(ids.identifier_mol(mol))} + if {"inchi", "inchikey"} & set(opts.keys): + text, key, _notes = ids.inchi(ids.identifier_mol(mol)) + values["inchi"], values["inchikey"] = text, key + values["lipinski_violations"] = sum(1 for k, limit in props.LIPINSKI if values.get(k) is None or values[k] > limit) + values["veber_violations"] = sum(1 for k, limit in props.VEBER if values.get(k) is None or values[k] > limit) + out.update((k, values.get(k)) for k in opts.keys) + return out, rows, changed + + +def _safe(name: str) -> str: + return re.sub(r"[^A-Za-z0-9._-]+", "_", name).strip("._")[:60] + + +def _render(rec: Record, opts: Options, file: str) -> tuple[str | None, list[dict], list[str]]: + if rec.error: + return None, [row(file, rec.index, rec.name, "failed", rec.error)], [] + reaction = getattr(rec, "reaction", None) + item, rows, changed = (reaction, [], []) if reaction is not None else _standard(rec, opts, file) + if item is None: + return None, rows, changed + stem = f"{rec.index + 1:05d}" + (f"-{_safe(rec.name)}" if _safe(rec.name) else "") + path = Path(opts.out_dir) / f"{stem}.{opts.to}" + try: + if opts.to == "png": + path.write_bytes(depict.png(item, opts.size, transparent=opts.transparent)) + else: + path.write_text(depict.svg(item, opts.size, transparent=opts.transparent), encoding="utf-8") + except Exception as exc: + return None, rows + [row(file, rec.index, rec.name, "failed", f"{type(exc).__name__}: {exc}")], changed + return str(path), rows, changed + + +def _process(rec: Record, opts: Options, file: str) -> tuple[object, list[dict], list[str]]: + if opts.task == "describe": + return _describe(rec, opts, file) + if opts.task == "render": + return _render(rec, opts, file) + return _payload(rec, opts, file) + + +def _payload(rec: Record, opts: Options, file: str) -> tuple[str | Record | None, list[dict], list[str]]: + if rec.error: + return None, [row(file, rec.index, rec.name, "failed", rec.error)], [] + reaction = getattr(rec, "reaction", None) + if reaction is not None: + try: + return records.reaction_text(reaction, opts.to, rec.name), [], [] + except Exception as exc: + return None, [row(file, rec.index, rec.name, "failed", str(exc))], [] + if opts.to in records.REACTIONS: + return None, [row(file, rec.index, rec.name, "failed", "a single structure is not a reaction; write it as sdf, smiles or molfile")], [] + mol, rows, changed = _standard(rec, opts, file) + if mol is None: + return None, rows, changed + if opts.to == "fchem": + return Record(rec.index, mol, rec.name, rec.data), rows, changed + try: + return records.mol_text(mol, opts.to, rec.name, rec.data, opts.v3000), rows, changed + except Exception as exc: + return None, rows + [row(file, rec.index, rec.name, "failed", str(exc))], changed + + +Result = tuple[list, list[dict], int, int, Counter] + + +def _run(items: Iterable[Record], opts: Options, file: str) -> Result: + out, rows, n, ok, changed = [], [], 0, 0, Counter() + for rec in items: + n += 1 + payload, found, steps = _process(rec, opts, file) + rows.extend(found) + changed.update(steps) + if payload is not None: + out.append(payload) + ok += 1 + return out, rows, n, ok, changed + + +def _chunk(task: tuple[str, str, int, Options, str]) -> Result: + fmt, text, start, opts, file = task + return _run(records.parse_chunk(fmt, text, start), opts, file) + + +class Sink: + def __init__(self, target: str, fmt: str, title: str): + self.target, self.fmt, self.title = target, fmt, title + self.paths: list[str] = [] + self.count = 0 + self.first: str | None = None + self.docs: list[Record] = [] + self.skipped = 0 + self.stream = None + if target == "-": + self.stream = sys.stdout + elif fmt not in ONE_PER_FILE and fmt != "fchem": + Path(target).parent.mkdir(parents=True, exist_ok=True) + self.stream = open(target, "w", encoding="utf-8", newline="\n") + self.paths.append(target) + + def _numbered(self, n: int) -> Path: + p = Path(self.target) + return p.with_name(f"{p.stem}-{n:04d}{p.suffix}") + + def write(self, payload: str | Record) -> bool: + self.count += 1 + if isinstance(payload, Record): + if len(self.docs) >= MAX_DOCUMENT: + self.skipped += 1 + return False + self.docs.append(payload) + return True + if self.stream is not None: + self.stream.write(payload) + return True + if self.count == 1: + self.first = payload + return True + if self.count == 2: + self._save(self._numbered(1), self.first or "") + self.first = None + self._save(self._numbered(self.count), payload) + return True + + def _save(self, p: Path, text: str) -> None: + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(text, encoding="utf-8", newline="\n") + self.paths.append(str(p)) + + def close(self) -> None: + if self.first is not None: + self._save(Path(self.target), self.first) + if self.fmt == "fchem" and self.docs: + if self.target == "-": + raise BadArguments("a FormChem document cannot be written to the terminal; give a file name") + Path(self.target).parent.mkdir(parents=True, exist_ok=True) + records.write_document(self.target, self.docs, self.title) + self.paths.append(self.target) + if self.stream is not None and self.stream is not sys.stdout: + self.stream.close() + if not self.count: + Path(self.target).unlink(missing_ok=True) + self.paths.remove(self.target) + elif self.stream is sys.stdout: + sys.stdout.flush() + + +def formats(src: str | Path, dst: str, opts: Options) -> tuple[str, str]: + fin = records.format_of(src, opts.source) + fout = records.format_of(dst if dst != "-" else "", opts.to) + if fin not in records.READ: + raise BadArguments(f"cannot tell the format of {Path(str(src)).name}; give --from ({', '.join(records.READ)})") + if fout not in records.WRITE: + what = "to the terminal without --to" if dst == "-" and not fout else (fout or Path(dst).suffix or "that") + raise BadArguments(f"cannot write {what}; give --to ({', '.join(records.WRITE)})") + return fin, fout + + +def _results(src: Path, fin: str, opts: Options, file: str, summary: Summary) -> Iterator[Result]: + if fin not in records.STREAMED: + yield _run(records.iter_records(src, fin), opts, file) + return + tasks = ((fin, text, start, opts, file) for start, text in records.chunks(src, fin, CHUNK)) + jobs = max(1, opts.jobs) + if jobs == 1: + yield from map(_chunk, tasks) + return + head = list(islice(tasks, 2)) + if len(head) < 2: + yield from map(_chunk, head) + return + summary.jobs = jobs + with multiprocessing.get_context().Pool(jobs) as pool: + yield from pool.imap(_chunk, chain(head, tasks)) + + +def convert_file(src: str | Path, dst: str, opts: Options) -> Summary: + t0 = time.perf_counter() + src = Path(src) + fin, fout = formats(src, dst, opts) + if not src.is_file(): + raise BadArguments(f"{src} is not a file") + if dst != "-" and Path(dst).resolve() == src.resolve(): + raise BadArguments("the output would overwrite the input; choose another name") + opts = replace(opts, to=fout, source=fin, task="convert") + summary = Summary(str(src), dst, fin, fout) + sink = Sink(dst, fout, src.stem.split(".")[0]) + file = src.name + try: + for out, rows, n, ok, changed in _results(src, fin, opts, file, summary): + for payload in out: + sink.write(payload) + summary.add(rows, n, ok, changed) + except BadArguments: + raise + except Exception as exc: + summary.rows.append(row(file, None, "", "failed", f"{type(exc).__name__}: {exc}")) + summary.failed += 1 + finally: + sink.close() + if sink.skipped: + summary.written -= sink.skipped + summary.rows.append(row(file, None, "", "failed", f"{sink.skipped} records left out: a FormChem document here holds at most {MAX_DOCUMENT} structures")) + summary.failed += sink.skipped + summary.outputs = sink.paths + summary.seconds = time.perf_counter() - t0 + return summary + + +def _convert_task(task: tuple[str, str, Options]) -> Summary: + src, dst, opts = task + try: + return convert_file(src, dst, opts) + except Exception as exc: + s = Summary(src, dst) + s.rows.append(row(Path(src).name, None, "", "failed", str(exc))) + s.failed = 1 + return s + + +def batch_files(folder: str | Path, out: str | Path | None, recursive: bool = False) -> tuple[Path, list[Path]]: + folder = Path(folder) + if not folder.is_dir(): + raise BadArguments(f"{folder} is not a folder") + target = Path(out) if out else folder / "converted" + found = folder.rglob("*") if recursive else folder.iterdir() + files = sorted(p for p in found if p.is_file() and records.format_of(p) in records.READ and target.resolve() not in p.resolve().parents) + return target, files + + +def batch(folder: str | Path, opts: Options, out: str | Path | None = None, recursive: bool = False) -> list[Summary]: + target, files = batch_files(folder, out, recursive) + fout = records.format_of("", opts.to) + if fout not in records.WRITE: + raise BadArguments(f"cannot write {opts.to}; give --to ({', '.join(records.WRITE)})") + taken: set[str] = set() + tasks = [] + for p in files: + rel = p.relative_to(Path(folder)).parent + name = p.name[: -len(".gz")] if p.name.lower().endswith(".gz") else p.name + stem, ext = Path(name).stem, Path(name).suffix.lstrip(".").lower() + dst = target / rel / f"{stem}{EXT[fout]}" + if str(dst) in taken: + dst = target / rel / f"{stem}-{ext}{EXT[fout]}" + taken.add(str(dst)) + tasks.append((str(p), str(dst), replace(opts, to=fout, source=None, jobs=1))) + jobs = max(1, opts.jobs) + if jobs > 1 and len(tasks) > 1: + with multiprocessing.get_context().Pool(min(jobs, len(tasks))) as pool: + return list(pool.imap(_convert_task, tasks)) + if len(tasks) == 1: + tasks[0] = (tasks[0][0], tasks[0][1], replace(tasks[0][2], jobs=jobs)) + return [_convert_task(t) for t in tasks] + + +def _source(src: str | Path, opts: Options) -> tuple[Path, str]: + src = Path(src) + fin = records.format_of(src, opts.source) + if fin not in records.READ: + raise BadArguments(f"cannot tell the format of {src.name}; give --from ({', '.join(records.READ)})") + if not src.is_file(): + raise BadArguments(f"{src} is not a file") + return src, fin + + +def _drain(src: Path, fin: str, opts: Options, summary: Summary, take) -> None: + try: + for out, rows, n, ok, changed in _results(src, fin, opts, src.name, summary): + take(out) + summary.add(rows, n, ok, changed) + except BadArguments: + raise + except Exception as exc: + summary.rows.append(row(src.name, None, "", "failed", f"{type(exc).__name__}: {exc}")) + summary.failed += 1 + + +def descriptors_file(src: str | Path, dst: str, opts: Options) -> Summary: + t0 = time.perf_counter() + src, fin = _source(src, opts) + opts = replace(opts, source=fin, task="describe", keys=opts.keys or parse_props(None)) + summary = Summary(str(src), dst, fin, "csv") + stream = sys.stdout if dst == "-" else None + if stream is None: + Path(dst).parent.mkdir(parents=True, exist_ok=True) + stream = open(dst, "w", encoding="utf-8", newline="") + try: + w = csv.DictWriter(stream, fieldnames=["record", "name", "smiles", *opts.keys], extrasaction="ignore") + w.writeheader() + _drain(src, fin, opts, summary, w.writerows) + finally: + if stream is not sys.stdout: + stream.close() + summary.outputs = [] if dst == "-" else [dst] + summary.seconds = time.perf_counter() - t0 + return summary + + +def render_file(src: str | Path, out_dir: str | Path, opts: Options) -> Summary: + t0 = time.perf_counter() + src, fin = _source(src, opts) + if opts.to not in depict.FORMATS: + raise BadArguments(f"render writes {' or '.join(depict.FORMATS)}, not {opts.to}") + Path(out_dir).mkdir(parents=True, exist_ok=True) + opts = replace(opts, source=fin, task="render", out_dir=str(out_dir)) + summary = Summary(str(src), str(out_dir), fin, opts.to) + _drain(src, fin, opts, summary, summary.outputs.extend) + summary.seconds = time.perf_counter() - t0 + return summary + + +def write_report(path: str | Path, rows: list[dict], fields: tuple[str, ...] = REPORT_FIELDS) -> None: + p = Path(path) + p.parent.mkdir(parents=True, exist_ok=True) + with open(p, "w", encoding="utf-8", newline="") as fh: + w = csv.DictWriter(fh, fieldnames=list(fields), extrasaction="ignore") + w.writeheader() + w.writerows(rows) diff --git a/backend/app/services/bridge.py b/backend/app/services/bridge.py index 981bacd0..ba6ec84c 100644 --- a/backend/app/services/bridge.py +++ b/backend/app/services/bridge.py @@ -5,7 +5,7 @@ from app.services.hub import HUB -READ_ONLY: frozenset[str] = frozenset() +READ_ONLY: frozenset[str] = frozenset({"render", "selection"}) def windows(doc: str | None = None) -> list: diff --git a/backend/app/services/chem/cdxio.py b/backend/app/services/chem/cdxio.py new file mode 100644 index 00000000..024da170 --- /dev/null +++ b/backend/app/services/chem/cdxio.py @@ -0,0 +1,452 @@ +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 +from app.services.model import ELEMENTS + +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", "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"), + "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 ("loadMolecule", "loadReaction", "loadQueryMolecule", "loadQueryReaction"): + 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: + size = round(float(digits) / PX_PER_PT, 2) + if abs(size - geometry.DEFAULT_FONT) > 0.05: + marks[i]["size"] = size + 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) + 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)) + 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) + 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) + last = None + for name in loaders: + try: + ket = json.loads(getattr(ind, name)(block).json()) + 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) + 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}) + 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") + 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 + 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(): + 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"]) + 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): + 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.")) + 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/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 diff --git a/backend/app/services/chem/depict.py b/backend/app/services/chem/depict.py new file mode 100644 index 00000000..655e880a --- /dev/null +++ b/backend/app/services/chem/depict.py @@ -0,0 +1,147 @@ +import os +import re +import struct +import zlib +from dataclasses import dataclass +from pathlib import Path + +from rdkit import Chem +from rdkit.Chem import rdChemReactions, rdDepictor +from rdkit.Chem.Draw import rdMolDraw2D + +FORMATS = ("svg", "png") +PNG_DPI = 300 +POINTS_PER_INCH = 72.0 +FONT_NAME = "Arimo-VariableFont_wght.ttf" +MOL_BOND = 1.5 + + +@dataclass(frozen=True) +class Style: + bond_length: float = 14.4 + line_width: float = 0.6 + bond_spacing: float = 0.18 + font_size: float = 10.0 + label_padding: float = 0.08 + padding: float = 0.06 + + +JOURNAL = Style() + + +def font_file() -> str | None: + roots = [os.environ.get("FORMCHEM_DIST"), os.environ.get("FORMCHEM_FONTS")] + here = Path(__file__).resolve() + roots += [str(here.parents[4] / "frontend" / "public"), str(here.parents[4] / "frontend" / "dist")] + for root in filter(None, roots): + for p in (Path(root) / "fonts" / FONT_NAME, Path(root) / FONT_NAME): + if p.is_file(): + return str(p) + return None + + +def _options(d: rdMolDraw2D.MolDraw2D, style: Style, scale: float, transparent: bool) -> None: + o = d.drawOptions() + o.useBWAtomPalette() + o.fixedBondLength = style.bond_length * scale + o.scalingFactor = style.bond_length * scale / MOL_BOND + o.bondLineWidth = style.line_width * scale + o.scaleBondWidth = False + o.multipleBondOffset = style.bond_spacing + o.fixedFontSize = max(1, round(style.font_size * scale)) + o.minFontSize = max(1, round(style.font_size * scale * 0.5)) + o.maxFontSize = max(2, round(style.font_size * scale * 2)) + o.additionalAtomLabelPadding = style.label_padding + o.padding = style.padding + o.clearBackground = not transparent + found = font_file() + if found: + o.fontFile = found + + +def _size(text: str | None) -> tuple[int, int]: + if not text: + return -1, -1 + m = re.fullmatch(r"\s*(\d+)\s*(?:[x,]\s*(\d+))?\s*", text) + if not m: + raise ValueError("size must be WIDTH or WIDTHxHEIGHT in pixels, for example 400 or 600x300") + w = int(m.group(1)) + h = int(m.group(2) or m.group(1)) + if not (16 <= w <= 10000 and 16 <= h <= 10000): + raise ValueError("size must be between 16 and 10000 pixels") + return w, h + + +def parse_size(text: str | None) -> tuple[int, int]: + return _size(text) + + +def _prepared(mol: Chem.Mol) -> Chem.Mol: + out = Chem.Mol(mol) + if not out.GetNumConformers() or out.GetConformer().Is3D(): + if out.GetNumConformers(): + Chem.AssignStereochemistryFrom3D(out) + rdDepictor.Compute2DCoords(out) + conf = out.GetConformer() + lengths = sorted((conf.GetAtomPosition(b.GetBeginAtomIdx()) - conf.GetAtomPosition(b.GetEndAtomIdx())).Length() for b in out.GetBonds()) + lengths = [x for x in lengths if x > 1e-4] + if lengths: + k = MOL_BOND / lengths[len(lengths) // 2] + for i in range(out.GetNumAtoms()): + p = conf.GetAtomPosition(i) + conf.SetAtomPosition(i, (p.x * k, p.y * k, 0.0)) + return out + + +def _reaction_size(rxn: rdChemReactions.ChemicalReaction, style: Style, scale: float) -> tuple[int, int]: + heavy = sum(t.GetNumAtoms() for t in list(rxn.GetReactants()) + list(rxn.GetProducts())) + w = int((heavy * 1.1 + 8) * style.bond_length * scale) + return max(200, min(w, 6000)), max(120, int(8 * style.bond_length * scale)) + + +def _draw(d: rdMolDraw2D.MolDraw2D, item: Chem.Mol | rdChemReactions.ChemicalReaction, legend: str) -> None: + if isinstance(item, rdChemReactions.ChemicalReaction): + d.DrawReaction(item) + else: + d.DrawMolecule(_prepared(item), legend=legend) + d.FinishDrawing() + + +def svg(item: Chem.Mol | rdChemReactions.ChemicalReaction, size: tuple[int, int] = (-1, -1), legend: str = "", style: Style = JOURNAL, + transparent: bool = False) -> str: + w, h = size + if isinstance(item, rdChemReactions.ChemicalReaction) and w < 0: + w, h = _reaction_size(item, style, 1.0) + if not isinstance(item, rdChemReactions.ChemicalReaction) and not item.GetNumAtoms(): + raise ValueError("the structure has no atoms") + d = rdMolDraw2D.MolDraw2DSVG(w, h) + _options(d, style, 1.0, transparent) + _draw(d, item, legend) + text = d.GetDrawingText() + if size[0] < 0: + text = re.sub(r"(]*?\bwidth=['\"])([\d.]+)px(['\"][^>]*?\bheight=['\"])([\d.]+)px", r"\g<1>\g<2>pt\g<3>\g<4>pt", text, count=1) + return text + + +def _png_dpi(data: bytes, dpi: int) -> bytes: + if data[:8] != b"\x89PNG\r\n\x1a\n" or b"pHYs" in data[:256]: + return data + per_metre = round(dpi / 0.0254) + body = b"pHYs" + struct.pack(">IIB", per_metre, per_metre, 1) + chunk = struct.pack(">I", 9) + body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF) + end = 8 + 8 + 13 + 4 + return data[:end] + chunk + data[end:] + + +def png(item: Chem.Mol | rdChemReactions.ChemicalReaction, size: tuple[int, int] = (-1, -1), legend: str = "", style: Style = JOURNAL, + dpi: int = PNG_DPI, transparent: bool = False) -> bytes: + scale = dpi / POINTS_PER_INCH + w, h = size + if isinstance(item, rdChemReactions.ChemicalReaction) and w < 0: + w, h = _reaction_size(item, style, scale) + if not isinstance(item, rdChemReactions.ChemicalReaction) and not item.GetNumAtoms(): + raise ValueError("the structure has no atoms") + d = rdMolDraw2D.MolDraw2DCairo(w, h) + _options(d, style, scale, transparent) + _draw(d, item, legend) + return _png_dpi(d.GetDrawingText(), dpi) diff --git a/backend/app/services/chem/formats.py b/backend/app/services/chem/formats.py new file mode 100644 index 00000000..e0fce8ba --- /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": ["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": ["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", + "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} diff --git a/backend/app/services/chem/geometry.py b/backend/app/services/chem/geometry.py index 69a53cdb..ac8dc2b0 100644 --- a/backend/app/services/chem/geometry.py +++ b/backend/app/services/chem/geometry.py @@ -6,6 +6,7 @@ LINE_HEIGHT = 1.2 LABEL_PAD = 0.4 DEFAULT_FONT = 10.0 +HYDRIDE_FIRST = {"O", "S", "Se", "Te", "F", "Cl", "Br", "I"} def _num(v: object) -> bool: @@ -47,7 +48,13 @@ def fragment_box(frag: dict, style: dict) -> Box | None: if a.get("element") != "C" or a.get("label") or a.get("show_carbon") == "always" or len(atoms) == 1: shown = str(a.get("label") or a.get("element") or "") half = max(1, len(shown)) * size * TEXT_ADVANCE / 2 + LABEL_PAD - boxes.append((a["x"] - half, a["y"] - size * 0.6, a["x"] + half, a["y"] + size * 0.6)) + left = right = half + if len(atoms) == 1 and not a.get("label") and a.get("element") not in ("H", "*", "R#"): + if a.get("element") in HYDRIDE_FIRST: + left += 2 * size * TEXT_ADVANCE + else: + right += 2 * size * TEXT_ADVANCE + boxes.append((a["x"] - left, a["y"] - size * 0.6, a["x"] + right, a["y"] + size * 0.6)) else: boxes.append((a["x"], a["y"], a["x"], a["y"])) return union(boxes) diff --git a/backend/app/services/chem/io.py b/backend/app/services/chem/io.py index a0d35a17..38fe19a9 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,46 +217,143 @@ 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 _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(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 _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) if total > max_records: - res.warnings.append(warning("truncated", f"Read the first {max_records} of {total} records.")) + res.warnings.append(counted("truncated", f"Read the first {max_records} of {total} records.", total - max_records)) 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,125 @@ 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: + 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)) + + +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: - 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) + 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()): - 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.")) + mol = amide_form(mol) + 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 +536,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 +601,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 +669,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") 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 + 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 +794,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 +869,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) diff --git a/backend/app/services/chem/layout.py b/backend/app/services/chem/layout.py index 9e87193c..bfa12565 100644 --- a/backend/app/services/chem/layout.py +++ b/backend/app/services/chem/layout.py @@ -3,27 +3,106 @@ 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, warning +from app.services.chem import DEFAULT_BOND_LENGTH, convert, layout_refine, layout_score, warning Point = tuple[float, float] -def depict(mol: Chem.Mol, fixed: dict[int, Point] | None = None) -> None: +CANDIDATE_LIMIT = 300 +SCORE_LIMIT = 600 +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 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: + 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() or not all(math.isfinite(c) for p in m.GetConformer().GetPositions() for c in p): + continue + yield name, m + if fixed or n < 3: + continue + straight = Chem.Mol(m) + try: + rdDepictor.StraightenDepiction(straight) + except Exception: + continue + yield name + "-straight", straight + + +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 - 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: + 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, clearConfs=True) + return None + shape = 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) + 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) + rdDepictor.Compute2DCoords(mol, coordMap=coord_map, clearConfs=True) + return None + 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] 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): + 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(conf, assignId=True) + score.parts["method"] = name + return score def _fit(src: list[Point], dst: list[Point], reflect: bool) -> tuple[float, callable]: @@ -151,7 +230,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] @@ -162,6 +244,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 or len(atoms) > SCORE_LIMIT: + 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 {}, [] 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 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)) diff --git a/backend/app/services/chem/props.py b/backend/app/services/chem/props.py index d1ca05b8..a7d3140d 100644 --- a/backend/app/services/chem/props.py +++ b/backend/app/services/chem/props.py @@ -44,20 +44,16 @@ def _stereo_counts(mol: Chem.Mol, conv) -> tuple[int, int]: return len(found), sum(1 for si in found if si.specified != Chem.StereoSpecified.Specified) -def compute(frag: dict, expansions: dict | None = None) -> dict: - conv = perceive.prepare(frag, expansions) - mol = ids.identifier_mol(conv.mol) +def measure(whole: Chem.Mol, conv=None) -> tuple[dict, list[dict]]: + mol = ids.identifier_mol(whole) Chem.SanitizeMol(mol, Chem.SanitizeFlags.SANITIZE_ALL ^ Chem.SanitizeFlags.SANITIZE_PROPERTIES, catchErrors=True) mol.UpdatePropertyCache(strict=False) Chem.GetSymmSSSR(mol) - notes = [w for w in conv.warnings if w.get("code") in ("unknown_label", "abbreviation_bonds", "bad_expansion")] - excluded = sorted({conv.owner[a.GetIdx()] for a in conv.mol.GetAtoms() if a.GetAtomicNum() == 0}) - if excluded: - notes.append(warning("incomplete", f"{len(excluded)} label(s) or R-group(s) are not counted; descriptors treat them as dummy atoms.", excluded)) + notes: list[dict] = [] values: dict = { - "formula": ids.formula(conv.mol), - "mw": mass.average_mass(conv.mol), - "exact_mass": mass.exact_mass(conv.mol), + "formula": ids.formula(whole), + "mw": mass.average_mass(whole), + "exact_mass": mass.exact_mass(whole), "formal_charge": Chem.GetFormalCharge(mol), "heavy_atoms": mol.GetNumHeavyAtoms(), "pieces": len(Chem.GetMolFrags(mol, sanitizeFrags=False)), @@ -82,11 +78,22 @@ def compute(frag: dict, expansions: dict | None = None) -> dict: except Exception as exc: values[key] = None notes.append(warning("property_failed", f"{key} could not be computed: {exc}")) - values["stereocentres"], values["undefined_stereocentres"] = _stereo_counts(conv.mol, conv) + values["stereocentres"], values["undefined_stereocentres"] = _stereo_counts(whole, conv) for key, digits in ROUND.items(): if isinstance(values.get(key), float): values[key] = round(values[key], digits) - rows = [{"key": k, "label": label, "value": values.get(k), "unit": unit, "method": method, "note": note} for k, label, unit, method, note in ROWS] + return values, notes + + +def compute(frag: dict, expansions: dict | None = None) -> dict: + conv = perceive.prepare(frag, expansions) + notes = [w for w in conv.warnings if w.get("code") in ("unknown_label", "abbreviation_bonds", "bad_expansion")] + excluded = sorted({conv.owner[a.GetIdx()] for a in conv.mol.GetAtoms() if a.GetAtomicNum() == 0}) + if excluded: + notes.append(warning("incomplete", f"{len(excluded)} label(s) or R-group(s) are not counted; descriptors treat them as dummy atoms.", excluded)) + values, failed = measure(conv.mol, conv) + notes.extend(failed) + rows =[{"key": k, "label": label, "value": values.get(k), "unit": unit, "method": method, "note": note} for k, label, unit, method, note in ROWS] return { "rows": rows, "values": values, diff --git a/backend/app/services/chem/query.py b/backend/app/services/chem/query.py index e863d2ac..5da9744b 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 @@ -157,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"} @@ -276,12 +317,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) @@ -311,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(): @@ -331,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: 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" diff --git a/backend/app/services/chem/reactions.py b/backend/app/services/chem/reactions.py index 4f21a197..a5d8f067 100644 --- a/backend/app/services/chem/reactions.py +++ b/backend/app/services/chem/reactions.py @@ -146,7 +146,7 @@ def infer_step(doc: dict, page: dict, arrow_id: str, used: set[str] | None = Non for i in items: if i.role is None or not 0 <= i.s <= frame.length or i.gap() > BAND_BONDS * bl: continue - (conditions if i.role == "text" else agents).append(i) + (agents if i.role == "structure" else conditions).append(i) taken = {i.oid for i in agents + conditions} row = [i for i in items if i.oid not in taken and i.t1 >= -ROW_BONDS * bl and i.t0 <= ROW_BONDS * bl] tol = END_BONDS * bl diff --git a/backend/app/services/chem/records.py b/backend/app/services/chem/records.py new file mode 100644 index 00000000..9313f5c9 --- /dev/null +++ b/backend/app/services/chem/records.py @@ -0,0 +1,272 @@ +import gzip +import io as stdio +from dataclasses import dataclass, field +from pathlib import Path +from typing import Iterator + +from rdkit import Chem +from rdkit.Chem import rdChemReactions + +from app.services.chem import ids, io, perceive, stream + +READ =("sdf", "smiles", "cxsmiles", "inchi", "molfile", "rxn", "rsmiles", "rdf", "cml", "cdxml", "cdx", "fchem") +WRITE = ("smiles", "cxsmiles", "sdf", "molfile", "inchi", "inchikey", "cml", "rxn", "rsmiles", "fchem") +STREAMED = ("sdf", "smiles", "cxsmiles", "inchi") +REACTIONS = ("rxn", "rsmiles") +EXTENSIONS = { + ".sdf": "sdf", ".sd": "sdf", ".smi": "smiles", ".smiles": "smiles", ".ism": "smiles", ".cxsmi": "cxsmiles", ".cxsmiles": "cxsmiles", + ".inchi": "inchi", ".ich": "inchi", ".mol": "molfile", ".mdl": "molfile", ".rxn": "rxn", ".rsmi": "rsmiles", ".cml": "cml", + ".cdxml": "cdxml", ".cdx": "cdx", ".fchem": "fchem", ".inchikey": "inchikey", ".key": "inchikey", ".rdf": "rdf", ".rd": "rdf", +} +NAMES = { + "sdf": "SD file", "smiles": "SMILES", "cxsmiles": "CXSMILES", "inchi": "InChI", "inchikey": "InChIKey", "molfile": "MDL molfile", + "rxn": "MDL reaction file", "rsmiles": "reaction SMILES", "cml": "Chemical Markup Language", "cdxml": "CDXML", "cdx": "ChemDraw binary", + "fchem": "FormChem document", "rdf": "RD file", +} +ALIASES = {"smi": "smiles", "mol": "molfile", "mdl": "molfile", "sd": "sdf", "cxsmi": "cxsmiles", "key": "inchikey", "rsmi": "rsmiles"} + + +@dataclass +class Record: + index: int + mol: Chem.Mol | None + name: str = "" + data: dict = field(default_factory=dict) + error: str | None = None + reaction: rdChemReactions.ChemicalReaction | None = None + + +def format_of(path: str | Path, given: str | None = None) -> str | None: + if given: + g = given.lower().lstrip(".") + return ALIASES.get(g, g) + p = Path(str(path)) + suffixes = [s.lower() for s in p.suffixes] + if suffixes and suffixes[-1] == ".gz": + suffixes = suffixes[:-1] + return EXTENSIONS.get(suffixes[-1]) if suffixes else None + + +def read_text(path: str | Path) -> str: + p = Path(path) + raw = gzip.open(p, "rb").read() if p.suffix.lower() == ".gz" else p.read_bytes() + if raw[:2] in (b"\xff\xfe", b"\xfe\xff"): + return raw.decode("utf-16") + try: + return raw.decode("utf-8-sig") + except UnicodeDecodeError: + return raw.decode("cp1252", errors="replace") + + +def _lines(path: str | Path) -> Iterator[str]: + p = Path(path) + opener = gzip.open(p, "rt", encoding="utf-8", errors="replace") if p.suffix.lower() == ".gz" else open(p, encoding="utf-8-sig", errors="replace") + with opener as fh: + yield from fh + + +def chunks(path: str | Path, fmt: str, size: int) -> Iterator[tuple[int, str]]: + start, count, buf = 0, 0, [] + if fmt == "sdf": + for line in _lines(path): + buf.append(line) + if line.startswith("$$$$"): + count += 1 + if count == size: + yield start, "".join(buf) + start, count, buf = start + count, 0, [] + if any(s.strip() for s in buf): + if not buf[-1].endswith("\n"): + buf[-1] += "\n" + yield start, "".join(buf) + ("" if buf[-1].startswith("$$$$") else "$$$$\n") + return + for line in _lines(path): + if not line.strip() or line.lstrip().startswith("#"): + continue + buf.append(line) + if len(buf) == size: + yield start, "".join(buf) + start, buf = start + len(buf), [] + if buf: + yield start, "".join(buf) + + +def _first_line(text: str) -> str: + return next((l.strip() for l in text.splitlines()), "") + + +def _problem(mol: Chem.Mol | None) -> str: + if mol is None: + return "not readable" + try: + found = Chem.DetectChemistryProblems(mol) + except Exception as exc: + return str(exc) + return "; ".join(p.Message() for p in found) or "not readable" + + +def _offset(found: Iterator, start: int) -> Iterator: + for rec in found: + rec.index += start + yield rec + + +def parse_chunk(fmt: str, text: str, start: int = 0) -> Iterator[stream.Record]: + if fmt not in STREAMED: + raise ValueError(f"{fmt} is not read record by record") + return _offset(stream.iter_records(stdio.StringIO(text), fmt), start) + + +def _fragment_records(frags: list[dict], expansions: dict | None = None) -> Iterator[Record]: + for n, frag in enumerate(frags): + try: + conv = perceive.prepare(frag, expansions) + mol = ids.identifier_mol(conv.mol) + yield Record(n, mol, str(frag.get("name") or ""), dict(frag.get("data") or {})) + except Exception as exc: + yield Record(n, None, str(frag.get("name") or ""), {}, f"{type(exc).__name__}: {exc}") + + +def _document_records(path: str | Path) -> Iterator[Record]: + from app.services import package + doc, _media = package.read(path) + order: list[str] = [] + + def walk(ids_: list) -> None: + for oid in ids_: + obj = (doc.get("objects") or {}).get(oid) + if isinstance(obj, dict) and obj.get("kind") == "fragment" and obj.get("atoms"): + order.append(oid) + elif isinstance(obj, dict) and obj.get("kind") == "group": + walk(obj.get("children") or []) + + for page in doc.get("pages") or []: + walk(page.get("order") or []) + yield from _fragment_records([doc["objects"][oid] for oid in order], doc.get("expansions")) + + +def _reaction_records(path: str | Path, fmt: str) -> Iterator[Record]: + text = read_text(path) + if fmt == "rxn": + try: + rxn = rdChemReactions.ReactionFromRxnBlock(text, sanitize=False, removeHs=False, strictParsing=False) + except Exception as exc: + yield Record(0, None, _first_line(text[4:]), {}, f"not a readable RXN file: {exc}") + return + yield Record(0, None, (text.splitlines()[1].strip() if len(text.splitlines()) > 1 else ""), {}, None, rxn) + return + for n, line in enumerate(l for l in text.splitlines() if l.strip()): + parts = line.strip().split(None, 1) + try: + rxn = rdChemReactions.ReactionFromSmarts(parts[0], useSmiles=True) + yield Record(n, None, parts[1] if len(parts) > 1 else "", {}, None, rxn) + except Exception as exc: + yield Record(n, None, parts[1] if len(parts) > 1 else "", {}, f"not a valid reaction SMILES: {exc}") + + +def _own_records(path: str | Path, fmt: str | None = None) -> Iterator[Record]: + kind = format_of(path, fmt) + if kind in STREAMED: + for start, text in chunks(path, kind, 1000): + yield from parse_chunk(kind, text, start) + return + if kind == "molfile": + text = read_text(path) + mol = Chem.MolFromMolBlock(text, sanitize=True, removeHs=True, strictParsing=False) + if mol is None: + why = stream.explain(lambda: Chem.MolFromMolBlock(text, sanitize=True, strictParsing=False)) + yield Record(0, None, _first_line(text), {}, why or _problem(Chem.MolFromMolBlock(text, sanitize=False, strictParsing=False))) + else: + yield Record(0, mol, mol.GetProp("_Name").strip() if mol.HasProp("_Name") else "") + return + if kind in REACTIONS: + yield from _reaction_records(path, kind) + return + if kind == "fchem": + yield from _document_records(path) + return + if kind == "rdf": + yield from stream.iter_records(Path(path), "rdf") + return + if kind in ("cml", "cdxml", "cdx"): + res = io.read_file(path) + yield from _fragment_records(res.fragments) + return + raise ValueError(f"FormChem cannot read {Path(str(path)).name}: unknown format") + + +iter_records = _own_records + + +def mol_text(mol: Chem.Mol, fmt: str, name: str = "", data: dict | None = None, v3000: bool = False) -> str: + if fmt == "smiles": + text = ids.smiles(mol) + if not text: + raise ValueError("no SMILES could be written") + return f"{text} {name}\n" if name else text + "\n" + if fmt == "cxsmiles": + text = ids.cxsmiles(mol) + if not text: + raise ValueError("no CXSMILES could be written") + return f"{text} {name}\n" if name else text + "\n" + if fmt in ("inchi", "inchikey"): + text, key, notes = ids.inchi(mol) + value = text if fmt == "inchi" else key + if not value: + raise ValueError(notes[0]["text"] if notes else "no InChI could be written") + return f"{value} {name}\n" if name else value + "\n" + if fmt in ("sdf", "molfile"): + out = Chem.Mol(mol) + out.SetProp("_Name", name) + block = Chem.MolToMolBlock(out, forceV3000=v3000 or out.GetNumAtoms() > 999 or out.GetNumBonds() > 999) + if fmt == "molfile": + return block + lines = [block] + for k, v in (data or {}).items(): + lines.append(f"> <{k}>\n{v}\n\n") + return "".join(lines) + "$$$$\n" + if fmt == "cml": + out = Chem.Mol(mol) + out.SetProp("_Name", name) + return Chem.MolToCMLBlock(out) + raise ValueError(f"{fmt} cannot be written record by record") + + +def reaction_text(rxn: rdChemReactions.ChemicalReaction, fmt: str, name: str = "") -> str: + if fmt == "rsmiles": + text = rdChemReactions.ReactionToSmiles(rxn) + return f"{text} {name}\n" if name else text + "\n" + if fmt == "rxn": + block = rdChemReactions.ReactionToRxnBlock(rxn) + lines = block.splitlines(True) + if name and len(lines) > 1: + lines[1] = name + "\n" + return "".join(lines) + raise ValueError(f"a reaction cannot be written as {NAMES.get(fmt, fmt)}; use rxn or rsmiles") + + +def document(records: list[Record], title: str) -> dict: + from app import __version__ + from app.services import importers, model + from app.services.chem import convert + doc = model.empty_document(title or "Untitled", None, f"formchem {__version__}") + page = doc["pages"][0] + bond_length = float(model.resolve_style(doc).get("bond_length", 14.4)) + used = {doc["id"], page["id"]} + frags = [] + for rec in records: + frag = convert.from_mol(rec.mol, bond_length, (0.0, 0.0), name=rec.name or None, used=used) + if rec.data: + frag["data"] = {k: v if isinstance(v, (int, float, str, bool)) else str(v) for k, v in rec.data.items()} + frags.append(frag) + importers.place(frags, page, bond_length) + for f in frags: + doc["objects"][f["id"]] = f + page["order"].append(f["id"]) + return doc + + +def write_document(path: str | Path, records: list[Record], title: str) -> None: + from app.services import package + package.write(path, document(records, title)) + diff --git a/backend/app/services/chem/report.py b/backend/app/services/chem/report.py new file mode 100644 index 00000000..59d9c405 --- /dev/null +++ b/backend/app/services/chem/report.py @@ -0,0 +1,92 @@ +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, + "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") + if code in INTERNAL: + continue + 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")] diff --git a/backend/app/services/chem/scheme.py b/backend/app/services/chem/scheme.py index 9b2b400a..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,130 @@ 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() + 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] = [] + 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] + 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 or f["id"] in dropped: + 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: + if f["id"] in dropped: + continue + 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 diff --git a/backend/app/services/chem/standardise.py b/backend/app/services/chem/standardise.py new file mode 100644 index 00000000..6ecebe02 --- /dev/null +++ b/backend/app/services/chem/standardise.py @@ -0,0 +1,530 @@ +import copy +from collections import Counter +from typing import Callable + +from rdkit import Chem +from rdkit.Chem.MolStandardize import rdMolStandardize as MS + +from app.services import ops as opsmod +from app.services.chem import ENGINE, abbrev, convert, ids, warning +from app.services.model import new_id +from app.services.ops import atom_path, bond_path, object_path + +SAN = Chem.SanitizeFlags +KEY = "fc_std" +STEPS: tuple[tuple[str, str, str], ...] = ( + ("cleanup", "Clean up", "Sanitises the structure, fixes hypervalent nitro and perchlorate groups and breaks bonds from metals to N, O and halogens into ions (Chem.Cleanup, rdMolStandardize.MetalDisconnector)."), + ("normalise", "Normalise functional groups", "Writes nitro, N-oxide, azide, diazo, sulfoxide and similar groups in one form, charge-separated where needed (rdMolStandardize.Normalizer, the MolVS transforms)."), + ("salts", "Remove salts and solvents", "Removes counter-ions and solvents on the built-in list (halides, alkali metals, water, common acids and solvents), never the last fragment (rdMolStandardize.FragmentRemover)."), + ("largest", "Keep the largest fragment", "Keeps the largest organic fragment and removes every other piece (rdMolStandardize.LargestFragmentChooser)."), + ("reionise", "Reionise", "Moves charges so the strongest acid group is the one ionised (rdMolStandardize.Reionizer)."), + ("neutralise", "Neutralise", "Removes charges by adding or removing hydrogens where the species stays the same; quaternary nitrogen and balanced salts keep their charges (rdMolStandardize.Uncharger)."), + ("tautomer", "Canonical tautomer", "Replaces the structure by the canonical tautomer of RDKit's scoring rules, for example 2-hydroxypyridine to 2-pyridone; never applied unless chosen (rdMolStandardize.TautomerEnumerator.Canonicalize)."), + ("isotopes", "Remove isotopes", "Sets every atom to natural abundance, so D becomes H."), + ("stereo", "Remove stereochemistry", "Removes tetrahedral and double bond stereo, wedges and stereo groups (Chem.RemoveStereochemistry)."), + ("strip_h", "Remove explicit hydrogens", "Removes drawn H atoms, keeping those with an isotope, a map number or a wedge (Chem.RemoveHs)."), +) +ORDER = tuple(s[0] for s in STEPS) +LABELS = {s[0]: s[1] for s in STEPS} +METHODS = {s[0]: s[2] for s in STEPS} +DEFAULT = ("cleanup", "normalise", "salts", "reionise", "neutralise", "strip_h") +ALIASES = { + "clean": "cleanup", "metals": "cleanup", "normalize": "normalise", "normalise_groups": "normalise", "groups": "normalise", + "salt": "salts", "strip_salts": "salts", "solvents": "salts", "fragments": "salts", "largest_fragment": "largest", + "fragment": "largest", "reionize": "reionise", "neutralize": "neutralise", "uncharge": "neutralise", "charges": "neutralise", + "tautomers": "tautomer", "canonical_tautomer": "tautomer", "isotope": "isotopes", "stereochemistry": "stereo", + "hydrogens": "strip_h", "remove_h": "strip_h", "explicit_h": "strip_h", "strip-h": "strip_h", "h": "strip_h", +} +STEREO_FIELDS = ("wedge", "hash", "hollow", "wavy", "either") + + +def parse_steps(spec: str | list | tuple | None) -> list[str]: + if spec is None: + return list(DEFAULT) + words = spec if isinstance(spec, (list, tuple)) else str(spec).replace(",", " ").split() + chosen: set[str] = set() + for raw in words: + if not isinstance(raw, str): + raise ValueError("steps must be names") + word = raw.strip().lower() + drop = word.startswith("-") + word = word.lstrip("+-") + if not word: + continue + if word in ("default", "defaults"): + group = set(DEFAULT) + elif word == "all": + group = set(ORDER) + elif word == "none": + group = set(ORDER) if drop else set() + chosen.clear() + else: + name = ALIASES.get(word, word) + if name not in LABELS: + raise ValueError(f"unknown standardise step {raw}; the steps are {', '.join(ORDER)}") + group = {name} + chosen = chosen - group if drop else chosen | group + return [s for s in ORDER if s in chosen] + + +def sanitise(mol: Chem.Mol, cleanup: bool = False) -> None: + ops = SAN.SANITIZE_ALL if cleanup else SAN.SANITIZE_ALL ^ SAN.SANITIZE_CLEANUP + for _ in range(6): + failed = Chem.SanitizeMol(mol, ops, catchErrors=True) + if failed == SAN.SANITIZE_NONE: + break + ops ^= failed + try: + mol.UpdatePropertyCache(strict=False) + except Exception: + pass + try: + Chem.GetSymmSSSR(mol) + except Exception: + Chem.FastFindRings(mol) + + +def _cleanup(mol: Chem.Mol) -> Chem.Mol: + out = Chem.RWMol(mol) + Chem.Cleanup(out) + out = Chem.RWMol(MS.MetalDisconnector().Disconnect(out)) + sanitise(out, cleanup=True) + return out + + +def _normalise(mol: Chem.Mol) -> Chem.Mol: + return MS.Normalizer().normalize(mol) + + +def _salts(mol: Chem.Mol) -> Chem.Mol: + return MS.FragmentRemover().remove(mol) + + +def _largest(mol: Chem.Mol) -> Chem.Mol: + return MS.LargestFragmentChooser(preferOrganic=True).choose(mol) + + +def _reionise(mol: Chem.Mol) -> Chem.Mol: + return MS.Reionizer().reionize(mol) + + +def _neutralise(mol: Chem.Mol) -> Chem.Mol: + return MS.Uncharger(canonicalOrder=True).uncharge(mol) + + +def _strip_h(mol: Chem.Mol) -> Chem.Mol: + params = Chem.RemoveHsParameters() + params.removeWithWedgedBond = False + params.removeMapped = False + params.removeIsotopes = False + return Chem.RemoveHs(mol, params, sanitize=False) + + +def _tautomer(mol: Chem.Mol) -> Chem.Mol: + params = MS.CleanupParameters() + params.tautomerRemoveSp3Stereo = False + params.tautomerRemoveBondStereo = False + params.tautomerRemoveIsotopicHs = False + return MS.TautomerEnumerator(params).Canonicalize(_strip_h(mol)) + + +def _isotopes(mol: Chem.Mol) -> Chem.Mol: + out = Chem.Mol(mol) + for a in out.GetAtoms(): + a.SetIsotope(0) + return out + + +def _stereo(mol: Chem.Mol) -> Chem.Mol: + out = Chem.Mol(mol) + Chem.RemoveStereochemistry(out) + for b in out.GetBonds(): + b.SetBondDir(Chem.BondDir.NONE) + return out + + +FUNCS: dict[str, Callable[[Chem.Mol], Chem.Mol]] = { + "cleanup": _cleanup, "normalise": _normalise, "salts": _salts, "largest": _largest, "reionise": _reionise, + "neutralise": _neutralise, "tautomer": _tautomer, "isotopes": _isotopes, "stereo": _stereo, "strip_h": _strip_h, +} + + +def smiles(mol: Chem.Mol) -> str: + return ids.smiles(ids.identifier_mol(mol)) + + +def _pieces(mol: Chem.Mol) -> Counter: + try: + parts = Chem.GetMolFrags(mol, asMols=True, sanitizeFrags=False) + except Exception: + return Counter() + return Counter(ids.formula(p) for p in parts) + + +def _charged(mol: Chem.Mol) -> int: + return sum(1 for a in mol.GetAtoms() if a.GetFormalCharge()) + + +def _detail(step: str, before: Chem.Mol, after: Chem.Mol) -> str: + parts = [] + p0, p1 = _pieces(before), _pieces(after) + if step in ("salts", "largest"): + gone = p0 - p1 + if gone: + parts.append("removed " + ", ".join(f"{n} x {f}" if n > 1 else f for f, n in sorted(gone.items()))) + elif sum(p1.values()) > sum(p0.values()): + parts.append(f"{sum(p1.values()) - sum(p0.values())} metal bond(s) broken into ions") + h0 = sum(1 for a in before.GetAtoms() if a.GetAtomicNum() == 1) + h1 = sum(1 for a in after.GetAtoms() if a.GetAtomicNum() == 1) + if h1 < h0 and step not in ("salts", "largest"): + parts.append(f"{h0 - h1} explicit H removed") + c0, c1 = _charged(before), _charged(after) + if c0 != c1 and step not in ("salts", "largest"): + parts.append(f"charged atoms {c0} to {c1}") + i0 = sum(1 for a in before.GetAtoms() if a.GetIsotope()) + if step == "isotopes" and i0: + parts.append(f"{i0} isotope label(s) removed") + if step == "tautomer" and not parts: + parts.append("hydrogens and double bonds moved") + if step == "stereo": + parts.append("stereo removed") + return "; ".join(parts) or "changed" + + +def _carry(before: Chem.Mol, after: Chem.Mol) -> None: + lost = [a.GetIdx() for a in after.GetAtoms() if not a.HasProp(KEY)] + if not lost: + return + + def skeleton(m: Chem.Mol) -> Chem.Mol: + rw = Chem.RWMol(m) + for a in rw.GetAtoms(): + a.SetFormalCharge(0) + a.SetIsotope(0) + a.SetIsAromatic(False) + a.SetNumExplicitHs(0) + a.SetNoImplicit(True) + a.SetNumRadicalElectrons(0) + a.SetChiralTag(Chem.ChiralType.CHI_UNSPECIFIED) + for b in rw.GetBonds(): + b.SetBondType(Chem.BondType.SINGLE) + b.SetIsAromatic(False) + m2 = rw.GetMol() + m2.UpdatePropertyCache(strict=False) + Chem.FastFindRings(m2) + return m2 + + known = {a.GetIdx(): a.GetIntProp(KEY) for a in after.GetAtoms() if a.HasProp(KEY)} + keys = [a.GetIntProp(KEY) if a.HasProp(KEY) else -1 for a in before.GetAtoms()] + matches = skeleton(before).GetSubstructMatches(skeleton(after), uniquify=False, useChirality=False, maxMatches=256) + if not matches: + return + best = max(matches, key=lambda m: sum(1 for i, k in known.items() if keys[m[i]] == k)) + taken = set(known.values()) + for i in lost: + k = keys[best[i]] + if k >= 0 and k not in taken: + after.GetAtomWithIdx(i).SetIntProp(KEY, k) + taken.add(k) + + +def run(mol: Chem.Mol, steps: list[str], track: bool = False) -> tuple[Chem.Mol, list[dict]]: + cur = mol + text = smiles(cur) + report = [] + for step in (s for s in ORDER if s in steps): + row: dict = {"step": step, "label": LABELS[step], "changed": False, "detail": ""} + try: + nxt = FUNCS[step](cur) + if nxt is None: + raise ValueError("the step returned nothing") + except Exception as exc: + row["error"] = f"{type(exc).__name__}: {exc}" + report.append(row) + continue + if track: + _carry(cur, nxt) + after = smiles(nxt) + if after != text or nxt.GetNumAtoms() != cur.GetNumAtoms(): + row["changed"] = True + row["detail"] = _detail(step, cur, nxt) + row["smiles"] = after + report.append(row) + cur, text = nxt, after + return cur, report + + +def standardise_mol(mol: Chem.Mol, steps: list[str]) -> tuple[Chem.Mol, list[dict]]: + return run(mol, steps, track=False) + + +Row = tuple[str, str, bool] + + +def _prepare(frags: dict[str, dict], expansions: dict | None) -> tuple[Chem.Mol | None, list[Row], list[dict]]: + combined: Chem.Mol | None = None + table: list[Row] = [] + notes: list[dict] = [] + for fid, frag in frags.items(): + conv = convert.to_mol(frag, expansions=expansions) + sanitise(conv.mol) + convert.assign_stereo(conv) + notes.extend(w for w in conv.warnings if w.get("code") in ("unknown_label", "bad_expansion")) + mol = conv.mol.GetMol() + for a in mol.GetAtoms(): + a.SetIntProp(KEY, len(table) + a.GetIdx()) + table.extend((fid, conv.owner[i], conv.drawn[i]) for i in range(mol.GetNumAtoms())) + combined = mol if combined is None else Chem.CombineMols(combined, mol) + return combined, table, notes + + +class _Sets: + def __init__(self) -> None: + self.parent: dict[str, str] = {} + + def find(self, x: str) -> str: + self.parent.setdefault(x, x) + while self.parent[x] != x: + self.parent[x] = self.parent[self.parent[x]] + x = self.parent[x] + return x + + def join(self, a: str, b: str) -> None: + self.parent[self.find(a)] = self.find(b) + + +def _fresh(prefix: str, used: set[str]) -> str: + while True: + i = new_id(prefix) + if i not in used: + used.add(i) + return i + + +def _atom_changes(rec: dict, a0: Chem.Atom, a1: Chem.Atom) -> dict: + out: dict = {} + if a1.GetAtomicNum() and a1.GetAtomicNum() != a0.GetAtomicNum(): + out["element"] = a1.GetSymbol() + if a1.GetFormalCharge() != a0.GetFormalCharge(): + out["charge"] = a1.GetFormalCharge() or None + if a1.GetAtomicNum() and a1.GetIsotope() != a0.GetIsotope(): + out["isotope"] = a1.GetIsotope() or None + if not a1.GetIsotope() and rec.get("label") in ("D", "T"): + out["label"] = None + if a1.GetNumRadicalElectrons() != a0.GetNumRadicalElectrons(): + out["radical"] = convert._radical_name(a1.GetNumRadicalElectrons()) if a1.GetNumRadicalElectrons() else None + return out + + +def _set(path: list, value) -> dict: + return {"op": "set", "path": path} if value is None else {"op": "set", "path": path, "value": value} + + +def _fragment_ops(fid: str, frag: dict, base: Chem.Mol, final: Chem.Mol, table: list[Row], steps: list[str], used: set[str]) -> tuple[list[dict], bool, list[dict]]: + atoms: dict = frag.get("atoms") or {} + bonds: dict = frag.get("bonds") or {} + before = {owner: k for k, (f, owner, drawn) in enumerate(table) if f == fid and drawn} + after: dict[str, int] = {} + alive: set[str] = set() + inner: dict[str, list[int]] = {} + for a in final.GetAtoms(): + if not a.HasProp(KEY): + continue + f, owner, drawn = table[a.GetIntProp(KEY)] + if f != fid: + continue + alive.add(owner) + if drawn: + after[owner] = a.GetIdx() + else: + inner.setdefault(owner, []).append(a.GetIdx()) + gone = {aid for aid in atoms if aid not in alive} + if atoms and len(gone) == len(atoms): + return [], True, [] + notes: list[dict] = [] + hidden = [owner for owner, idx in inner.items() + if len(idx) != sum(1 for f, o, d in table if f == fid and o == owner and not d) + or any(final.GetAtomWithIdx(j).GetFormalCharge() != base.GetAtomWithIdx(final.GetAtomWithIdx(j).GetIntProp(KEY)).GetFormalCharge() for j in idx)] + if hidden: + notes.append(warning("abbreviation_kept", "Changes inside these abbreviations are not drawn; expand them first to standardise them.", hidden)) + changes: dict[str, dict] = {} + touched: set[str] = set() + for aid, j in after.items(): + a0, a1 = base.GetAtomWithIdx(before[aid]), final.GetAtomWithIdx(j) + found = _atom_changes(atoms[aid], a0, a1) + if found: + changes[aid] = found + if found or a0.GetTotalNumHs() != a1.GetTotalNumHs(): + touched.add(aid) + systems = _Sets() + pairs: set[frozenset] = set() + for b in bonds.values(): + ia, ib = b["a"], b["b"] + pairs.add(frozenset((ia, ib))) + if ia not in after or ib not in after: + continue + b0 = base.GetBondBetweenAtoms(before[ia], before[ib]) + b1 = final.GetBondBetweenAtoms(after[ia], after[ib]) + if (b0 is not None and b0.GetIsAromatic()) or (b1 is not None and b1.GetIsAromatic()): + systems.join(ia, ib) + if b0 is None or b1 is None or b0.GetBondType() != b1.GetBondType(): + touched.update((ia, ib)) + hot = {systems.find(a) for a in touched} + kek = Chem.RWMol(final) + try: + Chem.Kekulize(kek, clearAromaticFlags=True) + kekulised = True + except Exception: + kekulised = False + ops: list[dict] = [] + new_orders: dict[str, object] = {} + dropped: set[str] = set() + for bid, b in sorted(bonds.items()): + ia, ib = b["a"], b["b"] + if ia in gone or ib in gone: + dropped.add(bid) + continue + if ia not in after or ib not in after: + continue + b1 = final.GetBondBetweenAtoms(after[ia], after[ib]) + if b1 is None: + dropped.add(bid) + continue + b0 = base.GetBondBetweenAtoms(before[ia], before[ib]) + drawn = convert._order_key(b.get("order", 1)) + ring = b1.GetIsAromatic() or (b0 is not None and b0.GetIsAromatic()) + if (ring and systems.find(ia) in hot) or b0 is None or b0.GetBondType() != b1.GetBondType(): + if b1.GetIsAromatic() and (drawn == 1.5 or not kekulised): + order = 1.5 + else: + order = convert.RDKIT_TO_ORDER.get((kek if kekulised else final).GetBondWithIdx(b1.GetIdx()).GetBondType(), 1) + if order != drawn: + new_orders[bid] = order + ops.append(_set(bond_path(fid, bid, "order"), order)) + mark = b.get("stereo") + if mark in STEREO_FIELDS and ("stereo" in steps or new_orders.get(bid, drawn) not in (1, 2)): + ops.append(_set(bond_path(fid, bid, "stereo"), None)) + added: dict[str, dict] = {} + for b1 in final.GetBonds(): + ends = [] + for a in (b1.GetBeginAtom(), b1.GetEndAtom()): + row = table[a.GetIntProp(KEY)] if a.HasProp(KEY) else None + ends.append(row[1] if row and row[0] == fid and row[2] else None) + if None in ends or frozenset(ends) in pairs: + continue + bid = _fresh("b", used) + order = convert.RDKIT_TO_ORDER.get((kek if kekulised else final).GetBondWithIdx(b1.GetIdx()).GetBondType(), 1) + added[bid] = {"id": bid, "a": ends[0], "b": ends[1], "order": order} + ops.append(_set(bond_path(fid, bid), added[bid])) + ops.extend(_set(bond_path(fid, bid), None) for bid in sorted(dropped)) + ops.extend(_set(atom_path(fid, aid), None) for aid in sorted(gone)) + for aid, found in sorted(changes.items()): + ops.extend(_set(atom_path(fid, aid, k), v) for k, v in found.items() if v is not None or k in atoms[aid]) + trial_atoms = {} + for aid, rec in atoms.items(): + if aid in gone: + continue + rec = {**rec, **{k: v for k, v in changes.get(aid, {}).items() if v is not None}} + for k, v in changes.get(aid, {}).items(): + if v is None: + rec.pop(k, None) + trial_atoms[aid] = rec + near_gone = {x for b in bonds.values() if b["a"] in gone or b["b"] in gone for x in (b["a"], b["b"])} - gone + check = {aid for aid in after if aid in touched or aid in near_gone or "hydrogens" in atoms[aid]} + for aid in check: + trial_atoms[aid] = {k: v for k, v in trial_atoms[aid].items() if k != "hydrogens"} + trial_bonds = {bid: {**b, "order": new_orders.get(bid, b.get("order", 1))} for bid, b in bonds.items() if bid not in dropped} + trial_bonds.update(added) + probe = convert.to_mol({"atoms": trial_atoms, "bonds": trial_bonds}, expand=False) + try: + probe.mol.UpdatePropertyCache(strict=False) + except Exception: + pass + for aid in sorted(check): + want = final.GetAtomWithIdx(after[aid]).GetTotalNumHs() + got = probe.mol.GetAtomWithIdx(probe.index[aid]).GetTotalNumHs() + pin = None if got == want else max(0, min(12, want)) + if pin != atoms[aid].get("hydrogens"): + ops.append(_set(atom_path(fid, aid, "hydrogens"), pin)) + label = atoms[aid].get("label") + if aid in touched and label and "label" not in changes.get(aid, {}) and abbrev.element_like(label, trial_atoms[aid].get("element", "C")): + ops.append(_set(atom_path(fid, aid, "label"), None)) + if "stereo" in steps: + ops.extend(_set(object_path(fid, k), None) for k in ("stereo_groups", "chiral") if k in frag) + elif gone and frag.get("stereo_groups"): + kept = [{**g, "atoms": [a for a in g.get("atoms") or [] if a not in gone]} for g in frag["stereo_groups"]] + ops.append(_set(object_path(fid, "stereo_groups"), [g for g in kept if g["atoms"]] or None)) + return ops, False, notes + + +def removal_ops(doc: dict, fid: str) -> list[dict]: + out: list[dict] = [] + for page in doc.get("pages") or []: + pid = page.get("id") + if fid in (page.get("order") or []): + out.append({"op": "del", "path": ["pages", {"id": pid}, "order"], "id": fid}) + for r in page.get("reactions") or []: + for s in r.get("steps") or []: + for role in ("reactants", "products", "agents"): + if fid in (s.get(role) or []): + out.append(_set(["pages", {"id": pid}, "reactions", {"id": r["id"]}, "steps", {"id": s["id"]}, role], [x for x in s[role] if x != fid])) + for oid, obj in (doc.get("objects") or {}).items(): + if isinstance(obj, dict) and obj.get("kind") == "group" and fid in (obj.get("children") or []): + if len(obj["children"]) == 1: + return out + [_set(object_path(fid), None)] + removal_ops(doc, oid) + out.append({"op": "del", "path": object_path(oid, "children"), "id": fid}) + out.append(_set(object_path(fid), None)) + return out + + +def _doc_ids(doc: dict | None, frags: dict[str, dict]) -> set[str]: + out: set[str] = set(frags) + for frag in frags.values(): + out.update(frag.get("atoms") or {}) + out.update(frag.get("bonds") or {}) + for obj in ((doc or {}).get("objects") or {}).values(): + if isinstance(obj, dict) and obj.get("kind") == "fragment": + out.update(obj.get("atoms") or {}) + out.update(obj.get("bonds") or {}) + return out + + +def standardise_fragments(frags: dict[str, dict], steps: list[str], expansions: dict | None = None, doc: dict | None = None) -> dict: + base, table, notes = _prepare(frags, expansions) + if base is None or not base.GetNumAtoms(): + raise ValueError("there is no structure to standardise") + final, report = run(Chem.Mol(base), steps, track=True) + try: + final.UpdatePropertyCache(strict=False) + except Exception: + pass + used = _doc_ids(doc, frags) + work = copy.deepcopy(doc) if doc is not None else None + ops: list[dict] = [] + removed: list[str] = [] + for fid, frag in frags.items(): + found, empty, extra = _fragment_ops(fid, frag, base, final, table, steps, used) + notes.extend(extra) + if not empty: + ops.extend(found) + continue + removed.append(fid) + if work is None: + ops.extend(_set(bond_path(fid, bid), None) for bid in sorted(frag.get("bonds") or {})) + ops.extend(_set(atom_path(fid, aid), None) for aid in sorted(frag.get("atoms") or {})) + continue + for op in removal_ops(work, fid): + ops.append(op) + opsmod.apply(work, op) + if removed: + notes.append(warning("removed", f"{len(removed)} structure(s) removed as salts, solvents or smaller fragments.")) + return { + "steps": report, + "before": smiles(base), + "after": smiles(final), + "changed": bool(ops), + "removed": removed, + "tx": {"label": "Standardise", "ops": ops} if ops else None, + "warnings": notes, + "engine": ENGINE, + } diff --git a/backend/app/services/chem/stream.py b/backend/app/services/chem/stream.py new file mode 100644 index 00000000..35e49f7e --- /dev/null +++ b/backend/app/services/chem/stream.py @@ -0,0 +1,211 @@ +import io as stdio +import re +import sys +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import IO, Callable, Iterator + +from rdkit import Chem, RDLogger, rdBase + +from app.services.chem import ids, io + +STREAMED = ("sdf", "smiles", "cxsmiles", "inchi", "rdf", "molfile") +TARGETS = ("smiles", "cxsmiles", "inchi", "inchikey", "sdf", "molfile") +NOISE = ("****", "Violation occurred", "Failed Expression", "Stacktrace", "----------", "Post-condition", "Pre-condition", "Invariant Violation") + + +def explain(parse: Callable[[], object]) -> str: + buf = stdio.StringIO() + old = sys.stderr + rdBase.LogToPythonStderr() + RDLogger.EnableLog("rdApp.error") + sys.stderr = buf + try: + parse() + except Exception as exc: + buf.write(f"\n{exc}\n") + finally: + sys.stderr = old + RDLogger.DisableLog("rdApp.*") + lines = [re.sub(r"^\[\d\d:\d\d:\d\d\]\s*", "", l).strip() for l in buf.getvalue().splitlines()] + kept = [l for l in lines if l and not l.startswith(NOISE)] + return "; ".join(dict.fromkeys(kept))[:240] + + +@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: + why = explain(lambda: Chem.MolFromMolBlock(text, strictParsing=False)) + return Record(i, None, name, text, why or _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() and not l.lstrip().startswith("#")): + 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: + why = explain(lambda: Chem.MolFromSmiles(text, params)) + if not why: + raw = Chem.MolFromSmiles(text, io._smiles_params(False)) + why = "not a valid SMILES" if raw is None else _sanitize_error(raw) + parts = text.split(None, 1) + yield Record(i, None, parts[1].strip() if len(parts) > 1 else "", text, why) + 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} diff --git a/backend/app/services/chem/writers.py b/backend/app/services/chem/writers.py new file mode 100644 index 00000000..aa42d000 --- /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 []} + 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(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" + 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) diff --git a/backend/app/services/consent.py b/backend/app/services/consent.py index d811e520..943d205e 100644 --- a/backend/app/services/consent.py +++ b/backend/app/services/consent.py @@ -17,6 +17,7 @@ _declined = [0.0] _tasks: set = set() _open: dict[str, asyncio.Future] = {} +STOPPED: dict[str, float] = {} def asked(name: str, args: dict | None = None) -> str: @@ -101,6 +102,20 @@ async def refusal(agent_name: str, summary: str, inapp: bool = False) -> str | N return "The person did not allow agents to edit drawings in FormChem. Ask them to allow it in the FormChem window, then retry." +def stop(agent_name: str) -> None: + STOPPED[agent_name] = time.time() + if config.read_settings().get("agentsAllowed"): + config.write_settings({"agentsAllowed": False}) + + +def resume(agent_name: str) -> bool: + return STOPPED.pop(agent_name, None) is not None + + +def stopped(agent_name: str) -> bool: + return agent_name in STOPPED + + async def ask(agent_name: str, summary: str) -> bool: return await refusal(agent_name, summary) is None diff --git a/backend/app/services/embedded_source.py b/backend/app/services/embedded_source.py new file mode 100644 index 00000000..b33bdfb2 --- /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) + 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 + 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/importers.py b/backend/app/services/importers.py index f40d0335..b87bfd5b 100644 --- a/backend/app/services/importers.py +++ b/backend/app/services/importers.py @@ -1,10 +1,11 @@ +import base64 import copy import statistics from pathlib import Path from app import __version__ from app.core import config -from app.services import model +from app.services import embedded_source, model, package FORMATS = { ".mol": "MDL molfile", @@ -12,6 +13,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", @@ -24,6 +29,10 @@ GAP_BONDS = 2.0 PAD_BONDS = 0.5 FRAGMENT_KEYS = ("id", "kind", "atoms", "bonds") +INSERT_LIMIT = 50 +INSERT_MAX = 1000 +MEDIA_LIMIT = 16 * 1024 * 1024 +PICTURES = {".svg": "SVG picture", ".png": "PNG picture", ".pdf": "PDF picture", ".eps": "EPS picture"} class ImportFailed(ValueError): @@ -34,6 +43,11 @@ def can_import(path: str | Path) -> bool: return Path(path).suffix.lower() in FORMATS +def can_insert(path: str | Path) -> bool: + suffix = Path(path).suffix.lower() + return suffix in FORMATS or suffix == package.EXT or embedded_source.can_open(path) + + def _parser(): try: from app.services.chem.io import read_file @@ -42,12 +56,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,32 +178,113 @@ 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 grid(frags: list[dict], page: dict, bond_length: float) -> None: + _scale(frags, bond_length) + size = page.get("size") if isinstance(page.get("size"), dict) else model.page_size_for(None) + margin = float(page.get("margins", 36)) + pad = PAD_BONDS * bond_length + gap = GAP_BONDS * bond_length + boxes = [model.fragment_bounds(f) or {"x": 0, "y": 0, "w": 0, "h": 0} for f in frags] + n = len(boxes) + if not n: + return + usable = size["w"] - 2 * margin + + def widths(cols: int) -> list[float]: + return [max(boxes[i]["w"] for i in range(c, n, cols)) + 2 * pad for c in range(cols)] + + cols = n + while cols > 1 and sum(widths(cols)) + gap * (cols - 1) > usable: + cols -= 1 + ws = widths(cols) + hs = [max(b["h"] for b in boxes[r:r + cols]) + 2 * pad for r in range(0, n, cols)] + xs = [margin + sum(ws[:c]) + gap * c for c in range(cols)] + ys = [margin + sum(hs[:r]) + gap * r for r in range(len(hs))] + for i, (f, b) in enumerate(zip(frags, boxes)): + row, col = divmod(i, cols) + _shift(f, xs[col] + ws[col] / 2 - (b["x"] + b["w"] / 2), ys[row] + hs[row] / 2 - (b["y"] + b["h"] / 2)) + + +def _left_out(warnings: list, kept: int, cut: int, exact: bool) -> list: + rest = [w for w in warnings if not (isinstance(w, dict) and w.get("code") == "truncated")] + skipped = [w for w in warnings if isinstance(w, dict) and w.get("code") == "truncated"] + left = cut + sum(int(w.get("count") or 1) for w in skipped) + if not left: + return warnings + if exact: + text = f"Inserted {kept} of {kept + left} structures; {left} {'was' if left == 1 else 'were'} left out." + else: + text = f"Inserted the first {kept} structures; the rest of the file was left out." + rest.append({"code": "left_out", "count": left, "severity": "warn", + "text": f"{text} Use File > Open to open the whole file as a drawing of its own."}) + return rest + + +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 import_file(path: str | Path) -> tuple[dict, list[str]]: +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 + + +def import_file(path: str | Path, bond_length: float | None = None, limit: int | None = None) -> tuple[dict, list[str]]: p = Path(path).expanduser() if not can_import(p): raise ImportFailed(f"FormChem cannot import {p.suffix or 'this kind of'} files.") read_file = _parser() doc = model.empty_document(p.stem or "Untitled", _locale(), f"formchem {__version__}") + if bond_length: + doc["style"]["bond_length"] = float(bond_length) bond_length = float(model.resolve_style(doc).get("bond_length", 14.4)) try: - result = read_file(str(p), bond_length=bond_length) + result = read_file(str(p), bond_length=bond_length, **({"max_records": limit} if limit else {})) except ImportFailed: raise except Exception as exc: @@ -205,17 +294,94 @@ 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) + if limit: + cut = max(0, len(frags) - limit) + frags = frags[:limit] + warnings = _left_out(warnings, len(frags), cut, p.suffix.lower() not in (".rdf", ".rd")) + grid(frags, page, bond_length) + else: + 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) + + +def _reachable(doc: dict, order: list) -> list[dict]: + seen: set[str] = set() + out: list[dict] = [] + todo = list(order) + while todo: + oid = todo.pop() + obj = doc.get("objects", {}).get(oid) + if oid in seen or not isinstance(obj, dict): + continue + seen.add(oid) + out.append(obj) + if obj.get("kind") == "group" and isinstance(obj.get("children"), list): + todo.extend(obj["children"]) + return out + + +def _carried_media(doc: dict, blobs: dict[str, bytes]) -> dict[str, str]: + listed = doc.get("media") if isinstance(doc.get("media"), dict) else {} + out: dict[str, str] = {} + total = 0 + for mid, data in blobs.items(): + total += len(data) + if total > MEDIA_LIMIT: + break + mime = (listed.get(mid) or {}).get("mime") or "application/octet-stream" + out[mid] = f"data:{mime};base64,{base64.b64encode(data).decode('ascii')}" + return out + + +def read_for_insert(path: str | Path, bond_length: float | None = None, limit: int = INSERT_LIMIT) -> dict: + p = Path(path).expanduser() + suffix = p.suffix.lower() + media: dict[str, str] = {} + if suffix in FORMATS: + doc, _ = import_file(p, bond_length, max(1, min(int(limit), INSERT_MAX))) + items = list(doc["meta"]["imported"].get("report") or []) + fmt, keep_style = FORMATS[suffix], False + elif suffix == package.EXT: + doc, blobs = package.read(p) + media = _carried_media(doc, blobs) + items, fmt, keep_style = [], "FormChem drawing", True + elif embedded_source.can_open(p): + doc, _ = embedded_source.open_picture(p) + items, fmt, keep_style = [], PICTURES.get(suffix, "picture"), True + else: + raise ImportFailed(f"FormChem cannot import {suffix or 'this kind of'} files.") + pages = [pg for pg in doc.get("pages") or [] if pg.get("order")] + if not pages: + raise ImportFailed(f"{p.name} holds nothing FormChem can draw.") + if len(pages) > 1: + n = len(pages) - 1 + items.append({"code": "pages_left_out", "count": n, "severity": "warn", + "text": f"Only the first page with content was inserted; {n} other {'page was' if n == 1 else 'pages were'} left out."}) + lost = [o for o in _reachable(doc, pages[0]["order"]) if o.get("kind") == "image" and o.get("media") not in media] + if lost: + items.append({"code": "pictures_left_out", "count": len(lost), "severity": "warn", + "text": f"{len(lost)} {'picture' if len(lost) == 1 else 'pictures'} inside the drawing could not be carried over.", "objects": [o["id"] for o in lost if isinstance(o.get("id"), str)]}) + from app.services.chem import report + items = report.collect(items) + structures = sum(1 for o in _reachable(doc, pages[0]["order"]) if o.get("kind") == "fragment") + return {"name": p.name, "format": fmt, "document": doc, "media": media, "keep_style": keep_style, + "structures": structures, "report": items, "warnings": report.lines(items)} 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/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/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 diff --git a/backend/app/services/pictures/fonts.py b/backend/app/services/pictures/fonts.py new file mode 100644 index 00000000..d3aa5b92 --- /dev/null +++ b/backend/app/services/pictures/fonts.py @@ -0,0 +1,195 @@ +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) + static.recalcTimestamp = 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)), recalcTimestamp=False) + 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 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 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) diff --git a/backend/app/services/store.py b/backend/app/services/store.py index 99591ff5..bd3121ac 100644 --- a/backend/app/services/store.py +++ b/backend/app/services/store.py @@ -11,12 +11,14 @@ 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 DRAWINGS = "Drawings" LABEL_LIMIT = 120 OUTSIDE_ORIGINS = ("user", "agent", "system") +AFTER_CHANGE: list = [] log = logging.getLogger("formchem.store") @@ -210,6 +212,14 @@ 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, "report": doc["meta"]["imported"].get("report", [])} + 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.") @@ -432,6 +442,11 @@ async def _applied(self, doc_id: str, result: dict, client: str | None, agent: s if agent: message["agent"] = agent await HUB.broadcast_all(message) + for hook in list(AFTER_CHANGE): + try: + await hook(doc_id, result) + except Exception: + log.exception("a change hook failed for %s", doc_id) self.schedule_derive(s) history.after_change(s, result["tx"].get("origin", "user")) 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/build_app b/build_app index bb0e3f52..df7d668a 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,18 +226,23 @@ 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}." \ --add-data "$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[@]}"} \ "$ROOT/backend/formchem_engine.py" ) @@ -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 diff --git a/docs/AGENTS.md b/docs/AGENTS.md new file mode 100644 index 00000000..bc01b310 --- /dev/null +++ b/docs/AGENTS.md @@ -0,0 +1,286 @@ +# FormChem for agents + +From 0.8.0 an agent draws in FormChem directly. The engine's MCP server has 42 tools: it opens and makes drawings, draws structures and reaction schemes from SMILES or molfiles, builds and edits them atom by atom by id, reads every structure back in machine form, checks its own work with a picture drawn by the window's own renderer, and converts files with the same code as the command line. The person watches every change land in the FormChem window, can undo any agent call in one step, and can stop an agent at any time. + +This page is the reference for agent authors and for anyone wiring a client. The generated list of every argument is `.claude/skills/formchem-harness/references/tools.md` (`./formchem agents sync` writes it from the server); how to set a client up step by step is in the wiki's Agents page. + +## Contents + +- Connecting +- The agent token +- Asking the person, and Stop +- One call, one undo step +- What a write returns +- Which drawing a tool uses +- The tools +- Errors +- The agent call log +- Example: draw aspirin and check it +- Example: build acetic acid atom by atom +- Where the code lives +- Known limits + +## Connecting + +| Transport | Address | Credentials | +| --- | --- | --- | +| HTTP (Streamable HTTP) | `http://127.0.0.1:8220/mcp` (`FORMCHEM_PORT`, else `engine.json` in the data folder, else 8220) | `Authorization: Bearer ` on every POST and DELETE | +| stdio | `./formchem mcp` (`setup/mcp_stdio.py`), which relays to HTTP and starts the engine when it is not running | none to set: it reads the token file itself | +| FormChem's own agent tabs | the Claude Code, Codex, Cursor and Antigravity tabs of the dock | a per-tab token the tab sends (`x-formchem-inapp`); never asked for consent | + +Protocol versions 2026-07-28 and 2025-11-25 are spoken; 2025-06-18, 2025-03-26 and 2024-11-05 are accepted. The engine listens on loopback only and refuses requests whose Host or Origin is not local. `./formchem agents install` writes the configs for Claude Code (`.mcp.json`, with the token), Codex (`.codex/config.toml`), Cursor (`.cursor/mcp.json`) and Antigravity (`~/.gemini/config/mcp_config.json`), and installs the skills. + +## The agent token + +Before 0.8.0 any program on the computer could call the HTTP endpoint. From 0.8.0 `POST /mcp` and `DELETE /mcp` answer only a request that carries one of: `Authorization: Bearer `, a live in-app tab token, or the window key. Anything else gets: + +``` +HTTP/1.1 401 Unauthorized +www-authenticate: Bearer realm="FormChem" + +{"jsonrpc": "2.0", "id": null, "error": {"code": -32001, "message": "FormChem's MCP endpoint needs the agent token: send the header Authorization: Bearer , the token being the one line in agent-token in FormChem's data folder. Run ./formchem agents install in the FormChem folder to write it into your agent's config, or use the stdio transport (./formchem mcp), which sends it itself."}} +``` + +- The token is one line in `agent-token` in the data folder (`~/formchem`, or `FORMCHEM_DATA_DIR`), 32 random bytes, readable by the owner only. The engine creates it at start, or `./formchem agents install` does, whichever runs first. +- `./formchem agents token` prints it. The Agents dialog (Window > Agents and MCP) shows the setup lines with it filled in. +- To change it, delete the file and restart the engine (a replaced file is picked up without a restart), then run `./formchem agents install` again. +- The `.mcp.json` files that install writes hold the token. Keep them out of version control; FormChem's own `.gitignore` does. +- If a client that worked with 0.7.0 stops connecting, run `./formchem agents install` again, or add the header to its FormChem entry. + +``` +$ curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:8220/mcp -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"ping"}' +401 +$ curl -s -X POST http://127.0.0.1:8220/mcp -H "Authorization: Bearer $(./formchem agents token)" -H 'Content-Type: application/json' -d '{"jsonrpc":"2.0","id":1,"method":"ping"}' +{"jsonrpc": "2.0", "id": 1, "result": {}} +``` + +## Asking the person, and Stop + +Reading never asks. The first change an outside agent makes asks the person in the FormChem window: Deny, Allow once (that call only) or Always allow (for every outside agent, until the person changes it). Only the window can change the choice, and the engine seals the saved value with a key in the system keychain. + +| Tool | Asks the person | +| --- | --- | +| `get_context`, `list_open_documents`, `render`, `get_structure`, `validate`, `compute_properties`, `get_atoms`, `list_commands`, `extensions_list`, `export_reaction`, `reaction_stoichiometry`, `properties`, `check_structure`, `stereo`, `substructure` | never | +| `new_document`, `open_document`, `save_document`, `close_document`, `draw_from_smiles`, `draw_from_molfile`, the 14 edit tools, `run_command`, `extension_command`, `perceive_reactions`, `map_reaction` | the first time | +| `convert` | only with `output` outside the system's temporary folder | +| `batch_convert` | unless its output folder is inside the temporary folder | +| `handoff` | only with a `state` | + +While an agent changes the drawing the person is looking at, the title bar shows "[agent] is editing" with a Stop button. Stop refuses every further call of that agent name, reads included, with a sentence that tells the agent to ask the person to allow it again; it also withdraws Always allow, so every outside agent is asked again on its next change. A call already running when Stop is pressed finishes. The person lets the agent in again from Agent activity (Allow again); its next change asks first. Stops last until the engine restarts. Agents are known by the MCP `clientInfo` name (or the in-app tab's name), so two sessions with one name stop together. + +## One call, one undo step + +Every tool that changes a drawing applies exactly one transaction, with origin `agent` and the agent's name, so one Edit > Undo in the window (or one Undo in Agent activity) removes the whole call, whatever it did: a 13-atom structure, a reaction scheme of eight objects, or one charge. Calls never merge with each other or with the person's edits. The undo label names the tool: Draw from SMILES, Draw from Molfile, Draw Reaction from SMILES, Add atom, Add bond, Set charge, Set atom, Set stereo, Replace substructure, Delete, Move, Scale, Align, Lay Out Structure, Clean Up Structure, Add arrow, Add text, Add reaction. A call that changes nothing says so and adds no undo step. + +## What a write returns + +Every draw and edit tool, and `open_document`, answers with the structure it now holds and a picture of it, so the agent can check its work without another call: + +``` +content: + {type: "text", text: " (rev N, one undo step).\n- \"\": · · · atoms\nPicture: W x H PNG drawn by the window."} + {type: "image", mimeType: "image/png", data: ""} +structuredContent: + doc the drawing id + rev its revision after the call + changed true when a transaction landed + undo "one step", or null when nothing changed + objects per touched object: id, kind, atoms, bonds, smiles, cxsmiles, inchikey, formula, mw, warnings, valence_errors + (a group lists its fragments; a deleted id has gone: true) + image renderer ("window" or "engine"), mime, width, height, warnings + ... the tool's own fields: new (draw), edit and label (edit tools), created and shown, notes, reaction +``` + +The values come from the engine's derived cache after the transaction, never echoed from the input. The picture is the touched objects at up to 640 x 480 pixels. If no picture can be made the image is left out and the text says why; the write still stands. + +## Which drawing a tool uses + +`doc` when given; else the only open drawing; else the drawing the FormChem window shows; else the tool asks for `doc` (an id from `list_open_documents`). `draw_from_smiles`, `draw_from_molfile`, `add_atom` and `add_reaction` make a new drawing when none is open, show it in the window, and close it again when their input cannot be read. The 0.5.0 and 0.6.0 tools (the reaction and analysis tools) still need `doc` when several drawings are open. + +Coordinates are points, x to the right and y down, on the page; the default bond length is 14.4 points. Ids are the ones the tools return (`fragment`, `atom`, `bond`, `arrow` and so on); they never change while the object exists. + +## The tools + +Arguments with `?` are optional. The full argument notes are in the generated tools reference. + +### Context and documents + +| Tool | Arguments | Result | +| --- | --- | --- | +| `get_context` | none | version, `window`, `windows`, `agentsAllowed`, `agentsBlocked`, `inapp`, `documents`, `drawingTools: true`, `drawingFrom`, `commands` (catalogue size), `handoff` | +| `list_open_documents` | none | `documents` (`id`, `title`, `path`, `dirty`, `rev`, `fragments`, `formula`), `active` (the drawing the window shows), `window` | +| `new_document` | `title?` | `doc`, `title`, `shown`; the drawing shows in the window | +| `open_document` | `path` (absolute: `.fchem`, molfile, SD, RXN, RD, SMILES, CXSMILES, CML, CDXML, CDX, InChI, or a picture FormChem exported with its drawing) | a write result of the objects on the first page, with `opened`, `title`, `shown`, `objectsOnPage` and the import `warnings`; a file already open is not opened twice | +| `save_document` | `doc?`, `path?` (absolute; `.fchem` added) | `doc`, `saved` (the path), `rev`, `bytes`. With no path and no file yet it saves to a free name in the Drawings folder. It never writes over another existing file | +| `close_document` | `doc?` | `doc`, `closed`. A drawing with unsaved changes is not closed | + +### Drawing + +| Tool | Arguments | Result | +| --- | --- | --- | +| `draw_from_smiles` | `smiles` (SMILES, CXSMILES or reaction SMILES; one structure per line), `doc?`, `x?`, `y?` (top-left in points), `name?` | a write result with `new` (the new object ids), `created`, `shown`, `notes`, and `reaction` for a scheme | +| `draw_from_molfile` | `molfile` (V2000 or V3000, or SD records, with line breaks), `doc?`, `x?`, `y?` | as above; the file's own coordinates are kept at the drawing's bond length | +| `add_reaction` | `reaction_smiles`, `doc?`, `x?`, `y?`, `page?` | a write result of the scheme's objects; the reaction step is recorded with its roles | + +Structures are laid out with FormChem's scored 2D layout and placed in free space: right of the page's content, top aligned, two bond lengths clear, when it fits the page width; otherwise below it at the left. A page that holds an arrow always grows downwards, so a new structure never lands after an arrow where it would read as a product. With `x` and `y` the drawing goes exactly there, and a note says when it overlaps something. A reaction SMILES (`reactants>agents>products`) draws the structures, plus signs and an arrow with the agents above it, exactly as Insert Reaction does. + +### Checking + +| Tool | Arguments | Result | +| --- | --- | --- | +| `render` | `doc?`, `scope?` (`object`, `selection` or `page`; default `object` with ids, else `page`), `ids?`, `format?` (`png` or `svg`), `width?`, `height?` (16 to 8192 px), `dpi?` (18 to 1200, default 144) | an image block (PNG) or the SVG text, and `doc`, `scope`, `ids`, `format`, `renderer`, `width`, `height`, `warnings` | +| `get_structure` | `doc?`, `object?` (a fragment or group id), `selection?` (true: what the person selected) | `fragments`: per fragment `id`, `name`, `atoms`, `bonds`, `smiles`, `cxsmiles`, `inchi`, `inchikey`, `formula`, `mw`, `exact_mass`, `mz` (charged only), `elemental_analysis`, `warnings`, `molfile`, `molfile_version`; `more` when over 200 | +| `validate` | `doc?`, `object?` | the structure check per fragment (issues with `code`, `severity`, `text`, `atoms`, `bonds`, `fix`) and `valid` (no errors, every fragment read) | +| `compute_properties` | `doc?`, `object?` | per fragment the Analysis panel's properties, each with `method` (the RDKit call) and `note` | + +With a window open, `render` is drawn by the window with the same renderer as File > Export, in the person's display preferences, arrows, plus signs, text and brackets included, on white. With no window, or when the window does not answer within 25 seconds, the engine draws the structures in the journal style and leaves out arrows and text; `renderer` and the text always say which. The molfile of `get_structure` is V2000 unless the structure needs V3000 (more than 999 atoms or bonds, AND or OR stereo groups, queries, R-groups, dative or hydrogen bonds). `validate` and `compute_properties` are the same checks as `check_structure` and `properties`, which stay for agents written against 0.6.0. + +### Editing by id + +| Tool | Arguments | What it does | +| --- | --- | --- | +| `get_atoms` | `doc?`, `object?` | per fragment `id`, `page`, `formula`, `smiles`, `inchikey`; per atom `id`, `element`, `x`, `y`, `charge`, isotope, label, radical, `h` (implicit hydrogens), `cip`, `bonds`; per bond `id`, `a`, `b`, `order`, `stereo`, `cip`. Reads only | +| `add_atom` | `element` (symbol, or `*`), `bond_to?`, `order?` (1, 2, 3, 1.5 or single, double, triple, aromatic), `fragment?`, `x?`, `y?`, `doc?` | adds one atom; bonded, it sits at the bond length in the freest direction (a zigzag for chains, the widest gap at a branch) | +| `add_bond` | `atom1`, `atom2`, `order?` (also 4, dative, zero, hydrogen, ionic), `stereo?` (`none`, `wedge`, `hash`, `hollow`, `wavy`, `either`), `doc?` | bonds two atoms; on two bonded atoms it sets that bond's order and wedge; atoms of two fragments join into one. The narrow end of a wedge is at `atom1` | +| `set_charge` | `atom`, `charge` (-15 to 15), `doc?` | sets the formal charge; hydrogens follow the valence | +| `set_atom` | `atom`, `element?`, `isotope?` (0 for natural), `label?`, `radical?` (`none`, `doublet`, `singlet`, `triplet`), `doc?` | changes one atom; a new element drops the label, hydrogen count and isotope, as the window's element menu does | +| `set_stereo` | `atom` or `bond`, `label` (R, S, E or Z), `doc?` | R or S rewrites that centre's wedges; E or Z mirrors the smaller side of a chain double bond. Fails with the reason when it cannot | +| `replace_substructure` | `smarts`, `replacement` (SMILES, with `*` for the attachment if needed), `object?`, `all?`, `doc?` | replaces matches as RDKit ReplaceSubstructs does; untouched atoms keep their ids and places, and a difference from RDKit's own result is reported | +| `delete` | `ids` (atoms, bonds, objects), `doc?` | deletes as the window's Delete does: an atom takes its bonds, an emptied fragment and an emptied group go | +| `move` | `ids`, `dx?`, `dy?`, `doc?` | moves atoms and objects by points; anchored captions follow | +| `scale` | `ids?`, `percent?` (5 to 2000) or `bond_length?`, `labels?`, `doc?` | makes structures larger or smaller on the sheet, each about its own centre (all of them without ids); `labels` scales line widths, labels and text too | +| `align` | `ids`, `mode` (`left`, `centre`, `right`, `top`, `middle`, `bottom`, `distribute_h`, `distribute_v`), `doc?` | lines up two or more objects, or spaces three or more evenly | +| `clean_layout` | `objects?`, `mode?` (`clean` or `layout`), `doc?` | Clean Up or Lay Out with the scored layout; flips wedges the new geometry would invert; reports the layout score before and after (0 is best) | +| `add_arrow` | `from`, `to?` ([x, y] or an object, atom or bond id), `kind?` (15 arrow types, default `forward`), `bend?`, `head?`, `tail?`, `page?`, `doc?` | adds an arrow; object ends stop half a bond length outside the object, atom and bond ends are anchored (electron pushing) | +| `add_text` | `text`, `x?`, `y?`, `style?` (`plain`, `formula`, `bold`, `italic`), `size?`, `align?`, `below?` (an id to caption), `page?`, `doc?` | adds text; `formula` writes subscripts; `below` makes a caption that moves with its structure | + +Every edit tool answers with a write result whose `edit` field says what it did (the new atom and bond ids, what was replaced, the score before and after, and so on). Text above or below a reaction arrow becomes the step's conditions once `perceive_reactions` runs; text with `formula` set counts as conditions too. + +### Converting + +| Tool | Arguments | Result | +| --- | --- | --- | +| `convert` | `input` (structure text, or the absolute path of a file), `from?`, `to` (`smiles`, `cxsmiles`, `sdf`, `molfile`, `inchi`, `inchikey`, `cml`, `rxn`, `rsmiles`, `fchem`), `output?` (absolute path), `v3000?`, `standardise?` (`default` or step names) | `text` (the converted text, up to 2 MB) or `written_to`, with `records`, `written`, `failed`, `warned`, `seconds`, `format_in`, `format_out`, `standardised`, and `rows` of failed records (at most 50) | +| `batch_convert` | `input_dir`, `to`, `output_dir?` (default `converted` inside the input folder), `standardise?`, `recursive?`, `v3000?` | per file the same summary, the totals, `seconds` and `report` (the path of `formchem-batch-report.csv` when any record failed) | + +Both run the code behind `./formchem convert` and `./formchem batch` ([CLI.md](CLI.md)), so the output is byte for byte the same. Neither writes over an existing file or into a folder that already holds files. A long batch answers when it is done; there is no progress stream. + +### Window commands, extensions and handoffs + +| Tool | Arguments | Result | +| --- | --- | --- | +| `list_commands` | `text?`, `group?`, `id?`, `limit?` | the window's command catalogue (id, label, group, what it does, params, whether it is on now) | +| `run_command` | `id`, `params?`, `confirm?` | runs one command in the window as the person's click would; one undo step for a changing command | +| `extensions_list` | none | the Form extensions found, their state and commands | +| `extension_command` | `id`, `command`, `args?` | runs an extension's command in the window | +| `handoff` | `state?` (`working`, `ready`, `question`, `clear`), `note?` | shows where the agent's work stands in the window; without a state, lists the handoffs | + +The commands reach what the drawing tools do not: export and print (the person picks where to save), the clipboard, Standardise, the grid and dark page, templates, the chemistry commands and dialogs. + +### Reactions and analysis (0.5.0 and 0.6.0) + +`perceive_reactions {doc?, page?}` and `map_reaction {doc?, reaction?, step?, mode?}` write; `export_reaction {doc?, reaction?, step?, format?}`, `reaction_stoichiometry {doc?, reaction?, step?}`, `properties {doc?, object?}`, `check_structure {doc?, object?, query?}`, `stereo {doc?, object?}` and `substructure {doc?, smarts or query_object, objects?, chirality?, max_hits?}` read. They are described in [REACTIONS.md](REACTIONS.md) and [ANALYSIS.md](ANALYSIS.md). + +### Resource + +`formchem://guide` (text/markdown): what exists in this version, the tools, asking the person and the errors. The server's `instructions` say the same in short. + +## Errors + +A tool that cannot act answers `isError: true` with one sentence that names the next step, such as "No drawing is open. draw_from_smiles or new_document makes one; open_document {path} opens a file.", "Several drawings are open and no window shows one of them; give doc, an id from list_open_documents.", "The person did not allow agents to edit drawings in FormChem. Ask them to allow it in the FormChem window, then retry." or "The person stopped [agent]'s access to FormChem from the window. Tell them what you were about to do and ask them to allow you again (Agent Activity, in the Window menu), then retry." Do the step once, then report; never retry a refusal in a loop. + +## The agent call log + +Every tool call, from HTTP, stdio, the in-app tabs or the window's own chat, passes through one function in the engine (`call_tool`) and is logged: agent, tool, an argument summary, start time, duration, status (`running`, `ok`, `error`, `refused`), whether it writes, the drawing, the transaction and the objects it touched, and the first line of its answer. In the summary strings are clipped at 48 characters, a molfile shows as its line count and anything that looks like a token, secret, password, API key or cookie shows as `(hidden)`. A call that runs a window command gets the transaction the window sends for it during the call or within 1.5 seconds after. + +| Route | Needs the window key | What it does | +| --- | --- | --- | +| `GET /api/agents/calls?limit=&agent=` | no | the log, newest first, with `undoable` (drawing id to the call on top of its undo stack), `agents`, `stopped`, `cap` and `file` | +| `POST /api/agents/calls/clear` | yes | empties the log in memory (the files stay; running calls stay) | +| `POST /api/agents/calls/{id}/undo` | yes | undoes that call while it is still the latest step of its drawing, else 409 | +| `POST /api/agents/stop {agent}` | yes | stops an agent and withdraws Always allow | +| `POST /api/agents/allow {agent}` | yes | lets a stopped agent in again | +| `GET /api/agents/token` | yes | `token`, `header`, `value` and `file`, for the Agents dialog | + +The live socket sends `agentCall {call}` when a call starts, ends and gets a transaction, `agentUndoable {doc, call}` when the undoable call of a drawing changes, `agentAccess {agent, state, stopped}` and `agentCallsCleared {kept}`. The engine keeps the newest 400 calls in memory and appends each finished call as one JSON line to `Agent log/-.jsonl` in the data folder (rotated at 1 MB, three older parts, the newest 20 engine sessions kept). + +In the window, Window > Agent Activity shows the log, and the title bar chip shows the call in progress (see the wiki's Agent Activity page). + +## Example: draw aspirin and check it + +The exit criterion of 0.8.0, recorded through `./formchem mcp` against a running window (images cut to their length): + +``` +> {"jsonrpc": "2.0", "method": "tools/call", "params": {"name": "draw_from_smiles", "arguments": {"smiles": "CC(=O)Oc1ccccc1C(=O)O", "name": "aspirin"}}, "id": 3} +< {"content": [{"type": "text", "text": "Drew the SMILES in dgka5nssq (a new drawing): 1 new object (rev 1, one undo step).\n- f0880vzr9 \"aspirin\": C9H8O4 · CC(=O)Oc1ccccc1C(=O)O · BSYNRYMUTXBXSQ-UHFFFAOYSA-N · 13 atoms\nPicture: 171 x 134 PNG drawn by the window."}, + {"type": "image", "data": "(7048 characters of base64)", "mimeType": "image/png"}], + "structuredContent": {"doc": "dgka5nssq", "rev": 1, "changed": true, "undo": "one step", + "objects": [{"id": "f0880vzr9", "kind": "fragment", "atoms": 13, "bonds": 13, "smiles": "CC(=O)Oc1ccccc1C(=O)O", "cxsmiles": "CC(=O)Oc1ccccc1C(=O)O", + "inchikey": "BSYNRYMUTXBXSQ-UHFFFAOYSA-N", "formula": "C9H8O4", "mw": 180.159, "warnings": [], "name": "aspirin"}], + "image": {"renderer": "window", "mime": "image/png", "width": 171, "height": 134, "warnings": []}, + "created": true, "shown": true, "notes": [], "new": ["f0880vzr9"]}} + +> {"name": "render", "arguments": {"ids": ["f0880vzr9"]}} +< "PNG of the object (f0880vzr9) of dgka5nssq, 171 x 134, drawn by the FormChem window's own renderer, as the person sees it." + the image + +> {"name": "get_structure", "arguments": {"object": "f0880vzr9"}} +< f0880vzr9 "aspirin": C9H8O4 · 13 atoms + SMILES CC(=O)Oc1ccccc1C(=O)O + CXSMILES CC(=O)Oc1ccccc1C(=O)O + InChI InChI=1S/C9H8O4/c1-6(10)13-8-5-3-2-4-7(8)9(11)12/h2-5H,1H3,(H,11,12) + InChIKey BSYNRYMUTXBXSQ-UHFFFAOYSA-N + MW 180.159 · monoisotopic 180.042259 + Molfile (V2000): ... +``` + +With a fresh data folder the person clicked Allow once in the consent box for the draw call, and that was the only click. The window showed the new drawing with the chip "[agent] just edited" and the aspirin outlined for a moment; Agent activity listed get_structure, render and draw_from_smiles; one `Ctrl+Z` in the window removed the aspirin (rev 2, no fragments) and marked the draw row Undone. Before handing back, `validate {object: "f0880vzr9"}` starts its answer with "Valid: no errors." or names each error with its atom ids. + +## Example: build acetic acid atom by atom + +Edit tools by id, in the same drawing (each answer also carries a window-drawn PNG): + +``` +> add_atom {"element": "C"} +< Added C atom awkeofqrr to fragment f4d5o29ev, as a new fragment (rev 3, one undo step). + - f4d5o29ev: CH4 · C · VNWKTOKETHGBQD-UHFFFAOYSA-N · 1 atom +> add_atom {"element": "C", "bond_to": "awkeofqrr"} +< Added C atom ak684b952 to fragment f4d5o29ev, bonded to awkeofqrr by single bond bez8fahca (rev 4, one undo step). + - f4d5o29ev: C2H6 · CC · OTMSDBZUPAUEDD-UHFFFAOYSA-N · 2 atoms +> add_atom {"element": "O", "bond_to": "ak684b952"} +< Added O atom ajqlc4you to fragment f4d5o29ev, bonded to ak684b952 by single bond bneehnipa (rev 5, one undo step). + - f4d5o29ev: C2H6O · CCO · LFQSCWFLJHTTHZ-UHFFFAOYSA-N · 3 atoms +> add_atom {"element": "O", "bond_to": "ak684b952", "order": 2} +< Added O atom a0xo059aq to fragment f4d5o29ev, bonded to ak684b952 by double bond bh0hegvkw (rev 6, one undo step). + - f4d5o29ev: C2H4O2 · CC(=O)O · QTBSBXVTEAMEQO-UHFFFAOYSA-N · 4 atoms +> set_charge {"atom": "ajqlc4you", "charge": -1} +< Charge of ajqlc4you: 0 -> -1 (rev 7, one undo step). + - f4d5o29ev: C2H3O2- · CC(=O)[O-] · QTBSBXVTEAMEQO-UHFFFAOYSA-M · 4 atoms +``` + +Five calls, five undo steps: Undo in Agent activity five times walked back through CC(=O)O, CCO, CC and C to an empty page, and every row ended Undone. The same flow can be written with `add_bond` (ethanol plus an O at `x, y`, then `add_bond {atom1: "", atom2: "", order: 2}`), and `get_atoms` lists the ids when an agent has lost them. + +## Where the code lives + +| Path | What it holds | +| --- | --- | +| `backend/app/routers/mcp.py` | the server: `TOOLS`, `MUTATING`, the `t_` handlers, `call_tool`, the token check, `INSTRUCTIONS` and `GUIDE` | +| `backend/app/services/agent_out.py` | the write result, `render` through the window and its engine fallback, free space | +| `backend/app/services/agent_draw.py` | structures and reaction schemes from text as one set of ops | +| `backend/app/services/agent_edits.py` | the edit tools as pure builders `fn(doc, args) -> (ops, info)` | +| `backend/app/services/agent_convert.py` | convert and batch through `services/batch.py` | +| `backend/app/services/agent_log.py`, `routers/agent_activity.py` | the call log and its routes | +| `backend/app/core/agent_token.py` | the agent token | +| `frontend/src/app/agent-window.ts` | the `render`, `selection` and `show` window tools | +| `frontend/src/app/agent-activity.ts`, `ui/agent-activity.ts`, `ui/agent-chip.ts`, `canvas/agent-marks.ts` | Agent activity, the editing chip and the marks | +| `setup/mcp_stdio.py`, `setup/agents.py` | the stdio relay, `./formchem agents install`, `sync` and `token` | + +The reasons behind these choices are in `backend/HASHOUT_LOG.md` (entries 133 to 164) and `frontend/HASHOUT_LOG.md` (187 to 200). + +## Known limits + +- The reaction and analysis tools of 0.5.0 and 0.6.0 still need `doc` when several drawings are open. +- Read-only calls show no drawing in Agent activity. +- There is no `draw_from_name` yet; names wait for the decision on how name to structure ships. +- Agents cannot type amounts into the Stoichiometry panel. The export and copy commands hand their file to the person; use `convert` for text the agent can read. +- `perceive_reactions` lists the conditions below an arrow before those above it. +- Not run for 0.8.0: the macOS desktop app, and real Claude Code or Codex clients (the tools were checked with the stdio transport, curl and a browser window). diff --git a/docs/CLI.md b/docs/CLI.md new file mode 100644 index 00000000..949977c8 --- /dev/null +++ b/docs/CLI.md @@ -0,0 +1,161 @@ +# FormChem command line + +Four commands convert, describe and draw whole files of structures without opening the window, built from 0.7.0: `convert`, `batch`, `descriptors` and `render`. They run the engine's chemistry in-process from the source tree (the engine's `backend/venv`), with no server and no window. The formats they read and write are described in [FORMATS.md](FORMATS.md). + +## Contents + +- Quick start +- convert +- batch +- descriptors +- render +- Standardising first +- Failed records and exit codes +- Speed and parallel jobs +- Where the code lives +- Known limits + +## Quick start + +``` +./formchem convert big.sdf big.smi --errors failed.csv +./formchem convert salts.smi - --to smiles --standardise +./formchem convert in.sdf out.inchikey --jobs 0 +./formchem batch ~/mols --to sdf --out ~/mols-sdf --jobs 2 +./formchem descriptors big.sdf --csv props.csv --props mw,clogp,tpsa,hbd,hba,lipinski_violations +./formchem render big.sdf --out pictures --format png --size 600x400 +``` + +On Windows use `formchem.bat` with the same arguments; type the command name (`convert`, `batch`, `descriptors`, `render`) in lower case there. Paths are relative to the folder you ran the command from. + +## convert + +``` +./formchem convert IN OUT [--from FMT] [--to FMT] [--standardise [STEPS]] [--errors FILE] [--jobs N] [--v3000] [-q] +./formchem convert --formats +./formchem convert --steps +``` + +Converts one file. The formats come from the extensions, or from `--from` and `--to` when an extension does not say. `OUT` may be `-` to write to the terminal (then `--to` is required). + +| Id | Read | Write | Extensions | +| --- | --- | --- | --- | +| `sdf` | yes | yes (data fields kept) | `.sdf`, `.sd` | +| `molfile` | yes | yes (V2000; `--v3000`, or by itself past 999 atoms or bonds) | `.mol`, `.mdl` | +| `smiles` | yes | yes | `.smi`, `.smiles`, `.ism` | +| `cxsmiles` | yes | yes | `.cxsmi`, `.cxsmiles` | +| `inchi` | yes | yes | `.inchi`, `.ich` | +| `inchikey` | no | yes | `.inchikey`, `.key` | +| `cml` | yes | yes | `.cml` | +| `rxn` | yes | yes (reaction records only) | `.rxn` | +| `rsmiles` | yes | yes (reaction records only) | `.rsmi` | +| `rdf` | yes | no | `.rdf`, `.rd` | +| `cdxml`, `cdx` | yes (through Indigo) | no | `.cdxml`, `.cdx` | +| `fchem` | yes (every structure of every page, in page order) | yes (up to 1000 structures in rows on one page; the rest are reported) | `.fchem` | + +Any input may be gzip-compressed (`.sdf.gz`, `.smi.gz`). SMILES, InChI and InChIKey lines are written as `TEXT name`; the SMILES is the engine's canonical form, the same as the window's identifiers. Formats that hold one structure per file (molfile, CML, RXN) write `OUT` itself for one record and `OUT-0001.mol`, `OUT-0002.mol` and so on for more. + +Example: + +``` +$ ./formchem convert small.smi - --to smiles --standardise +CC(=O)Oc1ccccc1C(=O)O aspirin +O=C(O)c1ccccc1 sodium benzoate +converted 2 of 3 records from SMILES to SMILES in 0.01 s; 1 failed; standardise changed 1 by neutralise, 1 by salts + small.smi record 3 (broken): SMILES Parse Error: unclosed ring for input: 'C1CC' +``` + +## batch + +``` +./formchem batch DIR --to FMT [--out DIR] [--jobs N] [--standardise [STEPS]] [--recursive] [--errors FILE] [--v3000] +``` + +Converts every readable file in `DIR` into `OUT` (default `DIR/converted`, which is never read back as input), as the file's stem plus the target extension. With `--recursive` subfolders are converted too and mirrored under `OUT`. When two inputs would give the same name (`a.sdf` and `a.smi` to SMILES), the second becomes `a-smi.smi`. When anything fails, `OUT/formchem-batch-report.csv` lists it. + +`./formchem batch` converts files; `./formchem cli batch` is a different command that runs several window commands at once. + +## descriptors + +``` +./formchem descriptors IN --csv OUT [--props LIST] [--standardise [STEPS]] [--jobs N] [--errors FILE] +./formchem descriptors --list +``` + +Writes one CSV row per record: `record`, `name`, `smiles`, then the columns of `--props`. The values and their rounding are exactly those of the Analysis panel. The default columns are `formula`, `mw`, `exact_mass`, `clogp`, `mr`, `tpsa`, `tpsa_sp`, `hbd`, `hba`, `hbd_refined`, `hba_refined`, `rotatable_bonds`, `heavy_atoms`, `rings`, `aromatic_rings`, `fraction_csp3`, `formal_charge`, `stereocentres`, `undefined_stereocentres` and `pieces`; `--props all` adds `inchi`, `inchikey`, `lipinski_violations` and `veber_violations`. `--list` prints every column with its unit and method (for example `clogp cLogP Crippen.MolLogP`), which keeps the CSV to one header row. A reaction has no descriptors; give single structures. + +``` +$ ./formchem descriptors small.smi --csv props.csv --props mw,clogp,tpsa +record,name,smiles,mw,clogp,tpsa +1,aspirin,CC(=O)Oc1ccccc1C(=O)O,180.16,1.31,63.6 +2,sodium benzoate,O=C([O-])c1ccccc1.[Na+],144.1,-2.95,40.13 +``` + +## render + +``` +./formchem render IN --out DIR [--format svg|png] [--size W[xH]] [--transparent] [--standardise [STEPS]] [--jobs N] [--errors FILE] +``` + +Draws one picture per record, named `NNNNN-name.svg` or `.png` (the name made safe for file names, at most 60 characters). Reactions are drawn with their arrow. Without `--size` the drawing is at the journal scale (14.4 pt bonds); SVG is sized in points and PNG is 300 dpi. `--size` fits each drawing into that many pixels, and `--transparent` leaves out the white background. + +The command line draws with RDKit, not with the window's renderer, set close to the journal style: 0.6 pt lines, 10 pt Arimo labels, black and white. It places labels, hydrogens, wedges and double bonds its own way, has no aromatic or charge circles, and draws only the structures of a `.fchem` file, not its text, arrows or styles. For pictures exactly as the window draws them, use File > Export. + +## Standardising first + +Every command takes `--standardise` (also spelt `--standardize`): alone, it runs the default set of steps; with a value, it runs the steps named. Put it after the file names, or give it a value, because the value is optional. + +| Step | Default | What it does | +| --- | --- | --- | +| `cleanup` | yes | sanitises the structure, fixes hypervalent nitro and perchlorate groups, breaks bonds from metals to N, O and halogens into ions | +| `normalise` | yes | writes nitro, N-oxide, azide, diazo, sulfoxide and similar groups in one form | +| `salts` | yes | removes counter-ions and solvents on the built-in list, never the last fragment | +| `largest` | no | keeps the largest organic fragment | +| `reionise` | yes | moves charges so the strongest acid group is the one ionised | +| `neutralise` | yes | removes charges by adding or removing hydrogens where the species stays the same | +| `tautomer` | no | the canonical tautomer of RDKit's scoring rules (2-hydroxypyridine to 2-pyridone); keeps stereo | +| `isotopes` | no | sets every atom to natural abundance, so D becomes H | +| `stereo` | no | removes tetrahedral and double bond stereo | +| `strip_h` | yes | removes drawn H atoms, keeping those with an isotope, a map number or a wedge | + +Steps always run in this order, whatever order you give them. Examples: `--standardise`, `--standardise all`, `--standardise salts,neutralise,tautomer`, `--standardise default,tautomer,-strip_h`. The -ize spellings and a few other names (`strip_salts`, `largest_fragment`, `uncharge`, `hydrogens`) are accepted. `./formchem convert --steps` prints the list with the RDKit method behind each step. The window's Structure > Standardise... uses the same steps. + +## Failed records and exit codes + +A record that cannot be read or written never stops a run. Without `--errors` the first 20 failures are printed as `file record N (name): reason`, with a count of the rest; with `--errors FILE` every failed or warned record goes to a CSV with the columns `file`, `record` (counted from 1), `name`, `status` (`failed` or `warning`) and `message`. The reason is RDKit's own message, such as `Explicit valence for atom # 0 C, 5, is greater than permitted` or `Atom line too short: 'garbage line' on line 5`. + +| Exit code | Meaning | +| --- | --- | +| 0 | at least one record was written | +| 1 | nothing was written (no empty output file is left behind) | +| 2 | bad arguments: an unknown format, step or column, or a missing file | +| 130 | stopped with Ctrl+C | + +## Speed and parallel jobs + +`--jobs N` sets the number of worker processes (`0` is one per CPU). SD, SMILES, CXSMILES and InChI inputs are split into chunks of 1000 records, and the pool is used only when there are at least two chunks. `batch` spreads files over the pool and gives a lone file the whole pool. Output order always equals input order. + +Timings on a two-core Linux machine with other work running (RDKit 2025.09.3, Python 3.13), for an SD file of 10,000 varied NCI structures (15 MB, metal complexes and salts included): + +| Run | Time | +| --- | --- | +| SD to SMILES, one process (the whole command, Python start included) | 1.4 s | +| SD to SMILES, `--jobs 2` | 0.7 to 1.3 s | +| SD to SD | 1.5 s | +| SD to InChIKey | 4.1 s | +| SD to SMILES with `--standardise`, one process / `--jobs 2` | 22.3 s / 13.1 s | +| descriptors, every default column, one process / `--jobs 2` | 9.5 s / 4.3 to 5.3 s | +| render SVG, `--jobs 2` | 14.3 s | +| render PNG at 300 dpi, `--jobs 2` | 47.6 s | + +Standardising costs about 2 ms a record, most of it the canonical SMILES taken after each step to tell whether it changed anything. + +## Where the code lives + +`backend/app/cli.py` parses the arguments (started as `python -m app.cli` from `backend/` by `setup/convert` and `setup/convert.bat`, which `./formchem` and `formchem.bat` call). `backend/app/services/batch.py` holds the runners (`convert_file`, `batch`, `descriptors_file`, `render_file`), `services/chem/records.py` adapts records to the writers, `services/chem/stream.py` reads files record by record without building drawings, `services/chem/standardise.py` holds the steps and `services/chem/depict.py` draws. From 0.8.0 the agent tools `convert` and `batch_convert` call the same runners with the same options (`backend/app/services/agent_convert.py`), so an agent gets byte for byte the output of `./formchem convert` and `./formchem batch`, including `formchem-batch-report.csv`; they never write over an existing file or into a folder that already holds files ([AGENTS.md](AGENTS.md)). The reasons are in `backend/HASHOUT_LOG.md` entries 114, 122 to 128 and 141. + +## Known limits + +- The command line runs from the source tree; the desktop app does not include it yet. +- CDXML, CDX and RD files can be read but not written from the command line, and SMARTS is not offered; File > Export writes all four from a drawing. +- `formchem.bat` and the process pool on macOS and Windows (the spawn start method) were not run for this version. diff --git a/docs/EXTENSIONS.md b/docs/EXTENSIONS.md index 37fc49a0..52c05be3 100644 --- a/docs/EXTENSIONS.md +++ b/docs/EXTENSIONS.md @@ -63,7 +63,11 @@ Commands that work in 0.3.0 (besides the window ones such as New Drawing, Open, | `redo` | | redoes it | | `insert-smiles` | | asks for a SMILES string and adds the structure to the middle of the first page | | `toggle-analysis` | | shows or hides the Analysis panel | -| `show-grid` | | shows or hides the drawing grid | +| `show-grid` | `on` | shows or hides the drawing grid (toggles without `on`) | +| `snap-to-grid` | `on` | turns snapping to grid points on or off (toggles without `on`); built from 0.7.0 | +| `grid-type` | `type`, `scope` | sets the grid type: `lines`, `dots`, `crosses`, `isometric`, `isometric-dots`, `hex` or `hex-dots`, for the drawing (one undo step) or, with `scope` `default`, for new drawings; built from 0.7.0 | +| `grid-spacing` | `value`, `unit`, `scope` | sets the distance between grid points: a number in `unit` (`pt`, `mm`, `cm`, `in`; default the drawing units) or `"bond"` for the bond length; built from 0.7.0 | +| `grid-settings` | `type`, `spacing`, `unit`, `major`, `strength`, `scope` | applies any of these at once; without arguments it opens the Grid Settings dialog; built from 0.7.0 | | `command-palette` | | opens Find a Command | | `view-terminal` | | shows or hides the terminal dock | | `new-terminal` | | opens another terminal tab | diff --git a/docs/FORMAT.md b/docs/FORMAT.md index ed99b9ee..bc49a8c3 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -76,7 +76,7 @@ In a map (a JSON object keyed by id, such as `objects`, `atoms`, `bonds`), the k | `objects` | the map of every object in the document by id, on every page | | `expansions` | optional map of abbreviation expansions by id (built from 0.6.0) | | `media` | optional map of media files by id: `{ "name": "tlc.png", "mime": "image/png", "bytes": 48211, "w": 800, "h": 600, "sha256": "..." }`. The bytes live in the package, never in document.json | -| `meta` | free metadata: `author`, `app` (the writer and its version), `locale`, `notes`, and `data` (free key-value pairs for agents and lab notebooks). Readers keep keys they do not know | +| `meta` | free metadata: `author`, `app` (the writer and its version), `locale`, `notes`, and `data` (free key-value pairs for agents and lab notebooks). Keys the app writes itself: `imported` (`name`, `format` and, from 0.7.0, `report`, the import report items of a file opened from another format), `embedded` (`scope` and `from`, on the copy of a drawing carried inside an exported picture, 0.7.0) and `clipboard` (`kind`, `from`, `page`, optional `media`, on a clipboard payload, 0.7.0). Readers keep keys they do not know | Readers keep top-level keys they do not know and write them back unchanged. A document never contains `derived` (see The derived cache); a reader that finds one drops it. @@ -107,11 +107,31 @@ 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`. 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). +### 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. + +The window keeps three things about the grid outside the document, per device: whether the grid is shown, whether snapping is on, and the default grid for drawings without `style.grid`. None of them is written into a file. + ### Built-in presets Built-in presets are referenced by these fixed ids. User presets live in `presets` with their own ids (prefix `s` is customary) and a `name`. @@ -325,9 +345,9 @@ Built from 0.5.0. `page.reactions` lists reactions; each is `{ "id": "r...", "st "explicit": false, "coefficients": { "f1...": 2 } } ``` -`arrow` is the arrow object the step is bound to. Roles are object ids on the same page. With `explicit` false the roles were inferred from geometry (left of the tail: reactants; right of the head: products; in the arrow's band above or below: agents, and text there: conditions) and are recomputed when objects move; with `explicit` true the person or an agent set them and they are kept. Plus signs carry no role. Products of one step may be reactants of the next. +`arrow` is the arrow object the step is bound to. Roles are object ids on the same page. With `explicit` false the roles were inferred from geometry (left of the tail: reactants; right of the head: products; in the arrow's band above or below: agents, and text there, `formula` text included: conditions) and are recomputed when objects move; with `explicit` true the person or an agent set them and they are kept. Plus signs carry no role. Products of one step may be reactants of the next. -Inference measures along the arrow's shaft: an object is an agent or condition when its centre lies between the tail and the head and it comes within 1.5 bond lengths of the shaft; reactants and products must come within 2.5 bond lengths of the shaft's line and may overlap the tail or head by 0.5 bond lengths. Walking away from the arrow, the nearest structure takes the role and the next one joins only across a plus sign or a gap under 1 bond length. A retrosynthetic arrow swaps the sides; resonance, curved, fishhook, arc, plain, fragmentation and dissociation arrows are not steps. A step read from a reaction file has `explicit` true. +Inference measures along the arrow's shaft: an object is an agent or condition when its centre lies between the tail and the head and it comes within 1.5 bond lengths of the shaft; reactants and products must come within 2.5 bond lengths of the shaft's line and may overlap the tail or head by 0.5 bond lengths. Walking away from the arrow, the nearest structure (or text with `formula` true) takes the role and the next one joins only across a plus sign or a gap under 1 bond length. A retrosynthetic arrow swaps the sides; resonance, curved, fishhook, arc, plain, fragmentation and dissociation arrows are not steps. A step read from a reaction file has `explicit` true. A step may carry `stoich` (built from 0.5.0), the person's amounts for a stoichiometry grid: diff --git a/docs/FORMATS.md b/docs/FORMATS.md new file mode 100644 index 00000000..004d1580 --- /dev/null +++ b/docs/FORMATS.md @@ -0,0 +1,255 @@ +# FormChem formats and exchange + +How FormChem reads and writes chemistry files and pictures, what each format keeps and loses, the report items that say so, and the HTTP routes behind File > Open, File > Export, File > Import and the clipboard, built from 0.7.0. FormChem's own `.fchem` file is defined in [FORMAT.md](FORMAT.md), which wins over this page; the command line that converts whole files is in [CLI.md](CLI.md). + +## Contents + +- Where the code lives +- The formats +- What each format keeps +- Pictures and the drawing inside them +- Reports +- HTTP API +- The window +- Round trips +- Known limits + +## Where the code lives + +The engine code is in `backend/app/services/chem/`: `formats.py` (the table of formats), `report.py` (report items), `io.py` (readers), `writers.py` (writers), `cdxio.py` (CDXML and CDX through Indigo), `rdfio.py` (RD files), `cml.py` (CML) and `stream.py` (record by record reading for batch work). Pictures are in `backend/app/services/pictures/` (`fonts.py`, `svgdraw.py`, `pdf.py`, `eps.py`) and `backend/app/services/embedded_source.py`. The routes are in `backend/app/routers/chem.py`, `documents.py`, `files.py` and `pictures.py`. In the window, `frontend/src/app/picture.ts` builds pictures, `embedded-source.ts` carries the drawing inside them, `save-file.ts` saves every exported file and `export-commands.ts` holds the File > Export commands. The reasons for each choice are in `backend/HASHOUT_LOG.md` entries 106 to 121 and `frontend/HASHOUT_LOG.md` entries 169 to 179. + +## The formats + +One table in `formats.py` describes every format. The window's list of what a format will lose before saving and the report after saving both read it, so they agree. + +| Id | Name | Extensions | Read | Write | Several structures | Reactions | +| --- | --- | --- | --- | --- | --- | --- | +| `molfile` | MDL molfile, V2000 or V3000 chosen by the drawing | `.mol`, `.mdl` | yes | yes | merged into one | no | +| `molfile3000` | MDL molfile V3000 | `.mol` | yes | yes | merged into one | no | +| `sdf` | SD file | `.sdf`, `.sd` | yes | yes | one record each | no | +| `rxn` | MDL reaction file | `.rxn` | yes | yes | the first step | yes | +| `rdf` | RD file | `.rdf`, `.rd` | yes | yes | one record each | yes, every step | +| `smiles` | SMILES | `.smi`, `.smiles` | yes | yes | one line each | as reaction SMILES | +| `cxsmiles` | CXSMILES | `.cxsmi`, `.cxsmiles` | yes | yes | one line each | as reaction SMILES | +| `rsmiles` | Reaction SMILES | `.smi`, `.rsmi` | yes | yes | steps only | yes | +| `smarts` | SMARTS | `.sma`, `.smarts` | yes | yes | one line each | no | +| `inchi` | InChI | `.inchi` | yes | yes | one line each | no | +| `inchikey` | InChIKey | `.txt` | no | yes | one line each | no | +| `cml` | Chemical Markup Language | `.cml` | yes | yes | yes | yes, several | +| `cdxml` | CDXML drawing | `.cdxml` | yes | yes | yes | yes | +| `cdx` | CDX drawing (binary) | `.cdx` | yes | yes | yes | yes | + +Aliases accepted wherever a format id is: `mol` and `mdl` (molfile), `v3000` (molfile3000), `sd`, `rd`, `smi`, `cxsmi`, `sma`, `rxnv3000` (rxn) and `reaction_smiles` (rsmiles). Options: the molfile family takes `version` (`auto`, `v2000` or `v3000`) and CXSMILES takes `coords` (write the coordinates). Any file may be gzip-compressed when it is read by the command line. + +A molfile switches to V3000 by itself when the drawing has more than 999 atoms or bonds, AND or OR stereo groups, query features, R-groups, or dative or hydrogen bonds; the report says why with a `v3000` item. Forcing V2000 strips the stereo groups first. The molfile chiral flag is written only when the structure says `chiral: "absolute"` (FORMAT.md), so another program may read unflagged stereo as relative. + +## What each format keeps + +What a format cannot hold is listed by feature in `GET /api/formats` (`loses`, plus `loses_v2000` for the molfile family): + +| Format | Loses | +| --- | --- | +| molfile, molfile3000 | text, drawing objects, positions on the page, abbreviations (written expanded), data fields, reaction roles, styles; V2000 also loses enhanced stereo, queries and R-groups | +| sdf | text, drawing objects, positions, abbreviations, reaction roles, styles; V2000 records also lose enhanced stereo, queries and R-groups | +| rxn | text, drawing objects, positions, abbreviations, data, every step after the first, styles; V2000 as above | +| rdf | text, drawing objects, positions, abbreviations, styles; V2000 as above | +| smiles, rsmiles | text, drawing objects, positions, coordinates, enhanced stereo, queries, R-groups, abbreviations, data, conditions, styles | +| cxsmiles | text, drawing objects, positions, queries, R-groups, abbreviations, data, conditions, styles (it keeps enhanced stereo, labels and, with `coords`, coordinates) | +| smarts | text, drawing objects, positions, coordinates, enhanced stereo, R-groups (written as any atom), abbreviations, data, reaction roles, styles | +| inchi | everything but the structure: text, drawing objects, positions, coordinates, enhanced stereo, queries, R-groups, abbreviations, data, names, map numbers, reaction roles, styles, and the drawn tautomer and charge placement (InChI normalises them) | +| inchikey | everything except a hashed identity | +| cml | text, drawing objects, positions, enhanced stereo, queries, R-groups, abbreviations, map numbers, styles | +| cdxml, cdx | R-groups, abbreviations, data, names, styles (colours, fonts and the bond length; Indigo writes Arial and Times and a bond length of 30) | + +More about the formats that need it: + +- **SD files** are read with FormChem's own record splitter, so data fields are kept, V2000 and V3000 records can be mixed and a record that fails is skipped and counted. On writing, each structure is one record with its name in the header and its `data` as fields, and R-group members stay inside their scaffold's V3000 record. +- **RXN**: the title line becomes the step's name and the comment line its conditions. Only the first step is written; RD files and CML keep every step. +- **RD files** hold reaction (`$RFMT`) and molecule (`$MFMT`) records with data fields; a field whose name ends in CONDITIONS is read as the step's conditions, and each written step carries `RXN:CONDITIONS`. +- **SMILES and CXSMILES** files are one structure per line, `SMILES name`; a line with two `>` is a reaction. Query structures cannot be written as plain SMILES (`query_refused`); use SMARTS or a V3000 molfile. +- **SMARTS** files are `.sma` lines with optional names. Chirality in SMARTS is drawn as wedges on reading and written so that it reads back the same. +- **InChI** files are lines of `InChI=... name`. Amides that InChI hands back as iminols are drawn as amides again. +- **CML**: molecules with or without a namespace, `propertyList` as data, `label` for R and pseudo atoms, and reactions that refer to molecules by `ref` (several reactions and a `conditionList` included). The writer uses the same dialect. +- **CDXML and CDX** go through Indigo 1.49 and its document JSON: structures, arrows (mapped to FormChem arrow types), plus signs and text with bold, italic, underline, subscript, superscript and size come in; reaction steps are worked out from where things sit. On writing, structures, arrows, plus signs and text go out. See Known limits for what Indigo cannot carry. + +Documents read at most 1000 records of a file; the command line and the stream reader read any number. + +## Pictures and the drawing inside them + +File > Export writes pictures from the document model, never from the screen, so the dark page, the selection and the grid never reach them. + +| Format | What it is | Labels | The drawing inside | +| --- | --- | --- | --- | +| SVG | vector, sized in points | text, with WOFF subsets of Arimo and Tinos embedded as `@font-face`; programs that ignore them fall back to Arial, Helvetica or Times | `` holding `` | +| PNG | 72 to 600 dpi (300 by default), transparent or white, with a pHYs chunk giving the exact dpi | drawn | an uncompressed iTXt chunk with the keyword `application/x-formchem+json` | +| PDF | PDF 1.7, one page, vector | glyph outlines, plus an invisible text layer so the labels can be searched and copied | an embedded file `drawing.fchem.json` (`/AFRelationship /Source`), stored uncompressed | +| EPS | Level 2 EPSF-3.0 with a tight bounding box, vector | glyph outlines | `%FormChemSource:` comment lines of base64 | + +The drawing inside a picture is a plain document.json (FORMAT.md) holding one page and only the exported objects, with `meta.embedded = { "scope": "page" | "selection" | "structure", "from": "" }`. Pictures placed in the drawing are drawn into the export but left out of the embedded drawing, because their bytes are not carried. File > Open reads `.svg`, `.png`, `.pdf` and `.eps` files that hold a drawing and opens it as a new drawing with the file name as its title; the same drawing pastes back from the clipboard. "Keep the editable drawing inside the file" in the export dialog turns it off. + +Scope is Whole page (everything on the page, cropped to the drawing plus the margin, 6 pt by default), Selection (partly selected structures keep only the selected atoms and the bonds between them) or Each structure (one file per structure, named after the structure's name or the drawing's title and a number). Scale is a percent of real size: at 100 percent one point of the drawing is one point in the file. Gradients become their mean colour in PDF and EPS, and EPS has no transparency; a warning says so. + +## Reports + +Every reader and writer returns report items of one shape: + +```json +{ "code": "enhanced_stereo_lost", "count": 2, "text": "2 enhanced stereo groups (AND, OR) are not stored in SMILES; the centres are written as plain stereo.", + "severity": "warn", "atoms": ["a3", "a7"], "bonds": [], "objects": ["f1"] } +``` + +`code` is stable, so a program can act on it; `text` is a short English sentence; `count` is how many things the item covers; `atoms`, `bonds` and `objects` are present when known. Severity is `info` for routine changes, `warn` for real loss and `error` for a record or structure that failed. Items are merged by code and sorted error, warn, info, at most 200. + +Import codes (File > Open, File > Import, paste, `POST /api/chem/parse`): + +| Code | Severity | Meaning | +| --- | --- | --- | +| `record_failed` | error | a record could not be read and was skipped | +| `parse_failed` | error | part of the file could not be read | +| `structure_problem` | warn | valence or aromaticity problems, kept as drawn | +| `valence_fixed` | warn | atoms had their valence or hydrogen count adjusted | +| `stereo_unknown` | warn | stereocentres or double bonds of unknown configuration | +| `cannot_kekulise` | warn | aromatic systems that could not be kekulised | +| `unknown_label` | warn | labels that are not elements or known abbreviations | +| `sgroups_dropped` | warn | Sgroups (brackets, data or superatoms) that were not read | +| `unsupported_object` | warn | drawing objects of kinds FormChem does not read | +| `coordinates_generated` | info | structures without 2D coordinates got a layout | +| `coordinates_flattened` | info | 3D coordinates flattened to 2D | +| `rescaled` | info | a drawing scaled to the document's bond length | +| `styles_dropped` | info | fonts, colours and line breaks of text approximated | +| `abbreviations_expanded` | info | abbreviations read as their full structures | +| `inchi_normalised` | info | InChI normalised the tautomer or charges | +| `bond_length_changed`, `reaction_layout` | info | routine layout notes | +| `left_out` | warn | File > Import read only the first `limit` records; the count says how many were left out | +| `pages_left_out` | warn | File > Import inserted only the first page with content of a drawing | +| `pictures_left_out` | warn | pictures inside an embedded drawing could not be carried over | + +Export codes (File > Export, Copy As, `GET /api/documents/{id}/export`, `POST /api/chem/export`): + +| Code | Severity | Meaning | +| --- | --- | --- | +| `text_dropped`, `graphics_dropped` | warn | text, arrows, plus signs and other objects the format does not store | +| `enhanced_stereo_lost` | warn | AND and OR groups written as plain stereo | +| `query_lost` | warn | query features not stored | +| `rgroups_lost` | warn | R-group definitions not stored; R-group atoms written as any atoms | +| `data_dropped`, `maps_dropped` | warn | data fields or atom map numbers not stored | +| `names_dropped`, `styles_dropped` | info | structure names or styles not stored | +| `reactions_dropped` | warn | reaction steps written as separate structures | +| `steps_dropped` | warn | RXN holds one step; the others are not written | +| `structures_dropped` | warn | structures outside the reaction are not written to RXN | +| `conditions_dropped` | warn | reaction SMILES has no place for the conditions text | +| `query_refused` | warn | a query structure cannot be written as SMILES | +| `components_split` | warn | a salt or mixture written to CDXML reads back as one structure per part | +| `arrow_straightened` | warn | a curved arrow written straight to CDXML or CDX | +| `coordinates_dropped` | info | the format keeps no coordinates; a layout is made on reading | +| `molfile_merged` | info | several structures written as one molfile; use SD to keep them apart | +| `v3000` | info | written as V3000, and why | +| `tautomer_normalised` | info | InChI may give back a different tautomer | +| `inchi_unavailable`, `inchi_failed`, `inchi_warning` | warn, error, warn | the InChI library could not write a structure, or warned | +| `smarts_any_atom`, `smarts_bond_simplified`, `smarts_chirality`, `smarts_opaque`, `smarts_rgroups`, `smarts_stereo_groups` | warn | what SMARTS could not express exactly | +| `report_truncated` | info | the report was too long for the response header; ask with `as=json` | + +The window shows warn and error items after an export, and after opening a file from another program it shows a short note with a Details panel listing every item; the file on disk is never changed. The report of an opened file is kept in `meta.imported.report` until the drawing is saved as `.fchem`. + +## HTTP API + +Every POST needs the window key header (`x-formchem-window-key`), like every other POST in the engine; GETs do not. + +### GET /api/formats + +```json +{ "formats": [ { "id": "molfile", "name": "MDL molfile", "extensions": [".mol", ".mdl"], "mime": "chemical/x-mdl-molfile", + "read": true, "write": true, "binary": false, "multi": false, "reactions": false, + "scopes": ["document", "page", "selection", "fragments"], + "options": { "version": ["auto", "v2000", "v3000"] }, + "loses": [ { "code": "text", "text": "Text and captions" } ], + "loses_v2000": [ { "code": "enhanced_stereo", "text": "Enhanced stereo groups (AND, OR, ABS)" } ] } ], + "features": { "text": "Text and captions" }, "engine": "rdkit 2025.09.3" } +``` + +### GET /api/documents/{id}/export + +Query: `format` (an id or alias), `scope` (`page` by default, `selection` or `document`), `page` (a page id; default the first page), `ids` (comma-separated object ids for `selection`; groups are expanded and atom ids are refused with a 422 naming the id), `options` (URL-encoded JSON such as `{"version":"v3000"}` or `{"coords":true}`) and `as` (`bytes` by default, or `json`). + +- `as=bytes` answers the file body with `Content-Type` set to the format's mime (`; charset=utf-8` for text), `Content-Disposition: attachment` with `filename` and `filename*`, and `X-FormChem-Filename` (URL-encoded), `X-FormChem-Format` (the format actually written, so a molfile that switched says `molfile3000`) and `X-FormChem-Report` (URL-encoded JSON list, at most 8 KB, else one `report_truncated` item), all listed in `Access-Control-Expose-Headers`. +- `as=json` answers `{ "format", "filename", "mime", "binary", "text" | null, "base64" | null, "report": [...] }`. +- The suggested filename is the structure's name when the scope holds exactly one named structure, else the drawing's title, made safe, plus the format's first extension. +- Errors: 404 for an unknown document; 422 `{ "detail": { "message", "report" } }` for an unknown format or scope, nothing to write, a query written as plain SMILES, or Indigo refusing (CDX of a query). + +### POST /api/chem/export + +```json +{ "format": "sdf", "fragments": [ { "kind": "fragment", "atoms": {}, "bonds": {} } ], "objects": {}, "reactions": [], + "expansions": {}, "options": {}, "name": "Aspirin" } +``` + +`fragments` is a list or a map by id, validated like `/api/chem/convert`; `objects` (arrows, plus signs, text) and `reactions` (page reaction records) are optional. The answer is the `as=json` shape above. + +### POST /api/chem/parse + +Body `text` and an optional `format`, `bond_length` and `origin`, as before 0.7.0, or `base64` instead of `text` for binary data: CDX is recognised by its `VjCD0100` signature when no format is given. New format ids are `rdf` and `smarts`. The answer gains `report` (import report items), `reactions` (every step when there is more than one) and `objects` (arrows, plus signs and text read from CDXML or CDX). + +### POST /api/documents/open and /api/documents/upload + +As before, plus `report` when the file was imported from another format; `warnings` (strings) stays and holds the report texts. Both also open `.svg`, `.png`, `.pdf` and `.eps` pictures that carry a FormChem drawing, and refuse one that does not with a 400 whose message says it "has no FormChem drawing inside". + +### POST /api/documents/import + +Reads a file for File > Import without opening it as a drawing: nothing is added to the open drawings, the recent list or the Imports folder. + +```json +{ "path": "/Users/me/data/three.sdf", "bond_length": 14.4, "limit": 50 } +``` + +Send JSON with an absolute `path`, or a multipart field `file` with `?bond_length=&limit=` in the query. `bond_length` (1 to 500) is the target drawing's, so the structures arrive at its size; `limit` (1 to 1000, default 50) caps the records read. The answer is `{ "name", "format", "document", "media", "keep_style", "structures", "report", "warnings" }`: `document` is a document.json holding the structures laid out as a table, `media` the bytes of placed pictures of a `.fchem` file as data URLs, and `keep_style` says whether the window should keep the file's look (FormChem drawings and pictures) or use the target's (chemistry files). Chemistry files, `.fchem` files and pictures that carry a drawing are accepted, up to 50 MB; a relative or missing path is a 400. The window inserts the document through the clipboard's paste plan, as one undo step per file. + +### POST /api/files/write + +The desktop window shows the native save dialog and asks the engine to write the file, because the window cannot. + +```json +{ "path": "/Users/me/Desktop/Aspirin.svg", "text": "", "picked": true } +``` + +Send `text` (written as UTF-8) or `base64`. The answer is `{ "path", "bytes" }`. The engine refuses a relative path, a folder that does not exist, a folder as the target, a file over 200 MB, an extension outside its list (pictures `.svg`, `.svgz`, `.png`, `.pdf`, `.eps`, `.ps`; chemistry `.mol`, `.mdl`, `.sdf`, `.sd`, `.rxn`, `.rdf`, `.rd`, `.smi`, `.smiles`, `.cxsmi`, `.cxsmiles`, `.sma`, `.smarts`, `.inchi`, `.key`, `.cml`, `.cdxml`, `.cdx`, `.helm`, `.xyz`, `.mol2`, `.pdb`; data `.txt`, `.csv`, `.tsv`, `.json`, `.jdx`, `.dx`), and any path outside the home folder unless `picked` is true, which the window sends only for a path the person chose in a save dialog. `.fchem` files go through the drawing's own save path. The write is atomic. Agents on `/mcp` do not hold the window key and cannot call it. + +### Pictures + +- `GET /api/pictures/capabilities` answers `{ "formats": ["eps", "pdf"], "fonts": true }`; `fonts` is false when fontTools is missing. +- `POST /api/pictures/fonts` with `{ "faces": [ { "family": "Arimo", "bold": false, "italic": false, "text": "OHN" } ] }` answers WOFF subsets as base64 and lists the faces it could not find in `missing`. +- `POST /api/pictures/convert` with `{ "format": "pdf" | "eps", "svg": "", "source": "" | null, "title": "..." }` answers `{ "base64", "mime", "warnings" }`. + +## The window + +- **File > Open** reads every format above, pictures that carry a drawing and `.fchem`. A file from another program opens as a new, unsaved drawing, with the import report. +- **File > Import...** brings the structures, reactions and objects of one or more files (chemistry files, `.fchem` drawings and pictures that carry a drawing) into the drawing that is open, in free space to the right of or below what is there, selected, as one undo step per file, with the import report. An SD file brings at most 50 structures, laid out in a table, and the report says how many were left out; File > Open reads the whole file. Agents pass `path`. +- **File > Export** has Export Picture... (the dialog: format, scope, resolution, background, scale, margin and "Keep the editable drawing inside the file", remembered between exports), Export as PNG..., SVG..., PDF..., EPS..., CDXML..., Molfile... and SMILES..., and Print.... In the desktop app each one shows the native save dialog (Each structure asks for a folder); in a browser it downloads. +- **Edit > Copy As** writes SMILES, CXSMILES, Molfile, InChI, InChIKey, SMARTS, SVG, PNG or CDXML to the clipboard, and **Paste** reads every text format above. The clipboard is described in the wiki page Clipboard. +- Agents run the same through `run_command`: `export-png`, `export-svg`, `export-pdf`, `export-eps`, `export-picture`, `export-cdxml`, `export-mol`, `export-smiles`, `print`, the `copy-*` commands and `paste-special`. + +## Round trips + +A corpus of fourteen drawings (benzene, aspirin, caffeine, L-alanine, Taxol, sodium acetate, tetramethylammonium, chloroform-d, an AND group pair, an atom-list query, a Markush scaffold with two R1 members, an esterification with a conditions text, a two-step oxidation scheme, and a drawing with text, a curved arrow and a plus sign) was exported to every format and read back, comparing atoms and bonds, stereo and CIP labels, enhanced stereo, charges, isotopes, queries, R-groups, names, data, text, arrows and steps. "ok" means nothing was lost; every loss is named by a report item (code in brackets). + +| Drawing | molfile | sdf | rdf | smiles | cxsmiles | smarts | inchi | cml | cdxml, cdx | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| benzene, aspirin, caffeine, L-alanine, charged, isotope, Taxol | ok | ok | ok | ok (coordinates_dropped) | ok | ok | names (names_dropped) | ok | names | +| sodium acetate | ok | ok | ok | ok | ok | ok | names | ok | one structure per ion (components_split), names | +| AND group | ok (V3000) | ok | ok | groups lost (enhanced_stereo_lost) | ok | groups lost (smarts_stereo_groups) | groups lost | groups lost | names | +| atom-list query | ok (V3000) | ok | ok | refused (query_refused) | refused | ok | refused (inchi_unavailable) | query lost (query_lost) | CDXML names; CDX refused by Indigo | +| Markush R1 | ok (V3000) | ok | ok | R-groups lost (rgroups_lost) | R-groups lost | R as any atom (smarts_rgroups) | refused for the scaffold | R-groups lost | members lost | +| esterification with conditions | merged, arrow and text lost | reaction and text lost | ok | conditions lost (conditions_dropped) | conditions lost | reaction and text lost | reaction and text lost | ok | ok | +| two-step scheme | merged (molfile_merged) | steps lost (reactions_dropped) | ok | ok | ok | steps lost | steps lost | ok | ok | +| text, curved arrow, plus | text and graphics lost (text_dropped, graphics_dropped) | same | same | same | same | same | same | same | arrow written straight (arrow_straightened) | + +RXN keeps the esterification whole and the first step of the scheme (steps_dropped); it refuses drawings without a reaction. Pictures were checked separately: Taxol and the esterification exported as SVG, PNG, PDF and EPS reopen with the same object, atom and bond ids, no coordinate change, the same wedges and the same reaction steps. + +Timings on a two-core Linux machine: the whole corpus to every format and back in about 3 s; Taxol from SMILES, CXSMILES or InChI in about 0.13 s each; 10,000 SD records to SMILES through the stream reader in 0.73 s, against about 11 s through the drawing reader, which is why batch work uses the stream reader (see CLI.md). + +## Known limits + +- CDXML and CDX go through Indigo, which does not carry colours, fonts (it writes Arial and Times), the bond length (it writes 30), line breaks in text (read back as spaces), curved arrows (written straight), shapes, brackets, tables, TLC plates and images, structure names and data, or R-group members on reading. Query structures cannot be written as CDX. Only files written by Indigo were tested, not files from the program that made the format. +- Enhanced stereo is lost in CML, SMILES, InChI and SMARTS, conditions in SMILES, and every step after the first in RXN: these are limits of the formats. Abbreviations are written as their full structures in every format but `.fchem`. +- Chemical names are not read: a name pasted as text becomes a text object. +- EPS was checked by reopening its drawing, not by drawing it in a PostScript viewer. +- In the desktop app the engine writes where the window says the person chose; it cannot prove a save dialog produced the path, and relies on the window key and its list of extensions. diff --git a/formchem b/formchem index b2f41818..5f3ad4be 100755 --- a/formchem +++ b/formchem @@ -16,15 +16,24 @@ 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) claude [args] Claude Code in this terminal with FormChem's MCP tools attached + convert IN OUT [--from FMT] [--to FMT] [--standardise [STEPS]] [--errors FILE] [--jobs N] + convert a structure file (SD, SMILES, CXSMILES, InChI, molfile, RXN, CML, CDXML, CDX, .fchem) without the window; + --formats lists the formats, --steps the standardise steps (cleanup, normalise, salts, largest, reionise, + neutralise, tautomer, isotopes, stereo, strip_h; the default set without a list) + batch DIR --to FMT [--out DIR] [--jobs N] [--standardise [STEPS]] [--recursive] + convert every structure file in a folder (default DIR/converted, with formchem-batch-report.csv) + descriptors IN --csv OUT [--props LIST] calculated properties of every record as CSV (--list for the columns and methods) + render IN --out DIR [--format svg|png] [--size W[xH]] one image per record in the journal style (PNG at 300 dpi) + failed records never stop a run: they are listed, or written to --errors FILE; exit 1 when nothing was written cli list|describe|run|batch the window's command catalogue from a terminal: list [text], run (the window must be open) i18n check|scan|export|import the translations: check for gaps, find new strings, or a language as CSV for a native reviewer and back mcp FormChem over MCP's stdio transport, for Claude Desktop and other MCP clients - agents install|sync set up Claude Code, Codex, Cursor and Antigravity to draw with FormChem (install), or refresh the skills (sync) + agents install|sync|token set up Claude Code, Codex, Cursor and Antigravity to draw with FormChem (install), refresh the skills (sync), or print the HTTP MCP token (token) clean [--all] remove build output (--all also venv and node_modules) help this text EOF @@ -52,6 +61,7 @@ case "$cmd" in doctor) exec setup/doctor "$@" ;; counts) exec setup/counts "$@" ;; claude) exec python3 setup/claude_launch.py "$@" ;; + convert|batch|descriptors|render) exec setup/convert "$cmd" "$@" ;; cli) exec python3 setup/catalogue.py "$@" ;; i18n) exec python3 setup/i18n_tool.py "$@" ;; mcp) exec python3 setup/mcp_stdio.py "$@" ;; diff --git a/formchem.bat b/formchem.bat index a68c687e..5e958e82 100644 --- a/formchem.bat +++ b/formchem.bat @@ -36,6 +36,10 @@ if /i "%CMD%"=="desktop" ( if /i "%CMD%"=="doctor" ( call setup\doctor.bat %REST% & goto :eof ) if /i "%CMD%"=="counts" ( call setup\counts.bat %REST% & goto :eof ) if /i "%CMD%"=="claude" ( python setup\claude_launch.py %REST% & goto :eof ) +if "%CMD%"=="convert" ( call setup\convert.bat %* & goto :eof ) +if "%CMD%"=="batch" ( call setup\convert.bat %* & goto :eof ) +if "%CMD%"=="descriptors" ( call setup\convert.bat %* & goto :eof ) +if "%CMD%"=="render" ( call setup\convert.bat %* & goto :eof ) if /i "%CMD%"=="cli" ( python setup\catalogue.py %REST% & goto :eof ) if /i "%CMD%"=="i18n" ( python setup\i18n_tool.py %REST% & goto :eof ) if /i "%CMD%"=="mcp" ( python setup\mcp_stdio.py %REST% & goto :eof ) @@ -67,10 +71,19 @@ echo desktop dev^|build^|check run, bundle (takes --config FILE) or check the echo doctor check the toolchain, installs and ports echo counts [--check] the README's code sizes (--check: exit 1 if README.md has drifted) echo claude [args] Claude Code in this terminal with FormChem's MCP tools attached +echo convert IN OUT [--from FMT] [--to FMT] [--standardise [STEPS]] [--errors FILE] [--jobs N] +echo convert a structure file (SD, SMILES, CXSMILES, InChI, molfile, RXN, CML, CDXML, CDX, .fchem) without the window; +echo --formats lists the formats, --steps the standardise steps (cleanup, normalise, salts, largest, reionise, +echo neutralise, tautomer, isotopes, stereo, strip_h; the default set without a list) +echo batch DIR --to FMT [--out DIR] [--jobs N] [--standardise [STEPS]] [--recursive] +echo convert every structure file in a folder (default DIR\converted, with formchem-batch-report.csv) +echo descriptors IN --csv OUT [--props LIST] calculated properties of every record as CSV (--list for the columns and methods) +echo render IN --out DIR [--format svg^|png] [--size W[xH]] one image per record in the journal style (PNG at 300 dpi) +echo failed records never stop a run: they are listed, or written to --errors FILE; exit 1 when nothing was written echo cli list^|describe^|run^|batch the window's command catalogue from a terminal (the window must be open) echo i18n check^|scan^|export^|import the translations: check for gaps, find new strings, or a language as CSV for a native reviewer and back echo mcp FormChem over MCP's stdio transport, for Claude Desktop and other MCP clients -echo agents install^|sync set up Claude Code, Codex, Cursor and Antigravity to draw with FormChem (install), or refresh the skills (sync) +echo agents install^|sync^|token set up Claude Code, Codex, Cursor and Antigravity to draw with FormChem (install), refresh the skills (sync), or print the HTTP MCP token (token) echo clean [--all] remove build output (--all also venv and node_modules) echo help this text exit /b 0 diff --git a/frontend/HASHOUT_LOG.md b/frontend/HASHOUT_LOG.md index 5910c7e5..866b72e4 100644 --- a/frontend/HASHOUT_LOG.md +++ b/frontend/HASHOUT_LOG.md @@ -1,6 +1,6 @@ # frontend HASHOUT_LOG -Living log for the FormChem frontend and its desktop shell (src-tauri), _v0.1.0 to _v0.6.0. For 0.1.0 and 0.2.0 it follows the family template (formdeck's window and formvis's title bar), so most reasons there are about what was kept, what was dropped, and why. From 0.3.0 it records the document client, the window's own chemistry, from 0.4.0 the canvas: renderer, tools, view and tool rail, and from 0.5.0 the drawn objects (arrows, symbols, brackets, shapes, tables, TLC, orbitals, images, captions, groups), their tools and handles, the stoichiometry panel, the template library and the Reaction commands, and from 0.6.0 the analysis client, the chemistry marks layer, the stereo, query, R-group and abbreviation commands and dialogs, the structure check panel, the properties section with the isotope plot, Set Reaction Roles, and the Tauri CLI pin. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. +Living log for the FormChem frontend and its desktop shell (src-tauri), _v0.1.0 to _v0.8.0. For 0.1.0 and 0.2.0 it follows the family template (formdeck's window and formvis's title bar), so most reasons there are about what was kept, what was dropped, and why. From 0.3.0 it records the document client, the window's own chemistry, from 0.4.0 the canvas: renderer, tools, view and tool rail, and from 0.5.0 the drawn objects (arrows, symbols, brackets, shapes, tables, TLC, orbitals, images, captions, groups), their tools and handles, the stoichiometry panel, the template library and the Reaction commands, and from 0.6.0 the analysis client, the chemistry marks layer, the stereo, query, R-group and abbreviation commands and dialogs, the structure check panel, the properties section with the isotope plot, Set Reaction Roles, and the Tauri CLI pin, and from 0.7.0 the one-folder engine start, the dark page, scaling on the sheet, the wrapping panel rows, the folding menu row, grids and snapping, picture export, print and the shared save path, the embedded source, the clipboard, the import report, Standardise and the quick command state mirror, and from 0.8.0 the window tools that render, report the selection and show drawings for agents, Agent activity, the editing chip with Stop, the agent marks and the token in the Agents dialog. The code carries almost no comments; the reasons live here, anchored by file and symbol. Read the map and the TOC first. ## Org navi map @@ -40,8 +40,21 @@ src/styles/ tokens.css (the only z-index source), base.css, shel stoich.css, templates.css, chem-marks.css, chem-ui.css public/ favicon.svg, manifest.webmanifest, splash.html index.html pre-paint script: theme, overlay title bar, native menus, dock reservation -src-tauri/src/ main.rs (windows, chrome), traffic_lights.rs, reveal.rs, engine_start.rs -src-tauri/ tauri.conf.json, capabilities, Info.plist, entitlements.plist, flatpak/ +src/canvas/ also dark-page.ts, grid.ts, grid-layer.ts, tools/scale.ts (0.7.0) +src/app/ also save-file.ts, embedded-source.ts, picture.ts, print.ts, export-commands.ts, grid-commands.ts, + clip-data.ts, clip-formats.ts, clip-system.ts, clip-picture.ts, clipboard.ts, standardise-command.ts, + import-files.ts (0.7.0) +src/engine/standardise-api.ts the client of /api/analysis/standardise (0.7.0) +src/ui/ also scale-dialog.ts, grid-dialog.ts, export-dialog.ts, import-report.ts, paste-special-dialog.ts, + standardise-dialog.ts (0.7.0) +src/styles/ also clipboard.css, standardise.css, print.css (0.7.0) +src/app/ also agent-window.ts (the render, selection and show window tools), agent-calls.ts (the call log + mirror), agent-activity.ts (panel, chip and marks wiring, the agent-activity command) (0.8.0) +src/ui/ also agent-activity.ts (the Agent activity panel), agent-chip.ts (who is editing, with Stop) (0.8.0) +src/canvas/agent-marks.ts the keyed layer that flashes what an agent call changed (0.8.0) +src/styles/ also agent-activity.css (0.8.0) +src-tauri/src/ main.rs (windows, chrome), traffic_lights.rs, reveal.rs, engine_start.rs, packaged.rs (0.7.0) +src-tauri/ tauri.conf.json, tauri.macos.conf.json (0.7.0), capabilities, Info.plist, entitlements.plist, flatpak/ assets/ formchem_mark.svg, icon_src/build.py, icon set ``` @@ -195,6 +208,58 @@ assets/ formchem_mark.svg, icon_src/build.py, icon set 146. Set Reaction Roles rewrites only the lists that changed · chem/reaction-roles.ts, ui/roles-dialog.ts, app/reaction-commands.ts 147. SMARTS export copies in the desktop shell · app/chem-commands.ts exportSmarts 148. Icons, stylesheets and strings of 0.6.0 · ui/icons.ts, styles/chem-marks.css, styles/chem-ui.css, index.html, i18n/keys/part06.json +149. The shell starts the engine folder on macOS · src-tauri/src/packaged.rs, src-tauri/src/main.rs, src-tauri/tauri.macos.conf.json +150. The splash floor stays at 2.6 s · src-tauri/src/reveal.rs, public/splash.html +151. The dark page is one attribute set before first paint · canvas/dark-page.ts, index.html +152. The whole drawing svg is filtered, the marks live beside it · canvas/render/renderer.ts, styles/canvas-view.css +153. Pictures are un-inverted by one colour matrix · canvas/dark-page.ts initDarkPage, styles/canvas-view.css +154. The dark-page command and its switches · app/canvas-commands.ts, app/menus.ts, canvas/context.ts, ui/prefs +155. Scaling a selection scales its sizes and styles too · canvas/tools/scale.ts scaleSelection +156. Corner handles, a frame and a readout · canvas/tools/scale.ts, canvas/view.ts, canvas/tools/select.ts +157. Scale commands, the dialog and the labels preference · app/canvas-commands.ts scaleCommands, ui/scale-dialog.ts, ui/prefs +158. Panel rows reserve the value column and wrap · styles/panel.css, styles/chem-ui.css, styles/dialogs.css +159. A container query stacks long values, not JS · styles/panel.css .fc-ap-body +160. Wrap points and the m/z row · ui/analysis-properties.ts glued, ionMz +161. Ink tokens for status text in light themes · styles/tokens.css, the status text rules +162. Menus that do not fit fold into More menus · ui/menu.ts MenuBar fold, live, step +163. The title bar measures the menu row · ui/titlebar.ts fitMenuRow, styles/shell.css, styles/titlebar.css, app.ts +164. Escape goes to an open bar menu first · canvas/view.ts ours, ui/menu.ts menuBarOpen +165. Grid lattices, the window default and snap state · canvas/grid.ts +166. The grid is one svg in the paper, drawn as page paths · canvas/grid-layer.ts GridLayer, planGrid +167. Snapping keeps bond geometry and lands lattice atoms · canvas/grid.ts snapStart, latticeDirections, snapRingCentre, tools +168. Grid commands, the dialog and the preferences · app/grid-commands.ts, ui/grid-dialog.ts, ui/prefs, app/menus.ts +169. One save path for every exported file · app/save-file.ts saveFile, saveFiles +170. The drawing inside a picture is a plain document · app/embedded-source.ts +171. Pictures come from the document model, off screen · app/picture.ts pictureSvg +172. PNG is the export SVG drawn into a canvas · app/picture.ts picturePng +173. The export dialog and the File > Export commands · ui/export-dialog.ts, app/export-commands.ts +174. Print sizes the paper to the page · app/print.ts printPicture, styles/print.css +175. The import report is a toast with a details panel · ui/import-report.ts, app/documents.ts +176. The clipboard payload is a document with a paste plan · app/clip-data.ts extractClip, pastePlan +177. Text formats out through the export route, in through parse · app/clip-formats.ts clipText, parseClipText +178. Several clipboard flavours with platform fallbacks · app/clip-system.ts writeClipboard, readClipboard +179. Keyboard copy and paste go through the DOM events · app/clipboard.ts mountClipboard, app/commands-shell.ts +180. The desktop windows may use the clipboard from script · src-tauri/src/main.rs chrome +181. Cut, Copy, Paste and Select All are system items on macOS · ui/native-menu.ts ALWAYS_NATIVE +182. Command state reaches the engine within 120 ms · app/catalogue.ts mirrorCatalogue +183. Standardise: a client, a dialog with a preview and one command · engine/standardise-api.ts, ui/standardise-dialog.ts, app/standardise-command.ts +184. Duplicate goes through the paste plan · app/canvas-commands.ts +185. File > Import inserts files into the open drawing · app/import-files.ts mountImport, freeSpot; app/clipboard.ts insert; app/commands-shell.ts import +186. Stylesheets, icons and strings of 0.7.0 · styles/clipboard.css, styles/standardise.css, styles/print.css, ui/icons.ts, index.html, i18n/keys/part07.json, part08.json +187. The window draws agent pictures with the export renderer · app/agent-window.ts render, rasterise +188. selection and show are window tools too · app/agent-window.ts selected, show +189. Window modules add their own window tools · app/window-tools.ts addWindowTool +190. The window mirrors the engine's call log · app/agent-calls.ts +191. Agent activity is one panel built once and patched by row · ui/agent-activity.ts +192. The editing chip shows who is changing this drawing, with Stop · ui/agent-chip.ts +193. What an agent changed flashes in a keyed marks layer · canvas/agent-marks.ts +194. Wiring Agent activity, and flashing what was drawn into a new drawing · app/agent-activity.ts +195. The Agents dialog carries the token · ui/agents-dialog.ts +196. The copied prompt explains the token without holding it · ui/chat-panel.ts PROMPT +197. A lone hydride is written hydrogen first · canvas/render/label.ts labelSide, chem/valence.ts HYDRIDE_FIRST +198. Engine messages after a translated prefix are translated too · app.ts errText and the module errText helpers +199. Analysis warnings and Standardise details translate one by one · ui/analysis-properties.ts, ui/standardise-dialog.ts +200. The agent activity stylesheet and the strings of 0.8.0 · styles/agent-activity.css, index.html ## 1. Dependencies are the template's, nothing more · _v0.1.0 (package.json) @@ -788,6 +853,214 @@ In a browser Export SMARTS downloads a `.sma` Blob. The desktop window has no fi Twelve glyphs in the shared 24 box were added: stereoCentre, stereoGroup, hydrogenAdd, hydrogenRemove, expandAbbr, contractAbbr, atomList, queryBond, rgroup, assignWedges, substructure and periodicTable (the last unused so far). chem-marks.css and chem-ui.css load after canvas-view.css and take every z-index from tokens. part06.json keys 154 strings (commands, submenus, dialogs, panels, toasts, undo labels and the property method sentences); plural forms are still built as a number plus a word, as elsewhere in the app. +## 149. The shell starts the engine folder on macOS · _v0.7.0 (src-tauri/src/packaged.rs engine_folder; src-tauri/src/main.rs setup; src-tauri/tauri.macos.conf.json) + +The one-file sidecar unpacked several hundred megabytes at every launch and macOS scanned every library again (backend log 99), which made the owner's app take about 30 seconds to open. On macOS the engine is now a folder that Tauri ships as a resource: `tauri.macos.conf.json` empties `externalBin` and adds `"engine": "engine"` to the resources (LICENSE, NOTICE.md and THIRD-PARTY-NOTICES.txt as in tauri.conf.json), so it lands in `FormChem.app/Contents/Resources/engine`. `engine_folder()` returns `/../Resources/engine/formchem-engine` (the app bundle) or `/engine/formchem-engine` (where `tauri dev` copies resources), and main.rs runs it with `app.shell().command(program)`; without it the shell falls back to `.sidecar("formchem-engine")`, which is what Linux and Windows still use. The environment (`FORMCHEM_PORT=0`, `FORMCHEM_PORT_PREFER=8221`, `FORMCHEM_WINDOW_KEY_STDOUT=1`, `FORMCHEM_SHELL_PID`), the output events, the 90 s address wait and the Windows job object are unchanged. A Rust-side `shell().command` is not scope-checked, so the capabilities did not change. The engine log stays at `FORMCHEM_DATA_DIR` or `~/formchem/Logs` (FormVis's portable mode, which logs beside the program, has no FormChem counterpart), and the engine's own "started without its app" relaunch already looks in `../../MacOS`, which from `Resources/engine` is `Contents/MacOS/FormChem`. Ported from FormVis 2.9.0 (Apache-2.0, same owner). + +## 150. The splash floor stays at 2.6 s · _v0.7.0 (src-tauri/src/reveal.rs SPLASH_MIN, BAR_FINISH; public/splash.html) + +`SPLASH_MIN` (2.6 s) counts from the first line of `main`, so it runs at the same time as the engine start; it is a floor, not a wait added after the engine. The page's `app_ready` waits for fonts, visible images (capped at 1.5 s) and two animation frames, and `BAR_FINISH` adds 220 ms. With the one-folder engine the expected macOS open time is max(2.6 s, engine start plus page load) plus 0.22 s. 2.6 s is the family value and matches the bar animation in splash.html; to show the window sooner, lower both together. + +## 151. The dark page is one attribute set before first paint · _v0.7.0 (canvas/dark-page.ts darkPageOn, setDarkPage, onDarkPage, initDarkPage; index.html) + +The owner asked for a dark page like FormTxt's `view.darkPage` (Apache-2.0, same owner), on by default with an off switch. The state is `data-page-dark` on the root, read by `darkPageOn()`, stored in `formchem.darkPage` (missing or `1` is on, `0` is off), and the `storage` event keeps other windows in step. The pre-paint script in index.html sets the attribute before any stylesheet, the way FormTxt does, so a hard reload or Home followed by New drawing never shows a white frame (checked with a CDP screencast and probes at first rAF, DOMContentLoaded, first paint and first contentful paint). Reset All Preferences removes the key, so the dark page comes back on. + +## 152. The whole drawing svg is filtered, the marks live beside it · _v0.7.0 (canvas/render/renderer.ts; styles/canvas-view.css) + +WebKit does not apply CSS filter functions such as `invert()` and `hue-rotate()` to SVG child elements, so a filter per layer would leave black ink on a dark paper in the macOS app. CSS filters do work on the outer `` box, so `filter: invert(0.9) hue-rotate(180deg)` (`invert(1)` with the AMOLED Black theme, `data-oled`) goes on `.fc-canvas-paper` and the whole `.fc-canvas-svg`, inside `@media screen` so printing never sees it. To keep the orange selection and hover, the preview and the red warnings in their real colours, the renderer now puts those four layers into a sibling `svg.fc-canvas.fc-canvas-marks` with its own `g.fc-root`, which gets the same transform and `--fc-zoom`; it paints above the drawing by DOM order at `--z-local-2` (no new token), and `destroy()` removes it. When the drawing svg has no parent at mount, the layers stay in it as before. Rulers, find marks, handles, the marquee and the key cursor were already in the unfiltered `.fc-canvas-overlay`. The hue rotation keeps hues and inverts lightness, so O shows light red and N light blue, and no renderer colour changed. The paper ring and shadow are pre-inverted, and the HTML text editor box gets dark colours so editing a label does not flash white. Measured under 4x CPU throttling while dragging an atom of Taxol: about 0.5 ms more main-thread time per frame and under 0.1 ms more raster, no dropped frames, so ink and paper were not moved into renderer custom properties. + +## 153. Pictures are un-inverted by one colour matrix · _v0.7.0 (canvas/dark-page.ts initDarkPage; styles/canvas-view.css) + +FormTxt un-inverts images with `invert(1) hue-rotate(180deg)` on the image, which is a filter function on an SVG child and ignored by WebKit. `initDarkPage(host)` adds a zero-size `svg.fc-canvas-defs` (zero size, not `display: none`, which breaks filter references) holding two `feColorMatrix` filters, `#fc-page-undark` and `#fc-page-undark-oled`, which SVG `image` elements reference by url, a form both WebKit and Chromium apply. The matrix is the exact inverse of the page filter in one pass, `1.25 (I - 2A) c + 1.125` with A the luminance rows 0.213, 0.715, 0.072 (`(I - 2A) c + 1` with OLED), avoiding the extra clamp of a two-step chain. The page filter cannot produce very saturated light colours, so pure yellow comes back beige and pure red brick, and whites show at about 90 percent; FormTxt has the same limit, and the command says pictures stay "close to their real colours". Exports never see any of this (entry 171). + +## 154. The dark-page command and its switches · _v0.7.0 (app/canvas-commands.ts dark-page; app/menus.ts; canvas/context.ts; ui/prefs/sections.ts, ui/prefs/index.ts) + +`dark-page` (View, icon `moon`, `checked`, param `on`, returns `{on}`) sits right after Show Grid in the View menu and the canvas background menu, and Preferences > Interface has a Page group with a `data-local="darkPage"` checkbox that follows `onDarkPage`, so it stays right when the menu toggles while Preferences is open. Every change calls `commandStateChanged()`, so the in-window menus and the macOS native menu, built from the same definitions, refresh their check marks. + +## 155. Scaling a selection scales its sizes and styles too · _v0.7.0 (canvas/tools/scale.ts scaleSelection, scaleTargets, clampScale; canvas/tools/handles.ts setBox) + +The owner asked for a way to make a structure larger on the sheet. Positions move through the existing `mapSelection`; sizes always scale (shapes, images, brackets, TLC plates and tables through `setBox`, the 0.5.0 handle resize step factored out of `dragHandle`, plus shape radius, plus-sign and orbital size and arrow `shorter`). A whole fragment (all its atoms selected) also gets its `bond_length` override, because bond spacing, wedge and charge distances derive from it; a partly selected fragment only moves atoms. With Scale Labels and Text with Structures on (the default, because the owner wants the structure visibly larger), per-object style overrides scale too, written as the object's partial `style`: line and bold widths, hash spacing, margin width, absolute bond spacing and the whole label font for fragments; caption font, run sizes and wrap width for text, which is re-centred (captions keep their top centre so `offset` stays right); widths and head sizes for arrows and brackets; widths, fonts, padding and cell sizes for tables and TLC plates. A field that comes back within 0.006 of the document value is dropped and an empty override removed, so scaling and scaling back leave no residue; values round to 0.01. The factor is clamped to 5 to 2000 percent. No contract file changed. transform.ts lost its coordinate-only `scaleSelection` and the unused `scaleBy`. + +## 156. Corner handles, a frame and a readout · _v0.7.0 (canvas/tools/scale.ts scaleHandles, scaleHandleAt, scaleFromDrag, SCALE_HANDLE_PAD_PX; canvas/view.ts placeHandle, setReadout; canvas/tools/select.ts mode scale) + +Four corner handles, drawn by `placeHandle` into the same `.fc-canvas-handle` path and 7 px squares as the 0.5.0 object handles, show for the select and lasso tools only when the rotate handle shows (never during a marquee) and only when the selection holds a structure (`hasStructure`). They sit 8 screen px outside the atom bounds, so the nearest corner is at least 17 px from the rotate handle, more than two 8 px hit slops; single-object handles exist only for selections without atoms, so they never meet. There are no side handles: structures scale uniformly. A thin `.fc-canvas-frame` joins the corners unless the selection is one boxed object, whose dashed box already frames it. The drag projects the pointer on the corner diagonal; the anchor is the opposite corner (`Alt`: the centre), rounded to 1 percent (`Shift`: 10 percent), previewed through `previewDraft` and committed as one Scale transaction on release; Escape cancels with the revision unchanged. Hit order: object handle, scale corner, rotate handle. The readout ("Scale 150%", "Bond 21.6 pt") is one `.fc-scale-readout` node created once in `#overlay-root` (fixed, `--z-raised`, pointer-events none) and patched by `setReadout`; tools reach it through `ViewToolContext.readout`, so canvas/types.ts did not change. A MutationObserver saw no element removed during a drag. + +## 157. Scale commands, the dialog and the labels preference · _v0.7.0 (app/canvas-commands.ts scaleCommands; ui/scale-dialog.ts; ui/prefs/store.ts ENGINE_DEFAULTS; app/menus.ts) + +`scale-selection {percent | bond_length, labels?}` (both is an error; no params opens the dialog with linked percent and bond-length fields) answers a plain sentence for agents ("Scaled to 138.9%, bond length 20.0 pt") and flashes the same in the status hint. `scale-up` (`Alt+Mod+=`, x 1.1) and `scale-down` (`Alt+Mod+-`, divides by 1.1 so the pair cancels exactly; the label says 10% as the owner asked) leave `Mod+=` and `Mod+-` to zoom, and `Mod+[` and `Mod+]` were taken by Bring Forward and Send Backward. `scale-labels` toggles the `scaleLabels` preference (default true, also in Preferences > Drawing > Scaling and in the dialog). With nothing selected, every top-level structure on the page scales about its own centre, so a scheme keeps its layout and the arrows stay put. The Arrange menu gets the four items, which also feed the macOS native menu through `accelerator()`. Icons `scale`, `scaleUp` and `scaleDown` were added. + +## 158. Panel rows reserve the value column and wrap · _v0.7.0 (styles/panel.css .fc-ap-row; styles/chem-ui.css .fc-apx-row, .fc-iso-head, .fc-iso-ion; styles/dialogs.css .fc-kv) + +The owner saw the Analysis panel's "Elemental analysis" label run into its value. On 0.6.0 the Properties rows cut long values with an ellipsis and truncated labels at 240 px. Every label and value row is now a grid of `minmax(0, max-content) minmax(min(, 50%), 1fr)`: the label takes its natural width and wraps when it must (`overflow-wrap: anywhere` only breaks a word longer than the column), the value column never drops below its reserved width (the `PROPERTY_ROWS` width in ch, capped at half the row), values are right-aligned with tabular figures and wrap inside their own column. Labels and values therefore cannot overlap, whatever the value text or language. Monospace was dropped from analysis values, ion labels and the isotope header (tabular figures in the UI font align digits and are narrower) and kept for SMILES and check codes. The same grid fixes the Agents and MCP dialog's key and value rows, the reaction roles rows and the Markush list, which cut paths, formulas and SMILES. In the check panel the problem code moved under its message, because an unbreakable code had squeezed German messages to three words a line. + +## 159. A container query stacks long values, not JS · _v0.7.0 (styles/panel.css .fc-ap-body container fc-ap) + +`.fc-ap-body` is an inline-size container. Under 340 px of content (a panel under about 372 px, which includes the 296 px default) Elemental analysis and Lipinski put the value under the label, so the second line exists from the first paint (a dash) and Taxol's value fits on it; under 250 px the isotope header stacks with a reserved line for the monoisotopic mass. The empty hint now hides as soon as a structure is in scope, in the same frame as the edit, instead of when the values arrive, so the properties no longer move up 48 px afterwards; a 25 ms sampler of every row's box saw one layout change at the edit and none when properties and the isotope pattern landed. Under 600 px of window width the panel uses `min(--fc-panel-w, 100vw)`. 1lh was avoided on purpose for older Safari. + +## 160. Wrap points and the m/z row · _v0.7.0 (ui/analysis-properties.ts glued, ionMz) + +`glued()` puts a no-break space between an element symbol and its percentage and between a number and its unit, on screen only (Copy Analysis text is untouched), so a wrapped Elemental analysis never leaves "C" at the end of one line and "61.89" on the next. The m/z row was a dash for every structure, because the properties reply has no `mz` key; `ionMz()` shows "[M+H]+ 854.3382" for a neutral molecule from the isotope pattern's adducts (falling back to the exact mass plus the proton, 1.007276467) and the [M] ion for a charged one (falling back to the exact mass over |charge|). "[M+H]+" is chemical notation in a `translate="no"` cell, not a string. + +## 161. Ink tokens for status text in light themes · _v0.7.0 (styles/tokens.css --ok-ink, --warn-ink, --danger-ink; styles/chem-ui.css, base.css, dialogs.css, extensions.css, terminal.css, shell.css) + +In the Light, Sand and 90s themes the Lipinski verdict (`--warn`) and the check counts were nearly invisible: the status colours are tuned as fills and borders on dark surfaces. The ink tokens equal `--ok-soft`, `--warn` and `--danger-text` in dark themes and are mixed toward `--text-primary` in `body.theme-light`, so dark themes look exactly as before. They are used for text only: the Lipinski verdict, the check counts and icons, `.fc-note.is-error`, error toasts, the copied tick, extension state and refusal text, chat errors and the danger button hover. Borders, dots and the find mark keep the plain colours. Left on purpose: `.fc-btn-danger` resting text (`--danger-soft`, not equal to the ink in dark themes) and `.fc-chat-tool-state` (an icon on `--ok`). + +## 162. Menus that do not fit fold into More menus · _v0.7.0 (ui/menu.ts MenuBar fold, live, step, open, reveal) + +At 1440 px with the Analysis panel open, Help was clipped to "H" behind the document title. The bar now ends with a More menus button (`.fc-menu-overflow`, icon `more3`) whose items are computed when it opens, one submenu per folded menu with its live items (File's recent list, View, Extensions), following FormWeb's More menus scheme; they inherit the bar floor, the 75 percent height cap and the more-below pill. `fold(room)` only toggles `.is-folded` on whole buttons from the right: `position: absolute; visibility: hidden` takes a folded button out of the flow and the tab order but keeps its width, which `fold` reads on every pass, so there is no width cache to go stale after a density or font change, and nothing is rebuilt (0 nodes added or removed over a 159-step resize sweep). Arrows, Home and End, Left and Right between open menus and Alt alone skip folded buttons through `live(i)` and `step(from, dir)`; opening a folded menu (Alt+letter, a typed letter, F10 with File folded) opens More, reveals that menu's submenu and focuses its first row. + +## 163. The title bar measures the menu row · _v0.7.0 (ui/titlebar.ts fitMenuRow; styles/shell.css; styles/titlebar.css .is-tight; app.ts) + +`fitMenuRow(bar, menus)` observes the title bar with a ResizeObserver; the room for the row is the bar's content width minus three column gaps, `--fc-title-min`, the brand and the tools. If every menu fits, nothing changes; otherwise `.is-tight` hides the brand name, folds the Analysis label to its icon and tightens the buttons (the set of the 1439 px breakpoint), and then menus fold from the right. The callback runs after layout and before paint, so no frame shows an unfitted row, and only the title bar is observed, so there is no ResizeObserver loop. It refits on `document.fonts` `loadingdone`. The brand and tools columns became `max-content`, because `auto` let the grid squeeze the tools and threw the arithmetic off; the menu row is `overflow: clip` with a 3 px negative margin and padding so focus rings are not clipped, and the 0.6.0 wheel scroller is gone. `.is-tight` is scoped to `:root:not(.has-native-menus)`, so the macOS system menu path is untouched. Results: in English at 980 px Window, Extensions and Help fold, at 1024 and 1180 Extensions and Help, from 1280 all twelve show (tight at 1440); German folds a little more. 1180 folds one more than 1024 because the 1099 px breakpoint lowers the title minimum from 160 to 96 px; left so above 1100 px the stated minimum holds. + +## 164. Escape goes to an open bar menu first · _v0.7.0 (canvas/view.ts ours; ui/menu.ts menuBarOpen) + +The canvas listens for keys on window in the capture phase, and its `ours()` guard checked modals and the context menu but not bar menus, so with the canvas focused the select tool took Escape (clear selection) and stopped it before `MenuBar.key` saw it: File stayed open. Arrow keys could also reach the tool while a bar menu was open. `ours()` now also returns false when `menuBarOpen()`. + +## 165. Grid lattices, the window default and snap state · _v0.7.0 (canvas/grid.ts latticeOf, cleanSpec, withType, docSpec, resolveGrid, windowGrid, snapOn, onGridChange) + +The owner asked for grid types, patterns and sizes. A drawing's grid is `style.grid` (`{type, spacing, major, strength}`), read straight from `doc.style.grid` by `docSpec`, never through `resolveStyle`, so presets and object overrides never carry a grid; the style already holds `units` and `background`, there is one per document, "Apply to This Drawing" is one `set` op and one undo step, and new pages need nothing. A document without it shows the window default and writes nothing, so old documents load and save unchanged (a new drawing stays at revision 0). The window keeps `formchem.showGrid` (default on), `formchem.snapToGrid` (default off) and `formchem.gridDefault` (lines, 7.2 pt, major 5, normal) in localStorage with one change event that also follows `storage`. Spacing is stored in points or `"bond"`: the square family defaults to 7.2 pt (the old fixed step) and the isometric and hex family to the bond length; switching type within a family keeps the spacing, across families resets it (`withType`). Isometric and hex use the pointy orientation (vertical lines and lines at 30 and 150 degrees, hexagons with vertical sides), because FormChem's bonds and chains run at plus and minus 30 degrees. Everything is clamped through `cleanSpec`; FORMAT got no validation rule. + +## 166. The grid is one svg in the paper, drawn as page paths · _v0.7.0 (canvas/grid-layer.ts GridLayer, planGrid, GRID_MIN_PX; styles/tokens.css --fc-grid-*) + +`` sits inside `.fc-canvas-paper`, so panning moves only the paper (zero grid mutations and zero stage childList changes over 24 wheel pans under 4x throttling). Line types draw as two page-sized paths, minor and major, with `crispEdges`, because a Chrome SVG pattern with a fractional tile size or offset is resampled and every 1 px line becomes a 2 px blur; the segment count depends on page size and spacing, not zoom (about 3000 for hex on Letter), with a pattern fallback above 12000. Dots and crosses use one pattern tile. Every attribute is patched through `setAttr`, keyed on type, spacing, major, strength, zoom, sub-pixel offset and page size, so only zoom or a grid change touches it. Under 4 px a minor cell hides; square grids coarsen by the major count (or 5) and isometric by 2, and hex hides, since no sub-lattice of a honeycomb is a useful honeycomb. The ink is page-relative (`--fc-grid-ink` and the strength tokens), not the theme's `--grid-color`, which several themes set to 4 to 6 percent white and which vanished on the white sheet; the dark page filter inverts it with the paper, so no extra rule was needed. + +## 167. Snapping keeps bond geometry and lands lattice atoms · _v0.7.0 (canvas/grid.ts snapStart, snapPoint, settlePoint, latticeDirections, snapRingCentre, snapShift; canvas/tools) + +New structures start on a grid point (bond click and drag, chain, ring centre). On square grids bonds and chains keep the bond length and the 15 degree steps, so only the start atom is on a point and the rest settle only within 2 percent of a cell. On isometric and hex grids whose spacing equals the bond length, bond directions snap to the lattice directions (30 + 60k degrees; on hex only the three that lead to corners from that corner's parity), chain axes to multiples of 60, the start corner is chosen so the first bond leads to a corner, and a chain whose first atom would land on a hexagon centre is mirrored; six-membered rings dropped on empty canvas turn 30 degrees and centre on a lattice point (on hex a hexagon centre), so all six atoms land on points. Moves snap the grabbed atom, the nearer bond end, an arrow or line end, a plus or orbital centre or the nearest box corner, and on hex keep the grabbed corner's parity so a whole structure stays on the honeycomb. Handle drags (not the arc bend) and new arrows, shapes, brackets, tables and TLC plates snap. Shift keeps its meaning (axis lock, angle steps) and snapping is skipped while it constrains; Alt bypasses everywhere, matching the bond and chain tools' free angle, which also means the arrow tool's alternate kind and the box tools' from-centre drawing come with it. Scale corners and rotation do not snap. Measured: 32 of 32 atoms on lattice points for chains, bonds and a dropped benzene on the four lattice types; an Alt-drawn chain 0 of 12. + +## 168. Grid commands, the dialog and the preferences · _v0.7.0 (app/grid-commands.ts; ui/grid-dialog.ts; ui/prefs/sections.ts; app/menus.ts GRID; canvas/context.ts; app/commands-shell.ts show-grid) + +Commands: `snap-to-grid {on?}`, `grid-type {type, scope?}`, `grid-spacing {value, unit?, scope?}` (a number or `"bond"`), `grid-settings {type?, spacing?, unit?, major?, strength?, scope?}` (no params opens the dialog) and the radio items `grid-lines`, `grid-dots`, `grid-crosses`, `grid-isometric`, `grid-isometric-dots`, `grid-hex` and `grid-hex-dots`; `scope: "default"` changes the window default instead of the drawing, and `show-grid` gained `{on?}`. View gets one `GRID` submenu in place of Show Grid, which the macOS native menu builds from the same definitions, and the empty-canvas menu gains Snap to Grid and Grid Settings. The dialog's scrim is `fc-scrim-clear` (transparent, no blur, dialog on the right), so `setGridPreview` shows the change on the page, cleared on Cancel, Escape and close. app.ts keeps the stage's `is-gridless` class in step through `onGridChange`. The unused `GRID_TYPE_COMMANDS` list was removed at integration. + +## 169. One save path for every exported file · _v0.7.0 (app/save-file.ts saveFile, saveFiles, safeFileName) + +`saveFile({name, mime, data, kind})` shows the native save dialog in the desktop shell (`plugin:dialog|save`, as Save As does) and asks the engine to write through `POST /api/files/write` with `picked: true` (backend log 115); in a browser it downloads a Blob. `saveFiles` (Each structure) asks for one folder with `plugin:dialog|open {directory: true}` and writes each file. A cancelled dialog returns `{saved: false}` and shows nothing. The last folder is kept in `formchem.saveFolder` and offered as the next default. `dialog:allow-save` and `dialog:allow-open` were already in the capability, so nothing changed there. Export SMARTS moved onto this path, so it saves a file in the desktop app instead of copying (entry 147 is superseded). + +## 170. The drawing inside a picture is a plain document · _v0.7.0 (app/embedded-source.ts subsetDocument, sourceText, readSourceText, embedInSvg, embedInPng, extractSource, SOURCE_MIME) + +The payload is a document.json with one page and only the exported objects, `meta.embedded = {scope, from}`, under `application/x-formchem+json`, the same mime the clipboard uses, so a picture's source and a clipboard payload paste through one reader. `subsetDocument(doc, page, pick, scope)` takes the whole page, a list of top-level objects or the canvas selection (a partly selected fragment keeps only its selected atoms and the bonds between them; groups bring their children; reaction steps keep only included members). Images render in the picture, but `sourceText` leaves them and `media` out, because their bytes are not carried. Carriers match the engine's readers (backend log 116); `extractSource` sniffs SVG, PNG, PDF and EPS so the window can read a dropped or pasted file without the engine. + +## 171. Pictures come from the document model, off screen · _v0.7.0 (app/picture.ts pictureSvg, PictureOptions, Picture) + +`pictureSvg(doc, derived, opts)` mounts a fresh renderer on a hidden stage (fixed, off screen, visibility hidden, removed afterwards), renders the subset document with no selection, no hover and no valence warnings, and clones only the content layers (objects, bonds, atoms, text, stereo). It never reads the live canvas, so the dark page filter cannot reach an export: SVG and PNG exported with the dark page on and off are byte-identical. Class styles that matter are inlined before classes are stripped (group and flag marks 600, query and R-group marks 500, map numbers at 0.85 opacity); the screen-only hairline minimum is not exported, so exports use the true line width. Bounds are the union of the renderer's model boxes and `getBBox()` of each content layer (which catches CIP and query marks) plus the margin (6 pt by default); `crop: false` uses the fixed page rectangle for printing. Fonts: `'subset'` asks the engine for WOFF subsets and falls back to the full TTF per face, `'full'` embeds the TTF (for PNG rasterising), `'none'` embeds nothing. Scale is a percent of real size, and the SVG states width and height in pt. A placed picture that cannot be read is left out with a warning. + +## 172. PNG is the export SVG drawn into a canvas · _v0.7.0 (app/picture.ts picturePng, pngSize) + +The export SVG with full fonts is drawn into a canvas at `width_pt / 72 * dpi`, twice across two animation frames so the data-URI fonts inside the SVG image are in place, after `document.fonts.load` for all eight faces, because label layout measures with canvas text metrics. `embedInPng` then adds pHYs (the exact dpi), `tEXt Software=FormChem` and the iTXt source. Sizes are capped at 16384 px a side and 120 Mpx, with a warning. Against the canvas at 100 percent, a 300 dpi PNG resampled to 96 dpi differed by a mean 3.46 of 255 (antialiasing and the screen hairline minimum). PNG rasterising of an SVG with data-URI fonts in WebKit was not run. + +## 173. The export dialog and the File > Export commands · _v0.7.0 (ui/export-dialog.ts; app/export-commands.ts registerExportCommands; app/menus.ts EXPORT; app.ts EXPORT_ITEMS) + +Commands: `export-png` (also the title bar's main export button), `export-svg`, `export-pdf`, `export-eps` (new), `export-picture` (the dialog, starting at the last format), `export-cdxml`, `export-mol`, `export-smiles` and `print` (`Mod+P`). The chemistry exports call `GET /api/documents/{id}/export?...&as=json` and save through entry 169, showing warn and error report items in the toast. The dialog has format, scope (Whole page, Selection, Each structure), resolution for PNG, background, scale, margin and "Keep the editable drawing inside the file", remembered in `formchem.exportPicture` (never Selection as the remembered scope); its size line is an estimate from the live renderer's model boxes. The 0.7.0 placeholders in commands-shell.ts were removed; `import` stayed a placeholder for the parallel Import work (entry 185). There is no printer icon, so Print has none. + +## 174. Print sizes the paper to the page · _v0.7.0 (app/print.ts printPicture; styles/print.css) + +Print builds the page picture (a fixed page whole and white, an auto page as its content plus the page margins; with a selection, only the selection in its place on the page), puts it into a persistent `.fc-print-host` `` as a blob SVG, which isolates the subset `@font-face` rules from the app's own Arimo, sets `@page { size: W H; margin: 0 }` in a print-only style element and prints. A browser calls `window.print()`; the desktop shell calls the existing `print_window` command (`WebviewWindow::print`), because WKWebView ignores `window.print()`. print.css hides everything but the host in print media. In Chromium the printed PDF was one A4 page with the scheme at real size. + +## 175. The import report is a toast with a details panel · _v0.7.0 (ui/import-report.ts showImportReport, showImportReportOf, closeImportReport; app/documents.ts; ui/home.ts STRUCTURE_ACCEPT) + +After File > Open, an upload or a recent file that was imported, `showImportReportOf(name, meta)` reads `meta.imported.report` and shows a toast ("opened with notes" or how many things were lost or changed) with a Details action for 12 s; Details opens a non-modal panel in `#overlay-root` that reuses the structure check classes (`fc-popover fc-check-panel`, z-index through `.fc-popover`) with severity counts and one row per code. It skips `.fchem` names, so a saved drawing that kept `meta.imported` does not show an old report. The Open filters gained RD, SMARTS, CXSMILES, InChI and the picture formats. + +## 176. The clipboard payload is a document with a paste plan · _v0.7.0 (app/clip-data.ts extractClip, pastePlan, CLIP_MIME, CLIP_KIND) + +`extractClip(doc, page, selection)` returns a mini document.json that passes `validate`: the selection, or the whole page when nothing is selected, with partly selected fragments cut to their selected atoms and stereo groups filtered, the source's resolved style, every abbreviation expansion its atoms use (nested ones too), the media records of its pictures, R-group definitions filtered to copied members, and the reaction steps whose arrow was copied, with members, coefficients and stoichiometry filtered; `meta.clipboard = {kind, from, page}`. `pastePlan(target, page, clip, {at, keepStyle, media, offset})` translates the clip so its bounds centre lands on `at` (through `translateSelection` on a Draft over the clip, so every object kind moves the way a drag moves it), gives fresh ids to every object, atom, bond, reaction and step and remaps every reference (bond ends, stereo groups, R-group members and attachments, caption targets, arrow anchors, bracket atoms, orbital atom, table cells, stoichiometry, group children, reaction members). Expansions are reused when identical, kept when their id is free, renamed otherwise. The difference between the source style and the target's goes into each pasted object's `style`, so a structure copied from a 14.4 pt drawing into a 30 pt one keeps its look. A picture whose bytes cannot be found is left out rather than pointing at nothing. + +## 177. Text formats out through the export route, in through parse · _v0.7.0 (app/clip-formats.ts clipText, parseClipText, looksLikeName, looksLikeSmarts) + +`clipText(clip, format)` asks `POST /api/chem/export` and falls back only on 404 or 405 to the older routes (convert, the analysis molfile and SMARTS routes, the reaction step export), so the branch worked before and after the formats engine merged; a reaction clip turns SMILES into reaction SMILES and Molfile into RXN, and one-line formats are trimmed. `parseClipText(text)` tries, in order: native JSON, reaction text (`$RXN` or `>` in the first token) through the reaction import route, everything `/api/chem/parse` detects, then SMARTS when the text looks like a query. Notes come from the import report's warn and error items only. Pasted text structures take the target's bond length and no style override. Names are not read (plan Q7 is open): a name-like text pastes as a text object with a toast saying names are not read yet. + +## 178. Several clipboard flavours with platform fallbacks · _v0.7.0 (app/clip-system.ts writeClipboard, readClipboard, flavoursOfTransfer, htmlFlavour, WEB_CLIP_MIME, HTML_SOURCE_ATTR) + +`writeClipboard(sync, rich, event)` first writes the synchronous flavours (text/plain SMILES from the derived cache, text/html carrying the payload, the native JSON as a DataTransfer custom type) into the copy event, or into one it raises with `execCommand('copy')`; then it writes everything through `navigator.clipboard.write` with one `ClipboardItem` whose values are promises, so Safari and WKWebView keep the user activation while the engine and the renderer work, keeping only types `ClipboardItem.supports` accepts and retrying with the basic types if the item is refused. The HTML flavour is `

`: Chromium re-encodes clipboard PNGs and drops their iTXt chunk, but the attribute and the data URL survive its HTML sanitiser, so the HTML picture is the real carrier of the drawing, and in WebKit the origin-scoped custom type changes with the desktop port. Measured: Chromium writes and reads every flavour; WebKitGTK 2.52 writes the custom type as `org.webkitgtk.WebKit.custom-pasteboard-data` and reads pictures only through the Clipboard API; `image/svg+xml` is sanitised in Chromium (metadata and fonts dropped), so Copy as SVG also writes the full SVG as text/plain, which pastes back editable. Image bytes travel as data URLs in the async custom flavour up to 16 MB, otherwise paste fetches them from the source drawing while it is open. The reference suite's OS clipboard formats are not written: a web page cannot register them. + +## 179. Keyboard copy and paste go through the DOM events · _v0.7.0 (app/clipboard.ts mountClipboard, choicesOf; app/commands-shell.ts cut, copy, paste; ui/paste-special-dialog.ts; app/menus.ts) + +The paste event gives every flavour without a permission prompt, while `navigator.clipboard.read()` prompts in Chromium and shows a callout in WebKit, so the keyboard path uses the events and the menu commands use the Clipboard API (a click is a user gesture). The controller answers `copy`, `cut` and `paste` (and `beforecopy`, `beforecut`, `beforepaste`, which WebKit needs to enable the commands without a text selection) when no text field has focus, no dialog is open and no text outside the canvas is selected. A capture keydown listener stops the app's own dispatch of Mod+C, X and V without preventing the default. Paste lands at the pointer over the canvas, at the right-click point when it comes from the canvas menu (within 20 s), else at the view centre; repeated pastes cascade by 10 pt; one transaction each (`Paste`, `Paste Text`, `Cut`), selected. With no drawing open, paste creates one. Copy and Copy As are enabled whenever a drawing is open (an empty page gives a note). Copy As lists SMILES, CXSMILES, Molfile, InChI, InChIKey, SMARTS, SVG, PNG and CDXML (`copy-*`, with Copy as SMARTS moved in from the end of Edit), and `paste-special` (`Shift+Mod+V`) lists the ways to paste with the raw clipboard types under them. The four 0.7.0 Copy As placeholders were removed. + +## 180. The desktop windows may use the clipboard from script · _v0.7.0 (src-tauri/src/main.rs chrome enable_clipboard_access) + +Without it, WebKitGTK refused every script paste (`execCommand('paste')` false, `clipboard.read` NotAllowedError), so Edit > Paste and Paste Special could not work in the Linux app. `.enable_clipboard_access()` on every window makes wry set WebKitGTK's `javascript-can-access-clipboard` and auto-allow WebView2's clipboard-read permission; macOS ignores it. It is a builder method of the tauri 2 crate already pinned, so no dependency changed. + +## 181. Cut, Copy, Paste and Select All are system items on macOS · _v0.7.0 (ui/native-menu.ts ALWAYS_NATIVE, NativeMenus selectstart; app/clipboard.ts) + +A muda `PredefinedMenuItem` for Cut, Copy, Paste or Select All is bound to the AppKit selectors `cut:`, `copy:`, `paste:` and `selectAll:` with the system key equivalents, and goes down the responder chain to the WKWebView, which raises real `beforecopy` and `copy` (and the cut and paste pairs) events with the pasteboard data, so no Paste callout. `ALWAYS_NATIVE` makes those four predefined items always, not only while a text field has focus; `undo` and `redo` stay predefined only in text fields, because WebKit's `undo:` acts on its own stack, not on the drawing's history. In WKWebView a Cmd key first reaches the page as keydown and goes back to the menu when the page does not prevent it, so clipboard.ts now stops the app's dispatch of Mod+C, X and V on the macOS desktop too. `selectAll:` outside a text field fires `selectstart` on the body; NativeMenus cancels that (only with no pointer button down, no text field focused and the body as target) and runs `select-all`, which selects the drawing. Evidence: WebKitGTK 2.52 driven with `webkit_web_view_execute_editing_command`, the GTK counterpart of the selectors, fired trusted copy, cut and paste events and a cancellable `selectstart`. With "Menus in Window" on macOS sets no menu, so Tauri's default macOS menu, with the same predefined items, applies. The canvas right-click Paste still reads through the Clipboard API and may get WebKit's Paste callout. + +## 182. Command state reaches the engine within 120 ms · _v0.7.0 (app/catalogue.ts mirrorCatalogue, STATE_MS) + +The full mirror ran on registry changes, live reconnects and every two minutes, so the engine refused `undo` and `duplicate` for agents right after a keyboard paste. Besides it, a state pass now runs at most 120 ms after a transaction, reset, derived, dirty or saved event of the active document (preview events ignored), a change of active document, `COMMAND_STATE_EVENT` (selection, client, panels, grid, dark page) and `registry.onRun`; it diffs enabled and checked flags against what was last sent and posts only the changes to `POST /api/commands/state` (backend log 129). The full mirror's signature now includes `checked`. Measured: `undo` enabled in the engine 0.096 s after a keyboard redo. + +## 183. Standardise: a client, a dialog with a preview and one command · _v0.7.0 (engine/standardise-api.ts standardiseApi; ui/standardise-dialog.ts askStandardise; app/standardise-command.ts registerStandardiseCommand; app/canvas.ts; app/menus.ts) + +Structure > Standardise... (after Check Structure) opens a checklist of the steps with their methods as tooltips, the scope sentence (the selection, or every structure on the page together) and before and after SMILES from a preview call; Apply re-runs the route and commits its ops through `client.commit` as one undo step after checking that no fragment changed meanwhile, as engine commands do (entry 141). The chosen steps are kept in `formchem.standardise.steps`. `standardise {steps?}` without steps opens the dialog and so waits for the person; with steps it runs directly. Step labels come from the engine and pass through `t()`; the result toast lower-cases them only in English, because German capitalises nouns. + +## 184. Duplicate goes through the paste plan · _v0.7.0 (app/canvas-commands.ts duplicate) + +Duplicate now runs `extractClip` and `pastePlan` with a 10 pt offset, so the copy keeps stereo groups, R-groups, expansions and reaction steps with remapped ids. The older `duplicateSelection` in canvas/tools/select.ts still serves Alt-drag and drops fragment-level data; it is worth moving onto the plan. + +## 185. File > Import inserts files into the open drawing · _v0.7.0 (app/import-files.ts mountImport, freeSpot; app/clipboard.ts insert, insertDrawing; app/documents.ts dialogOpenPaths; app/commands-shell.ts import; ui/import-report.ts) + +File > Import... (`import {path?}`) picks one or more files (the Open list: `OPEN_EXTENSIONS` in the desktop dialog through `dialogOpenPaths(multiple, title)` in app/documents.ts, `STRUCTURE_ACCEPT` in the browser), asks the engine to read each one without opening it (`POST /api/documents/import`, backend log 132) and inserts it into the active drawing, a new one only when none is open, through the clipboard's paste plan: `ClipboardApi.insert(clip, {label, keepStyle, spot, alsoSelect})` gives fresh ids, carries expansions, media and reactions, and keeps earlier plans of the same run selected. Each file is one undo step ("Import [name]"), and everything a run brought in stays selected and is revealed. app/import-files.ts `freeSpot()` places a file to the right of the page content (top aligned) when it fits inside the page margins, else below it, else at the first free spot found in bond-length steps with a two-bond gap to every object box, else below the content past the page bottom (the drawing grows; nothing overlaps); auto-size pages always take the right. Chemistry files take the target drawing's style, as pasted SMILES does; `.fchem` files and pictures keep theirs per object, as a native paste does. The import report shows with "imported with notes". There is no shortcut, because Ctrl+Shift+I opens the browser and webview inspector. The `later()` placeholder and the last 0.7.0 LATER text are gone. + +## 186. Stylesheets, icons and strings of 0.7.0 · _v0.7.0 (styles/clipboard.css, styles/standardise.css, styles/print.css, index.html, ui/icons.ts, i18n/keys/part07.json, part08.json) + +Three stylesheets were added and linked in index.html (standardise.css and clipboard.css after chem-ui.css, print.css after terminal.css); every z-index still comes from tokens. The new icons are `scale`, `scaleUp` and `scaleDown`; the grid, dark page, export and clipboard commands reuse existing glyphs. The i18n scanner was taught template placeholders and the `h()` and `x()` wrappers (backend log 131), which found 282 more strings; `i18n/keys/part07.json` keys them (the 0.7.0 strings and older Home, Help, About, Agents, Chat, Preferences and stoichiometry texts the scan could not see), and `NOT_TEXT` with three narrow `NOT_TEXT_RE` rules keeps code, MIME types, font names and report lines out of the scan. No scan can see the texts the engine writes and the window shows (import and export report items, structure check, Standardise, balance, Markush, stereo and file errors), so `part08.json` keys them as the window renders them, with pattern keys for counts and names; it also holds whole-sentence keys for the toasts built from pieces (import, scale, copy, paste, export), which `KEYED_WHOLE` keeps out of the scan so translators can reorder name, count and format. `part09.json` keys File > Import and its engine messages. The parallel translators add the 25 languages. Command and parameter descriptions stay English agent text. + +## 187. The window draws agent pictures with the export renderer · _v0.8.0 (app/agent-window.ts render, rasterise, DEFAULT_DPI, DPI_RANGE, MARGIN, SECOND_PAINT_MS; app/picture.ts pictureSvg, pngSize; app/embedded-source.ts subsetDocument) + +The engine sends the whole document and its derived cache with the `render` window tool (backend entry 134), so the window never needs the drawing to be open or active. `subsetDocument(doc, page, ids)` cuts the objects asked for (or the page), and `pictureSvg` draws them off screen with the same code as File > Export, in the person's display preferences (`display()` from app/canvas.ts, now exported), so the agent sees exactly what the person would export: wedges, aromatic circles, arrows, plus signs, text and brackets. The background is white by default (black on white reads best for a model), fonts are subset through `/api/pictures/fonts` as in export because an SVG drawn as an image cannot use the page's fonts, and `embedSource` is off. Width and height fit by scale for SVG and by dpi for PNG (18 to 1200). PNG is rasterised here rather than with `picturePng`: that waits on requestAnimationFrame, which never fires in a hidden or background window, and the agent would hang. The image is painted twice 30 ms apart with setTimeout, because the embedded fonts of an SVG image can be ready only after its first paint. + +## 188. selection and show are window tools too · _v0.8.0 (app/agent-window.ts selected, show, registerAgentWindow) + +`selection` answers the active drawing's id, page, the fragment and object ids touched by the selection (`fragmentsTouched` plus whole objects) and the atom and bond keys, for `render {scope: "selection"}` and `get_structure {selection: true}`. `show` attaches a drawing the engine made or opened for an agent, leaves Home and activates it when the window did not have it yet or when asked to focus; it is idempotent, because the engine cannot know which drawings a window holds (backend entry 136). Their answers are agent-facing English, sent back to the engine, never shown in the window, so they need no i18n keys. + +## 189. Window modules add their own window tools · _v0.8.0 (app/window-tools.ts addWindowTool, windowTool, ADDED; app.ts) + +`windowTool` answered `run_command` and the extension tools from one switch in window-tools.ts. A small registry lets a module answer its own tool without window-tools.ts importing the canvas or the picture code: `addWindowTool(name, fn)` returns its remover, `windowTool` looks there after `run_command`. app.ts calls `registerAgentWindow` right after `answerWindowTools`. + +## 190. The window mirrors the engine's call log · _v0.8.0 (app/agent-calls.ts AgentCalls, agentCalls, CALLS_CAP, WINDOW_TOOLS, parse) + +One store per window, filled by `GET /api/agents/calls` whenever the live socket opens and kept current by `agentCall`, `agentUndoable`, `agentAccess` and `agentCallsCleared`, capped at the engine's 400. `undoable(call)` is true only for the call the engine named on top of that drawing's undo stack, so the panel never offers an undo the engine would refuse. Each `call` event carries `touched`: all objects for a new call, or only those added by a newly attributed transaction (else all again), so marks flash what changed now, not the whole history of the call. `ended` marks the moment a running call finishes. + +## 191. Agent activity is one panel built once and patched by row · _v0.8.0 (ui/agent-activity.ts AgentActivityPanel, SHOWN, ACTIVITY_OPEN_KEY, duration, clock) + +The panel sits absolutely in `.fc-stage` at the bottom right, at `--z-local-5`, so it floats over the canvas without moving it. Rows are keyed by call id through `patchList`; an update of an existing call patches only that row's text, status and buttons, so a running call that ends does not rebuild the list (checked with a MutationObserver: the first row stayed the same element across updates). At most 200 of the 400 kept calls are shown, with a line that says so. Each row shows tool, argument summary, duration, status, agent, drawing title and time, the first line of the result as its tooltip, Undo when the store says so, and "Undone" struck through after. The agent filter, Clear, and a strip of stopped agents with Allow again sit above the list. Whether it is open survives a reload (`formchem.agentActivityOpen`). + +## 192. The editing chip shows who is changing this drawing, with Stop · _v0.8.0 (ui/agent-chip.ts AgentChip, LINGER_MS, LOOK_BACK) + +The person must be able to see who is changing the drawing in front of them and stop it in one click. The chip lives in `.fc-doc-slot` beside the document title and shows for a writing call on the active drawing (its doc matches, or it is a window tool, which has no doc until its transaction arrives) while it runs, and for 3 s after it ended with a transaction; never for a stopped agent or an undone call. The newest 40 calls are looked at. It also sets `.fc-stage.is-agent-editing`, which lights the canvas edge with `.fc-stage::after` (no other rule used that pseudo-element). The chip's main button opens Agent activity, Stop calls `POST /api/agents/stop`. One timer re-checks when the next linger ends, so nothing polls. + +## 193. What an agent changed flashes in a keyed marks layer · _v0.8.0 (canvas/agent-marks.ts AgentMarks, FLASH_MS, FADE_MS, PAD_PT) + +A document layer `fc-agent-marks` (`view.docLayer`, `Keyed`, like the Find marks) holds one rounded rectangle per touched object around its bounds (`objectBounds` with the renderer's own box when it has one), padded 3 pt, for 2.2 s, then a 0.4 s fade. A mark whose box did not change is not re-patched. Under reduced motion the fade is skipped and the mark is simply removed, and the chip's pulse and the edge animation are off (computed `animation-name: none` checked). + +## 194. Wiring Agent activity, and flashing what was drawn into a new drawing · _v0.8.0 (app/agent-activity.ts mountAgentActivity, reveal, PENDING_MS, PANEL_GAP; app.ts; app/menus.ts) + +`mountAgentActivity` builds the panel, the chip and the marks, registers the `agent-activity` command (Window menu after Agents and MCP, icon `history`, checked while open) and starts the store. A row click activates the call's drawing, selects what it changed (fragments whole, other objects by id), reveals the box clear of the panel and flashes it; when the drawing is not in this window or the objects are gone, a toast says so. A call that creates a drawing sends its transaction before `show` activates that drawing, so its touched ids used to be dropped as "another drawing"; they now wait per drawing and flash when it becomes active within 10 s (integration fix 6b9dc2e). + +## 195. The Agents dialog carries the token · _v0.8.0 (ui/agents-dialog.ts SETUP, TOKEN_HOLDER, token) + +The setup lines for Claude Code (`--header "Authorization: Bearer ..."`), Codex (`http_headers`) and Cursor (`headers`) are filled with the token from `GET /api/agents/token` (window key), or `` when the call fails; the install and Claude Desktop notes say the token is written or sent for you. Two notes say HTTP needs the token and what Agent Activity does, and a button opens it. The dialog is the one place the window shows the token, because it is where the person copies setup lines. + +## 196. The copied prompt explains the token without holding it · _v0.8.0 (ui/chat-panel.ts PROMPT) + +The chat panel's prompt for an outside agent named only the MCP URL, so such an agent hit the 401 and had to read the error to recover. It now says the endpoint needs the agent token, from `./formchem agents token` in the FormChem folder, or to connect with `./formchem mcp`. The token itself stays out of the prompt: it would sit in the clipboard and in agent transcripts. + +## 197. A lone hydride is written hydrogen first · _v0.8.0 (canvas/render/label.ts labelSide; chem/valence.ts HYDRIDE_FIRST) + +`labelSide` put the hydrogens of any unbonded atom on the right, so reaction SMILES drew water as OH2. It now uses the rule chem/valence.ts already had for formula text: O, S, Se, Te, F, Cl, Br and I write their hydrogens first; N, P and C after (NH3, CH4, NH4+). Only an atom with no neighbour and no typed label is affected. `HYDRIDE_FIRST` is exported for it, and the engine measures the box the same way (backend entry 162). Checked in the window and in the render tool: H2O, H2S, HCl, HF, HBr, HO-, NH3, CH4, NH4+. + +## 198. Engine messages after a translated prefix are translated too · _v0.8.0 (app.ts errText; app/clipboard.ts, canvas-commands.ts, chem-commands.ts, standardise-command.ts, documents.ts, export-commands.ts, reaction-commands.ts; ui/agent-chip.ts, agent-activity.ts; ui/prefs/index.ts, agents-dialog.ts, updates.ts; canvas/tools/image.ts, ui/home.ts, ui/stoich-panel.ts) + +A toast read "Could not ...:" in the person's language and then the engine's sentence in English. Each module's local `errText` now returns `t(message)`, so an engine sentence with a key translates and any other passes through unchanged. The shared `errText` in ui/prefs/store.ts stays raw, because updates.ts matches it against a regular expression, and is wrapped `t(errText(e))` at its seven display sites; the three inline `e.message` toasts get `t()` too. Not changed: extensions/host.ts (extension errors also go back to agents) and app/agent-window.ts (its answers go to the engine for the agent). + +## 199. Analysis warnings and Standardise details translate one by one · _v0.8.0 (ui/analysis-properties.ts; ui/standardise-dialog.ts; styles/chem-ui.css .fc-apx-note-item; styles/standardise.css .fc-std-part) + +A joined sentence of several warnings has no key, so it never translated. The Analysis note now patches each warning as a keyed `.fc-apx-note-item` span (`patchList`), and the Standardise dialog splits a step's `detail` on "; " into `.fc-std-part` spans keyed by index; CSS draws the separators (`+ ::before` with a space or "; "), so the look did not change and the engine's API did not either. + +## 200. The agent activity stylesheet and the strings of 0.8.0 · _v0.8.0 (styles/agent-activity.css; index.html; i18n/keys) + +agent-activity.css (linked in index.html after standardise.css) styles the panel, the chip, the stage edge and the marks from tokens only (`--z-local-5` for the panel, accent mixes for the chip and the edge) with one `prefers-reduced-motion` block. No icon was missing: `agent`, `close`, `undo`, `stop` and `history` existed. The chip and panel strings use the named placeholders `{agent}`, `{tool}`, `{n}` and `{total}`, replaced after `t()`, so their keys keep the names as written; `./formchem i18n scan` does not see them and they are listed in the integration notes for the keys. The undo labels of agent calls (Draw from SMILES, Add atom and the rest) come from the engine and show in Edit > Undo. + ## Not verified at 0.4.0 The lasso tool in the real window (its band path is the marquee's), touch pinch and Safari gesture events, the Tauri webview (dialogs, native accelerators, `contenteditable="plaintext-only"` in older WebKit), light themes, the rotate handle on dark pages, extensions against a real package, and socket drop with resync during an edit. The title field collapses to a sliver at 1280 px wide because the menu bar takes the room; it predates this work. @@ -799,3 +1072,11 @@ The macOS native menu with the new Reaction submenus and the desktop export path ## Not verified at 0.6.0 The macOS native menu with the new Structure, View and Analysis items and Export SMARTS in the desktop shell (no Tauri here). With the pinned CLI the owner's `./build_app` on macOS arm64 (Python 3.14.6, Node 24.16, Rust 1.97.1) built the desktop app; nothing was reported about running it. The isotope plot with very large molecules in the window (the route was timed, the plot was not). A `data.attach` member atom that is not a stub gets its wavy mark on its first bond; only stubs and declared `attach` ids were drawn and checked. Everything else in entries 134 to 148 was exercised in the built window served by the engine under 4x CPU throttling, through menus, dialogs and canvas clicks, with state read back from the engine and a MutationObserver showing no shell or canvas container removed. + +## Not verified at 0.7.0 + +No macOS build was made, so none of the macOS paths ran: the one-folder engine in `Contents/Resources/engine` and the launch time against the old 30 seconds, `tauri dev` finding `target/debug/engine`, the dark page in WKWebView (the design avoids WebKit's known gap, but nobody has looked), the native menu with Scale, Grid, Dark Page, Export, Copy As and Paste Special, the predefined Cut, Copy, Paste and Select All, the native save and folder dialogs with `/api/files/write`, the multi-file open dialog of File > Import, `print_window`, PNG rasterising of a data-URI font SVG in WebKit, and the clipboard in WKWebView. Windows WebView2, Firefox and touch widths were not run, nor Ctrl+Alt+= where AltGr types a character. Scaling of images, TLC plates, tables, brackets and orbitals ran only through code shared with the 0.5.0 handles. `cargo check` passed on Linux with a placeholder sidecar. Everything else in entries 149 to 186 was exercised in the built window served by the engine in headless Chromium under 4x CPU throttling, with state read back from the engine and a MutationObserver showing no live container rebuilt. + +## Not verified at 0.8.0 + +The desktop window was not run: the chip in the macOS overlay title bar, a `render` answered by a minimised or hidden WKWebView (the setTimeout path was chosen for it, untried), and WebKitGTK beyond `cargo check`. The agent UI strings were checked in English only; the errText path was checked in German with the 0.7.0 keys. Windows WebView2 was not run. Entries 187 to 200 were exercised in the built window in headless Chromium under 4x CPU throttling (the aspirin and acetic acid runs, Stop and Allow again, undo from the panel, the flashes into a new drawing), with no console errors and no live container rebuilt. diff --git a/frontend/index.html b/frontend/index.html index 3b93a2cf..df5ccd9d 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)'); @@ -108,6 +111,9 @@ + + + @@ -115,6 +121,7 @@ +
diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 47e2ba66..1c7ec3bc 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "formchem", - "version": "0.6.0", + "version": "0.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formchem", - "version": "0.6.0", + "version": "0.8.0", "license": "Apache-2.0", "dependencies": { "@tauri-apps/api": "2.12.1", diff --git a/frontend/package.json b/frontend/package.json index 467043c0..d4ae9411 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "formchem", "private": true, - "version": "0.6.0", + "version": "0.8.0", "description": "FormChem · chemical structure drawing in the FormAI family", "license": "Apache-2.0", "type": "module", diff --git a/frontend/src/app.ts b/frontend/src/app.ts index c83bc698..a11ad4c6 100644 --- a/frontend/src/app.ts +++ b/frontend/src/app.ts @@ -1,7 +1,12 @@ -import { mountCanvas } from './app/canvas'; +import { mountAgentActivity } from './app/agent-activity'; +import { registerAgentWindow } from './app/agent-window'; +import { display as canvasDisplay, mountCanvas } from './app/canvas'; +import { gridShown, onGridChange, setGridShown } from './canvas/grid'; import { mirrorCatalogue } from './app/catalogue'; +import { mountClipboard } from './app/clipboard'; import { commandStateChanged, FIELD_NATIVE, registerShellCommands } from './app/commands-shell'; import { DocumentActions } from './app/documents'; +import { mountImport } from './app/import-files'; import { session } from './engine/session'; import { showHandoffs } from './app/handoffs'; import { buildMenus } from './app/menus'; @@ -28,7 +33,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'; @@ -89,11 +94,10 @@ function isTyping(t: EventTarget | null): boolean { return t instanceof HTMLInputElement || t instanceof HTMLTextAreaElement || t instanceof HTMLSelectElement || (t instanceof HTMLElement && t.isContentEditable); } -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 errText = (e: unknown): string => t(e instanceof Error ? e.message : String(e)); const tauriCore = (): Promise => import('@tauri-apps/api/core'); const tauriWindow = (): Promise => import('@tauri-apps/api/window'); @@ -118,12 +122,8 @@ async function nextWindow(): Promise { await all[(at + 1) % all.length].setFocus(); } -function gridOn(): boolean { - try { return localStorage.getItem(GRID_KEY) !== '0'; } catch { return true; } -} - function syncGrid(stage: HTMLElement): void { - setClass(stage, 'is-gridless', !gridOn()); + setClass(stage, 'is-gridless', !gridShown()); } function recentCommands(lib: Library, open: (item: LibraryItem) => void): { ids: string[]; off: () => void } { @@ -201,6 +201,7 @@ export function startApp(): ShellHosts { }); syncGrid(h.stage); + onGridChange(() => syncGrid(h.stage)); let home: Home | null = null; const canvas = mountCanvas(h, () => !!home?.isOpen()); const tplHooks: TemplateHooks = { @@ -208,6 +209,8 @@ export function startApp(): ShellHosts { inserted: (c, frags) => canvas.inserted(c, frags), createOptions: () => { const preset = canvas.preset(); return { ...(preset ? { preset } : {}), style: canvas.style() }; }, }; + const clip = mountClipboard({ view: canvas.view, homeOpen: () => !!home?.isOpen(), createOptions: () => tplHooks.createOptions?.() ?? {} }); + const imports = mountImport({ clip, reveal: (c, box) => { if (canvas.view.client === c) canvas.view.reveal(box); }, leaveHome: () => leaveHome() }); let native: NativeMenus | null = null; let recentIds: string[] = []; let recentOff: () => void = () => undefined; @@ -253,6 +256,7 @@ export function startApp(): ShellHosts { saveCopy: () => void docs.saveCopy(), closeDocument: () => void docs.close(), insertSmiles: (smiles?: string) => docs.insertSmiles(smiles), + importFiles: (path?: string) => imports.run(path), hasDocument: () => docs.hasDocument(), canUndo: () => docs.canUndo(), canRedo: () => docs.canRedo(), @@ -292,16 +296,15 @@ export function startApp(): ShellHosts { }, undo: () => docs.undo(), redo: () => docs.redo(), - cut: () => undefined, - copy: () => undefined, - paste: () => undefined, + cut: () => clip.cut(), + copy: () => clip.copy(), + paste: () => clip.paste(), + canCopy: () => clip.canCopy(), + canCut: () => clip.canCut(), + canPaste: () => clip.canPaste(), selectAll: () => { if (canvas.view.client && !home?.isOpen()) canvas.view.selectAll(); }, - showGrid: () => { - try { localStorage.setItem(GRID_KEY, gridOn() ? '0' : '1'); } catch { return; } - syncGrid(h.stage); - commandStateChanged(); - }, - gridOn, + showGrid: (on?: boolean) => ({ on: setGridShown(on ?? !gridShown()) }), + gridOn: gridShown, helpGithub: openGitHub, }); @@ -312,13 +315,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(); @@ -349,8 +346,10 @@ export function startApp(): ShellHosts { if (!session.active) home.open('start'); answerWindowTools(commands, live); + registerAgentWindow({ view: canvas.view, display: canvasDisplay, hideHome: leaveHome }); mirrorCatalogue(commands, live, () => menus); showHandoffs(live); + mountAgentActivity({ stage: h.stage, docSlot: h.docSlot, view: canvas.view }); live.onStatus((s) => { if (s === 'open' && home?.isOpen()) void home.refresh(); }); session.onRecent(() => { void home?.refresh(); }); live.connect(); diff --git a/frontend/src/app/agent-activity.ts b/frontend/src/app/agent-activity.ts new file mode 100644 index 00000000..d31bb7da --- /dev/null +++ b/frontend/src/app/agent-activity.ts @@ -0,0 +1,99 @@ +import { AgentMarks } from '../canvas/agent-marks'; +import type { Box } from '../canvas/hit'; +import { EMPTY_SELECTION, fragmentSelection, isEmpty, makeSelection, union } from '../canvas/selection'; +import type { CanvasView } from '../canvas/view'; +import { commands } from '../commands/registry'; +import { session } from '../engine/session'; +import { t } from '../i18n'; +import { live } from '../io/live'; +import { AgentActivityPanel } from '../ui/agent-activity'; +import { AgentChip } from '../ui/agent-chip'; +import { toast } from '../ui/toast'; +import { agentCalls, type AgentCall } from './agent-calls'; +import { commandStateChanged } from './commands-shell'; + +const PANEL_GAP = 24; +const PENDING_MS = 10_000; + +export interface AgentActivityHosts { stage: HTMLElement; docSlot: HTMLElement; view: CanvasView } + +function around(boxes: Box[]): Box | null { + if (!boxes.length) return null; + const x0 = Math.min(...boxes.map((b) => b.x)), y0 = Math.min(...boxes.map((b) => b.y)); + const x1 = Math.max(...boxes.map((b) => b.x + b.w)), y1 = Math.max(...boxes.map((b) => b.y + b.h)); + return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }; +} + +export function mountAgentActivity(h: AgentActivityHosts): AgentActivityPanel { + const { view } = h; + const marks = new AgentMarks(view); + let panel: AgentActivityPanel | null = null; + + const reveal = (call: AgentCall): void => { + if (!call.doc || !call.objects.length) { + if (call.note) toast(call.note); + return; + } + if (session.active?.id !== call.doc) { + if (!session.get(call.doc)) { toast(t('The drawing this call changed is not open in this window.')); return; } + session.activate(call.doc); + } + if (!view.client) return; + const doc = view.doc; + const present = call.objects.filter((id) => doc.objects[id] !== undefined); + let sel = EMPTY_SELECTION; + const others: string[] = []; + for (const id of present) { + const o = doc.objects[id]; + if (o.kind === 'fragment') sel = union(sel, fragmentSelection(o)); + else others.push(id); + } + if (others.length) sel = union(sel, makeSelection([], [], others)); + if (isEmpty(sel)) { toast(t('What this call changed is no longer in the drawing.')); return; } + view.setSelection(sel); + const box = around(present.map((id) => marks.boxOf(id)).filter((b): b is Box => b !== null)); + if (box) view.reveal(box, panel?.isOpen() ? { right: panel.root.offsetWidth + PANEL_GAP } : {}); + marks.flash(present); + }; + + const shown = new AgentActivityPanel(h.stage, agentCalls, { title: (doc) => session.get(doc)?.title ?? null, reveal }); + panel = shown; + const chip = new AgentChip(h.docSlot, h.stage, agentCalls, { + activeDoc: () => session.active?.id ?? null, + openActivity: () => { shown.toggle(true); }, + }); + + const waiting = new Map(); + agentCalls.on((e) => { + if (e.kind !== 'call' || !e.touched.length || e.call.undone || !e.call.doc) return; + const ids = e.touched; + if (e.call.doc !== session.active?.id) { + const had = waiting.get(e.call.doc); + waiting.set(e.call.doc, { ids: [...(had?.ids ?? []), ...ids], at: performance.now() }); + return; + } + requestAnimationFrame(() => marks.flash(ids)); + }); + session.onActive((c) => { + marks.clear(); + chip.sync(); + const held = c ? waiting.get(c.id) : undefined; + if (!c || !held) return; + waiting.delete(c.id); + if (performance.now() - held.at < PENDING_MS) requestAnimationFrame(() => marks.flash(held.ids)); + }); + shown.onToggle(() => commandStateChanged()); + + commands.register({ + id: 'agent-activity', + label: () => t('Agent Activity'), + group: 'Window', + icon: 'history', + description: 'Shows every call agents made to FormChem, newest first, with undo for the latest one and a way to stop an agent.', + checked: () => shown.isOpen(), + run: () => { shown.toggle(); }, + }); + + agentCalls.start(live); + return shown; +} diff --git a/frontend/src/app/agent-calls.ts b/frontend/src/app/agent-calls.ts new file mode 100644 index 00000000..e42f03e2 --- /dev/null +++ b/frontend/src/app/agent-calls.ts @@ -0,0 +1,171 @@ +import { get, post } from '../io/api'; +import type { LiveClient, LiveMessage } from '../io/live'; + +export type CallStatus = 'running' | 'ok' | 'error' | 'refused'; + +export interface AgentCall { + id: string; + agent: string; + inapp: boolean; + tool: string; + args: string; + started: number; + ms: number | null; + status: CallStatus; + writes: boolean; + doc: string | null; + tx: string | null; + txs: number; + rev: number | null; + objects: string[]; + note: string; + undone: boolean; +} + +export type CallsEvent = + | { kind: 'call'; call: AgentCall; fresh: boolean; touched: string[]; ended: boolean } + | { kind: 'reset' } + | { kind: 'undoable'; doc: string } + | { kind: 'access'; agent: string; state: string }; + +interface Listing { calls?: unknown[]; undoable?: Record; stopped?: unknown[] } + +const URL = '/api/agents'; +export const CALLS_CAP = 400; +export const WINDOW_TOOLS: ReadonlySet = new Set(['run_command', 'extension_command']); +const STATUSES: ReadonlySet = new Set(['running', 'ok', 'error', 'refused']); + +const str = (v: unknown): string => (typeof v === 'string' ? v : ''); +const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null); + +function parse(raw: unknown): AgentCall | null { + if (!raw || typeof raw !== 'object') return null; + const r = raw as Record; + if (!str(r.id) || !str(r.tool)) return null; + return { + id: str(r.id), + agent: str(r.agent) || 'agent', + inapp: r.inapp === true, + tool: str(r.tool), + args: str(r.args), + started: num(r.started) ?? Date.now(), + ms: num(r.ms), + status: (STATUSES.has(str(r.status)) ? str(r.status) : 'ok') as CallStatus, + writes: r.writes === true, + doc: str(r.doc) || null, + tx: str(r.tx) || null, + txs: num(r.txs) ?? 0, + rev: num(r.rev), + objects: Array.isArray(r.objects) ? r.objects.filter((x): x is string => typeof x === 'string') : [], + note: str(r.note), + undone: r.undone === true, + }; +} + +export class AgentCalls { + private readonly byId = new Map(); + private order: string[] = []; + private readonly undoableByDoc = new Map(); + private stoppedSet = new Set(); + private readonly fns = new Set<(e: CallsEvent) => void>(); + private loaded = false; + + start(live: LiveClient): void { + live.on('agentCall', (m: LiveMessage) => this.upsert(m.call)); + live.on('agentUndoable', (m: LiveMessage) => { + const doc = str(m.doc); + if (!doc) return; + const call = str(m.call); + if (call) this.undoableByDoc.set(doc, call); else this.undoableByDoc.delete(doc); + this.emit({ kind: 'undoable', doc }); + }); + live.on('agentCallsCleared', (m: LiveMessage) => { + const kept = new Set(Array.isArray(m.kept) ? m.kept.filter((x): x is string => typeof x === 'string') : []); + for (const id of [...this.byId.keys()]) if (!kept.has(id)) this.byId.delete(id); + this.order = this.order.filter((id) => kept.has(id)); + this.emit({ kind: 'reset' }); + }); + live.on('agentAccess', (m: LiveMessage) => { + this.stoppedSet = new Set(Array.isArray(m.stopped) ? m.stopped.filter((x): x is string => typeof x === 'string') : []); + this.emit({ kind: 'access', agent: str(m.agent), state: str(m.state) }); + }); + live.onStatus((s) => { if (s === 'open') void this.load(); }); + } + + on(fn: (e: CallsEvent) => void): () => void { + this.fns.add(fn); + return () => { this.fns.delete(fn); }; + } + + get ready(): boolean { return this.loaded; } + get size(): number { return this.order.length; } + + list(): AgentCall[] { + const out: AgentCall[] = []; + for (const id of this.order) { + const c = this.byId.get(id); + if (c) out.push(c); + } + return out; + } + + get(id: string): AgentCall | undefined { return this.byId.get(id); } + + agents(): string[] { + const seen = new Set(); + for (const c of this.byId.values()) seen.add(c.agent); + for (const a of this.stoppedSet) seen.add(a); + return [...seen].sort((a, b) => a.localeCompare(b)); + } + + stopped(): string[] { return [...this.stoppedSet].sort((a, b) => a.localeCompare(b)); } + isStopped(agent: string): boolean { return this.stoppedSet.has(agent); } + + undoable(call: AgentCall): boolean { + return !!call.doc && !call.undone && this.undoableByDoc.get(call.doc) === call.id; + } + + async load(): Promise { + let said: Listing; + try { said = await get(`${URL}/calls`); } catch { return; } + this.byId.clear(); + const calls = (said.calls ?? []).map(parse).filter((c): c is AgentCall => c !== null); + for (const c of calls) this.byId.set(c.id, c); + this.order = calls.map((c) => c.id); + this.undoableByDoc.clear(); + for (const [doc, id] of Object.entries(said.undoable ?? {})) if (typeof id === 'string') this.undoableByDoc.set(doc, id); + this.stoppedSet = new Set((said.stopped ?? []).filter((x): x is string => typeof x === 'string')); + this.loaded = true; + this.emit({ kind: 'reset' }); + } + + undo(id: string): Promise { return post(`${URL}/calls/${encodeURIComponent(id)}/undo`, {}); } + clear(): Promise { return post(`${URL}/calls/clear`, {}); } + stop(agent: string): Promise { return post(`${URL}/stop`, { agent }); } + allow(agent: string): Promise { return post(`${URL}/allow`, { agent }); } + + private upsert(raw: unknown): void { + const call = parse(raw); + if (!call) return; + const had = this.byId.get(call.id); + const fresh = had === undefined; + if (fresh) this.order.unshift(call.id); + this.byId.set(call.id, call); + while (this.order.length > CALLS_CAP) this.byId.delete(this.order.pop() as string); + let touched: string[] = []; + if (!had) touched = call.objects; + else if (call.txs > had.txs) { + const added = call.objects.filter((o) => !had.objects.includes(o)); + touched = added.length ? added : call.objects; + } + this.emit({ kind: 'call', call, fresh, touched, ended: call.status !== 'running' && (!had || had.status === 'running') }); + } + + private emit(e: CallsEvent): void { + for (const fn of [...this.fns]) { + try { fn(e); } catch (err) { console.error('[agent-calls] listener failed', err); } + } + } +} + +export const agentCalls = new AgentCalls(); diff --git a/frontend/src/app/agent-window.ts b/frontend/src/app/agent-window.ts new file mode 100644 index 00000000..8543fbaf --- /dev/null +++ b/frontend/src/app/agent-window.ts @@ -0,0 +1,137 @@ +import { fragmentsTouched } from '../canvas/selection'; +import type { RenderDisplay } from '../canvas/types'; +import type { CanvasView } from '../canvas/view'; +import type { Derived, FormChemDocument, Id } from '../engine/model'; +import { session } from '../engine/session'; +import type { ToolResult } from '../extensions/host'; +import { subsetDocument } from './embedded-source'; +import { pictureSvg, pngSize, type Picture, type PictureOptions } from './picture'; +import { toBase64 } from './save-file'; +import { addWindowTool } from './window-tools'; + +export interface AgentWindowDeps { + view: CanvasView; + display(): RenderDisplay; + hideHome(): void; +} + +const DEFAULT_DPI = 144; +const DPI_RANGE: [number, number] = [18, 1200]; +const MARGIN = 6; +const SECOND_PAINT_MS = 30; + +const ok = (text: string, data: Record): ToolResult => ({ content: [{ type: 'text', text }], structuredContent: data }); +const fail = (text: string): ToolResult => ({ content: [{ type: 'text', text }], isError: true }); +const positive = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : null); +const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e)); + +function selected(view: CanvasView): { doc: Id | null; page: Id | null; ids: Id[]; atoms: string[]; bonds: string[] } { + const s = view.selection(); + return { + doc: view.client?.id ?? null, + page: view.page()?.id ?? null, + ids: [...new Set([...fragmentsTouched(s), ...s.objects])], + atoms: [...s.atoms], + bonds: [...s.bonds], + }; +} + +async function rasterise(pic: Picture, dpi: number, white: boolean): Promise<{ data: Uint8Array; w: number; h: number }> { + const { w, h } = pngSize(pic, dpi); + const url = URL.createObjectURL(new Blob([pic.svg], { type: 'image/svg+xml' })); + try { + const img = new Image(); + 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 (white) { ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, w, h); } + ctx.drawImage(img, 0, 0, w, h); + }; + paint(); + await new Promise((r) => window.setTimeout(r, SECOND_PAINT_MS)); + 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 { data: new Uint8Array(await blob.arrayBuffer()), w, h }; + } finally { + URL.revokeObjectURL(url); + } +} + +async function render(deps: AgentWindowDeps, args: Record): Promise { + const doc = args.doc as FormChemDocument | undefined; + if (!doc || typeof doc !== 'object' || !Array.isArray(doc.pages) || !doc.objects) return fail('The engine sent no drawing to render.'); + const derived = (args.derived && typeof args.derived === 'object' ? args.derived : null) as Derived | null; + const pageId = typeof args.page === 'string' ? args.page : doc.pages[0]?.id; + if (!pageId) return fail('The drawing has no page to render.'); + let pick: Id[] | null = Array.isArray(args.ids) ? args.ids.filter((x): x is Id => typeof x === 'string' && !!doc.objects[x]) : null; + if (args.selection === true) { + const s = selected(deps.view); + if (s.doc !== doc.id) return fail(`The drawing ${doc.id} is not the one shown in the FormChem window, so it has no selection there. Give ids, or scope page.`); + if (!s.ids.length) return fail('Nothing is selected in the FormChem window. Ask the person to select what to render, or give ids.'); + pick = s.ids; + } + if (pick && !pick.length) pick = null; + const sub = subsetDocument(doc, pageId, pick, pick ? 'selection' : 'page'); + const fmt = args.format === 'svg' ? 'svg' : 'png'; + const white = args.background !== 'transparent'; + const base: Omit = { + margin: positive(args.margin) ?? MARGIN, background: white ? 'white' : 'transparent', embedSource: false, fonts: 'subset', display: deps.display(), + }; + let pic: Picture; + try { + pic = await pictureSvg(sub, derived, { scale: 1, ...base }); + } catch (e) { + return fail(`The window could not draw it: ${errText(e)}.`); + } + const width = positive(args.width), height = positive(args.height); + const fit = Math.min(width ? width / pic.width : Infinity, height ? height / pic.height : Infinity); + const drawn = sub.pages[0]?.order ?? []; + if (fmt === 'svg') { + if (Number.isFinite(fit)) pic = await pictureSvg(sub, derived, { scale: fit, ...base }); + return ok(`Drew ${drawn.length} object${drawn.length === 1 ? '' : 's'} as SVG in the window.`, + { format: 'svg', svg: pic.svg, width: Math.round(pic.width), height: Math.round(pic.height), warnings: pic.warnings, ids: drawn }); + } + const asked = positive(args.dpi); + let dpi = asked ?? DEFAULT_DPI; + if (Number.isFinite(fit)) dpi = asked ? Math.min(asked, 72 * fit) : 72 * fit; + dpi = Math.min(DPI_RANGE[1], Math.max(DPI_RANGE[0], dpi)); + try { + const png = await rasterise(pic, dpi, white); + return ok(`Drew ${drawn.length} object${drawn.length === 1 ? '' : 's'} as a ${png.w} x ${png.h} PNG in the window.`, + { format: 'png', base64: toBase64(png.data), width: png.w, height: png.h, dpi: Math.round(dpi), warnings: pic.warnings, ids: drawn }); + } catch (e) { + return fail(`The window could not make the PNG: ${errText(e)}.`); + } +} + +async function show(deps: AgentWindowDeps, args: Record): Promise { + const id = typeof args.doc === 'string' ? args.doc : ''; + if (!id) return fail('Give doc, the drawing to show.'); + const had = !!session.get(id); + try { + const c = await session.attach(id); + if (!had || args.focus === true) { + deps.hideHome(); + session.activate(c.id); + } + } catch (e) { + return fail(`The window could not open the drawing ${id}: ${errText(e)}.`); + } + return ok(had ? `The drawing ${id} was already open in the window.` : `Opened the drawing ${id} in the window.`, { doc: id, opened: !had, active: session.active?.id === id }); +} + +export function registerAgentWindow(deps: AgentWindowDeps): () => void { + const offs = [ + addWindowTool('render', (args) => render(deps, args)), + addWindowTool('selection', async () => { const s = selected(deps.view); return ok(`${s.ids.length} object${s.ids.length === 1 ? '' : 's'} selected.`, s); }), + addWindowTool('show', (args) => show(deps, args)), + ]; + return () => { for (const off of offs) off(); }; +} diff --git a/frontend/src/app/canvas-commands.ts b/frontend/src/app/canvas-commands.ts index 0f410628..8a9fd9c9 100644 --- a/frontend/src/app/canvas-commands.ts +++ b/frontend/src/app/canvas-commands.ts @@ -1,11 +1,11 @@ -import { fragmentsTouched, isEmpty } from '../canvas/selection'; +import { darkPageOn, initDarkPage, onDarkPage, setDarkPage, toggleDarkPage } from '../canvas/dark-page'; +import { fragmentsTouched, isEmpty, makeSelection } from '../canvas/selection'; import { align, distribute, flipHorizontal, flipVertical, rotate90, type AlignHow } from '../canvas/tools'; import { atomsOfSelection, commitDraft, draftFor } from '../canvas/tools/common'; import { deleteSelection } from '../canvas/tools/edit'; 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'; @@ -14,7 +14,12 @@ 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 { extractClip, pastePlan } from './clip-data'; +import { commandStateChanged } from './commands-shell'; export interface CanvasCommandDeps { view: CanvasView; @@ -30,6 +35,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 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() }), + }; +} + 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'; @@ -41,12 +56,64 @@ 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'; const DUPLICATE_OFFSET = 10; -const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e)); +const errText = (e: unknown): string => t(e instanceof Error ? e.message : String(e)); function pageFragments(view: CanvasView): Fragment[] { const page = view.page(); @@ -123,13 +190,13 @@ function visibleCentre(view: CanvasView): Point { } function duplicate(view: CanvasView): void { - const ctx = view.context; + const client = view.client; + const page = view.page(); const sel = view.selection(); - if (isEmpty(sel)) return; - const d = draftFor(ctx); - const next = duplicateSelection(d, sel); - translateSelection(d, next, DUPLICATE_OFFSET, DUPLICATE_OFFSET); - if (commitDraft(ctx, t('Duplicate'), d)) view.setSelection(next); + if (!client || !page || isEmpty(sel)) return; + const clip = extractClip(client.doc, page, sel); + const plan = clip ? pastePlan(client.doc, page.id, clip, { at: null, offset: [DUPLICATE_OFFSET, DUPLICATE_OFFSET] }) : null; + if (plan && client.commit(t('Duplicate'), plan.ops)) view.setSelection(makeSelection(plan.atoms, plan.bonds, plan.objects)); } function remove(view: CanvasView): void { @@ -182,8 +249,13 @@ 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(), ]; - return commands.register(...defs); + initDarkPage(view.root); + const offDark = onDarkPage(() => commandStateChanged()); + const off = commands.register(...defs); + return () => { offDark(); off(); }; } diff --git a/frontend/src/app/canvas.ts b/frontend/src/app/canvas.ts index 4ec0b451..9570e4ce 100644 --- a/frontend/src/app/canvas.ts +++ b/frontend/src/app/canvas.ts @@ -17,8 +17,11 @@ 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 { registerGridCommands } from './grid-commands'; import { objectCommandDefs } from './object-commands'; import { registerReactionCommands } from './reaction-commands'; +import { registerStandardiseCommand } from './standardise-command'; export interface CanvasHosts { stage: HTMLElement; stageCol: HTMLElement } @@ -31,7 +34,7 @@ export interface MountedCanvas { style(): StyleOverride; } -function display(): RenderDisplay { +export function display(): RenderDisplay { const carbons = pref('carbonLabels'); return { colorByElement: pref('colorAtoms'), @@ -55,9 +58,12 @@ export function mountCanvas(h: CanvasHosts, homeOpen: () => boolean): MountedCan const find = mountFindBar(h.stage, view); find.onChange(() => commandStateChanged()); registerCanvasCommands({ view, homeOpen, find, rulers }); + registerGridCommands(view, homeOpen); commands.register(...objectCommandDefs(view, () => open() && !isEmpty(view.selection()))); registerReactionCommands({ view, homeOpen }); registerChemCommands({ host: view, homeOpen }); + registerExportCommands({ view, homeOpen, display }); + registerStandardiseCommand({ host: view, homeOpen }); onMarksView(() => view.setDisplay(display())); view.setDisplay(display()); diff --git a/frontend/src/app/catalogue.ts b/frontend/src/app/catalogue.ts index 8066400c..67efbff9 100644 --- a/frontend/src/app/catalogue.ts +++ b/frontend/src/app/catalogue.ts @@ -1,9 +1,13 @@ import type { CommandRegistry } from '../commands/registry'; +import type { EngineDocumentClient } from '../engine/client'; +import { session } from '../engine/session'; import { api } from '../io/api'; import type { LiveClient } from '../io/live'; import type { MenuDef, MenuItem } from '../ui/menu'; +import { COMMAND_STATE_EVENT } from './commands-shell'; const SETTLE_MS = 600; +const STATE_MS = 120; const REFRESH_MS = 120000; function menuIds(defs: MenuDef[]): string[] { @@ -17,21 +21,75 @@ function menuIds(defs: MenuDef[]): string[] { return [...out]; } +type Flags = Map; + +function flagsOf(registry: CommandRegistry): Flags { + const out: Flags = new Map(); + for (const c of registry.list()) { + const on = registry.checked(c); + out.set(c.id, `${registry.enabled(c) ? 1 : 0}${on === undefined ? '' : on ? 1 : 0}`); + } + return out; +} + export function mirrorCatalogue(registry: CommandRegistry, live: LiveClient, menus: () => MenuDef[]): () => void { let timer = 0; + let stateTimer = 0; let last = ''; + let sent: Flags = new Map(); + const push = (): void => { const entries = registry.catalogue(); const have = new Set(entries.map((e) => e.id)); const missing = menuIds(menus()).filter((id) => !have.has(id)); - const sig = JSON.stringify(entries.map((e) => [e.id, e.label, e.enabled, e.keys])); + const sig = JSON.stringify(entries.map((e) => [e.id, e.label, e.enabled, e.checked, e.keys])); if (sig === last) return; - void api.mirrorCommands({ size: entries.length, missing, commands: entries }).then(() => { last = sig; }).catch(() => undefined); + const flags = flagsOf(registry); + void api.mirrorCommands({ size: entries.length, missing, commands: entries }).then(() => { last = sig; sent = flags; }).catch(() => undefined); + }; + + const pushState = (): void => { + stateTimer = 0; + if (!last) return; + const flags = flagsOf(registry); + const enabled: Record = {}; + const checked: Record = {}; + let n = 0; + for (const [id, f] of flags) { + const was = sent.get(id); + if (was === undefined) { schedule(); return; } + if (was === f) continue; + enabled[id] = f[0] === '1'; + if (f.length > 1) checked[id] = f[1] === '1'; + n++; + } + if (!n) return; + void api.post('/api/commands/state', { enabled, checked }).then(() => { + for (const id of Object.keys(enabled)) sent.set(id, flags.get(id)!); + last = 'state'; + }).catch(() => undefined); }; + const schedule = (): void => { window.clearTimeout(timer); timer = window.setTimeout(push, SETTLE_MS); }; + const stateSoon = (): void => { if (!stateTimer) stateTimer = window.setTimeout(pushState, STATE_MS); }; + + let offDoc: (() => void) | null = null; + const follow = (c: EngineDocumentClient | null): void => { + offDoc?.(); + offDoc = c ? c.on((e) => { if (e.type !== 'preview') stateSoon(); }) : null; + stateSoon(); + }; + const offChange = registry.onChange(schedule); + const offRun = registry.onRun(stateSoon); + const offActive = session.onActive(follow); + document.addEventListener(COMMAND_STATE_EVENT, stateSoon); const offStatus = live.onStatus((s) => { if (s === 'open') { last = ''; schedule(); } }); const every = window.setInterval(() => { last = ''; schedule(); }, REFRESH_MS); schedule(); - return () => { offChange(); offStatus(); window.clearInterval(every); window.clearTimeout(timer); }; + return () => { + offChange(); offRun(); offActive(); offDoc?.(); offStatus(); + document.removeEventListener(COMMAND_STATE_EVENT, stateSoon); + window.clearInterval(every); window.clearTimeout(timer); window.clearTimeout(stateTimer); + }; } diff --git a/frontend/src/app/chem-commands.ts b/frontend/src/app/chem-commands.ts index 2ad4d2ed..469f40d3 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; @@ -57,7 +57,7 @@ export const CHEM_COMMAND_IDS: readonly string[] = [ 'assign-wedges', 'check-structure', 'compute-properties', 'copy-analysis', 'search-substructure', 'enumerate-markush', 'copy-smarts', 'export-smarts', ]; -const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e)); +const errText = (e: unknown): string => t(e instanceof Error ? e.message : String(e)); function topFragments(doc: FormChemDocument, ids: readonly Id[], out: Id[] = [], seen = new Set()): Id[] { for (const id of ids) { @@ -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'); } @@ -608,5 +597,5 @@ export const CHEM_MENU_ITEMS = { structure: ['expand-abbreviation', 'contract-abbreviation', '-', 'add-hydrogens', 'remove-hydrogens', '-', 'assign-wedges', { label: 'Enhanced Stereo', items: ['set-stereo-group-abs', 'set-stereo-group-and', 'set-stereo-group-or', '-', 'clear-stereo-group', '-', 'stereo-group-popover'] }, { label: 'Query', items: ['set-atom-list', '-', ...BOND_QUERY_LABELS.map(([q]) => `set-query-bond-${q}`), 'clear-query-bond', '-', 'define-rgroup', 'enumerate-markush', '-', 'copy-smarts', 'export-smarts'] }] as MenuItem[], view: ['show-stereo', 'show-stereo-groups', 'show-query-marks'] as MenuItem[], analysis: ['compute-properties', '-', 'copy-analysis'] as MenuItem[], - edit: ['search-substructure', 'copy-smarts'] as MenuItem[], + edit: ['search-substructure'] as MenuItem[], }; diff --git a/frontend/src/app/clip-data.ts b/frontend/src/app/clip-data.ts new file mode 100644 index 00000000..cbea863f --- /dev/null +++ b/frontend/src/app/clip-data.ts @@ -0,0 +1,461 @@ +import { objectBoxById } from '../canvas/render/bounds'; +import { pageObjects } from '../canvas/selection'; +import { atomsOfSelection } from '../canvas/tools/common'; +import { Draft } from '../canvas/tools/draft'; +import { translateSelection } from '../canvas/tools/transform'; +import { selectionKey, type Selection } from '../canvas/types'; +import { + FORMAT, + FORMAT_VERSION, + isFragment, + newId, + nowIso, + resolveStyle, + validate, + type Anchor, + type Atom, + type Bond, + type DocObject, + type Expansion, + type FormChemDocument, + type Fragment, + type Id, + type Media, + type Page, + type Point, + type Reaction, + type ReactionStep, + type Style, + type StyleOverride, +} from '../engine/model'; +import type { Op } from '../engine/ops'; + +export const CLIP_MIME = 'application/x-formchem+json'; +export const CLIP_KIND = 'formchem-clipboard'; + +export interface ClipMeta { kind: typeof CLIP_KIND; from: Id; page: Id; media?: Record } + +export interface Bounds { x: number; y: number; w: number; h: number } + +type Rec = Record; +const isRec = (v: unknown): v is Rec => typeof v === 'object' && v !== null && !Array.isArray(v); +const clone = (v: T): T => structuredClone(v); + +function childrenOf(doc: FormChemDocument, id: Id, out: Set, depth = 0): void { + if (out.has(id) || depth > 32) return; + const o = doc.objects[id]; + if (!o) return; + out.add(id); + if (o.kind === 'group') for (const c of o.children) childrenOf(doc, c, out, depth + 1); +} + +function expansionsUsed(doc: FormChemDocument, atoms: Iterable, out: Record, depth = 0): void { + if (depth > 16) return; + for (const a of atoms) { + const eid = a.expansion; + const e = eid ? doc.expansions?.[eid] : undefined; + if (!eid || !e || out[eid]) continue; + out[eid] = clone(e); + expansionsUsed(doc, Object.values(e.atoms), out, depth + 1); + } +} + +function partialFragment(f: Fragment, keep: ReadonlySet): Fragment { + const atoms: Record = {}; + const bonds: Record = {}; + for (const id of keep) if (f.atoms[id]) atoms[id] = clone(f.atoms[id]); + for (const b of Object.values(f.bonds)) if (keep.has(b.a) && keep.has(b.b)) bonds[b.id] = clone(b); + const out: Fragment = { ...clone(f), atoms, bonds }; + if (f.stereo_groups) { + const groups = f.stereo_groups.map((g) => ({ ...g, atoms: (g.atoms ?? []).filter((a) => keep.has(a)) })).filter((g) => g.atoms.length); + if (groups.length) out.stereo_groups = groups; + else delete out.stereo_groups; + } + return out; +} + +function stepFor(step: ReactionStep, kept: ReadonlySet): ReactionStep | null { + if (!kept.has(step.arrow)) return null; + const only = (ids: Id[] | undefined): Id[] => (ids ?? []).filter((id) => kept.has(id)); + const out: ReactionStep = { ...clone(step), reactants: only(step.reactants), products: only(step.products), agents: only(step.agents) }; + if (step.conditions) out.conditions = only(step.conditions); + if (step.coefficients) out.coefficients = Object.fromEntries(Object.entries(step.coefficients).filter(([id]) => kept.has(id))); + if (step.stoich) { + const s = clone(step.stoich); + s.components = Object.fromEntries(Object.entries(s.components ?? {}).filter(([id]) => kept.has(id))); + if (s.limiting && !kept.has(s.limiting)) delete s.limiting; + if (s.product && !kept.has(s.product)) delete s.product; + out.stoich = s; + } + return out; +} + +export function clipPage(doc: FormChemDocument): Page | null { + return doc.pages.find((p) => p.order.length > 0) ?? doc.pages[0] ?? null; +} + +export function clipMeta(doc: FormChemDocument): ClipMeta | null { + const m = doc.meta?.clipboard; + return isRec(m) && m.kind === CLIP_KIND && typeof m.from === 'string' ? (m as unknown as ClipMeta) : null; +} + +export function extractClip(doc: FormChemDocument, page: Page, sel: Selection): FormChemDocument | null { + const kept = new Set(); + const partial = new Map>(); + const empty = !sel.atoms.size && !sel.bonds.size && !sel.objects.size; + if (empty) { + for (const id of page.order) childrenOf(doc, id, kept); + } else { + for (const [fid, atoms] of atomsOfSelection(doc, sel)) { + const f = doc.objects[fid]; + if (!isFragment(f)) continue; + kept.add(fid); + if (atoms.size < Object.keys(f.atoms).length) partial.set(fid, atoms); + } + for (const id of sel.objects) childrenOf(doc, id, kept); + } + for (const fid of partial.keys()) if (sel.objects.has(fid)) partial.delete(fid); + if (!kept.size) return null; + + const objects: Record = {}; + for (const id of kept) { + const o = doc.objects[id]; + if (!o) continue; + const part = partial.get(id); + objects[id] = isFragment(o) && part ? partialFragment(o, part) : clone(o); + } + for (const o of Object.values(objects)) { + if (o.kind === 'group') o.children = o.children.filter((c) => kept.has(c)); + if (isFragment(o) && o.rgroups) { + for (const [k, def] of Object.entries(o.rgroups)) { + def.members = def.members.filter((m) => kept.has(m)); + if (def.attach) def.attach = Object.fromEntries(Object.entries(def.attach).filter(([m]) => kept.has(m))); + if (!def.members.length) delete o.rgroups[k]; + } + if (!Object.keys(o.rgroups).length) delete o.rgroups; + } + } + for (const [id, o] of Object.entries(objects)) if (o.kind === 'group' && !o.children.length) delete objects[id]; + + const order: Id[] = []; + const walk = (ids: readonly Id[], parentKept: boolean, depth: number): void => { + for (const id of ids) { + const o = doc.objects[id]; + if (!o || depth > 32) continue; + const here = id in objects; + if (here && !parentKept) order.push(id); + if (o.kind === 'group') walk(o.children, parentKept || here, depth + 1); + } + }; + walk(page.order, false, 0); + if (!order.length) return null; + + const expansions: Record = {}; + for (const o of Object.values(objects)) if (isFragment(o)) expansionsUsed(doc, Object.values(o.atoms), expansions); + const media: Record = {}; + for (const o of Object.values(objects)) if (o.kind === 'image' && doc.media?.[o.media]) media[o.media] = clone(doc.media[o.media]); + const reactions: Reaction[] = []; + const objectIds = new Set(Object.keys(objects)); + for (const r of page.reactions ?? []) { + const steps = r.steps.map((s) => stepFor(s, objectIds)).filter((s): s is ReactionStep => !!s); + if (steps.length) reactions.push({ id: r.id, steps }); + } + + const at = nowIso(); + const style = resolveStyle(doc); + const out: FormChemDocument = { + format: FORMAT, + format_version: FORMAT_VERSION, + id: newId('d'), + title: doc.title, + created: at, + modified: at, + style: clone(style), + pages: [{ id: page.id, size: clone(page.size), order, ...(reactions.length ? { reactions } : {}) }], + objects, + meta: { app: 'FormChem', clipboard: { kind: CLIP_KIND, from: doc.id, page: page.id } satisfies ClipMeta }, + }; + if (Object.keys(expansions).length) out.expansions = expansions; + if (Object.keys(media).length) out.media = media; + return out; +} + +export function clipBounds(doc: FormChemDocument, page: Page): Bounds | null { + let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; + for (const id of page.order) { + const b = objectBoxById(doc, id); + if (!b) continue; + x0 = Math.min(x0, b.x); + y0 = Math.min(y0, b.y); + x1 = Math.max(x1, b.x + b.w); + y1 = Math.max(y1, b.y + b.h); + } + return x0 === Infinity ? null : { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }; +} + +export function clipFragments(doc: FormChemDocument): Fragment[] { + const page = clipPage(doc); + if (!page) return []; + const out: Fragment[] = []; + for (const id of pageObjects(doc, page)) { + const o = doc.objects[id]; + if (isFragment(o) && Object.keys(o.atoms).length) out.push(o); + } + return out; +} + +export function readClip(text: string): FormChemDocument | null { + let raw: unknown; + try { raw = JSON.parse(text); } catch { return null; } + if (!isRec(raw)) return null; + if (raw.format !== FORMAT && isRec(raw.document)) raw = raw.document; + if (!isRec(raw) || raw.format !== FORMAT) return null; + const doc = raw as unknown as FormChemDocument; + if (!isRec(doc.meta)) (doc as { meta: Rec }).meta = {}; + if (!isRec(doc.style)) (doc as { style: Rec }).style = {}; + return validate(doc).length ? null : doc; +} + +function styleDiff(src: Style, dst: Style): StyleOverride { + const out: Rec = {}; + const a = src as unknown as Rec, b = dst as unknown as Rec; + for (const k of Object.keys(a)) { + if (k === 'preset' || a[k] === undefined) continue; + if (JSON.stringify(a[k]) !== JSON.stringify(b[k])) out[k] = clone(a[k]); + } + return out as StyleOverride; +} + +export interface MediaMap { [oldId: Id]: { id: Id; media: Media | null } } + +export interface PastePlan { ops: Op[]; top: Id[]; atoms: string[]; bonds: string[]; objects: Id[]; fragments: Id[] } + +export interface PasteOptions { at: Point | null; keepStyle?: boolean; media?: MediaMap; offset?: Point } + +function sameJson(a: unknown, b: unknown): boolean { + return JSON.stringify(a) === JSON.stringify(b); +} + +export function pastePlan(target: FormChemDocument, pageId: Id, clip: FormChemDocument, opts: PasteOptions): PastePlan | null { + const page = clipPage(clip); + const dest = target.pages.find((p) => p.id === pageId); + if (!page || !dest || !page.order.length) return null; + + let source = clip; + const box = clipBounds(clip, page); + let dx = 0, dy = 0; + if (opts.at && box) { + dx = opts.at[0] - (box.x + box.w / 2); + dy = opts.at[1] - (box.y + box.h / 2); + } else if (opts.offset) { + [dx, dy] = opts.offset; + } + if (Math.abs(dx) > 1e-6 || Math.abs(dy) > 1e-6) { + const d = new Draft(clip, page.id); + const atoms: string[] = []; + for (const id of page.order) { + const o = clip.objects[id]; + if (isFragment(o)) for (const a of Object.keys(o.atoms)) atoms.push(selectionKey(id, a)); + } + translateSelection(d, { atoms: new Set(atoms), bonds: new Set(), objects: new Set(page.order) }, dx, dy); + source = d.doc; + } + + const ids = new Map(); + const fresh = (old: Id, prefix: string): Id => { + let id = ids.get(old); + if (!id) ids.set(old, (id = newId(prefix))); + return id; + }; + const all = pageObjects(source, page); + for (const id of all) fresh(id, isFragment(source.objects[id]) ? 'f' : 'o'); + for (const id of all) { + const o = source.objects[id]; + if (!isFragment(o)) continue; + for (const a of Object.keys(o.atoms)) fresh(a, 'a'); + for (const b of Object.keys(o.bonds)) fresh(b, 'b'); + } + const map = (id: Id): Id => ids.get(id) ?? id; + const has = (id: Id | undefined): id is Id => !!id && ids.has(id); + + const ops: Op[] = []; + const expMap = new Map(); + const srcExp = source.expansions ?? {}; + const haveExp = { ...(target.expansions ?? {}) }; + const expOps: Op[] = []; + for (const [eid, e] of Object.entries(srcExp)) { + const there = haveExp[eid]; + if (there && sameJson(there, e)) { expMap.set(eid, eid); continue; } + const nid = there ? newId('e') : eid; + expMap.set(eid, nid); + haveExp[nid] = e; + } + for (const [eid, e] of Object.entries(srcExp)) { + const nid = expMap.get(eid)!; + if (target.expansions?.[nid]) continue; + const atoms: Record = {}; + for (const [aid, a] of Object.entries(e.atoms)) atoms[aid] = a.expansion && expMap.has(a.expansion) ? { ...a, expansion: expMap.get(a.expansion) } : a; + expOps.push({ op: 'set', path: ['expansions', nid], value: { ...clone(e), id: nid, atoms: clone(atoms) } }); + } + if (expOps.length) { + if (!target.expansions) ops.push({ op: 'set', path: ['expansions'], value: {} }); + ops.push(...expOps); + } + + const media = opts.media ?? {}; + const mediaOps: Op[] = []; + for (const m of Object.values(media)) { + if (m.media && !target.media?.[m.id]) mediaOps.push({ op: 'set', path: ['media', m.id], value: m.media }); + } + if (mediaOps.length) { + if (!target.media) ops.push({ op: 'set', path: ['media'], value: {} }); + ops.push(...mediaOps); + } + + const carry = opts.keepStyle === false ? {} : styleDiff(resolveStyle(clip), resolveStyle(target)); + const carried = Object.keys(carry).length > 0; + const anchor = (a: Anchor | undefined): Anchor | undefined => { + if (!a || !has(a.object)) return undefined; + if ('atom' in a) return { ...a, object: map(a.object), atom: map(a.atom) }; + if ('bond' in a) return { ...a, object: map(a.object), bond: map(a.bond) }; + return { ...a, object: map(a.object), between: [map(a.between[0]), map(a.between[1])] }; + }; + + const out: PastePlan = { ops, top: [], atoms: [], bonds: [], objects: [], fragments: [] }; + const skipped = new Set(); + for (const id of all) { + const src = source.objects[id]; + const o = clone(src) as DocObject; + const nid = map(id); + (o as { id: Id }).id = nid; + if (carried) o.style = { ...carry, ...(o.style ?? {}) }; + switch (o.kind) { + case 'fragment': { + const atoms: Record = {}; + for (const a of Object.values(o.atoms)) { + const na: Atom = { ...a, id: map(a.id) }; + if (a.expansion) { + if (expMap.has(a.expansion)) na.expansion = expMap.get(a.expansion); + else if (!target.expansions?.[a.expansion]) delete na.expansion; + } + atoms[na.id] = na; + out.atoms.push(selectionKey(nid, na.id)); + } + const bonds: Record = {}; + for (const b of Object.values(o.bonds)) { + const nb: Bond = { ...b, id: map(b.id), a: map(b.a), b: map(b.b) }; + bonds[nb.id] = nb; + out.bonds.push(selectionKey(nid, nb.id)); + } + o.atoms = atoms; + o.bonds = bonds; + if (o.stereo_groups) o.stereo_groups = o.stereo_groups.map((g) => ({ ...g, atoms: (g.atoms ?? []).map(map) })); + if (o.rgroups) { + for (const def of Object.values(o.rgroups)) { + def.members = def.members.filter((m) => has(m)).map(map); + if (def.attach) def.attach = Object.fromEntries(Object.entries(def.attach).filter(([m]) => has(m)).map(([m, list]) => [map(m), list.map(map)])); + } + } + out.fragments.push(nid); + break; + } + case 'caption': + if (o.target) { if (has(o.target)) o.target = map(o.target); else delete o.target; } + break; + case 'arrow': + if (o.anchors) { + const tail = anchor(o.anchors.tail), head = anchor(o.anchors.head); + if (tail || head) o.anchors = { ...(tail ? { tail } : {}), ...(head ? { head } : {}) }; + else delete o.anchors; + } + break; + case 'bracket': + if (o.fragment) { + if (has(o.fragment)) { o.fragment = map(o.fragment); if (o.atoms) o.atoms = o.atoms.filter((a) => has(a)).map(map); } + else { delete o.fragment; delete o.atoms; } + } + break; + case 'orbital': + if (o.atom) { if (has(o.atom.object)) o.atom = { object: map(o.atom.object), atom: map(o.atom.atom) }; else delete o.atom; } + break; + case 'table': + for (const r of o.rows) for (const c of r.cells) if (c.object) { if (has(c.object)) c.object = map(c.object); else delete c.object; } + break; + case 'group': + o.children = o.children.filter((c) => has(c)).map(map); + break; + case 'image': { + const m = media[o.media]; + if (m) o.media = m.id; + else if (!target.media?.[o.media]) { skipped.add(id); continue; } + break; + } + default: + break; + } + ops.push({ op: 'set', path: ['objects', nid], value: o }); + out.objects.push(nid); + } + + const reactionIds = new Map(); + const stepIds = new Map(); + const reactions: Reaction[] = []; + for (const r of page.reactions ?? []) { + const steps: ReactionStep[] = []; + for (const s of r.steps) { + if (!has(s.arrow) || skipped.has(s.arrow)) continue; + const sid = newId('s'); + stepIds.set(s.id, sid); + const list = (v: Id[] | undefined): Id[] => (v ?? []).filter((id) => has(id) && !skipped.has(id)).map(map); + const ns: ReactionStep = { ...clone(s), id: sid, arrow: map(s.arrow), reactants: list(s.reactants), products: list(s.products), agents: list(s.agents) }; + if (s.conditions) ns.conditions = list(s.conditions); + if (s.coefficients) ns.coefficients = Object.fromEntries(Object.entries(s.coefficients).filter(([id]) => has(id)).map(([id, v]) => [map(id), v])); + if (s.stoich) { + const st = clone(s.stoich); + st.components = Object.fromEntries(Object.entries(st.components ?? {}).filter(([id]) => has(id)).map(([id, v]) => [map(id), v])); + if (st.limiting) { if (has(st.limiting)) st.limiting = map(st.limiting); else delete st.limiting; } + if (st.product) { if (has(st.product)) st.product = map(st.product); else delete st.product; } + ns.stoich = st; + } + steps.push(ns); + } + if (!steps.length) continue; + const rid = newId('r'); + reactionIds.set(r.id, rid); + reactions.push({ id: rid, steps }); + } + for (const op of ops) { + const v = op.op === 'set' && isRec(op.value) ? (op.value as unknown as DocObject) : null; + if (v?.kind !== 'table' || !v.stoich) continue; + const rid = reactionIds.get(v.stoich.reaction), sid = stepIds.get(v.stoich.step); + if (rid && sid) v.stoich = { reaction: rid, step: sid }; + else delete v.stoich; + } + + for (const id of page.order) { + if (!has(id) || skipped.has(id)) continue; + const nid = map(id); + ops.push({ op: 'ins', path: ['pages', { id: dest.id }, 'order'], value: nid }); + out.top.push(nid); + } + if (!out.top.length) return null; + if (reactions.length) { + if (dest.reactions) for (const r of reactions) ops.push({ op: 'ins', path: ['pages', { id: dest.id }, 'reactions'], value: r }); + else ops.push({ op: 'set', path: ['pages', { id: dest.id }, 'reactions'], value: reactions }); + } + out.objects = out.objects.filter((id) => !skipped.has(id)); + return out; +} + +export function fragmentsDoc(frags: Fragment[], title = 'Clipboard', extra: { objects?: DocObject[]; reactions?: Reaction[] } = {}): FormChemDocument { + const at = nowIso(); + const objects: Record = {}; + const order: Id[] = []; + for (const o of [...frags, ...(extra.objects ?? [])]) { + objects[o.id] = o; + order.push(o.id); + } + const page: Page = { id: newId('p'), size: 'auto', order }; + if (extra.reactions?.length) page.reactions = extra.reactions; + return { format: FORMAT, format_version: FORMAT_VERSION, id: newId('d'), title, created: at, modified: at, style: {}, pages: [page], objects, meta: {} }; +} diff --git a/frontend/src/app/clip-formats.ts b/frontend/src/app/clip-formats.ts new file mode 100644 index 00000000..db160eb4 --- /dev/null +++ b/frontend/src/app/clip-formats.ts @@ -0,0 +1,199 @@ +import { analysisApi } from '../engine/analysis-api'; +import { isFragment, type DocObject, type FormChemDocument, type Fragment, type Id, type Reaction, type StereoGroup } from '../engine/model'; +import { reactionsApi, warningText, type ReactionFormat } from '../engine/reactions-api'; +import { ApiError, post } from '../io/api'; +import { clipFragments, clipMeta, clipPage, fragmentsDoc, readClip } from './clip-data'; + +export type TextFormat = 'smiles' | 'cxsmiles' | 'molfile' | 'inchi' | 'inchikey' | 'smarts' | 'cdxml' | 'rsmiles' | 'rxn'; + +export interface TextOut { text: string; format: string; notes: string[] } + +export interface ParsedClip { doc: FormChemDocument; format: string; notes: string[]; reaction: boolean } + +interface ExportAnswer { format?: string; text?: string | null; report?: Array<{ text?: string; severity?: string }> } +interface ParseAnswer { format?: string; fragments?: Fragment[]; warnings?: Array<{ text?: string } | string>; report?: Array<{ text?: string; severity?: string }> } +interface ReactionParse { format?: string; objects?: DocObject[]; reaction?: Reaction | null; warnings?: Array<{ text?: string } | string>; report?: Array<{ text?: string; severity?: string }> } + +const EXPORT_URL = '/api/chem/export'; +const PARSE_URL = '/api/chem/parse'; +const CONVERT_URL = '/api/chem/convert'; +const REACTION_PARSE_URL = '/api/chem/reactions/import'; +const SMARTS_IMPORT_URL = '/api/analysis/smarts/import'; + +let fioExport: boolean | null = null; + +const noteOf = (w: { text?: string } | string | undefined): string => (typeof w === 'string' ? w : w?.text ?? ''); +const notesOf = (list: Array<{ text?: string } | string> | undefined): string[] => (list ?? []).map(noteOf).filter(Boolean); +type Report = Array<{ text?: string; severity?: string }> | undefined; +const reportNotes = (report: Report, warnings?: Array<{ text?: string } | string>): string[] => + report ? [...new Set(report.filter((i) => i.severity !== 'info').map((i) => i.text ?? '').filter(Boolean))] : notesOf(warnings); +const ONE_LINE = new Set(['smiles', 'cxsmiles', 'rsmiles', 'inchi', 'inchikey', 'smarts']); + +export function clipReactions(doc: FormChemDocument): Reaction[] { + return (clipPage(doc)?.reactions ?? []).filter((r) => r.steps.some((s) => s.reactants.length || s.products.length)); +} + +export const isReactionClip = (doc: FormChemDocument): boolean => clipReactions(doc).length > 0; + +export function mergedFragment(frags: Fragment[]): Fragment { + const out: Fragment = { id: 'fclip', kind: 'fragment', atoms: {}, bonds: {} }; + const groups: StereoGroup[] = []; + for (const f of frags) { + Object.assign(out.atoms, f.atoms); + Object.assign(out.bonds, f.bonds); + if (f.stereo_groups) groups.push(...f.stereo_groups); + if (f.chiral && !out.chiral) out.chiral = f.chiral; + } + if (groups.length) out.stereo_groups = groups; + return out; +} + +const needsV3000 = (f: Fragment): boolean => + !!f.stereo_groups?.length || !!f.rgroups || Object.values(f.atoms).some((a) => a.query || a.element === 'R#' || a.generic) || Object.values(f.bonds).some((b) => b.query || b.order === 'dative' || b.order === 'hydrogen'); + +async function viaFio(doc: FormChemDocument, format: TextFormat): Promise { + if (fioExport === false) return null; + const page = clipPage(doc); + const frags = clipFragments(doc); + const objects: Record = {}; + for (const [id, o] of Object.entries(doc.objects)) if (!isFragment(o)) objects[id] = o; + const body = { format, fragments: frags, objects, reactions: page?.reactions ?? [], expansions: doc.expansions ?? {}, options: format === 'molfile' || format === 'rxn' ? { version: 'auto' } : {}, name: doc.title }; + try { + const r = await post(EXPORT_URL, body); + fioExport = true; + const text = r.text ?? ''; + return { text: ONE_LINE.has(format) ? text.trim() : text, format: r.format ?? format, notes: reportNotes(r.report ?? []) }; + } catch (e) { + if (e instanceof ApiError && (e.status === 404 || e.status === 405)) { fioExport = false; return null; } + throw e; + } +} + +async function reactionText(doc: FormChemDocument, format: ReactionFormat): Promise { + const meta = clipMeta(doc); + const r = clipReactions(doc)[0]; + const step = r?.steps[0]; + if (!meta || !r || !step) throw new Error('the reaction was not copied from an open drawing'); + const out = await reactionsApi.exportText(meta.from, { page: meta.page, reaction: r.id, step: step.id }, format); + return { text: out.text, format: format === 'smiles' ? 'rsmiles' : 'rxn', notes: out.warnings.map(warningText).filter(Boolean) }; +} + +async function legacy(doc: FormChemDocument, format: TextFormat): Promise { + if (format === 'rsmiles') return reactionText(doc, 'smiles'); + if (format === 'rxn') return reactionText(doc, 'rxn'); + const frags = clipFragments(doc); + if (!frags.length) throw new Error('there is no structure to write'); + const expansions = doc.expansions && Object.keys(doc.expansions).length ? doc.expansions : undefined; + if (format === 'smarts') { + const parts: string[] = []; + const notes: string[] = []; + for (const f of frags) { + const r = await analysisApi.smarts(expansions ? { fragment: f, expansions } : { fragment: f }); + if (r.smarts) parts.push(r.smarts); + notes.push(...r.warnings.map((w) => w.text)); + } + return { text: parts.join('.'), format, notes }; + } + if (format === 'cdxml') throw new Error('CDXML needs the file formats engine of this version; update the engine and try again'); + const one = mergedFragment(frags); + if (format === 'molfile' && needsV3000(one)) { + const r = await post<{ text: string; warnings?: Array<{ text?: string } | string> }>('/api/analysis/molfile', { fragment: one, ...(expansions ? { expansions } : {}) }); + return { text: r.text, format: 'molfile3000', notes: notesOf(r.warnings) }; + } + const r = await post<{ text: string; warnings?: Array<{ text?: string } | string> }>(CONVERT_URL, { fragment: one, to: format, ...(expansions ? { expansions } : {}) }); + return { text: r.text, format, notes: notesOf(r.warnings) }; +} + +export async function clipText(doc: FormChemDocument, format: TextFormat): Promise { + let want = format; + if (isReactionClip(doc)) { + if (format === 'smiles' || format === 'cxsmiles') want = 'rsmiles'; + else if (format === 'molfile') want = 'rxn'; + } + const fio = await viaFio(doc, want); + if (fio?.text) return fio; + return legacy(doc, want); +} + +export function plainText(doc: FormChemDocument): string { + const out: string[] = []; + const page = clipPage(doc); + for (const id of page?.order ?? []) { + const o = doc.objects[id] as DocObject | undefined; + if (o && (o.kind === 'text' || o.kind === 'caption')) out.push(o.runs.map((r) => r.t).join('')); + } + return out.join('\n'); +} + +const SMARTS_HINT = /\[[^\]]*([;&,!~$]|#\d)[^\]]*\]|~|\$\(|\[\*\]|\[[^\]]*[DXRrvx]\d*[^\]]*\]/; +const NAME_HINT = /^[A-Za-z0-9][A-Za-z0-9 ,'()[\]{}+-]*[A-Za-z0-9)\]]$/; +const WORDY = /[a-z]{4,}/; + +export const looksLikeSmarts = (text: string): boolean => SMARTS_HINT.test(text.trim().split(/\s+/)[0] ?? ''); + +export function looksLikeName(text: string): boolean { + const s = text.trim(); + return s.length > 2 && s.length < 200 && !s.includes('\n') && NAME_HINT.test(s) && WORDY.test(s.toLowerCase()) && s.split(/\s+/).length <= 8; +} + +export function looksLikeReaction(text: string): boolean { + const s = text.trimStart(); + if (s.startsWith('$RXN')) return true; + const first = s.split(/\s+/)[0] ?? ''; + return /^[^>]*>[^>]*>[^>]*$/.test(first.replace(/->|<-/g, '')); +} + +export interface ParseOptions { bondLength?: number; format?: string } + +async function parseReaction(text: string, opts: ParseOptions): Promise { + const r = await post(REACTION_PARSE_URL, { text, ...(opts.bondLength ? { bond_length: opts.bondLength } : {}), ...(opts.format ? { format: opts.format } : {}) }); + const objects = r.objects ?? []; + if (!objects.some((o) => isFragment(o) && Object.keys(o.atoms).length)) return null; + const frags = objects.filter(isFragment); + const rest = objects.filter((o) => !isFragment(o)); + return { doc: fragmentsDoc(frags, 'Reaction', { objects: rest, reactions: r.reaction ? [r.reaction] : [] }), format: r.format ?? 'rsmiles', notes: reportNotes(r.report, r.warnings), reaction: true }; +} + +async function parseSmarts(text: string, opts: ParseOptions): Promise { + let r: ParseAnswer; + try { + r = await post(PARSE_URL, { text, format: 'smarts', ...(opts.bondLength ? { bond_length: opts.bondLength } : {}) }); + } catch (e) { + if (!(e instanceof ApiError) || e.status !== 422) throw e; + r = await post(SMARTS_IMPORT_URL, { text: text.trim(), ...(opts.bondLength ? { bond_length: opts.bondLength } : {}) }); + } + const frags = (r.fragments ?? []).filter((f) => isFragment(f) && Object.keys(f.atoms).length); + return frags.length ? { doc: fragmentsDoc(frags), format: 'smarts', notes: reportNotes(r.report, r.warnings), reaction: false } : null; +} + +export async function parseClipText(text: string, opts: ParseOptions = {}): Promise { + const s = text.replace(/^/, ''); + if (!s.trim()) return null; + const trimmed = s.trim(); + if (trimmed.startsWith('{')) { + const native = readClip(trimmed); + if (native) return { doc: native, format: 'formchem', notes: [], reaction: isReactionClip(native) }; + } + const fmt = opts.format; + if (fmt === 'smarts') return parseSmarts(trimmed, opts); + if (fmt === 'rsmiles' || fmt === 'rxn' || (!fmt && looksLikeReaction(s))) { + try { + const r = await parseReaction(s, opts); + if (r || fmt) return r; + } catch (e) { + if (fmt) throw e; + } + } + let r: ParseAnswer | null = null; + try { + r = await post(PARSE_URL, { text: s, ...(fmt ? { format: fmt } : {}), ...(opts.bondLength ? { bond_length: opts.bondLength } : {}) }); + } catch (e) { + if (fmt || !(e instanceof ApiError) || e.status !== 422) throw e; + } + const frags = (r?.fragments ?? []).filter((f) => isFragment(f) && Object.keys(f.atoms).length); + if (frags.length) { + return { doc: fragmentsDoc(frags), format: r?.format ?? 'smiles', notes: reportNotes(r?.report, r?.warnings), reaction: false }; + } + if (!fmt && looksLikeSmarts(trimmed)) return parseSmarts(trimmed, opts).catch(() => null); + return null; +} diff --git a/frontend/src/app/clip-picture.ts b/frontend/src/app/clip-picture.ts new file mode 100644 index 00000000..287c733e --- /dev/null +++ b/frontend/src/app/clip-picture.ts @@ -0,0 +1,59 @@ +import type { RenderDisplay } from '../canvas/types'; +import type { Derived, FormChemDocument } from '../engine/model'; +import { readClip } from './clip-data'; + +export interface Picture { svg: string; width: number; height: number; box: { x: number; y: number; w: number; h: number } } +interface PictureOptions { + scale: number; + margin: number; + background: 'transparent' | 'white'; + embedSource: boolean; + fonts: 'subset' | 'full' | 'none'; + display?: RenderDisplay; +} +interface PictureModule { + pictureSvg(doc: FormChemDocument, derived: Derived | null, opts: PictureOptions): Promise; + picturePng(pic: Picture, dpi: number, background: 'transparent' | 'white', source: FormChemDocument | null): Promise; +} +interface SourceModule { + extractSource(data: Blob | Uint8Array | string): Promise<{ doc: FormChemDocument } | null>; +} + +const kits = import.meta.glob(['./picture.ts', './embedded-source.ts']); + +async function load(path: string): Promise { + const get = kits[path]; + if (!get) return null; + try { return (await get()) as T; } catch { return null; } +} + +export const PNG_DPI = 192; + +export async function picturesAvailable(): Promise { + return !!(await load('./picture.ts')); +} + +export async function clipSvg(doc: FormChemDocument, derived: Derived | null, display?: RenderDisplay): Promise { + const kit = await load('./picture.ts'); + if (!kit) return null; + const pic = await kit.pictureSvg(doc, derived, { scale: 1, margin: 4, background: 'transparent', embedSource: true, fonts: 'subset', ...(display ? { display } : {}) }); + return pic.svg; +} + +export async function clipPng(doc: FormChemDocument, derived: Derived | null, display?: RenderDisplay): Promise { + const kit = await load('./picture.ts'); + if (!kit) return null; + const pic = await kit.pictureSvg(doc, derived, { scale: 1, margin: 4, background: 'transparent', embedSource: false, fonts: 'full', ...(display ? { display } : {}) }); + const bytes = await kit.picturePng(pic, PNG_DPI, 'transparent', doc); + return new Blob([bytes as BlobPart], { type: 'image/png' }); +} + +export async function sourceOfPicture(data: Blob | string): Promise { + const kit = await load('./embedded-source.ts'); + if (kit) { + const found = await kit.extractSource(data).catch(() => null); + const doc = found?.doc ? readClip(JSON.stringify(found.doc)) : null; + if (doc && doc.pages.some((p) => p.order.length)) return doc; + } + return null; +} diff --git a/frontend/src/app/clip-system.ts b/frontend/src/app/clip-system.ts new file mode 100644 index 00000000..24b80f71 --- /dev/null +++ b/frontend/src/app/clip-system.ts @@ -0,0 +1,222 @@ +import { CLIP_MIME } from './clip-data'; + +export const WEB_CLIP_MIME = `web ${CLIP_MIME}`; +export const HTML_SOURCE_ATTR = 'data-formchem-source'; + +export type FlavourValue = string | Blob; +export interface Flavour { type: string; text?: string; blob?: Blob } + +export interface SyncFlavours { text?: string; html?: string; native?: string } +export type RichFlavours = Partial>>; + +export interface WriteResult { ok: boolean; via: 'async' | 'event' | 'none'; types: string[]; error?: string } + +const IMAGE_TYPES = ['image/png', 'image/svg+xml', 'image/jpeg', 'image/gif', 'image/webp']; +const SAFE_TYPES = new Set(['text/plain', 'text/html', 'image/png']); + +let inEvent = false; + +function fillTransfer(dt: DataTransfer, sync: SyncFlavours): string[] { + const out: string[] = []; + const put = (type: string, value: string | undefined): void => { + if (!value) return; + try { dt.setData(type, value); out.push(type); } catch { return; } + }; + put('text/plain', sync.text); + put('text/html', sync.html); + put(CLIP_MIME, sync.native); + return out; +} + +export function writeEvent(e: ClipboardEvent, sync: SyncFlavours): string[] { + if (!e.clipboardData) return []; + e.preventDefault(); + return fillTransfer(e.clipboardData, sync); +} + +function execCopy(sync: SyncFlavours): string[] { + if (inEvent) return []; + let types: string[] = []; + const grab = (e: ClipboardEvent): void => { + e.stopImmediatePropagation(); + types = writeEvent(e, sync); + }; + inEvent = true; + document.addEventListener('copy', grab, { capture: true }); + try { document.execCommand('copy'); } catch { types = []; } finally { + document.removeEventListener('copy', grab, { capture: true }); + inEvent = false; + } + return types; +} + +const supports = (type: string): boolean => { + const C = window.ClipboardItem as (typeof ClipboardItem & { supports?: (t: string) => boolean }) | undefined; + if (!C) return false; + if (typeof C.supports === 'function') { + try { return C.supports(type); } catch { return false; } + } + return SAFE_TYPES.has(type); +}; + +const asBlob = (type: string, v: FlavourValue): Blob => (typeof v === 'string' ? new Blob([v], { type }) : v.type === type ? v : new Blob([v], { type })); + +async function writeAsync(all: Record>): Promise { + const types = Object.keys(all).filter(supports); + if (!types.length || !navigator.clipboard?.write) return []; + const settled = new Map>(); + for (const type of types) { + settled.set(type, all[type].then((v) => { + if (v === null || v === undefined || (typeof v === 'string' && !v)) throw new Error(`no ${type}`); + return asBlob(type.startsWith('web ') ? type.slice(4) : type, v); + })); + } + const present = async (): Promise => { + const ok: string[] = []; + for (const [type, p] of settled) if (await p.then(() => true, () => false)) ok.push(type); + return ok; + }; + const item = (list: string[]): ClipboardItem => new ClipboardItem(Object.fromEntries(list.map((t) => [t, settled.get(t)!]))); + try { + await navigator.clipboard.write([item(types)]); + return present(); + } catch { + const ok = await present(); + const basic = ok.filter((t) => SAFE_TYPES.has(t) || t === WEB_CLIP_MIME); + if (!basic.length) return []; + try { + await navigator.clipboard.write([new ClipboardItem(Object.fromEntries(basic.map((t) => [t, settled.get(t)!])))]); + return basic; + } catch { + return []; + } + } +} + +export async function writeClipboard(sync: SyncFlavours, rich: RichFlavours, event?: ClipboardEvent): Promise { + const first = event ? writeEvent(event, sync) : execCopy(sync); + const all: Record> = {}; + if (sync.text) all['text/plain'] = Promise.resolve(sync.text); + if (sync.html) all['text/html'] = Promise.resolve(sync.html); + if (sync.native) all[WEB_CLIP_MIME] = Promise.resolve(sync.native); + for (const [type, p] of Object.entries(rich)) if (p) all[type] = p; + let types: string[] = []; + let error = ''; + try { types = await writeAsync(all); } catch (e) { error = e instanceof Error ? e.message : String(e); } + if (types.length >= first.length && types.length) return { ok: true, via: 'async', types }; + if (first.length) return { ok: true, via: 'event', types: first }; + return { ok: false, via: 'none', types: [], ...(error ? { error } : {}) }; +} + +export async function writePlain(text: string, type = 'text/plain'): Promise { + const sync: SyncFlavours = { text }; + const rich: RichFlavours = type === 'text/plain' ? {} : { [type]: Promise.resolve(text) }; + return (await writeClipboard(sync, rich)).ok; +} + +export async function writeBlob(blob: Promise, type: string, alt?: SyncFlavours): Promise { + return writeClipboard(alt ?? {}, { [type]: blob }); +} + +export function flavoursOfTransfer(dt: DataTransfer | null): Flavour[] { + if (!dt) return []; + const out: Flavour[] = []; + for (const type of Array.from(dt.types)) { + if (type === 'Files') continue; + let text = ''; + try { text = dt.getData(type); } catch { text = ''; } + if (text) out.push({ type, text }); + } + for (const f of Array.from(dt.files ?? [])) if (IMAGE_TYPES.includes(f.type) || /\.(png|svg|jpe?g|gif|webp)$/i.test(f.name)) out.push({ type: f.type || 'image/png', blob: f }); + if (!dt.files?.length) { + for (const it of Array.from(dt.items ?? [])) { + if (it.kind !== 'file') continue; + const f = it.getAsFile(); + if (f) out.push({ type: f.type || it.type, blob: f }); + } + } + return out; +} + +export interface ReadResult { flavours: Flavour[]; denied: boolean; error?: string } + +export async function readClipboard(): Promise { + let denied = false; + let error = ''; + if (navigator.clipboard?.read) { + try { + const items = await navigator.clipboard.read(); + const out: Flavour[] = []; + for (const item of items) { + for (const type of item.types) { + try { + const blob = await item.getType(type); + if (type.startsWith('text/') || type.startsWith('web ') || type === CLIP_MIME) out.push({ type, text: await blob.text() }); + else out.push({ type, blob }); + } catch { continue; } + } + } + return { flavours: out, denied: false }; + } catch (e) { + denied = e instanceof DOMException && e.name === 'NotAllowedError'; + error = e instanceof Error ? e.message : String(e); + } + } + if (navigator.clipboard?.readText) { + try { + const text = await navigator.clipboard.readText(); + return { flavours: text ? [{ type: 'text/plain', text }] : [], denied: false }; + } catch (e) { + denied = denied || (e instanceof DOMException && e.name === 'NotAllowedError'); + error = error || (e instanceof Error ? e.message : String(e)); + } + } + return { flavours: [], denied, ...(error ? { error } : {}) }; +} + +const ESCAPES: Record = { '&': '&', '<': '<', '>': '>', '"': '"' }; +const esc = (s: string): string => s.replace(/[&<>"]/g, (c) => ESCAPES[c]); + +export function toBase64Text(text: string): string { + const bytes = new TextEncoder().encode(text); + let bin = ''; + for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + return btoa(bin); +} + +export function fromBase64Text(b64: string): string | null { + try { + const bin = atob(b64.replace(/\s+/g, '')); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); + return new TextDecoder().decode(bytes); + } catch { return null; } +} + +export function htmlFlavour(native: string, title: string, imageUrl?: string): string { + const img = imageUrl ? `${esc(title)}` : `${esc(title)}`; + return `
${img}
`; +} + +export function nativeFromHtml(html: string): string | null { + const m = new RegExp(`${HTML_SOURCE_ATTR}="([A-Za-z0-9+/=\\s]+)"`).exec(html); + return m ? fromBase64Text(m[1]) : null; +} + +export function imageFromHtml(html: string): string | null { + const m = /]*\bsrc="(data:image\/[a-z+]+;base64,[^"]+)"/i.exec(html); + return m ? m[1] : null; +} + +export async function dataUrlBlob(url: string): Promise { + try { return await (await fetch(url)).blob(); } catch { return null; } +} + +export function blobDataUrl(blob: Blob): Promise { + return new Promise((resolve, reject) => { + const r = new FileReader(); + r.onload = () => resolve(String(r.result)); + r.onerror = () => reject(r.error ?? new Error('could not read the picture')); + r.readAsDataURL(blob); + }); +} diff --git a/frontend/src/app/clipboard.ts b/frontend/src/app/clipboard.ts new file mode 100644 index 00000000..36765420 --- /dev/null +++ b/frontend/src/app/clipboard.ts @@ -0,0 +1,465 @@ +import { isEmpty, makeSelection } from '../canvas/selection'; +import { commitDraft, draftFor } from '../canvas/tools/common'; +import { deleteSelection } from '../canvas/tools/edit'; +import { imageBox, mediaUrl, naturalSize, placeImage, uploadMedia } from '../canvas/tools/image'; +import type { CanvasView } from '../canvas/view'; +import { commands, IS_MAC, type CommandDef } from '../commands/registry'; +import type { DocumentClient } from '../engine/client-api'; +import { isFragment, newId, pageSizeFor, resolveStyle, type FormChemDocument, type Id, type Page, type Point, type StyleOverride, type TextObject } from '../engine/model'; +import { session } from '../engine/session'; +import { t } from '../i18n'; +import { request } from '../io/api'; +import { copyText, anyDialogOpen } from '../ui/dialogs'; +import { flashHint } from '../ui/status'; +import { toast } from '../ui/toast'; +import { clipFragments, clipMeta, extractClip, fragmentsDoc, pastePlan, readClip, CLIP_MIME, type MediaMap, type PastePlan } from './clip-data'; +import { clipText, isReactionClip, looksLikeName, looksLikeSmarts, parseClipText, plainText, type TextFormat } from './clip-formats'; +import { clipPng, clipSvg, sourceOfPicture } from './clip-picture'; +import { + blobDataUrl, + dataUrlBlob, + flavoursOfTransfer, + htmlFlavour, + imageFromHtml, + nativeFromHtml, + readClipboard, + writeClipboard, + WEB_CLIP_MIME, + type Flavour, + type RichFlavours, +} from './clip-system'; + +export interface ClipboardDeps { + view: CanvasView; + homeOpen(): boolean; + createOptions(): { preset?: string; style?: StyleOverride }; +} + +export interface InsertOptions { + label: string; + keepStyle: boolean; + spot?: (doc: FormChemDocument, page: Page, clip: FormChemDocument) => Point; + alsoSelect?: PastePlan[]; +} + +export interface Inserted { client: DocumentClient; plan: PastePlan } + +export interface ClipboardApi { + copy(e?: ClipboardEvent): Promise; + cut(e?: ClipboardEvent): Promise; + paste(e?: ClipboardEvent): Promise; + insert(clip: FormChemDocument, opts: InsertOptions): Promise; + canCopy(): boolean; + canCut(): boolean; + canPaste(): boolean; +} + +export type Payload = + | { kind: 'drawing'; doc: FormChemDocument; keepStyle: boolean; notes: string[]; format: string } + | { kind: 'image'; blob: Blob } + | { kind: 'text'; text: string }; + +export interface Choice { id: string; label: string; detail: string; load: () => Promise } + +const NEED_DRAWING = 'Open or create a drawing first'; +const MEDIA_LIMIT = 16 * 1024 * 1024; +const CASCADE = 10; +const MENU_POINT_MS = 20000; + +const errText = (e: unknown): string => t(e instanceof Error ? e.message : String(e)); +const typing = (n: Element | null): boolean => + n instanceof HTMLInputElement || n instanceof HTMLTextAreaElement || n instanceof HTMLSelectElement || (n instanceof HTMLElement && n.isContentEditable); +const short = (s: string, n = 72): string => { const one = s.replace(/\s+/g, ' ').trim(); return one.length > n ? `${one.slice(0, n - 3)}...` : one; }; +const kb = (n: number): string => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1024))} KB`); +const IMAGE_MIME = /^image\/(png|jpeg|gif|webp|svg\+xml)$/; + +const FORMAT_NAMES: Record = { + formchem: 'FormChem drawing', smiles: 'SMILES', cxsmiles: 'CXSMILES', rsmiles: 'reaction SMILES', molfile: 'molfile', molfile3000: 'molfile V3000', + sdf: 'SD file', rxn: 'RXN', rdf: 'RD file', cml: 'CML', cdxml: 'CDXML', inchi: 'InChI', inchikey: 'InChIKey', smarts: 'SMARTS', picture: 'picture', +}; +const formatName = (f: string): string => t(FORMAT_NAMES[f] ?? f); + +export function describeDrawing(doc: FormChemDocument): string { + const frags = clipFragments(doc).length; + const total = Object.keys(doc.objects).length; + const parts: string[] = []; + if (frags) parts.push(`${frags} ${frags === 1 ? t('structure') : t('structures')}`); + if (isReactionClip(doc)) parts.push(t('a reaction')); + const other = total - frags; + if (other > 0) parts.push(`${other} ${other === 1 ? t('other object') : t('other objects')}`); + return parts.join(', '); +} + +export function choicesOf(flavours: Flavour[], opts: { bondLength?: number } = {}): Choice[] { + const out: Choice[] = []; + const text = (type: string): string => flavours.find((f) => f.type === type && f.text)?.text ?? ''; + const native = text(CLIP_MIME) || text(WEB_CLIP_MIME); + const html = text('text/html'); + const plain = text('text/plain'); + const fromHtml = html ? nativeFromHtml(html) : null; + const drawing = (doc: FormChemDocument | null, format = 'formchem'): Payload | null => (doc ? { kind: 'drawing', doc, keepStyle: true, notes: [], format } : null); + if (native) out.push({ id: 'native', label: t('FormChem drawing'), detail: '', load: async () => drawing(readClip(native)) }); + if (fromHtml) out.push({ id: 'html-native', label: t('FormChem drawing (from HTML)'), detail: '', load: async () => drawing(readClip(fromHtml)) }); + const htmlImage = html ? imageFromHtml(html) : null; + if (htmlImage && !fromHtml) out.push({ id: 'html-image-source', label: t('Picture with FormChem drawing'), detail: t('from HTML'), load: async () => { const b = await dataUrlBlob(htmlImage); return b ? drawing(await sourceOfPicture(b), 'picture') : null; } }); + const images = flavours.filter((f) => f.blob && IMAGE_MIME.test(f.blob.type || f.type)); + for (const f of images) { + out.push({ id: `source-${f.type}`, label: t('Picture with FormChem drawing'), detail: `${f.type}, ${kb(f.blob!.size)}`, load: async () => drawing(await sourceOfPicture(f.blob!), 'picture') }); + } + const svgText = text('image/svg+xml') || (/^\s*(<\?xml[^>]*>\s*)? drawing(await sourceOfPicture(svgText), 'picture') }); + if (plain && !svgText) { + const bondLength = opts.bondLength; + out.push({ id: 'chem-text', label: t('Structure from text'), detail: short(plain), load: async () => { + const r = await parseClipText(plain, { bondLength }); + return r ? { kind: 'drawing', doc: r.doc, keepStyle: r.format === 'formchem', notes: r.notes, format: r.format } : null; + } }); + if (looksLikeSmarts(plain)) { + out.push({ id: 'smarts-text', label: t('Query from SMARTS'), detail: short(plain), load: async () => { + const r = await parseClipText(plain, { bondLength, format: 'smarts' }); + return r ? { kind: 'drawing', doc: r.doc, keepStyle: false, notes: r.notes, format: 'smarts' } : null; + } }); + } + } + for (const f of images) out.push({ id: `image-${f.type}`, label: t('Picture'), detail: `${f.type}, ${kb(f.blob!.size)}`, load: async () => ({ kind: 'image', blob: f.blob! }) }); + if (!images.length && svgText) out.push({ id: 'image-svg-text', label: t('Picture'), detail: 'image/svg+xml', load: async () => ({ kind: 'image', blob: new Blob([svgText], { type: 'image/svg+xml' }) }) }); + if (htmlImage && !images.length) out.push({ id: 'html-image', label: t('Picture'), detail: t('from HTML'), load: async () => { const b = await dataUrlBlob(htmlImage); return b ? { kind: 'image', blob: b } : null; } }); + if (plain) out.push({ id: 'text', label: t('Text'), detail: short(plain), load: async () => ({ kind: 'text', text: plain }) }); + return out; +} + +function textDoc(text: string): FormChemDocument { + const o: TextObject = { id: newId('o'), kind: 'text', x: 0, y: 0, runs: [{ t: text.replace(/\r\n?/g, '\n') }] }; + return fragmentsDoc([], 'Text', { objects: [o] }); +} + +export function mountClipboard(deps: ClipboardDeps): ClipboardApi { + const { view } = deps; + let pointer: Point | null = null; + let menuAt: { p: Point; at: number } | null = null; + let cascade = { key: '', n: 0 }; + + view.root.addEventListener('pointermove', (e) => { if (view.client) pointer = view.toDoc(e.clientX, e.clientY); }); + view.root.addEventListener('pointerleave', () => { pointer = null; }); + view.root.addEventListener('contextmenu', (e) => { if (view.client) menuAt = { p: view.toDoc(e.clientX, e.clientY), at: performance.now() }; }); + + const open = (): boolean => !!view.client && !deps.homeOpen(); + + const snapshot = (): { client: DocumentClient; page: Page; clip: FormChemDocument } | null => { + const client = view.client; + const page = view.page(); + if (!client || !page || deps.homeOpen()) return null; + const clip = extractClip(client.doc, page, view.selection()); + return clip ? { client, page, clip } : null; + }; + + const quickText = (client: DocumentClient, clip: FormChemDocument): string => { + if (isReactionClip(clip)) return ''; + const frags = clipFragments(clip); + if (!frags.length) return plainText(clip); + const parts: string[] = []; + for (const f of frags) { + const live = client.doc.objects[f.id]; + const smiles = client.derived?.fragments[f.id]?.smiles; + if (!isFragment(live) || Object.keys(live.atoms).length !== Object.keys(f.atoms).length || !smiles) return ''; + parts.push(smiles); + } + return parts.join('.'); + }; + + const withMedia = async (client: DocumentClient, clip: FormChemDocument): Promise => { + const ids = Object.keys(clip.media ?? {}); + if (!ids.length) return clip; + const data: Record = {}; + let total = 0; + for (const id of ids) { + try { + const res = await request(`${mediaUrl(client.id)}/${encodeURIComponent(id)}`); + if (!res.ok) continue; + const blob = await res.blob(); + total += blob.size; + if (total > MEDIA_LIMIT) break; + data[id] = await blobDataUrl(blob); + } catch { continue; } + } + const meta = clipMeta(clip); + return meta ? { ...clip, meta: { ...clip.meta, clipboard: { ...meta, media: data } } } : clip; + }; + + const copyClip = async (snap: { client: DocumentClient; clip: FormChemDocument }, event?: ClipboardEvent): Promise => { + const { client, clip } = snap; + const native = JSON.stringify(clip); + const quick = quickText(client, clip); + const title = client.doc.title || t('Untitled'); + const derived = client.derived; + const hasChem = clipFragments(clip).length > 0; + const png = hasChem || Object.keys(clip.objects).length ? clipPng(clip, derived).catch(() => null) : Promise.resolve(null); + const rich: RichFlavours = { + [WEB_CLIP_MIME]: withMedia(client, clip).then((d) => JSON.stringify(d)), + 'image/png': png, + 'image/svg+xml': clipSvg(clip, derived).catch(() => null), + 'text/html': png.then((b) => (b ? blobDataUrl(b) : undefined)).then((url) => htmlFlavour(native, title, url)).catch(() => htmlFlavour(native, title)), + }; + if (hasChem) rich['text/plain'] = clipText(clip, 'smiles').then((r) => r.text || quick || null, () => quick || plainText(clip) || null); + else if (quick) rich['text/plain'] = Promise.resolve(quick); + const res = await writeClipboard({ text: quick || undefined, html: htmlFlavour(native, title), native }, rich, event); + if (!res.ok) toast(`${t('Could not copy to the clipboard')}${res.error ? `: ${res.error}` : ''}`, 'error'); + else flashHint(`${t('Copied')}: ${describeDrawing(clip)}`); + return res.ok; + }; + + const copy = async (event?: ClipboardEvent): Promise => { + const snap = snapshot(); + if (!snap) { if (view.client) toast(t('There is nothing on the page to copy.')); return false; } + return copyClip(snap, event); + }; + + const cut = async (event?: ClipboardEvent): Promise => { + if (!view.client || isEmpty(view.selection())) return false; + const snap = snapshot(); + if (!snap) return false; + const done = copyClip(snap, event); + const ctx = view.context; + const d = draftFor(ctx); + deleteSelection(d, view.selection()); + if (commitDraft(ctx, t('Cut'), d)) view.clearSelection(); + return done; + }; + + const target = async (): Promise => { + if (session.active) return session.active; + try { return await session.create(deps.createOptions()); } catch (e) { + toast(`${t('Could not create a drawing')}: ${errText(e)}`, 'error'); + return null; + } + }; + + const placement = (client: DocumentClient, page: Page): Point => { + if (menuAt && performance.now() - menuAt.at < MENU_POINT_MS) { const p = menuAt.p; menuAt = null; return p; } + if (pointer && view.client === client) return pointer; + const r = view.root.getBoundingClientRect(); + if (view.client === client && r.width && r.height) return view.toDoc(r.left + r.width / 2, r.top + r.height / 2); + const size = page.size === 'auto' ? pageSizeFor() : page.size; + return [size.w / 2, size.h / 2]; + }; + + const pageOf = (client: DocumentClient): Page | null => (view.client === client ? view.page() : null) ?? client.doc.pages[0] ?? null; + + const resolveMedia = async (clip: FormChemDocument, client: DocumentClient): Promise => { + const out: MediaMap = {}; + const meta = clipMeta(clip); + for (const [id, rec] of Object.entries(clip.media ?? {})) { + const there = client.doc.media?.[id]; + if (there && (meta?.from === client.id || (rec.sha256 && there.sha256 === rec.sha256))) { out[id] = { id, media: null }; continue; } + let blob: Blob | null = meta?.media?.[id] ? await dataUrlBlob(meta.media[id]) : null; + if (!blob && meta?.from) { + try { + const res = await request(`${mediaUrl(meta.from)}/${encodeURIComponent(id)}`); + if (res.ok) blob = await res.blob(); + } catch { blob = null; } + } + if (!blob) continue; + try { + const sent = await uploadMedia(client.id, new File([blob], rec.name || 'picture', { type: rec.mime || blob.type })); + out[id] = { id: sent.id, media: { ...sent.media, ...(rec.w && sent.media.w === undefined ? { w: rec.w, h: rec.h } : {}) } }; + } catch { continue; } + } + return out; + }; + + const insertDrawing = async (clip: FormChemDocument, keepStyle: boolean, label: string, opts: Partial = {}): Promise => { + const client = await target(); + if (!client) return null; + const page = pageOf(client); + if (!page) { toast(t('The drawing has no page to insert into.'), 'error'); return null; } + let at: Point; + if (opts.spot) at = opts.spot(client.doc, page, clip); + else { + at = placement(client, page); + const key = `${clip.id}|${client.id}|${at[0].toFixed(1)},${at[1].toFixed(1)}`; + cascade = cascade.key === key ? { key, n: cascade.n + 1 } : { key, n: 0 }; + if (cascade.n) at = [at[0] + CASCADE * cascade.n, at[1] + CASCADE * cascade.n]; + } + const media = clip.media && Object.keys(clip.media).length ? await resolveMedia(clip, client) : {}; + const plan = pastePlan(client.doc, page.id, clip, { at, keepStyle, media }); + if (!plan) { toast(t('There was nothing to paste.'), 'error'); return null; } + let errors: string[] = []; + const off = client.on((e) => { if (e.type === 'rejected') errors = e.errors; }); + const tx = client.commit(label, plan.ops); + off(); + if (!tx) { toast(`${opts.spot ? t('Could not insert') : t('Could not paste')}: ${errors[0] ?? ''}`, 'error'); return null; } + if (view.client === client) { + const all = [...(opts.alsoSelect ?? []), plan]; + view.setSelection(makeSelection(all.flatMap((p) => p.atoms), all.flatMap((p) => p.bonds), all.flatMap((p) => p.objects))); + view.focus(); + } + return { client, plan }; + }; + + const insertImage = async (blob: Blob): Promise => { + const client = await target(); + if (!client || view.client !== client) return false; + const page = pageOf(client); + if (!page) return false; + const ext = (blob.type.split('/')[1] ?? 'png').replace('svg+xml', 'svg').replace('jpeg', 'jpg'); + const file = blob instanceof File ? blob : new File([blob], `pasted.${ext}`, { type: blob.type || 'image/png' }); + const at = placement(client, page); + const box = imageBox([0, 0], await naturalSize(file), null); + const id = await placeImage(view.context, [at[0] - box.w / 2, at[1] - box.h / 2], null, file); + if (!id) return false; + view.setSelection(makeSelection([], [], [id])); + view.focus(); + return true; + }; + + const run = async (payload: Payload): Promise => { + if (payload.kind === 'image') return insertImage(payload.blob); + if (payload.kind === 'text') return !!(await insertDrawing(textDoc(payload.text), false, t('Paste Text'))); + const ok = !!(await insertDrawing(payload.doc, payload.keepStyle, t('Paste'))); + if (ok) { + const note = payload.notes[0]; + flashHint(`${t('Pasted')}: ${describeDrawing(payload.doc)}${payload.format !== 'formchem' ? ` (${formatName(payload.format)})` : ''}`); + if (note) toast(note); + } + return ok; + }; + + const bondLength = (): number | undefined => (session.active ? resolveStyle(session.active.doc).bond_length : undefined); + + const pasteFlavours = async (flavours: Flavour[]): Promise => { + const choices = choicesOf(flavours, { bondLength: bondLength() }); + if (!choices.length) { toast(t('The clipboard holds nothing FormChem can paste.'), 'error'); return false; } + for (const c of choices) { + let payload: Payload | null = null; + try { payload = await c.load(); } catch (e) { + if (c.id === 'chem-text') continue; + toast(`${t('Could not paste')}: ${errText(e)}`, 'error'); + return false; + } + if (!payload) continue; + if (payload.kind === 'text') { + const named = looksLikeName(payload.text); + toast(named ? t('No structure was found in the text, so it was pasted as text. Chemical names such as aspirin are not read yet; name to structure arrives in a later version.') : t('No structure was found in the text, so it was pasted as text.')); + } + return run(payload); + } + toast(t('The clipboard holds nothing FormChem can paste.'), 'error'); + return false; + }; + + const paste = async (event?: ClipboardEvent): Promise => { + if (deps.homeOpen()) return false; + let flavours: Flavour[]; + if (event) { + event.preventDefault(); + flavours = flavoursOfTransfer(event.clipboardData); + if (!flavours.length) flavours = (await readClipboard()).flavours; + } else { + const r = await readClipboard(); + if (!r.flavours.length) { + toast(r.denied ? t('FormChem may not read the clipboard here. Press Ctrl+V on the canvas, or allow clipboard access for this page.').replace('Ctrl+V', IS_MAC ? 'Cmd+V' : 'Ctrl+V') : t('The clipboard is empty.'), r.denied ? 'error' : 'info'); + return false; + } + flavours = r.flavours; + } + return pasteFlavours(flavours); + }; + + const copyAs = async (format: TextFormat | 'svg' | 'png'): Promise => { + const snap = snapshot(); + if (!snap) { toast(t('There is nothing on the page to copy.')); return; } + const { client, clip } = snap; + let res; + let notes: string[] = []; + if (format === 'png') { + const blob = clipPng(clip, client.derived); + const html = blob.then((b) => (b ? blobDataUrl(b) : null)).then((url) => (url ? `` : null)); + res = await writeClipboard({}, { 'image/png': blob, 'text/html': html }); + if (!res.ok && !(await blob)) { toast(t('Pictures arrive with the export module of this version; it is not available in this build.'), 'error'); return; } + } else if (format === 'svg') { + const svg = clipSvg(clip, client.derived); + res = await writeClipboard({}, { 'image/svg+xml': svg, 'text/plain': svg }); + if (!res.ok && !(await svg)) { toast(t('Pictures arrive with the export module of this version; it is not available in this build.'), 'error'); return; } + } else { + const out = clipText(clip, format); + res = await writeClipboard({}, { 'text/plain': out.then((r) => r.text || null) }); + try { + const done = await out; + notes = done.notes; + if (!done.text) { toast(t('The engine wrote no text for this format.'), 'error'); return; } + if (!res.ok) res = { ...res, ok: await copyText(done.text) }; + } catch (e) { + toast(`${t('Could not copy')}: ${errText(e)}`, 'error'); + return; + } + } + if (!res.ok) { toast(t('Could not copy to the clipboard'), 'error'); return; } + toast(`${t('Copied as')} ${formatName(format === 'svg' ? 'SVG' : format === 'png' ? 'PNG' : isReactionClip(clip) && format === 'smiles' ? 'rsmiles' : isReactionClip(clip) && format === 'molfile' ? 'rxn' : format)}${notes[0] ? ` (${notes[0]})` : ''}`); + }; + + const textSelected = (): boolean => { + const s = window.getSelection(); + if (!s || s.isCollapsed || !s.rangeCount) return false; + return !view.root.contains(s.getRangeAt(0).commonAncestorContainer); + }; + const ours = (e: Event): boolean => { + if (!open() || anyDialogOpen() || typing(document.activeElement)) return false; + return e.type.endsWith('paste') || !textSelected(); + }; + + document.addEventListener('beforecopy', (e) => { if (ours(e)) e.preventDefault(); }); + document.addEventListener('beforecut', (e) => { if (ours(e) && !isEmpty(view.selection())) e.preventDefault(); }); + document.addEventListener('beforepaste', (e) => { if (ours(e)) e.preventDefault(); }); + document.addEventListener('copy', (e) => { if (ours(e)) void copy(e); }); + document.addEventListener('cut', (e) => { if (ours(e)) void cut(e); }); + document.addEventListener('paste', (e) => { if (ours(e)) void paste(e); }); + window.addEventListener('keydown', (e) => { + if (e.defaultPrevented || e.altKey || e.shiftKey || !(IS_MAC ? e.metaKey : e.ctrlKey) || typing(document.activeElement)) return; + const k = e.key.toLowerCase(); + if (k === 'c' || k === 'x' || k === 'v') e.stopImmediatePropagation(); + }, { capture: true }); + + const as = (id: string, label: string, format: TextFormat | 'svg' | 'png', description: string): CommandDef => ({ + id, label: () => t(label), group: 'Edit', icon: 'copy', description, when: NEED_DRAWING, enabled: open, run: () => copyAs(format), + }); + const SCOPE = 'the selection, or the whole page when nothing is selected'; + commands.register( + as('copy-smiles', 'Copy as SMILES', 'smiles', `Copies ${SCOPE}, as canonical SMILES (reaction SMILES for a reaction).`), + as('copy-cxsmiles', 'Copy as CXSMILES', 'cxsmiles', `Copies ${SCOPE}, as CXSMILES with coordinates and enhanced stereo.`), + as('copy-molfile', 'Copy as Molfile', 'molfile', `Copies ${SCOPE}, as an MDL molfile (V3000 when V2000 cannot hold it; RXN for a reaction).`), + as('copy-inchi', 'Copy as InChI', 'inchi', `Copies the standard InChI of ${SCOPE}.`), + as('copy-inchikey', 'Copy as InChIKey', 'inchikey', `Copies the standard InChIKey of ${SCOPE}.`), + as('copy-svg', 'Copy as SVG', 'svg', `Copies ${SCOPE}, as an SVG picture with the editable drawing inside.`), + as('copy-png', 'Copy as PNG', 'png', `Copies ${SCOPE}, as a PNG picture with the editable drawing inside.`), + as('copy-cdxml', 'Copy as CDXML', 'cdxml', `Copies ${SCOPE}, as CDXML text.`), + { id: 'paste-special', label: () => t('Paste Special...'), group: 'Edit', keys: ['Shift+Mod+V'], icon: 'paste', mutates: true, description: 'Lists what the clipboard holds (FormChem drawing, picture with its drawing, structure text, SMARTS, picture, text) and pastes the one the person picks at the pointer or the middle of the view, selected, as one undo step.', enabled: () => !deps.homeOpen(), run: () => pasteSpecial() }, + ); + + const pasteSpecial = async (): Promise => { + const r = await readClipboard(); + if (!r.flavours.length) { + toast(r.denied ? t('FormChem may not read the clipboard here. Allow clipboard access for this page and try again.') : t('The clipboard is empty.'), r.denied ? 'error' : 'info'); + return; + } + const { askPasteSpecial } = await import('../ui/paste-special-dialog'); + const choice = await askPasteSpecial(choicesOf(r.flavours, { bondLength: bondLength() }), r.flavours.map((f) => f.type)); + if (!choice) return; + try { + const payload = await choice.load(); + if (!payload) { toast(`${choice.label}: ${t('nothing could be read from the clipboard in this form.')}`, 'error'); return; } + await run(payload); + } catch (e) { + toast(`${t('Could not paste')}: ${errText(e)}`, 'error'); + } + }; + + return { + copy, + cut, + paste, + insert: (clip, opts) => insertDrawing(clip, opts.keepStyle, opts.label, opts), + canCopy: open, + canCut: () => open() && !isEmpty(view.selection()), + canPaste: () => !deps.homeOpen(), + }; +} diff --git a/frontend/src/app/commands-shell.ts b/frontend/src/app/commands-shell.ts index e7e8477c..0211f7fc 100644 --- a/frontend/src/app/commands-shell.ts +++ b/frontend/src/app/commands-shell.ts @@ -36,14 +36,18 @@ export interface ShellCommandDeps { cut(): unknown; copy(): unknown; paste(): unknown; + canCopy?(): boolean; + canCut?(): boolean; + canPaste?(): boolean; selectAll(): unknown; - showGrid(): unknown; + showGrid(on?: boolean): unknown; helpGithub(): unknown; saveDocument(): unknown; saveAs(): unknown; saveCopy(): unknown; closeDocument(): unknown; insertSmiles(smiles?: string): unknown; + importFiles(path?: string): unknown; hasDocument(): boolean; canUndo?(): boolean; canRedo?(): boolean; @@ -119,7 +123,6 @@ const LATER: Record = { '0.3.0': 'Arrives in 0.3.0 with documents', '0.4.0': 'Arrives in 0.4.0 with the drawing canvas', '0.5.0': 'Arrives in 0.5.0 with reactions and annotations', - '0.7.0': 'Arrives in 0.7.0 with formats and exchange', '0.9.0': 'Arrives in 0.9.0 with names and spectra', '0.10.0': 'Arrives in 0.10.0 with 3D', '0.13.0': 'Arrives in 0.13.0 with the demos', @@ -149,29 +152,18 @@ export function registerShellCommands(deps: ShellCommandDeps): () => void { { id: 'save', label: () => t('Save'), group: 'File', keys: ['Mod+S'], icon: 'save', when: NO_DRAWING, enabled: () => deps.hasDocument(), run: () => deps.saveDocument() }, { 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: 'import', label: () => t('Import...'), group: 'File', icon: 'upload', mutates: true, description: 'Inserts the structures, reactions and objects of chemistry files (molfile, SD, RXN, RD, SMILES, CXSMILES, SMARTS, InChI, CML, CDXML, CDX), FormChem drawings, or PNG, SVG, PDF and EPS pictures that carry their FormChem drawing into the active drawing (a new one when none is open): in free space to the right of or below what is there, selected, one undo step per file, with the import report. An SD file brings at most 50 structures in a grid and the report says how many were left out. Without path it asks the person to pick one or more files.', params: { path: { type: 'string', description: 'Absolute path of a file on this computer to import; leave it out to ask the person', example: '/Users/me/Documents/ligands.sdf' } }, run: (params) => deps.importFiles(typeof params?.path === 'string' ? params.path : undefined) }, { 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() }, { id: 'undo', label: () => t('Undo'), group: 'Edit', keys: ['Mod+Z'], icon: 'undo', mutates: true, enabled: () => !!focusedField() || (deps.canUndo?.() ?? false), run: () => (fieldHistory('undo') ? undefined : deps.undo()) }, { id: 'redo', label: () => t('Redo'), group: 'Edit', keys: ['Shift+Mod+Z', 'Mod+Y'], icon: 'redo', mutates: true, enabled: () => !!focusedField() || (deps.canRedo?.() ?? false), run: () => (fieldHistory('redo') ? undefined : deps.redo()) }, - { id: 'cut', label: () => t('Cut'), group: 'Edit', icon: 'cut', when: 'A text field has focus', enabled: () => { const f = focusedField(); return !!f && hasSelection(f); }, run: fieldOr('cut', deps.cut) }, - { id: 'copy', label: () => t('Copy'), group: 'Edit', icon: 'copy', when: 'A text field has focus', enabled: () => { const f = focusedField(); return !!f && hasSelection(f); }, run: fieldOr('copy', deps.copy) }, - later('copy-smiles', 'Copy as SMILES', 'Edit', '0.7.0'), - later('copy-molfile', 'Copy as Molfile', 'Edit', '0.7.0'), - later('copy-inchi', 'Copy as InChI', 'Edit', '0.7.0'), - later('copy-svg', 'Copy as SVG', 'Edit', '0.7.0'), - { id: 'paste', label: () => t('Paste'), group: 'Edit', icon: 'paste', when: 'A text field has focus', enabled: () => !!focusedField(), run: fieldOr('paste', deps.paste) }, + { id: 'cut', label: () => t('Cut'), group: 'Edit', keys: ['Mod+X'], icon: 'cut', mutates: true, description: 'Cuts the selected text in a text field, or copies the selection on the canvas (in every clipboard flavour Copy writes) and deletes it as one undo step.', when: 'Select something on the canvas first', enabled: () => { const f = focusedField(); return f ? hasSelection(f) : deps.canCut?.() ?? false; }, run: fieldOr('cut', deps.cut) }, + { id: 'copy', label: () => t('Copy'), group: 'Edit', keys: ['Mod+C'], icon: 'copy', description: 'Copies the selected text in a text field, or the canvas selection (the whole page when nothing is selected) as FormChem data, SMILES or reaction SMILES text, a PNG and an SVG picture that carry the editable drawing, and HTML, as far as the platform allows.', when: NO_DRAWING, enabled: () => { const f = focusedField(); return f ? hasSelection(f) : deps.canCopy?.() ?? false; }, run: fieldOr('copy', deps.copy) }, + { id: 'paste', label: () => t('Paste'), group: 'Edit', keys: ['Mod+V'], icon: 'paste', mutates: true, description: 'Pastes into a text field, or onto the canvas: FormChem data, a PNG or SVG with an embedded drawing, SMILES, CXSMILES, SMARTS, reaction SMILES, molfile, SDF, RXN, InChI, CDXML or CML text, a picture, or else plain text as a text object; at the pointer or the middle of the view, selected, as one undo step.', enabled: () => !!focusedField() || (deps.canPaste?.() ?? false), run: fieldOr('paste', deps.paste) }, { id: 'select-all', label: () => t('Select All'), group: 'Edit', keys: ['Mod+A'], icon: 'selectAll', run: () => (fieldSelectAll() ? undefined : deps.selectAll()) }, - { id: 'show-grid', label: () => t('Show Grid'), group: 'View', icon: 'grid', checked: () => deps.gridOn?.() ?? true, run: () => deps.showGrid() }, + { id: 'show-grid', label: () => t('Show Grid'), group: 'View', icon: 'grid', description: 'Shows or hides the drawing grid on the page in this window. View > Grid > Grid Settings chooses its type, spacing, major lines and strength. On by default; the choice is remembered.', params: { on: { type: 'boolean', description: 'Show or hide the grid instead of toggling' } }, checked: () => deps.gridOn?.() ?? true, run: (p) => deps.showGrid(typeof p?.on === 'boolean' ? p.on : undefined) }, { id: 'toggle-analysis', label: () => t('Analysis Panel'), group: 'View', icon: 'panelProps', checked: () => deps.analysisOpen(), run: () => deps.toggleAnalysis() }, { id: 'show-stoichiometry', label: () => t('Stoichiometry Panel'), group: 'View', icon: 'table', checked: () => deps.stoichOpen(), run: () => deps.toggleStoich() }, { id: 'view-terminal', label: () => t('Terminal and Claude Code'), group: 'View', keys: ['Mod+`'], icon: 'terminal', checked: () => deps.terminalOpen?.() ?? false, run: () => deps.terminal() }, diff --git a/frontend/src/app/documents.ts b/frontend/src/app/documents.ts index c2334fe3..50764442 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,20 +27,24 @@ 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', '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'; -const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e)); +const errText = (e: unknown): string => t(e instanceof Error ? e.message : String(e)); const stem = (path: string): string => (path.split(/[\\/]/).pop() ?? path).replace(/\.fchem$/i, ''); const tauriCore = (): Promise => import('@tauri-apps/api/core'); -async function dialogOpen(): Promise { +export async function dialogOpenPaths(multiple: boolean, title?: string): Promise { const { invoke } = await tauriCore(); const found = await invoke('plugin:dialog|open', { - options: { multiple: false, directory: false, filters: [{ name: t('Drawings and structures'), extensions: OPEN_EXTENSIONS }] }, + options: { multiple, directory: false, ...(title ? { title } : {}), filters: [{ name: t('Drawings and structures'), extensions: OPEN_EXTENSIONS }] }, }); - return Array.isArray(found) ? found[0] ?? null : found; + return (Array.isArray(found) ? found : found ? [found] : []).filter((p): p is string => typeof p === 'string' && !!p); +} + +async function dialogOpen(): Promise { + return (await dialogOpenPaths(false))[0] ?? null; } async function dialogSave(defaultPath: string): Promise { @@ -78,7 +83,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 +98,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'); } @@ -189,7 +196,7 @@ export class DocumentActions { return refuse(`${t('Could not read the SMILES')}: ${errText(e)}`); } const frags = (answer.fragments ?? []).filter((f) => isFragment(f) && Object.keys(f.atoms).length > 0); - if (!frags.length) return refuse(`${t('Could not read the SMILES')}: ${answer.warnings?.find((w) => w?.text)?.text ?? t('it holds no structure')}`); + if (!frags.length) return refuse(`${t('Could not read the SMILES')}: ${t(answer.warnings?.find((w) => w?.text)?.text ?? 'it holds no structure')}`); let created = ''; const c = session.active ?? await session.create(this.createOpts()).catch((e: unknown) => { created = errText(e); return null; }); if (!c) return refuse(`${t('Could not create a drawing')}: ${created}`); diff --git a/frontend/src/app/embedded-source.ts b/frontend/src/app/embedded-source.ts new file mode 100644 index 00000000..46bcb6b5 --- /dev/null +++ b/frontend/src/app/embedded-source.ts @@ -0,0 +1,313 @@ +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); + 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; + 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(portable(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 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++; + 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)))); +} diff --git a/frontend/src/app/export-commands.ts b/frontend/src/app/export-commands.ts new file mode 100644 index 00000000..66eecb2a --- /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 => t(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/grid-commands.ts b/frontend/src/app/grid-commands.ts new file mode 100644 index 00000000..898b59b3 --- /dev/null +++ b/frontend/src/app/grid-commands.ts @@ -0,0 +1,159 @@ +import { + cleanSpec, docHasGrid, docSpec, formatLength, GRID_STRENGTHS, GRID_TYPES, GRID_UNITS, MAJOR_MAX, onGridChange, PT_PER, sameSpec, setSnap, + setWindowGrid, snapOn, SPACING_MAX, SPACING_MIN, windowGrid, withType, type FullGridSpec, +} from '../canvas/grid'; +import type { CanvasView } from '../canvas/view'; +import { commands, type CommandDef } from '../commands/registry'; +import type { GridType, Units } from '../engine/model'; +import { t } from '../i18n'; +import { gridSettingsDialog, type GridScope } from '../ui/grid-dialog'; +import { flashHint } from '../ui/status'; +import { toast } from '../ui/toast'; +import { commandStateChanged } from './commands-shell'; + +export const GRID_TYPE_LABELS: Readonly> = { + lines: 'Line Grid', + dots: 'Dot Grid', + crosses: 'Cross Grid', + isometric: 'Isometric Grid', + 'isometric-dots': 'Isometric Dot Grid', + hex: 'Hexagonal Grid', + 'hex-dots': 'Hexagonal Dot Grid', +}; + +const NEED_DRAWING = 'Open or create a drawing first'; + +export function currentGrid(view: CanvasView): FullGridSpec { + return view.client ? docSpec(view.doc, false) : windowGrid(); +} + +export function applyGrid(view: CanvasView, spec: FullGridSpec, scope: GridScope, label = t('Change Grid')): string { + const clean = cleanSpec(spec); + if (scope === 'default') { + setWindowGrid(clean); + return t('New drawings start with this grid.'); + } + const client = view.client; + if (!client) throw new Error('open or create a drawing first, or give scope "default"'); + const doc = client.doc; + if (docHasGrid(doc) && sameSpec(doc.style.grid, clean)) return t('Nothing changed.'); + const old = doc.style.grid; + client.commit(label, [{ op: 'set', path: ['style', 'grid'], value: clean, ...(old === undefined ? {} : { old }) }]); + return t('The drawing keeps this grid.'); +} + +function scopeOf(p?: Record): GridScope { + const s = p?.scope; + if (s === undefined || s === null || s === 'drawing') return 'drawing'; + if (s === 'default') return 'default'; + throw new Error('scope must be "drawing" or "default"'); +} + +function baseFor(view: CanvasView, scope: GridScope): FullGridSpec { + return scope === 'default' ? windowGrid() : currentGrid(view); +} + +export function parseSpacing(value: unknown, unit: unknown, fallback: Units): number | 'bond' { + if (value === 'bond') return 'bond'; + const n = typeof value === 'number' ? value : typeof value === 'string' ? Number.parseFloat(value) : NaN; + const u = unit === undefined || unit === null || unit === '' ? fallback : unit; + if (typeof u !== 'string' || !(GRID_UNITS as readonly string[]).includes(u)) throw new Error('unit must be pt, mm, cm or in'); + if (!Number.isFinite(n) || n <= 0) throw new Error('value must be a positive number, or "bond" for the bond length'); + const pt = n * PT_PER[u as Units]; + if (pt < SPACING_MIN - 1e-9 || pt > SPACING_MAX + 1e-9) throw new Error(`spacing must be from ${SPACING_MIN} to ${SPACING_MAX} pt (${formatLength(SPACING_MAX, u as Units)} ${u})`); + return pt; +} + +function typeParam(v: unknown): GridType { + if (typeof v === 'string' && (GRID_TYPES as readonly string[]).includes(v)) return v as GridType; + throw new Error(`type must be one of ${GRID_TYPES.join(', ')}`); +} + +function settingsRun(view: CanvasView, p?: Record): unknown { + const keys = ['type', 'spacing', 'unit', 'major', 'strength']; + if (!p || !keys.some((k) => p[k] !== undefined)) { + gridSettingsDialog(view, { + current: () => (p?.scope === 'default' ? windowGrid() : currentGrid(view)), + apply: (spec, scope) => { + try { flashHint(applyGrid(view, spec, scope)); } catch (e) { toast(e instanceof Error ? e.message : String(e), 'error'); } + view.focus(); + }, + }); + return null; + } + const scope = scopeOf(p); + if (scope === 'drawing' && !view.client) throw new Error('open or create a drawing first, or give scope "default"'); + let spec = baseFor(view, scope); + if (p.type !== undefined) spec = withType(spec, typeParam(p.type)); + if (p.spacing !== undefined) spec = { ...spec, spacing: parseSpacing(p.spacing, p.unit, view.client ? view.style().units : 'pt') }; + if (p.major !== undefined) { + const m = typeof p.major === 'number' ? p.major : Number.parseInt(String(p.major), 10); + if (!Number.isInteger(m) || m < 0 || m > MAJOR_MAX) throw new Error(`major must be a whole number from 0 to ${MAJOR_MAX}`); + spec = { ...spec, major: m }; + } + if (p.strength !== undefined) { + if (typeof p.strength !== 'string' || !(GRID_STRENGTHS as readonly string[]).includes(p.strength)) throw new Error('strength must be faint, normal or strong'); + spec = { ...spec, strength: p.strength as FullGridSpec['strength'] }; + } + return applyGrid(view, spec, scope); +} + +export function registerGridCommands(view: CanvasView, homeOpen: () => boolean): () => void { + const open = (): boolean => !!view.client && !homeOpen(); + const scopeParam = { type: 'string' as const, enum: ['drawing', 'default'], description: 'drawing (default): change the active drawing, one undo step; default: change the grid new drawings start with' }; + const typeCmd = (k: GridType): CommandDef => ({ + id: `grid-${k}`, label: () => t(GRID_TYPE_LABELS[k]), group: 'View', icon: 'grid', mutates: true, + description: `Shows the active drawing's grid as a ${GRID_TYPE_LABELS[k].toLowerCase()}, as one undo step. The drawing keeps its grid when saved.`, + when: NEED_DRAWING, enabled: open, checked: () => !!view.client && currentGrid(view).type === k, + run: () => applyGrid(view, withType(currentGrid(view), k), 'drawing'), + }); + const defs: CommandDef[] = [ + { + id: 'snap-to-grid', label: () => t('Snap to Grid'), group: 'View', icon: 'grid', + description: 'When on, new atoms, dragged atoms and objects, and handle drags land on the nearest grid point of the drawing\'s grid, in every grid type; bonds keep the bond length and angle snapping. Hold Alt (Option) while drawing or dragging to place freely. Off by default; the choice is remembered in this window.', + params: { on: { type: 'boolean', description: 'Turn snapping on or off instead of toggling' } }, + checked: snapOn, + run: (p) => ({ on: setSnap(typeof p?.on === 'boolean' ? p.on : !snapOn()) }), + }, + { + id: 'grid-type', label: () => t('Grid Type'), group: 'View', icon: 'grid', mutates: true, + description: 'Sets the grid type: lines, dots, crosses (small plus marks), isometric (triangular lines at 30, 90 and 150 degrees for 120 degree bond angles), isometric-dots, hex (hexagons at the bond length, so rings land on it) or hex-dots. Switching between the square types and the isometric or hex types also resets the spacing to that family\'s default (7.2 pt or the bond length). One undo step.', + params: { type: { type: 'string', required: true, enum: [...GRID_TYPES], description: 'The grid type', example: 'isometric' }, scope: scopeParam }, + when: NEED_DRAWING, enabled: open, + run: (p) => { const scope = scopeOf(p); return applyGrid(view, withType(baseFor(view, scope), typeParam(p?.type)), scope); }, + }, + { + id: 'grid-spacing', label: () => t('Grid Spacing'), group: 'View', icon: 'grid', mutates: true, + description: 'Sets the distance between neighbouring grid points. value is a number in unit (pt, mm, cm or in; default the drawing units), or "bond" to follow the drawing\'s bond length, which suits the isometric and hex grids. From 1 to 288 pt. One undo step.', + params: { + value: { type: 'string', required: true, description: 'A positive number, or bond', example: '5' }, + unit: { type: 'string', enum: [...GRID_UNITS], description: 'Unit of value; leave out for the drawing units' }, + scope: scopeParam, + }, + when: NEED_DRAWING, enabled: open, + run: (p) => { + const scope = scopeOf(p); + const spacing = parseSpacing(p?.value, p?.unit, view.client ? view.style().units : 'pt'); + return applyGrid(view, { ...baseFor(view, scope), spacing }, scope); + }, + }, + { + id: 'grid-settings', label: () => t('Grid Settings...'), group: 'View', icon: 'grid', mutates: true, + description: 'Without parameters, opens the Grid Settings dialog (type, spacing, major lines, strength, with a live preview). With any of type, spacing (a number in unit, or bond), unit, major (a stronger line every this many cells, 0 for none) and strength (faint, normal, strong), applies them at once to the drawing or, with scope default, to new drawings.', + params: { + type: { type: 'string', enum: [...GRID_TYPES], description: 'The grid type' }, + spacing: { type: 'string', description: 'A positive number in unit, or bond', example: '0.25' }, + unit: { type: 'string', enum: [...GRID_UNITS], description: 'Unit of spacing; leave out for the drawing units' }, + major: { type: 'integer', min: 0, max: MAJOR_MAX, description: 'A stronger line every this many cells; 0 for none' }, + strength: { type: 'string', enum: [...GRID_STRENGTHS], description: 'How strongly the grid shows' }, + scope: scopeParam, + }, + run: (p) => settingsRun(view, p), + }, + ...GRID_TYPES.map(typeCmd), + ]; + const off = commands.register(...defs); + const offChange = onGridChange(() => commandStateChanged()); + const offView = view.on('client', () => commandStateChanged()); + return () => { off(); offChange(); offView(); }; +} diff --git a/frontend/src/app/import-files.ts b/frontend/src/app/import-files.ts new file mode 100644 index 00000000..f4e66ac5 --- /dev/null +++ b/frontend/src/app/import-files.ts @@ -0,0 +1,144 @@ +import { objectBoxById } from '../canvas/render/bounds'; +import type { DocumentClient } from '../engine/client-api'; +import { resolveStyle, type FormChemDocument, type Page, type Point } from '../engine/model'; +import { session } from '../engine/session'; +import { t } from '../i18n'; +import { post, upload } from '../io/api'; +import { inTauri } from '../ui/dom'; +import { chooseStructureFiles } from '../ui/home'; +import { showImportReport } from '../ui/import-report'; +import { flashHint } from '../ui/status'; +import { toast } from '../ui/toast'; +import { clipBounds, clipPage, readClip, CLIP_KIND, type Bounds, type PastePlan } from './clip-data'; +import { describeDrawing, type ClipboardApi } from './clipboard'; +import { dialogOpenPaths } from './documents'; + +export const IMPORT_LIMIT = 50; +const IMPORT_URL = '/api/documents/import'; +const GAP_BONDS = 2; + +interface ImportAnswer { + name: string; + format: string; + document: unknown; + media?: Record; + keep_style?: boolean; + structures?: number; + report?: unknown[]; + warnings?: string[]; +} + +type Source = { name: string; path: string } | { name: string; file: File }; + +export interface ImportDeps { + clip: ClipboardApi; + reveal(client: DocumentClient, box: Bounds): void; + leaveHome(): void; +} + +const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e)); +const baseName = (path: string): string => path.split(/[\\/]/).pop() || path; + +function union(boxes: (Bounds | null)[]): Bounds | null { + const found = boxes.filter((b): b is Bounds => !!b); + if (!found.length) return null; + const x0 = Math.min(...found.map((b) => b.x)), y0 = Math.min(...found.map((b) => b.y)); + const x1 = Math.max(...found.map((b) => b.x + b.w)), y1 = Math.max(...found.map((b) => b.y + b.h)); + return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }; +} + +export function freeSpot(doc: FormChemDocument, page: Page, clip: FormChemDocument): Point { + const src = clipPage(clip); + const box = (src ? clipBounds(clip, src) : null) ?? { x: 0, y: 0, w: 0, h: 0 }; + const margin = page.margins ?? 36; + const step = resolveStyle(doc).bond_length; + const gap = GAP_BONDS * step; + const at = (x: number, y: number): Point => [x + box.w / 2, y + box.h / 2]; + const there = clipBounds(doc, page); + if (!there) return at(margin, margin); + const right = there.x + there.w + gap, below = there.y + there.h + gap; + if (page.size === 'auto') return at(right, there.y); + const maxX = page.size.w - margin, maxY = page.size.h - margin; + const taken = page.order.map((id) => objectBoxById(doc, id)).filter((b): b is Bounds => !!b); + const free = (x: number, y: number): boolean => x >= margin - 1e-6 && y >= margin - 1e-6 && x + box.w <= maxX && y + box.h <= maxY + && !taken.some((b) => x < b.x + b.w + gap && b.x < x + box.w + gap && y < b.y + b.h + gap && b.y < y + box.h + gap); + const left = Math.max(margin, Math.min(there.x, maxX - box.w)); + if (free(right, there.y)) return at(right, there.y); + if (free(left, below)) return at(left, below); + for (let y = margin; y + box.h <= maxY; y += step) for (let x = margin; x + box.w <= maxX; x += step) if (free(x, y)) return at(x, y); + return at(left, below); +} + +export function mountImport(deps: ImportDeps): { run(path?: string): Promise } { + const choose = async (): Promise => { + if (inTauri()) { + const paths = await dialogOpenPaths(true, t('Import into the Drawing')).catch((e: unknown) => { + toast(`${t('Could not import')}: ${errText(e)}`, 'error'); + return [] as string[]; + }); + return paths.map((path) => ({ name: baseName(path), path })); + } + return (await chooseStructureFiles(true)).map((file) => ({ name: file.name, file })); + }; + + const read = (src: Source, bondLength: number | undefined): Promise => { + const opts = { limit: IMPORT_LIMIT, ...(bondLength ? { bond_length: bondLength } : {}) }; + if ('path' in src) return post(IMPORT_URL, { path: src.path, ...opts }); + const query = new URLSearchParams(Object.entries(opts).map(([k, v]) => [k, String(v)])); + return upload(`${IMPORT_URL}?${query}`, [src.file], 'file'); + }; + + const run = async (given?: string): Promise => { + const fromAgent = typeof given === 'string'; + if (fromAgent && !/^(\/|[A-Za-z]:[\\/]|~[\\/])/.test(given.trim())) { + const text = t('Give the absolute path of the file to import.'); + toast(text, 'error'); + throw new Error(text); + } + const sources = fromAgent ? [{ name: baseName(given.trim()), path: given.trim() }] : await choose(); + if (!sources.length) return undefined; + deps.leaveHome(); + const plans: PastePlan[] = []; + const done: string[] = []; + const failed: string[] = []; + let client: DocumentClient | null = null; + for (const src of sources) { + const target: DocumentClient | null = session.active; + let answer: ImportAnswer; + try { + answer = await read(src, target ? resolveStyle(target.doc).bond_length : undefined); + } catch (e) { + failed.push(`${src.name}: ${errText(e)}`); + toast(`${t('Could not import')} ${src.name}: ${errText(e)}`, 'error'); + continue; + } + const doc = readClip(JSON.stringify(answer.document ?? null)); + const page = doc ? clipPage(doc) : null; + if (!doc || !page) { + failed.push(`${src.name}: ${t('it holds nothing FormChem can draw')}`); + toast(`${t('Could not import')} ${src.name}: ${t('it holds nothing FormChem can draw')}`, 'error'); + continue; + } + if (answer.media && Object.keys(answer.media).length) doc.meta = { ...doc.meta, clipboard: { kind: CLIP_KIND, from: '', page: page.id, media: answer.media } }; + const got = await deps.clip.insert(doc, { label: `${t('Import')} ${answer.name || src.name}`, keepStyle: !!answer.keep_style, spot: freeSpot, alsoSelect: client === session.active ? plans : [] }); + if (!got) { failed.push(`${src.name}: ${t('the drawing did not accept it')}`); continue; } + if (client !== got.client) plans.length = 0; + client = got.client; + plans.push(got.plan); + const what = describeDrawing(doc); + done.push(`${answer.name || src.name} (${what}${answer.format ? `, ${answer.format}` : ''})`); + showImportReport(answer.name || src.name, answer.format, answer.report, true); + flashHint(`${t('Imported')}: ${what}`); + } + if (client && plans.length) { + const box = clipBounds(client.doc, { id: '', size: 'auto', order: plans.flatMap((p) => p.top) }); + if (box) deps.reveal(client, box); + } + if (fromAgent && !done.length) throw new Error(failed[0] ?? t('Nothing was imported.')); + if (!done.length) return undefined; + const into = client ? `"${client.doc.title || 'Untitled'}" (${client.id})` : 'the drawing'; + return `Imported ${done.join('; ')} into ${into}, one undo step per file${failed.length ? `; failed: ${failed.join('; ')}` : ''}`; + }; + + return { run }; +} diff --git a/frontend/src/app/menus.ts b/frontend/src/app/menus.ts index 966e03aa..d3dff388 100644 --- a/frontend/src/app/menus.ts +++ b/frontend/src/app/menus.ts @@ -6,10 +6,11 @@ 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 COPY_AS: MenuItem = { label: 'Copy As', items: ['copy-smiles', 'copy-molfile', 'copy-inchi', 'copy-svg'] }; +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-cxsmiles', 'copy-molfile', 'copy-inchi', 'copy-inchikey', 'copy-smarts', '-', 'copy-svg', 'copy-png', '-', 'copy-cdxml'] }; 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'] }; +const GRID: MenuItem = { label: 'Grid', items: ['show-grid', 'snap-to-grid', '-', 'grid-lines', 'grid-dots', 'grid-crosses', 'grid-isometric', 'grid-isometric-dots', 'grid-hex', 'grid-hex-dots', '-', 'grid-settings'] }; const ALIGN: MenuItem ={ label: 'Align', items: ['align-left', 'align-center', 'align-right', '-', 'align-top', 'align-middle', 'align-bottom'] }; export function buildMenus(extensionItems?: MenuSource, recentItems?: MenuSource): MenuDef[] { @@ -19,15 +20,15 @@ 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: 'Edit', items: ['undo', 'redo', '-', 'cut', 'copy', COPY_AS, 'paste', 'paste-special', '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', '-', 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: 'Structure', items: ['clean-structure', 'layout-structure', '-', ...CHEM_MENU_ITEMS.structure, '-', 'check-structure', 'standardise', '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'] }, + { label: 'Window', items: ['next-window', '-', 'agents', 'agent-activity'] }, { label: 'Extensions', items: () => { const own = extensionItems?.(); return own?.length ? own : EXTENSIONS_FALLBACK; } }, { label: 'Help', items: ['help', 'whats-new', 'shortcuts', 'demos', '-', 'help-github', 'report-issue', '-', 'check-for-updates', 'system-info', 'about'] }, ]; 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); + } +} 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/app/reaction-commands.ts b/frontend/src/app/reaction-commands.ts index bfcf1d8f..dc5e83ac 100644 --- a/frontend/src/app/reaction-commands.ts +++ b/frontend/src/app/reaction-commands.ts @@ -23,7 +23,7 @@ const NEED_DRAWING = 'Open or create a drawing first'; const NEED_REACTION = 'Draw a reaction arrow with reactants and products first'; const EXT: Record = { rxn: 'rxn', rxnv3000: 'rxn', smiles: 'smi' }; -const errText = (e: unknown): string => (e instanceof Error ? e.message : String(e)); +const errText = (e: unknown): string => t(e instanceof Error ? e.message : String(e)); const fail = (what: string) => (e: unknown): void => { toast(`${t(what)}: ${errText(e)}`, 'error'); }; function scopeIds(view: CanvasView): Id[] | null { 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; +} diff --git a/frontend/src/app/standardise-command.ts b/frontend/src/app/standardise-command.ts new file mode 100644 index 00000000..8ba0e2f0 --- /dev/null +++ b/frontend/src/app/standardise-command.ts @@ -0,0 +1,110 @@ +import { fragmentsTouched, isEmpty } from '../canvas/selection'; +import { commands } from '../commands/registry'; +import type { FormChemDocument, Id } from '../engine/model'; +import { STANDARDISE_STEPS, standardiseApi, type StandardiseResult } from '../engine/standardise-api'; +import { language, t } from '../i18n'; +import { askStandardise } from '../ui/standardise-dialog'; +import { toast } from '../ui/toast'; +import type { ChemHost } from './chem-commands'; + +export interface StandardiseDeps { host: ChemHost; homeOpen(): boolean } + +const errText = (e: unknown): string => t(e instanceof Error ? e.message : String(e)); + +function fragmentsIn(doc: FormChemDocument, ids: Iterable, out: Id[] = [], seen = new Set()): Id[] { + for (const id of ids) { + if (seen.has(id)) continue; + seen.add(id); + const o = doc.objects[id]; + if (o?.kind === 'fragment' && Object.keys(o.atoms).length) out.push(id); + else if (o?.kind === 'group') fragmentsIn(doc, o.children, out, seen); + } + return out; +} + +function targets(host: ChemHost): { ids: Id[]; page: boolean } { + const doc = host.client?.doc; + if (!doc) return { ids: [], page: true }; + const sel = host.selection(); + if (!isEmpty(sel)) { + const ids = fragmentsIn(doc, [...fragmentsTouched(sel), ...sel.objects]); + if (ids.length) return { ids, page: false }; + } + return { ids: fragmentsIn(doc, host.page()?.order ?? []), page: true }; +} + +function stepsOf(v: unknown): string[] | null { + const list = Array.isArray(v) ? v : typeof v === 'string' ? v.split(/[\s,]+/) : null; + const out = list?.filter((s): s is string => typeof s === 'string' && s.trim() !== '').map((s) => s.trim()) ?? []; + return out.length ? out : null; +} + +function summary(res: StandardiseResult): string { + const changed = res.steps.filter((s) => s.changed).map((s) => (language() === 'en' ? s.label.toLowerCase() : t(s.label))); + return `${t('Standardised')}: ${changed.join(', ')}`; +} + +let busy = false; + +async function apply(host: ChemHost, steps: string[] | null, ids: Id[]): Promise { + const client = host.client; + if (!client || !ids.length || busy) return false; + busy = true; + const asked = new Map(ids.map((id) => [id, client.doc.objects[id]])); + let res: StandardiseResult; + try { + res = await standardiseApi.run(client.id, ids, steps); + } catch (e) { + toast(`${t('Standardise')}: ${errText(e)}`, 'error'); + return false; + } finally { + busy = false; + } + if (host.client !== client || [...asked].some(([id, o]) => client.doc.objects[id] !== o)) { + toast(t('The drawing changed while the engine worked; try again.'), 'error'); + return false; + } + if (!res.tx?.ops.length) { + toast(t('Already standard: nothing to change.')); + return true; + } + if (!client.commit(t('Standardise'), res.tx.ops)) return false; + toast(summary(res)); + return true; +} + +export async function standardiseWithDialog(host: ChemHost): Promise { + const client = host.client; + const { ids, page } = targets(host); + if (!client || !ids.length) { toast(t('Draw or select a structure to standardise.')); return; } + let steps: string[] | null; + try { + steps = await askStandardise({ page, count: ids.length, preview: (chosen, signal) => standardiseApi.run(client.id, ids, chosen, signal) }); + } catch (e) { + toast(`${t('Standardise')}: ${errText(e)}`, 'error'); + return; + } + if (steps) await apply(host, steps, ids); + host.focus(); +} + +export function registerStandardiseCommand(deps: StandardiseDeps): () => void { + const { host } = deps; + const open = (): boolean => !!host.client && !deps.homeOpen(); + return commands.register({ + id: 'standardise', + label: () => t('Standardise...'), + group: 'Structure', + icon: 'magic', + mutates: true, + description: 'Standardises the selected structures (or every structure on the page) together as one undo step: clean-up, functional group normalisation, salt and solvent removal, neutralisation and the other chosen steps. Without steps a dialog shows each step and the SMILES before and after.', + params: { steps: { type: 'array', description: `Steps to run, from ${STANDARDISE_STEPS.join(', ')}, or default for the default set; they always run in that order. Leave out to open the dialog.`, example: '["salts", "neutralise"]' } }, + when: 'Open or create a drawing first', + enabled: open, + run: (p) => { + const steps = stepsOf(p?.steps); + if (!steps) return standardiseWithDialog(host); + return apply(host, steps, targets(host).ids); + }, + }); +} diff --git a/frontend/src/app/window-tools.ts b/frontend/src/app/window-tools.ts index 1ca63ea4..f9f6637b 100644 --- a/frontend/src/app/window-tools.ts +++ b/frontend/src/app/window-tools.ts @@ -4,6 +4,14 @@ import type { LiveClient, LiveMessage } from '../io/live'; const ANSWERED_ELSEWHERE = new Set(['consent']); +export type WindowToolFn = (args: Record) => Promise; +const ADDED = new Map(); + +export function addWindowTool(name: string, fn: WindowToolFn): () => void { + ADDED.set(name, fn); + return () => { if (ADDED.get(name) === fn) ADDED.delete(name); }; +} + const ok = (text: string, data?: Record): ToolResult => ({ content: [{ type: 'text', text }], ...(data ? { structuredContent: data } : {}) }); const fail = (text: string): ToolResult => ({ content: [{ type: 'text', text }], isError: true }); const plain = (v: unknown): boolean => v === null || ['string', 'number', 'boolean'].includes(typeof v); @@ -29,6 +37,8 @@ async function runCommand(registry: CommandRegistry, args: Record): Promise { if (name === 'run_command') return runCommand(registry, args); + const added = ADDED.get(name); + if (added) return added(args); if ((AGENT_TOOLS as readonly string[]).includes(name)) { const host = extensions(); return host ? host.agent(name, args) : fail('The FormChem window has not loaded its extensions yet. Retry in a moment.'); diff --git a/frontend/src/canvas/agent-marks.ts b/frontend/src/canvas/agent-marks.ts new file mode 100644 index 00000000..4556e167 --- /dev/null +++ b/frontend/src/canvas/agent-marks.ts @@ -0,0 +1,71 @@ +import type { Id } from '../engine/model'; +import { objectBounds, type Box } from './hit'; +import { fmt, inflate } from './render/geom'; +import { Keyed, svgEl } from './render/svg'; +import type { CanvasView } from './view'; + +const PAD_PT = 3; +export const FLASH_MS = 2200; +const FADE_MS = 400; + +interface Lit { until: number; key: string } + +export class AgentMarks { + private readonly keyed: Keyed; + private readonly lit = new Map(); + private timer = 0; + + constructor(private readonly view: CanvasView) { + this.keyed = new Keyed(view.docLayer('fc-agent-marks'), (id) => svgEl('g', { 'data-agent-mark': id })); + } + + boxOf(id: Id): Box | null { + if (!this.view.client) return null; + const r = this.view.renderer as typeof this.view.renderer & { objectBox?: (id: Id) => Box | null }; + return objectBounds(this.view.doc, id, r.objectBox ? (x) => r.objectBox!(x) : undefined); + } + + flash(ids: readonly Id[], ms = FLASH_MS): void { + const now = performance.now(); + for (const id of ids) { + const box = this.boxOf(id); + if (!box) continue; + const b = inflate(box, PAD_PT); + const key = `${fmt(b.x)},${fmt(b.y)},${fmt(b.w)},${fmt(b.h)}`; + const g = this.keyed.get(id); + g.classList.remove('is-fading'); + this.keyed.patch(id, [{ tag: 'rect', a: { x: fmt(b.x), y: fmt(b.y), width: fmt(b.w), height: fmt(b.h), rx: fmt(PAD_PT), class: 'fc-agent-mark' } }], key); + this.lit.set(id, { until: now + ms, key }); + } + this.schedule(); + } + + clear(): void { + window.clearTimeout(this.timer); + this.timer = 0; + this.lit.clear(); + this.keyed.clear(); + } + + private schedule(): void { + if (this.timer || !this.lit.size) return; + const next = Math.min(...[...this.lit.values()].map((l) => l.until)); + this.timer = window.setTimeout(() => { this.timer = 0; this.sweep(); }, Math.max(16, next - performance.now())); + } + + private sweep(): void { + const now = performance.now(); + for (const [id, l] of [...this.lit]) { + if (l.until > now) continue; + const g = this.keyed.nodes.get(id)?.node; + if (g && !g.classList.contains('is-fading') && !matchMedia('(prefers-reduced-motion: reduce)').matches) { + g.classList.add('is-fading'); + this.lit.set(id, { until: now + FADE_MS, key: l.key }); + continue; + } + this.lit.delete(id); + this.keyed.drop(id); + } + this.schedule(); + } +} diff --git a/frontend/src/canvas/context.ts b/frontend/src/canvas/context.ts index 373fde75..ed595551 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[] { @@ -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', 'snap-to-grid', 'grid-settings', 'dark-page']; } export function canvasMenuItems(host: CanvasMenuHost, hit: Hit): { items: MenuItem[]; temp: Temp[] } { 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()); + }); +} diff --git a/frontend/src/canvas/geom.ts b/frontend/src/canvas/geom.ts index 914f9c34..805b2078 100644 --- a/frontend/src/canvas/geom.ts +++ b/frontend/src/canvas/geom.ts @@ -120,10 +120,10 @@ export function bestDirection(at: Point, s: Surroundings): number { export const ringRadius = (n: number, edge: number): number => edge / (2 * Math.sin(Math.PI / n)); export const ringApothem = (n: number, edge: number): number => edge / (2 * Math.tan(Math.PI / n)); -export function ringAtPoint(n: number, centre: Point, edge: number): Point[] { +export function ringAtPoint(n: number, centre: Point, edge: number, turn = 0): Point[] { const r = ringRadius(n, edge); const step = 360 / n; - const start = 270 - step / 2; + const start = 270 - step / 2 + turn; const out: Point[] = []; for (let k = 0; k < n; k++) out.push(polar(centre, start + k * step, r)); return out; diff --git a/frontend/src/canvas/grid-layer.ts b/frontend/src/canvas/grid-layer.ts new file mode 100644 index 00000000..d7abb342 --- /dev/null +++ b/frontend/src/canvas/grid-layer.ts @@ -0,0 +1,228 @@ +import { setAttr } from '../ui/dom'; +import type { Grid, GridMarks } from './grid'; + +const SVG_NS = 'http://www.w3.org/2000/svg'; +const SQ3 = Math.sqrt(3); + +export const GRID_MIN_PX = 4; +const FULL_MAX = 12000; +const DOT_R = 1; +const DOT_R_MAX = 1.5; +const DOT_GROW = 0.04; +const DOT_R_MAJOR = 1.6; +const ARM = 3; +const ARM_MAJOR = 5; + +let seq = 0; + +const f = (n: number): string => String(Math.round(n * 1e3) / 1e3); +const mod = (a: number, n: number): number => ((a % n) + n) % n; + +export interface GridPlan { full: boolean; w: number; h: number; x: number; y: number; minor: string; major: string; marks: GridMarks; crisp: boolean } + +class Paths { + minor = ''; + major = ''; + constructor(private readonly n: number, private readonly showMinor: boolean) {} + major_(k: number): boolean { return this.n > 1 && mod(k, this.n) === 0; } + add(major: boolean, d: string): void { + if (major) this.major += d; + else if (this.showMinor) this.minor += d; + } +} + +const seg = (x1: number, y1: number, x2: number, y2: number): string => `M${f(x1)} ${f(y1)}L${f(x2)} ${f(y2)}`; +const dot = (x: number, y: number, r: number): string => `M${f(x - r)} ${f(y)}a${f(r)} ${f(r)} 0 1 0 ${f(2 * r)} 0a${f(r)} ${f(r)} 0 1 0 ${f(-2 * r)} 0`; +const plus = (x: number, y: number, a: number): string => `M${f(x - a)} ${f(y)}h${f(2 * a)}M${f(x)} ${f(y - a)}v${f(2 * a)}`; + +function mark(p: Paths, marks: GridMarks, major: boolean, x: number, y: number, c: number): void { + if (marks === 'crosses') p.add(major, plus(x, y, Math.min(major ? ARM_MAJOR : ARM, c * (major ? 0.45 : 0.3)))); + else { + const r = Math.min(DOT_R_MAX, Math.max(DOT_R, c * DOT_GROW)); + p.add(major, dot(x, y, Math.min((major ? DOT_R_MAJOR : 1) * r, c * 0.25))); + } +} + +function range(lo: number, hi: number, fn: (k: number) => void): void { + for (let k = Math.ceil(lo); k <= Math.floor(hi); k++) fn(k); +} + +function squareFull(p: Paths, c: number, ox: number, oy: number, pw: number, ph: number): void { + range(-ox / c, (pw - ox) / c, (k) => p.add(p.major_(k), `M${f(ox + k * c)} 0V${f(ph)}`)); + range(-oy / c, (ph - oy) / c, (k) => p.add(p.major_(k), `M0 ${f(oy + k * c)}H${f(pw)}`)); +} + +function triFull(p: Paths, c: number, ox: number, oy: number, pw: number, ph: number): void { + const w = (c * SQ3) / 2, rise = (x: number): number => ((x - ox) / w) * (c / 2); + range(-ox / w, (pw - ox) / w, (a) => p.add(p.major_(a), `M${f(ox + a * w)} 0V${f(ph)}`)); + const family = (yl: number, yr: number): void => { + range((0 - Math.max(yl, yr)) / c, (ph - Math.min(yl, yr)) / c, (k) => p.add(p.major_(k), seg(0, yl + k * c, pw, yr + k * c))); + }; + family(oy + rise(0), oy + rise(pw)); + family(oy - rise(0), oy - rise(pw)); +} + +const vertex = (a: number, b: number): boolean => mod(a - b, 3) !== 2; +const HEX_STEPS: ReadonlyArray<[number, number]> = [[1, 0], [0, 1], [-1, 1]]; + +function hexFull(p: Paths, c: number, ox: number, oy: number, pw: number, ph: number): void { + const w = (c * SQ3) / 2; + const at = (a: number, b: number): [number, number] => [ox + a * w, oy + (a * c) / 2 + b * c]; + range(-ox / w - 1, (pw - ox) / w + 1, (a) => { + range((0 - oy - (a * c) / 2) / c - 1, (ph - oy - (a * c) / 2) / c + 1, (b) => { + if (!vertex(a, b)) return; + for (const [da, db] of HEX_STEPS) { + if (!vertex(a + da, b + db)) continue; + const [x1, y1] = at(a, b), [x2, y2] = at(a + da, b + db); + p.add(false, seg(x1, y1, x2, y2)); + } + }); + }); +} + +function squareTile(p: Paths, marks: GridMarks, c: number, n: number): { w: number; h: number; sx: number; sy: number } { + const h = c / 2; + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) mark(p, marks, n > 1 && i === 0 && j === 0, h + i * c, h + j * c, c); + } + return { w: n * c, h: n * c, sx: h, sy: h }; +} + +function triTile(p: Paths, marks: GridMarks, c: number, n: number): { w: number; h: number; sx: number; sy: number } { + const w = (c * SQ3) / 2; + for (let a = 0; a < 2 * n; a++) { + for (let j = 0; j < n; j++) mark(p, marks, p.major_(a) && p.major_(j - Math.floor(a / 2)), a * w + w / 2, (a % 2) * (c / 2) + j * c + c / 4, c); + } + return { w: 2 * n * w, h: n * c, sx: w / 2, sy: c / 4 }; +} + +function hexTile(p: Paths, marks: GridMarks, c: number): { w: number; h: number; sx: number; sy: number } { + const w = (c * SQ3) / 2; + const at = (a: number, b: number): [number, number] => [a * w + w / 2, (a * c) / 2 + b * c + c / 4]; + if (marks === 'lines') { + for (let a = -1; a <= 3; a++) { + for (let b = -3; b <= 4; b++) { + if (!vertex(a, b)) continue; + for (const [da, db] of HEX_STEPS) { + if (!vertex(a + da, b + db)) continue; + const [x1, y1] = at(a, b), [x2, y2] = at(a + da, b + db); + p.add(false, seg(x1, y1, x2, y2)); + } + } + } + } else { + for (let a = 0; a < 2; a++) for (let b = 0; b < 3; b++) if (vertex(a, b)) mark(p, marks, false, ...at(a, b), c); + } + return { w: 2 * w, h: 3 * c, sx: w / 2, sy: c / 4 }; +} + +function triLinesTile(p: Paths, c: number, n: number): { w: number; h: number; sx: number; sy: number } { + const w = (c * SQ3) / 2; + const tw = 2 * n * w, th = n * c; + const at = (a: number, b: number): [number, number] => [a * w + w / 2, (a * c) / 2 + b * c + c / 4]; + for (let a = 0; a < 2 * n; a++) p.add(p.major_(a), `M${f(a * w + w / 2)} 0V${f(th)}`); + for (let b = -n - 2; b <= n + 1; b++) p.add(p.major_(b), seg(...at(-1, b), ...at(2 * n + 1, b))); + for (let m = -1; m <= 2 * n + 2; m++) p.add(p.major_(m), seg(...at(-1, m + 1), ...at(2 * n + 1, m - 2 * n - 1))); + return { w: tw, h: th, sx: w / 2, sy: c / 4 }; +} + +function squareLinesTile(p: Paths, c: number, n: number): { w: number; h: number; sx: number; sy: number } { + const h = c / 2, size = n * c; + for (let i = 0; i < n; i++) p.add(p.major_(i), `M${f(h + i * c)} 0V${f(size)}M0 ${f(h + i * c)}H${f(size)}`); + return { w: size, h: size, sx: h, sy: h }; +} + +function fullCount(g: Grid, c: number, pw: number, ph: number): number { + const w = (c * SQ3) / 2; + if (g.lattice === 'square') return pw / c + ph / c; + if (g.lattice === 'tri') return pw / w + 2 * (ph / c + pw / (2 * w)); + return (pw / w + 3) * (ph / c + 3); +} + +export function planGrid(g: Grid, zoom: number, ox = 0, oy = 0, pw = 0, ph = 0): GridPlan | null { + let c = g.spacing * zoom; + let n = g.major >= 2 ? g.major : 1; + let minor = true; + if (!(c > 0) || !Number.isFinite(c)) return null; + if (g.lattice === 'hex') { + if (c < GRID_MIN_PX) return null; + n = 1; + } else if (c < GRID_MIN_PX) { + if (n > 1 && c * n >= GRID_MIN_PX) minor = false; + else { + const k = g.lattice === 'square' ? (n > 1 ? n : 5) : 2; + while (c < GRID_MIN_PX) c *= k; + n = 1; + } + } + const p = new Paths(n, minor); + if (g.marks === 'lines' && pw > 0 && ph > 0 && fullCount(g, c, pw, ph) <= FULL_MAX) { + if (g.lattice === 'square') squareFull(p, c, ox, oy, pw, ph); + else if (g.lattice === 'tri') triFull(p, c, ox, oy, pw, ph); + else hexFull(p, c, ox, oy, pw, ph); + return { full: true, w: pw, h: ph, x: 0, y: 0, minor: p.minor, major: p.major, marks: g.marks, crisp: g.lattice === 'square' }; + } + const t = g.lattice === 'hex' ? hexTile(p, g.marks, c) + : g.marks === 'lines' ? (g.lattice === 'square' ? squareLinesTile(p, c, n) : triLinesTile(p, c, n)) + : g.lattice === 'square' ? squareTile(p, g.marks, c, n) : triTile(p, g.marks, c, n); + return { full: false, w: t.w, h: t.h, x: ox - t.sx, y: oy - t.sy, minor: p.minor, major: p.major, marks: g.marks, crisp: g.lattice === 'square' }; +} + +export class GridLayer { + readonly svg: SVGSVGElement; + private readonly pattern: SVGPatternElement; + private readonly tile: [SVGPathElement, SVGPathElement]; + private readonly page: [SVGPathElement, SVGPathElement]; + private key = ''; + + constructor(host: HTMLElement) { + const id = `fc-grid-${++seq}`; + const make = (tag: string, attrs: Record = {}): T => { + const n = document.createElementNS(SVG_NS, tag) as T; + for (const [k, v] of Object.entries(attrs)) n.setAttribute(k, v); + return n; + }; + const pair = (): [SVGPathElement, SVGPathElement] => [make('path', { class: 'fc-grid-minor' }), make('path', { class: 'fc-grid-major' })]; + this.svg = make('svg', { class: 'fc-canvas-grid', 'aria-hidden': 'true', focusable: 'false', 'data-off': '' }); + const defs = make('defs'); + this.pattern = make('pattern', { id, patternUnits: 'userSpaceOnUse', x: '0', y: '0', width: '10', height: '10' }); + this.tile = pair(); + this.pattern.append(...this.tile); + defs.appendChild(this.pattern); + const rect = make('rect', { class: 'fc-grid-tiles', width: '100%', height: '100%', fill: `url(#${id})` }); + const full = make('g', { class: 'fc-grid-page' }); + this.page = pair(); + full.append(...this.page); + this.svg.append(defs, rect, full); + host.appendChild(this.svg); + } + + update(g: Grid | null, zoom: number, ox: number, oy: number, pw: number, ph: number): void { + const key = g ? `${g.type}|${g.spacing}|${g.major}|${g.strength}|${f(zoom)}|${f(ox)}|${f(oy)}|${pw}|${ph}` : ''; + if (key === this.key) return; + this.key = key; + const plan = g ? planGrid(g, zoom, ox, oy, pw, ph) : null; + if (!g || !plan) { + setAttr(this.svg, 'data-off', ''); + return; + } + const [minor, major] = plan.full ? this.page : this.tile; + const [oMinor, oMajor] = plan.full ? this.tile : this.page; + if (!plan.full) { + setAttr(this.pattern, 'x', f(plan.x)); + setAttr(this.pattern, 'y', f(plan.y)); + setAttr(this.pattern, 'width', f(plan.w)); + setAttr(this.pattern, 'height', f(plan.h)); + } + setAttr(minor, 'd', plan.minor || 'M0 0'); + setAttr(major, 'd', plan.major || 'M0 0'); + setAttr(oMinor, 'd', 'M0 0'); + setAttr(oMajor, 'd', 'M0 0'); + setAttr(this.svg, 'data-mode', plan.full ? 'page' : 'tiles'); + setAttr(this.svg, 'data-marks', plan.marks); + setAttr(this.svg, 'data-lattice', g.lattice); + setAttr(this.svg, 'data-strength', g.strength); + setAttr(this.svg, 'data-crisp', plan.crisp ? '' : null); + setAttr(this.svg, 'data-off', null); + } +} diff --git a/frontend/src/canvas/grid.ts b/frontend/src/canvas/grid.ts new file mode 100644 index 00000000..4819b975 --- /dev/null +++ b/frontend/src/canvas/grid.ts @@ -0,0 +1,272 @@ +import { resolveStyle, type FormChemDocument, type GridSpec, type GridStrength, type GridType, type Point, type Units } from '../engine/model'; +import { local, setLocal } from '../ui/prefs/store'; +import type { ToolContext } from './types'; + +export type GridLattice = 'square' | 'tri' | 'hex'; +export type GridMarks = 'lines' | 'dots' | 'crosses'; +export type FullGridSpec = Required; + +export interface Grid { + type: GridType; + lattice: GridLattice; + marks: GridMarks; + spacing: number; + bond: boolean; + major: number; + strength: GridStrength; +} + +export const GRID_TYPES: readonly GridType[] = ['lines', 'dots', 'crosses', 'isometric', 'isometric-dots', 'hex', 'hex-dots']; +export const GRID_STRENGTHS: readonly GridStrength[] = ['faint', 'normal', 'strong']; +export const GRID_UNITS: readonly Units[] = ['pt', 'mm', 'cm', 'in']; +export const PT_PER: Readonly> = { pt: 1, mm: 72 / 25.4, cm: 72 / 2.54, in: 72 }; + +export const SPACING_MIN = 1; +export const SPACING_MAX = 288; +export const MAJOR_MAX = 50; +export const SQUARE_SPACING = 7.2; + +export const SHOW_GRID_KEY = 'formchem.showGrid'; +export const SNAP_KEY = 'formchem.snapToGrid'; +export const GRID_DEFAULT_KEY = 'formchem.gridDefault'; + +const SQ3 = Math.sqrt(3); +const SETTLE = 0.02; +const DIR_TOL = 1; + +export const latticeOf = (t: GridType): GridLattice => (t.startsWith('isometric') ? 'tri' : t.startsWith('hex') ? 'hex' : 'square'); +export const marksOf = (t: GridType): GridMarks => (t === 'dots' || t.endsWith('-dots') ? 'dots' : t === 'crosses' ? 'crosses' : 'lines'); +export const bondFamily = (t: GridType): boolean => latticeOf(t) !== 'square'; +export const defaultSpacing = (t: GridType): number | 'bond' => (bondFamily(t) ? 'bond' : SQUARE_SPACING); + +export const DEFAULT_GRID: Readonly = Object.freeze({ type: 'lines', spacing: SQUARE_SPACING, major: 5, strength: 'normal' }); + +export const isGridType = (v: unknown): v is GridType => typeof v === 'string' && (GRID_TYPES as readonly string[]).includes(v); +export const isGridStrength = (v: unknown): v is GridStrength => typeof v === 'string' && (GRID_STRENGTHS as readonly string[]).includes(v); + +export const clampSpacing = (pt: number): number => Math.min(SPACING_MAX, Math.max(SPACING_MIN, Math.round(pt * 10000) / 10000)); + +export function cleanSpec(raw: unknown): FullGridSpec { + const r = (raw && typeof raw === 'object' ? raw : {}) as Record; + const type = isGridType(r.type) ? r.type : DEFAULT_GRID.type; + const sp = r.spacing; + const spacing = sp === 'bond' ? 'bond' : typeof sp === 'number' && Number.isFinite(sp) && sp > 0 ? clampSpacing(sp) : defaultSpacing(type); + const mj = r.major; + const major = typeof mj === 'number' && Number.isFinite(mj) ? Math.min(MAJOR_MAX, Math.max(0, Math.round(mj))) : DEFAULT_GRID.major; + const strength = isGridStrength(r.strength) ? r.strength : DEFAULT_GRID.strength; + return { type, spacing, major, strength }; +} + +export const sameSpec = (a: GridSpec | undefined, b: GridSpec | undefined): boolean => + !!a && !!b && a.type === b.type && a.spacing === b.spacing && a.major === b.major && a.strength === b.strength; + +export function withType(spec: FullGridSpec, type: GridType): FullGridSpec { + const family = bondFamily(type) === bondFamily(spec.type); + return { ...spec, type, spacing: family ? spec.spacing : defaultSpacing(type) }; +} + +const listeners = new Set<() => void>(); +let preview: FullGridSpec | null = null; +let wired = false; + +function emit(): void { + for (const fn of [...listeners]) fn(); +} + +function wire(): void { + if (wired) return; + wired = true; + window.addEventListener('storage', (e) => { + if (e.key === null || e.key === SNAP_KEY || e.key === GRID_DEFAULT_KEY || e.key === SHOW_GRID_KEY) emit(); + }); +} + +export function onGridChange(fn: () => void): () => void { + wire(); + listeners.add(fn); + return () => { listeners.delete(fn); }; +} + +export const gridShown = (): boolean => local(SHOW_GRID_KEY) !== '0'; + +export function setGridShown(on: boolean): boolean { + setLocal(SHOW_GRID_KEY, on ? '1' : '0'); + emit(); + return on; +} + +export const snapOn = (): boolean => local(SNAP_KEY) === '1'; + +export function setSnap(on: boolean): boolean { + setLocal(SNAP_KEY, on ? '1' : '0'); + emit(); + return on; +} + +export function windowGrid(): FullGridSpec { + const raw = local(GRID_DEFAULT_KEY); + if (!raw) return { ...DEFAULT_GRID }; + try { return cleanSpec(JSON.parse(raw)); } catch { return { ...DEFAULT_GRID }; } +} + +export function setWindowGrid(spec: GridSpec): FullGridSpec { + const clean = cleanSpec(spec); + setLocal(GRID_DEFAULT_KEY, JSON.stringify(clean)); + emit(); + return clean; +} + +export function setGridPreview(spec: GridSpec | null): void { + const next = spec ? cleanSpec(spec) : null; + if (next === preview || (next && preview && sameSpec(next, preview))) return; + preview = next; + emit(); +} + +export const docHasGrid = (doc: FormChemDocument): boolean => !!doc.style?.grid && typeof doc.style.grid === 'object'; + +export function docSpec(doc: FormChemDocument, withPreview = true): FullGridSpec { + if (withPreview && preview) return { ...preview }; + return docHasGrid(doc) ? cleanSpec(doc.style.grid) : windowGrid(); +} + +export function resolveSpec(spec: FullGridSpec, bondLength: number): Grid { + const bond = spec.spacing === 'bond'; + const raw = bond ? bondLength : (spec.spacing as number); + return { + type: spec.type, + lattice: latticeOf(spec.type), + marks: marksOf(spec.type), + spacing: clampSpacing(Number.isFinite(raw) && raw > 0 ? raw : SQUARE_SPACING), + bond, + major: spec.major >= 2 && latticeOf(spec.type) !== 'hex' ? spec.major : 0, + strength: spec.strength, + }; +} + +export const resolveGrid = (doc: FormChemDocument, withPreview = true): Grid => resolveSpec(docSpec(doc, withPreview), resolveStyle(doc).bond_length); + +export function formatLength(pt: number, unit: Units): string { + const v = pt / PT_PER[unit]; + const digits = unit === 'pt' || unit === 'mm' ? 2 : 4; + return String(Math.round(v * 10 ** digits) / 10 ** digits); +} + +type Want = 'any' | 'vertex' | 'centre' | 0 | 1; + +const hexClass = (a: number, b: number): number => (((a - b) % 3) + 3) % 3; + +function accepts(g: Grid, a: number, b: number, want: Want): boolean { + if (g.lattice !== 'hex' || want === 'any') return true; + const c = hexClass(a, b); + if (want === 'vertex') return c !== 2; + if (want === 'centre') return c === 2; + return c === want; +} + +export function nearestPoint(g: Grid, p: Point, want: Want = 'vertex'): Point { + const s = g.spacing; + if (g.lattice === 'square') return [Math.round(p[0] / s) * s, Math.round(p[1] / s) * s]; + const w = (s * SQ3) / 2; + const a0 = Math.round(p[0] / w); + let best: Point = p; + let bd = Infinity; + for (let a = a0 - 2; a <= a0 + 2; a++) { + const b0 = Math.round((p[1] - (a * s) / 2) / s); + for (let b = b0 - 2; b <= b0 + 2; b++) { + if (!accepts(g, a, b, want)) continue; + const x = a * w, y = (a * s) / 2 + b * s; + const d = (x - p[0]) ** 2 + (y - p[1]) ** 2; + if (d < bd) { bd = d; best = [x, y]; } + } + } + return best; +} + +export function latticeClass(g: Grid, p: Point): number { + if (g.lattice !== 'hex') return -1; + const s = g.spacing, w = (s * SQ3) / 2; + const a = Math.round(p[0] / w); + const b = Math.round((p[1] - (a * s) / 2) / s); + const x = a * w, y = (a * s) / 2 + b * s; + return Math.hypot(x - p[0], y - p[1]) <= SETTLE * s ? hexClass(a, b) : -1; +} + +export function onGrid(g: Grid, p: Point, tol = SETTLE): boolean { + const q = nearestPoint(g, p); + return Math.hypot(q[0] - p[0], q[1] - p[1]) <= tol * g.spacing; +} + +function hexClassFor(dir: number): 0 | 1 | null { + const d = ((dir % 360) + 360) % 360; + const near = (a: number): boolean => Math.abs((((d - a) % 360) + 540) % 360 - 180) <= DIR_TOL; + if ([330, 90, 210].some(near)) return 0; + if ([30, 150, 270].some(near)) return 1; + return null; +} + +function active(ctx: ToolContext, free?: boolean): Grid | null { + if (free || !snapOn()) return null; + try { return resolveSpec(docSpec(ctx.client.doc, false), ctx.style().bond_length); } catch { return null; } +} + +export const snapActive = (ctx: ToolContext, free?: boolean): boolean => active(ctx, free) !== null; + +export function latticeGrid(ctx: ToolContext, free?: boolean): Grid | null { + const g = active(ctx, free); + if (!g || g.lattice === 'square') return null; + return Math.abs(g.spacing - ctx.style().bond_length) <= 1e-6 * g.spacing ? g : null; +} + +const LATTICE_DIRS: Readonly> = { all: [30, 90, 150, 210, 270, 330], 0: [330, 90, 210], 1: [30, 150, 270] }; + +export function latticeDirections(g: Grid, from: Point): readonly number[] { + const c = latticeClass(g, from); + return c === 0 || c === 1 ? LATTICE_DIRS[c] : LATTICE_DIRS.all; +} + +export function latticeAngle(ctx: ToolContext, from: Point, raw: number, free?: boolean): number | null { + const g = latticeGrid(ctx, free); + if (!g) return null; + let best = raw, bd = Infinity; + for (const a of latticeDirections(g, from)) { + const d = Math.abs((((raw - a) % 360) + 540) % 360 - 180); + if (d < bd) { bd = d; best = a; } + } + return best; +} + +export function snapPoint(ctx: ToolContext, p: Point, free?: boolean): Point { + const g = active(ctx, free); + return g ? nearestPoint(g, p) : p; +} + +export function snapStart(ctx: ToolContext, p: Point, dir: number | null, free?: boolean): Point { + const g = active(ctx, free); + if (!g) return p; + const want = g.lattice === 'hex' && dir !== null ? hexClassFor(dir) : null; + return nearestPoint(g, p, want ?? 'vertex'); +} + +export function settlePoint(ctx: ToolContext, p: Point, free?: boolean): Point { + const g = active(ctx, free); + if (!g) return p; + const q = nearestPoint(g, p); + return Math.hypot(q[0] - p[0], q[1] - p[1]) <= SETTLE * g.spacing ? q : p; +} + +export function snapRingCentre(ctx: ToolContext, p: Point, free?: boolean): { centre: Point; turn: number } | null { + const g = active(ctx, free); + if (!g) return null; + if (g.lattice === 'square') return { centre: nearestPoint(g, p), turn: 0 }; + return { centre: nearestPoint(g, p, g.lattice === 'hex' ? 'centre' : 'any'), turn: 30 }; +} + +export function snapShift(ctx: ToolContext, ref: Point, dx: number, dy: number, opts: { free?: boolean; keepClass?: boolean } = {}): [number, number] { + const g = active(ctx, opts.free); + if (!g) return [dx, dy]; + const cls = opts.keepClass ? latticeClass(g, ref) : -1; + const want: Want = cls === 0 || cls === 1 ? cls : 'vertex'; + const q = nearestPoint(g, [ref[0] + dx, ref[1] + dy], want); + return [q[0] - ref[0], q[1] - ref[1]]; +} diff --git a/frontend/src/canvas/render/label.ts b/frontend/src/canvas/render/label.ts index 8c24f844..39382ce3 100644 --- a/frontend/src/canvas/render/label.ts +++ b/frontend/src/canvas/render/label.ts @@ -1,3 +1,4 @@ +import { HYDRIDE_FIRST } from '../../chem/valence'; import type { Atom, Bond, Style } from '../../engine/model'; import { ELEMENTS } from '../../engine/model'; import type { Box } from './geom'; @@ -36,7 +37,7 @@ export function labelSide(atom: Atom, nbrs: readonly Neighbour[], bondLength: nu if (forced === 'left') return 'left'; if (forced === 'above' || forced === 'below') return forced; if (forced === 'right' || forced === 'centre') return 'right'; - if (!nbrs.length) return 'right'; + if (!nbrs.length) return HYDRIDE_FIRST.has(atom.element) && !atom.label ? 'left' : 'right'; return nbrs.every((n) => n.atom.x > atom.x + 0.1 * bondLength) ? 'left' : 'right'; } 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; diff --git a/frontend/src/canvas/tools/arrow.ts b/frontend/src/canvas/tools/arrow.ts index ef34469e..452a4695 100644 --- a/frontend/src/canvas/tools/arrow.ts +++ b/frontend/src/canvas/tools/arrow.ts @@ -1,5 +1,6 @@ import type { ArrowHead, ArrowObject, ArrowType, Id, Point } from '../../engine/model'; import { dist } from '../geom'; +import { snapPoint } from '../grid'; import type { Tool, ToolContext, ToolPointer } from '../types'; import { commitDraft, draftFor, moved, previewDraft } from './common'; import type { Draft } from './draft'; @@ -91,10 +92,10 @@ export class ArrowTool implements Tool { } private draft(ctx: ToolContext, s: ToolPointer, p: ToolPointer, dragged: boolean): Draft | null { - const tail = s.doc; + const tail = snapPoint(ctx, s.doc, p.alt); let head: Point; if (dragged) { - head = p.shift ? snapEnd(tail, p.doc) : p.doc; + head = p.shift ? snapEnd(tail, p.doc) : snapPoint(ctx, p.doc, p.alt); if (dist(tail, head) < 1) return null; } else head = [tail[0] + ctx.style().bond_length * ARROW_CLICK_BONDS, tail[1]]; const d = draftFor(ctx); diff --git a/frontend/src/canvas/tools/bond.ts b/frontend/src/canvas/tools/bond.ts index 3c2cc5e4..07bbd51e 100644 --- a/frontend/src/canvas/tools/bond.ts +++ b/frontend/src/canvas/tools/bond.ts @@ -1,5 +1,6 @@ import { bondBetween, isFragment, type Bond, type BondOrder, type DoublePosition, type Id, type Point } from '../../engine/model'; import { angleFrom, polar, snapBondAngle } from '../geom'; +import { latticeAngle, settlePoint, snapActive, snapStart } from '../grid'; import type { Hit, Tool, ToolContext, ToolPointer } from '../types'; import { BOND_KINDS, @@ -134,7 +135,7 @@ export class BondTool implements Tool { } if (hit.kind === 'object') return; const d = draftFor(ctx); - freeBond(d, pr.at.doc, 30, style, this.props); + freeBond(d, snapStart(ctx, pr.at.doc, 30, pr.at.alt), 30, style, this.props); commitDraft(ctx, 'Add bond', d); } @@ -149,9 +150,13 @@ export class BondTool implements Tool { start = d.pos(from.frag, from.atom); refs = neighbourAngles(d, from); if (refs.length) ideal = nextDirection(d, from, style, this.props.order); + } else if (snapActive(ctx, p.alt)) { + const raw = angleFrom(start, p.doc); + start = snapStart(ctx, start, latticeAngle(ctx, start, raw, p.alt) ?? snapBondAngle(raw), p.alt); } - const angle = snapBondAngle(angleFrom(start, p.doc), { free: p.alt, refs, ideal }); - const end = polar(start, angle, style.bond_length); + const raw = angleFrom(start, p.doc); + const angle = latticeAngle(ctx, start, raw, p.alt) ?? snapBondAngle(raw, { free: p.alt, refs, ideal }); + const end = settlePoint(ctx, polar(start, angle, style.bond_length), p.alt); const skip = from ? [from] : []; const over = ctx.hitTest(p.doc, { ignoreAtoms: ignoreSet(skip) }); let target: AtomRef | null = over.kind === 'atom' && (!from || over.atom !== from.atom) ? { frag: over.frag, atom: over.atom } : null; diff --git a/frontend/src/canvas/tools/build.ts b/frontend/src/canvas/tools/build.ts index bdfb6993..73fa12cd 100644 --- a/frontend/src/canvas/tools/build.ts +++ b/frontend/src/canvas/tools/build.ts @@ -186,9 +186,9 @@ export function closeRing(d: Draft, fid: Id, verts: Point[], fixed: (Id | null)[ return { frag, atoms: ids }; } -export function ringAt(d: Draft, centre: Point, spec: RingSpec, style: Style): { frag: Id; atoms: Id[] } { +export function ringAt(d: Draft, centre: Point, spec: RingSpec, style: Style, turn = 0): { frag: Id; atoms: Id[] } { const fid = d.newFragment(); - return closeRing(d, fid, ringAtPoint(spec.size, centre, style.bond_length), [], spec.fill, style); + return closeRing(d, fid, ringAtPoint(spec.size, centre, style.bond_length, turn), [], spec.fill, style); } export function spiroRing(d: Draft, at: AtomRef, spec: RingSpec, style: Style): { frag: Id; atoms: Id[] } { diff --git a/frontend/src/canvas/tools/chain.ts b/frontend/src/canvas/tools/chain.ts index dd0c745f..25024925 100644 --- a/frontend/src/canvas/tools/chain.ts +++ b/frontend/src/canvas/tools/chain.ts @@ -1,5 +1,6 @@ import { isFragment, type Point } from '../../engine/model'; -import { angleFrom, DEG, dist, normAngle, snapBondAngle, zigzag } from '../geom'; +import { angleFrom, DEG, dist, flipAbout, normAngle, rotateAbout, snapAngle, snapBondAngle, zigzag } from '../geom'; +import { latticeGrid, onGrid, settlePoint, snapActive, snapStart } from '../grid'; import type { Hit, Tool, ToolContext, ToolPointer } from '../types'; import { chainAlong, freeBond, growBond, isFull } from './build'; import { atomRef, commitDraft, draftFor, moved, noteOps, previewDraft } from './common'; @@ -7,12 +8,13 @@ import type { AtomRef, Draft } from './draft'; import { hoverKey } from './hotkeys'; export const MAX_CHAIN = 99; +const LATTICE_AXIS = 60; interface Press { at: ToolPointer; from: AtomRef | null; dragging: boolean; typed: string } -export function chainPoints(start: Point, pointer: Point, chainAngle: number, edge: number, opts: { free?: boolean; count?: number } = {}): { points: Point[]; count: number } { +export function chainPoints(start: Point, pointer: Point, chainAngle: number, edge: number, opts: { free?: boolean; count?: number; axisStep?: number } = {}): { points: Point[]; count: number } { const raw = angleFrom(start, pointer); - const axis = snapBondAngle(raw, { free: opts.free }); + const axis = opts.axisStep ? snapAngle(raw, opts.axisStep) : snapBondAngle(raw, { free: opts.free }); const half = (180 - chainAngle) / 2; const step = edge * Math.cos(half * DEG); const along = dist(start, pointer) * Math.cos((raw - axis) * DEG); @@ -68,7 +70,7 @@ export class ChainTool implements Tool { } if (pr.at.hit.kind !== 'none') return; const d = draftFor(ctx); - freeBond(d, pr.at.doc, 30, style, { order: 1 }); + freeBond(d, snapStart(ctx, pr.at.doc, 30, pr.at.alt), 30, style, { order: 1 }); commitDraft(ctx, 'Add bond', d); } @@ -96,9 +98,22 @@ export class ChainTool implements Tool { const style = ctx.style(); const d = draftFor(ctx, pr.from ? [pr.from.frag] : []); let from = pr.from && isFragment(d.doc.objects[pr.from.frag]) ? pr.from : null; - const start: Point = from ? d.pos(from.frag, from.atom) : pr.at.doc; + let start: Point = from ? d.pos(from.frag, from.atom) : pr.at.doc; const typed = pr.typed ? parseInt(pr.typed, 10) : 0; - const { points, count } = chainPoints(start, p.doc, style.chain_angle, style.bond_length, { free: p.alt, count: typed > 0 ? typed : undefined }); + const lattice = latticeGrid(ctx, p.alt); + const opts = { free: p.alt, count: typed > 0 ? typed : undefined, axisStep: lattice ? LATTICE_AXIS : undefined }; + let pointer = p.doc; + let { points, count } = chainPoints(start, pointer, style.chain_angle, style.bond_length, opts); + if (!from && points.length && snapActive(ctx, p.alt)) { + start = snapStart(ctx, start, angleFrom(start, points[0]), p.alt); + ({ points, count } = chainPoints(start, pointer, style.chain_angle, style.bond_length, opts)); + } + if (lattice && points.length && !onGrid(lattice, points[0])) { + const axis = snapAngle(angleFrom(start, pointer), LATTICE_AXIS); + pointer = rotateAbout(flipAbout(rotateAbout(pointer, start, -axis), start, 'v'), start, axis); + ({ points, count } = chainPoints(start, pointer, style.chain_angle, style.bond_length, opts)); + } + points = points.map((q) => settlePoint(ctx, q, p.alt)); if (!from) { const fid = d.newFragment(); from = { frag: fid, atom: d.addAtom(fid, start) }; 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); diff --git a/frontend/src/canvas/tools/image.ts b/frontend/src/canvas/tools/image.ts index e7b3cd17..ce518294 100644 --- a/frontend/src/canvas/tools/image.ts +++ b/frontend/src/canvas/tools/image.ts @@ -78,7 +78,7 @@ export async function placeImage(ctx: ToolContext, at: Point, drawn: Rect | null d.addObject(o); return commitDraft(ctx, 'Add image', d) ? o.id : null; } catch (e) { - toast(`${t('Could not add the image')}: ${e instanceof Error ? e.message : String(e)}`, 'error'); + toast(`${t('Could not add the image')}: ${t(e instanceof Error ? e.message : String(e))}`, 'error'); return null; } } 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/objects.ts b/frontend/src/canvas/tools/objects.ts index 026b24f9..caf3950e 100644 --- a/frontend/src/canvas/tools/objects.ts +++ b/frontend/src/canvas/tools/objects.ts @@ -1,5 +1,6 @@ import { isFragment, newId, type Bounds, type DocObject, type FormChemDocument, type Fragment, type Id, type Point } from '../../engine/model'; import { angleFrom, dist, polar, snapAngle, type Rect } from '../geom'; +import { snapPoint } from '../grid'; import type { Hit, Tool, ToolContext, ToolPointer } from '../types'; import { commitDraft, draftFor, moved, objectBounds, previewDraft, topLevelObjects } from './common'; import type { Draft } from './draft'; @@ -34,7 +35,9 @@ export function boxFrom(a: Point, b: Point, opts: { square?: boolean; centre?: b return { x: Math.min(a[0], a[0] + dx), y: Math.min(a[1], a[1] + dy), w: Math.max(MIN_BOX, Math.abs(dx)), h: Math.max(MIN_BOX, Math.abs(dy)) }; } -export const boxAround = (c: Point, w: number, h: number): Rect => ({ x: c[0] - w / 2, y: c[1] - h / 2, w, h }); +const snapped = (ctx: ToolContext, q: ToolPointer, free: boolean): ToolPointer => ({ ...q, doc: snapPoint(ctx, q.doc, free) }); + +export const boxAround =(c: Point, w: number, h: number): Rect => ({ x: c[0] - w / 2, y: c[1] - h / 2, w, h }); export const inflateRect = (r: Rect, d: number): Rect => ({ x: r.x - d, y: r.y - d, w: r.w + 2 * d, h: r.h + 2 * d }); @@ -146,7 +149,7 @@ export abstract class BoxTool implements Tool { } if (!moved(s, p)) return; const d = draftFor(ctx); - previewDraft(ctx, this.build(ctx, d, this.rect(s, p), p, true) ? d : null); + previewDraft(ctx, this.build(ctx, d, this.rect(snapped(ctx, s, p.alt), snapped(ctx, p, p.alt)), p, true) ? d : null); } up(ctx: ToolContext, p: ToolPointer): void { @@ -159,7 +162,7 @@ export abstract class BoxTool implements Tool { return; } const d = draftFor(ctx); - const r = dragged ? this.rect(s, p) : this.clickBox(ctx, s.doc); + const r = dragged ? this.rect(snapped(ctx, s, p.alt), snapped(ctx, p, p.alt)) : this.clickBox(ctx, snapPoint(ctx, s.doc, p.alt)); if (!this.build(ctx, d, r, p, dragged)) { ctx.client.preview(null); return; diff --git a/frontend/src/canvas/tools/ring.ts b/frontend/src/canvas/tools/ring.ts index d6c1dad4..b1f461f1 100644 --- a/frontend/src/canvas/tools/ring.ts +++ b/frontend/src/canvas/tools/ring.ts @@ -1,5 +1,6 @@ import { isFragment, type Id } from '../../engine/model'; import { norm, perp, sub, dot } from '../geom'; +import { snapRingCentre } from '../grid'; import type { Hit, Tool, ToolContext, ToolPointer } from '../types'; import { fuseRing, ringAt, RING_SPECS, spiroRing, substituentRing, type RingSpec } from './build'; import { commitDraft, draftFor, moved, previewDraft } from './common'; @@ -80,7 +81,9 @@ export class RingTool implements Tool { } if (hit.kind === 'object') return null; const d = draftFor(ctx); - ringAt(d, pr.at.doc, spec, style); + const snap = snapRingCentre(ctx, pr.at.doc, pr.at.alt); + if (snap) ringAt(d, snap.centre, spec, style, spec.size === 6 ? snap.turn : 0); + else ringAt(d, pr.at.doc, spec, style); return d; } } diff --git a/frontend/src/canvas/tools/scale.ts b/frontend/src/canvas/tools/scale.ts new file mode 100644 index 00000000..7ffacecc --- /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 = 0.006; + +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 * 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 { + 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/select.ts b/frontend/src/canvas/tools/select.ts index 810463c6..2c911ae8 100644 --- a/frontend/src/canvas/tools/select.ts +++ b/frontend/src/canvas/tools/select.ts @@ -1,6 +1,7 @@ -import { bondBetween, bondsOf, isFragment, neighbours, newId, type Bond, type Fragment, type Id, type Point, type ShapeObject, type LineObject } from '../../engine/model'; +import { bondBetween, bondsOf, isFragment, neighbours, newId, type Bond, type FormChemDocument, type Fragment, type Id, type Point, type ShapeObject, type LineObject } from '../../engine/model'; import { atomPath, bondPath, objectPath, pagePath, type Op } from '../../engine/ops'; import { angleFrom, dist, inRect, pointInPolygon, polar, rectFrom, rectInside, rectsTouch, rectCentre, snapAngle, type Rect } from '../geom'; +import { snapPoint, snapShift } from '../grid'; import { selectionKey, type Band, type Hit, type Selection, type Tool, type ToolContext, type ToolPointer } from '../types'; import { MERGE_FRACTION } from './build'; import { atomsOfSelection, commitDraft, draftFor, EMPTY_SELECTION, makeSelection, moved, objectBounds, previewDraft, selectFragment, selectionEmpty, splitKey, topLevelObjects } from './common'; @@ -10,6 +11,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 +23,34 @@ 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 grabPoint(doc: FormChemDocument, h: Hit, at: Point): Point | null { + const near = (pts: Point[]): Point | null => (pts.length ? pts.reduce((a, b) => (dist(a, at) <= dist(b, at) ? a : b)) : null); + if (h.kind === 'atom' || h.kind === 'bond') { + const f = doc.objects[h.frag]; + if (!isFragment(f)) return null; + const ids = h.kind === 'atom' ? [h.atom] : [f.bonds[h.bond]?.a, f.bonds[h.bond]?.b]; + return near(ids.map((id) => (id ? f.atoms[id] : undefined)).filter((a) => !!a).map((a) => [a!.x, a!.y] as Point)); + } + if (h.kind !== 'object') return null; + const o = doc.objects[h.object]; + if (!o) return null; + if (isFragment(o)) return near(Object.values(o.atoms).map((a) => [a.x, a.y] as Point)); + if (o.kind === 'arrow') return near([[o.x1, o.y1], [o.x2, o.y2]]); + if (o.kind === 'line') return near(o.points.map((q) => [q[0], q[1]] as Point)); + if (o.kind === 'plus' || o.kind === 'orbital') return [o.x, o.y]; + const r = objectBounds(doc, o); + return r ? near([[r.x, r.y], [r.x + r.w, r.y], [r.x, r.y + r.h], [r.x + r.w, r.y + r.h]]) : null; +} + 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 +188,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 +226,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 +270,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 +315,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); @@ -293,7 +340,7 @@ export class SelectTool implements Tool { const c = d.pos(at.frag, nb[0]); const angle = p.alt ? angleFrom(c, p.doc) : snapAngle(angleFrom(c, p.doc), 15); target = polar(c, angle, dist(c, orig)); - } + } else target = snapPoint(ctx, target, p.alt); const skip = new Set([at.atom, ...nb]); const into = d.nearestAtom(target, style.bond_length * MERGE_FRACTION, { skip }); if (into) { @@ -306,6 +353,9 @@ export class SelectTool implements Tool { if (p.shift) { if (Math.abs(dx) >= Math.abs(dy)) dy = 0; else dx = 0; + } else { + const ref = grabPoint(d.doc, m.start.hit, m.start.doc); + if (ref) [dx, dy] = snapShift(ctx, ref, dx, dy, { free: p.alt, keepClass: true }); } translateSelection(d, sel, dx, dy); return { d, sel }; @@ -313,10 +363,18 @@ export class SelectTool implements Tool { private handleDraft(ctx: ToolContext, m: Extract, p: ToolPointer): Draft { const d = draftFor(ctx, [m.handle.object]); - dragHandle(d, m.handle, p.doc, { shift: p.shift, alt: p.alt }); + const at = p.shift || m.handle.kind === 'bend' ? p.doc : snapPoint(ctx, p.doc, p.alt); + dragHandle(d, m.handle, at, { shift: p.shift, alt: p.alt }); 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); 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)); diff --git a/frontend/src/canvas/view.ts b/frontend/src/canvas/view.ts index 581addd9..67a73d0d 100644 --- a/frontend/src/canvas/view.ts +++ b/frontend/src/canvas/view.ts @@ -3,14 +3,17 @@ 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 { modalOpen } from '../ui/menu'; +import { el, isMac, overlayRoot, q, setClass, setHidden, setText } from '../ui/dom'; +import { menuBarOpen, modalOpen } from '../ui/menu'; import { openCanvasMenu } from './context'; +import { onGridChange, resolveGrid } from './grid'; +import { GridLayer } from './grid-layer'; import { fmt } from './render/geom'; import { hitExists, hitTest, NO_HIT, objectBounds, sameHit, styleFor, visibleOrder, type Box } from './hit'; 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; @@ -19,7 +22,6 @@ export const ZOOM_MAX = 64; const ZOOM_STEPS = [5, 10, 25, 33.3, 50, 66.7, 75, 100, 125, 150, 200, 300, 400, 600, 800, 1200, 1600, 2400, 3200, 4800]; const FIT_PAD = 28; const KEEP_VISIBLE = 48; -const GRID_PT = 7.2; const WHEEL_ZOOM = 0.006; const CLICK_MS = 420; const CLICK_PX = 5; @@ -27,14 +29,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 } @@ -154,10 +160,13 @@ export class CanvasView { readonly renderer: Renderer; readonly editor: TextEditor; private readonly paper: HTMLElement; + private readonly grid: GridLayer; private readonly overlay: SVGSVGElement; 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 }; @@ -201,7 +210,8 @@ export class CanvasView { this.renderer = opts.renderer; this.root = el(`
`); this.paper = q(this.root, '.fc-canvas-paper'); - this.svg = document.createElementNS(SVG_NS, 'svg'); + this.grid = new GridLayer(this.paper); + this.svg =document.createElementNS(SVG_NS, 'svg'); this.svg.setAttribute('class', 'fc-canvas-svg'); this.svg.setAttribute('aria-hidden', 'true'); this.overlay = document.createElementNS(SVG_NS, 'svg'); @@ -213,7 +223,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 +251,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({ @@ -634,7 +649,10 @@ export class CanvasView { this.placeKeyCursor(); this.emit('viewport'); } - if (handle) this.placeHandle(); + if (handle) { + this.placeHandle(); + this.placeGrid(); + } if (this.renderDirty) { this.renderDirty = false; const pid = this.doc_ ? this.page()?.id ?? null : null; @@ -654,16 +672,44 @@ 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`; + 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'; + } } 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 { @@ -678,9 +724,7 @@ export class CanvasView { const bg = page?.background ?? this.style().background; const x = Math.round(this.vp.x + b.x * z), y = Math.round(this.vp.y + b.y * z); const w = Math.round(b.w * z), h = Math.round(b.h * z); - let step = GRID_PT * z; - while (step < 6) step *= 5; - const key = `${x},${y},${w},${h},${bg},${step.toFixed(2)},${this.doc_ ? 1 : 0}`; + const key = `${x},${y},${w},${h},${bg},${this.doc_ ? 1 : 0}`; if (key === this.placed) return; this.placed = key; this.paper.style.transform = `translate(${x}px, ${y}px)`; @@ -688,7 +732,17 @@ export class CanvasView { this.paper.style.height = `${h}px`; this.paper.style.backgroundColor = bg; this.paper.hidden = !this.doc_; - setStyleVar(this.paper, '--fc-grid-step', `${step.toFixed(2)}px`); + } + + private placeGrid(): void { + const z = this.vp.zoom, b = this.pageBox(); + const ox = this.vp.x - Math.round(this.vp.x + b.x * z), oy = this.vp.y - Math.round(this.vp.y + b.y * z); + this.grid.update(this.doc_ ? resolveGrid(this.doc) : null, z, ox, oy, Math.round(b.w * z), Math.round(b.h * z)); + } + + gridChanged(): void { + this.viewDirty = true; + this.invalidate(); } private pointer(e: PointerEvent, button: number): ViewPointer { @@ -888,7 +942,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; } @@ -1154,7 +1208,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 }); @@ -1166,6 +1220,7 @@ export class CanvasView { const ro = new ResizeObserver(() => this.onResize()); ro.observe(r); this.off.push(() => ro.disconnect()); + this.off.push(onGridChange(() => this.gridChanged())); } private onResize(): void { @@ -1193,6 +1248,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/chem/valence.ts b/frontend/src/chem/valence.ts index 76e3a9bb..adc0f402 100644 --- a/frontend/src/chem/valence.ts +++ b/frontend/src/chem/valence.ts @@ -86,7 +86,7 @@ export interface AtomLabel { } const LINEAR_TOLERANCE = 10; -const HYDRIDE_FIRST = new Set(['O', 'S', 'Se', 'Te', 'F', 'Cl', 'Br', 'I']); +export const HYDRIDE_FIRST: ReadonlySet = new Set(['O', 'S', 'Se', 'Te', 'F', 'Cl', 'Br', 'I']); export function chargeText(charge: number | undefined): string { if (!charge) return ''; 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