diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5c3fd4343d..354105c812 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -330,6 +330,9 @@ jobs: if: runner.os != 'Linux' run: cargo test --locked -p openbitfun-core --lib + - name: Run portable Office document engine tests + run: cargo test --locked -p openbitfun-office-documents + - name: Run full core library tests on Linux if: runner.os == 'Linux' run: cargo test --locked -p openbitfun-core --features product-full --lib diff --git a/Cargo.lock b/Cargo.lock index c1b5d1cd7e..db0762a26e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6044,6 +6044,7 @@ dependencies = [ "openbitfun-events", "openbitfun-external-sources", "openbitfun-legacy-migration-adapters", + "openbitfun-office-documents", "openbitfun-opencode-adapter", "openbitfun-opencode-plugin-host", "openbitfun-pi-adapter", @@ -6381,6 +6382,19 @@ dependencies = [ "windows 0.61.3", ] +[[package]] +name = "openbitfun-office-documents" +version = "1.0.9" +dependencies = [ + "base64 0.22.1", + "pulldown-cmark", + "roxmltree", + "serde", + "serde_json", + "sha2", + "zip 4.6.1", +] + [[package]] name = "openbitfun-opencode-adapter" version = "1.0.9" diff --git a/Cargo.toml b/Cargo.toml index 8a60920757..7003b594c6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -51,6 +51,7 @@ members = [ "src/crates/execution/runtime-services", "src/crates/execution/tool-provider-groups", "src/crates/execution/tool-execution", + "src/crates/execution/office-documents", "src/crates/contracts/core-types", "src/crates/contracts/config-contracts", "src/crates/contracts/events", diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 0f67332956..6f3eaf5548 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -78,3 +78,235 @@ 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. + +## GenOffice + +- Project: GenOffice +- Source: https://github.com/genspark-ai/genoffice +- Reference revision: f8c17004fb730df11f0f743164ffd8b4281bb38c +- License: Apache License, Version 2.0 +- Copyright: Copyright 2026 Mainfunc, Inc. + +OpenBitFun's Office document engine was developed with reference to GenOffice's +agent-facing Word operations, Excel cell DSL, and PowerPoint page specification. +OpenBitFun implements a Rust engine with atomic batches, embedded editable models, +OOXML package writers, and local/remote workspace integration. GenOffice-derived +material remains subject to Apache-2.0; OpenBitFun-authored additions use MIT. + +Applicable upstream notice: + +> GenOffice +> Copyright 2026 Mainfunc, Inc. +> +> This product includes software developed at Mainfunc, Inc. + +The full upstream NOTICE, reference paths, and implementation differences are +preserved under `src/crates/execution/office-documents/`. GenOffice's unrelated +bundled dependencies are not redistributed by this attribution. + +The complete upstream Apache-2.0 license follows: + +```text + + 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 2026 Mainfunc, Inc. + + 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. +``` diff --git a/docs/architecture/rust-build-dependency-boundaries.md b/docs/architecture/rust-build-dependency-boundaries.md index 0a7f548bb8..c932c487bf 100644 --- a/docs/architecture/rust-build-dependency-boundaries.md +++ b/docs/architecture/rust-build-dependency-boundaries.md @@ -86,6 +86,11 @@ Plugin Source 和完整 domain feature 集合一起带回 Agent Runtime。产品 配置驱动的 AI client 和生图协议适配。检查图片的窄消费者不应因此启用生成请求。完整产品和 需要生图的 CLI、ACP、SDK Host 显式选择这两个 owner,工具 provider 与注册顺序保持稳定。 +Office 文件生成由 `tools-office-documents` 独立选择:它只引入 `GenOfficeFile` 与可移植的 +OOXML 引擎 `openbitfun-office-documents`(execution 层,纯内存字节,不做 IO),不扩大 +`tools-basic` 的基线闭包。工具归属 `core.basic` provider,因此完整产品以及 CLI、ACP、 +SDK Host 与生图一样显式选择该 owner。 + ### 3.3 Workspace dependency 只提供共同底座 - workspace 声明负责版本和真正跨产品共享的最小 feature; diff --git a/docs/interactive-capabilities/README.md b/docs/interactive-capabilities/README.md index ed8b9542e2..6d7d04187f 100644 --- a/docs/interactive-capabilities/README.md +++ b/docs/interactive-capabilities/README.md @@ -1,9 +1,9 @@ # OpenBitFun 功能与设置目录 / OpenBitFun Features & Settings -OpenBitFun Playbook 当前包含 **22 个功能**和 **22 个设置页**,共 **44 个**用户可理解的条目、**333 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 +OpenBitFun Playbook 当前包含 **22 个功能**和 **22 个设置页**,共 **44 个**用户可理解的条目、**334 项**有源码证据的子能力。每个条目有独立 Markdown,并直接服务于说明书网站、OpenBitFun 全局搜索和 `OpenBitFunControl` 智能体工具。 -OpenBitFun Playbook currently contains **22 features**, **22 settings pages**, and **333** source-backed sub-capabilities across **44** user-facing entries. Every entry has its own Markdown page and directly powers the website, in-app global search, and the `OpenBitFunControl` agent tool. +OpenBitFun Playbook currently contains **22 features**, **22 settings pages**, and **334** source-backed sub-capabilities across **44** user-facing entries. Every entry has its own Markdown page and directly powers the website, in-app global search, and the `OpenBitFunControl` agent tool. ## 唯一事实源 / Single source of truth @@ -33,14 +33,14 @@ Docs, website, search, and agents see only features, settings, and documented su ## 控制边界 / Control boundary -- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **63**、委托 **70**、需交互 **200**、不支持 **0**。 +- 每个子能力都明确标记为直接控制、委托给专用智能体工具、需交互打开或不支持;“打开页面”不会再被统计成“智能体已控制”。当前覆盖:直接 **63**、委托 **71**、需交互 **200**、不支持 **0**。 - 稳定行为声明为带 JSON 输入契约的 `operations` 或 `options`,并绑定原生产品控制 Provider;智能体不接触原始 Tauri Command。 -- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 333 项子能力都不会写入 system prompt。 +- `OpenBitFunControl list` 和 `search` 都返回带 `nextCursor` 的精简分页结果;目录可持续增长,不靠固定总量上限。完整目录和 334 项子能力都不会写入 system prompt。 - 目录发现与契约读取不依赖 React 或可见窗口。普通配置型 option 统一由 Product Assembly 的共享 ConfigService 执行器读、写并回读,因此 Desktop、CLI 与 Headless 表面走同一份实现;只有宿主原生 operation/provider option 和界面导航按表面注册适配器,缺失时必须明确返回不可用,禁止静默回退本机。只读智能体只能发现和读取目录。 -- Every documented item is classified as direct control, delegated Agent control, interactive opening, or unsupported; opening a page is never counted as direct control. Current coverage is **63 direct**, **70 delegated**, **200 interactive**, and **0 unsupported**. +- Every documented item is classified as direct control, delegated Agent control, interactive opening, or unsupported; opening a page is never counted as direct control. Current coverage is **63 direct**, **71 delegated**, **200 interactive**, and **0 unsupported**. - Stable behavior becomes a typed `operation` or `option` with a JSON input contract and a native product-control provider. Agents never receive raw Tauri commands. -- `OpenBitFunControl list` and `search` return compact pages with a `nextCursor`; the catalog can grow without a fixed total-size ceiling. Neither the full catalog nor its 333 documented items enters the system prompt. +- `OpenBitFunControl list` and `search` return compact pages with a `nextCursor`; the catalog can grow without a fixed total-size ceiling. Neither the full catalog nor its 334 documented items enters the system prompt. - Discovery and contract lookup do not depend on React or a visible window. Ordinary config-backed options are read, written, and read back by one Product Assembly ConfigService executor shared by Desktop, CLI, and headless surfaces. Only host-native operations/provider options and presentation routes install surface adapters; missing adapters return explicit unavailability without local fallback. Read-only agents may only discover and inspect entries. ## 防腐化门禁 / Anti-drift gates diff --git a/docs/interactive-capabilities/capabilities.json b/docs/interactive-capabilities/capabilities.json index c28ab14b20..caa51d800d 100644 --- a/docs/interactive-capabilities/capabilities.json +++ b/docs/interactive-capabilities/capabilities.json @@ -4,9 +4,21 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "eac1f9fc6338c11451dfeb8ff17123dad2d8de1f1339de27eeaa17cb22e5ff66", + "digest": "8a02be2b328791ebb823e4b7a956bf0371c523caa7f881a6c778cbaa42d72575", "ownerDigest": "31d6371f7765bde7bee88e22a6a4f03c2c5370e138cf49975bdc88f3c5eeb052", "searchAcceptance": [ + { + "id": "native-office-generation", + "query": "GenOfficeFile", + "expectedFirstCapabilityId": "feature.ai-assistant", + "expectedCapabilityIds": [ + "feature.ai-assistant" + ], + "expectedItem": { + "capabilityId": "feature.ai-assistant", + "itemId": "office-document-generation" + } + }, { "id": "native-image-generation", "query": "generate_image", @@ -175,10 +187,10 @@ "features": 22, "settings": 22, "userFacing": 44, - "documentedItems": 333, + "documentedItems": 334, "controlCoverage": { "direct": 63, - "delegated": 70, + "delegated": 71, "interactive": 200, "unsupported": 0 } @@ -231,6 +243,7 @@ "model-mode-permissions", "creative-frontend-authoring", "image-generation", + "office-document-generation", "turn-control", "permission-mailbox", "history-search", @@ -517,6 +530,51 @@ "sceneId": "session" } }, + { + "id": "feature.ai-assistant:delegate:office-document-generation", + "capabilityId": "feature.ai-assistant", + "itemIds": [ + "office-document-generation" + ], + "kind": "delegate", + "risk": "execute", + "executionHost": "workspaceHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": true + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "delegateTools": [ + "GenOfficeFile" + ], + "presentationTarget": { + "kind": "scene", + "sceneId": "session" + } + }, { "id": "feature.ai-assistant:open:turn-control", "capabilityId": "feature.ai-assistant", @@ -20593,6 +20651,27 @@ ] } }, + { + "id": "office-document-generation", + "titleZh": "用 GenOfficeFile 创建并编辑 Word、Excel 和 PowerPoint 文件", + "titleEn": "Create and edit Word, Excel, and PowerPoint files with GenOfficeFile", + "control": { + "kind": "delegate", + "tools": [ + "GenOfficeFile" + ], + "workflowZh": [ + "先用 GenOfficeFile guide 读取格式指南,再通过 create 和 edit 分批生成或修改 .docx、.xlsx、.pptx 文件,无需安装 Office", + "用 read 分页查看文档结构;文件和引用图片通过当前工作区文件系统读写,支持本地或远程工作区", + "仅能继续编辑由该工具生成的文件;其他程序改过的内容默认拒绝覆盖,需要用户明确同意丢弃外部修改" + ], + "workflowEn": [ + "Read the format guide with GenOfficeFile guide, then use create and edit to build or revise .docx, .xlsx, and .pptx files in batches without installing Office", + "Use read to page through document structure; documents and referenced images use the active local or remote workspace filesystem", + "Only files generated by this tool can be reopened for editing; external changes are rejected by default and may be discarded only with the user's explicit agreement" + ] + } + }, { "id": "turn-control", "titleZh": "开始、引导、打断、取消或恢复一次智能体运行", @@ -20857,6 +20936,8 @@ "Extend client UI and runtime capabilities in Creative mode", "通过已配置的默认图像模型生成图片", "Generate images with the configured default image model", + "用 GenOfficeFile 创建并编辑 Word、Excel 和 PowerPoint 文件", + "Create and edit Word, Excel, and PowerPoint files with GenOfficeFile", "开始、引导、打断、取消或恢复一次智能体运行", "Start, steer, interrupt, cancel, or recover an agent turn", "查看并逐个或批量回答等待中的权限请求", @@ -20904,6 +20985,13 @@ "Use generate_image to create images from the user's description; omit service_id to use the configured default image model", "Specify count and size when needed and deliver the returned file paths; access remote workspace files through the active workspace data plane", "Report missing configuration, authentication failures, or quota limits explicitly without automatically switching services", + "GenOfficeFile", + "先用 GenOfficeFile guide 读取格式指南,再通过 create 和 edit 分批生成或修改 .docx、.xlsx、.pptx 文件,无需安装 Office", + "用 read 分页查看文档结构;文件和引用图片通过当前工作区文件系统读写,支持本地或远程工作区", + "仅能继续编辑由该工具生成的文件;其他程序改过的内容默认拒绝覆盖,需要用户明确同意丢弃外部修改", + "Read the format guide with GenOfficeFile guide, then use create and edit to build or revise .docx, .xlsx, and .pptx files in batches without installing Office", + "Use read to page through document structure; documents and referenced images use the active local or remote workspace filesystem", + "Only files generated by this tool can be reopened for editing; external changes are rejected by default and may be discarded only with the user's explicit agreement", "ListWorkspaces", "SessionControl", "SessionHistory", diff --git a/docs/interactive-capabilities/capabilities/feature.ai-assistant.md b/docs/interactive-capabilities/capabilities/feature.ai-assistant.md index d2aea4e449..31531ff649 100644 --- a/docs/interactive-capabilities/capabilities/feature.ai-assistant.md +++ b/docs/interactive-capabilities/capabilities/feature.ai-assistant.md @@ -27,6 +27,8 @@ Work with AI in project context, create sessions, continue tasks, answer permiss - Extend client UI and runtime capabilities in Creative mode - **由专用智能体工具控制 / Delegated Agent tool** · `generate_image` · 通过已配置的默认图像模型生成图片 - Generate images with the configured default image model +- **由专用智能体工具控制 / Delegated Agent tool** · `GenOfficeFile` · 用 GenOfficeFile 创建并编辑 Word、Excel 和 PowerPoint 文件 + - Create and edit Word, Excel, and PowerPoint files with GenOfficeFile - **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 开始、引导、打断、取消或恢复一次智能体运行 - Start, steer, interrupt, cancel, or recover an agent turn - **智能体可定位入口,需交互完成 / Agent opens; interaction required** · 查看并逐个或批量回答等待中的权限请求 diff --git a/docs/interactive-capabilities/technical/product-control-open-audit.json b/docs/interactive-capabilities/technical/product-control-open-audit.json index abe3ea40d5..8ebbc9b3c5 100644 --- a/docs/interactive-capabilities/technical/product-control-open-audit.json +++ b/docs/interactive-capabilities/technical/product-control-open-audit.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "eac1f9fc6338c11451dfeb8ff17123dad2d8de1f1339de27eeaa17cb22e5ff66", + "catalogDigest": "8a02be2b328791ebb823e4b7a956bf0371c523caa7f881a6c778cbaa42d72575", "count": 200, "reasonCounts": { "externalAuth": 4, diff --git a/docs/interactive-capabilities/technical/tauri-command-map.json b/docs/interactive-capabilities/technical/tauri-command-map.json index 8da6557530..4445789b4e 100644 --- a/docs/interactive-capabilities/technical/tauri-command-map.json +++ b/docs/interactive-capabilities/technical/tauri-command-map.json @@ -1,7 +1,7 @@ { "schemaVersion": 2, "generatedFrom": "src/shared/interactive-capabilities/catalog.json", - "catalogDigest": "eac1f9fc6338c11451dfeb8ff17123dad2d8de1f1339de27eeaa17cb22e5ff66", + "catalogDigest": "8a02be2b328791ebb823e4b7a956bf0371c523caa7f881a6c778cbaa42d72575", "commandCount": 705, "coverage": { "commandCount": 705, diff --git a/scripts/check-core-boundaries.test.mjs b/scripts/check-core-boundaries.test.mjs index e5483c5f3d..5c8181d106 100644 --- a/scripts/check-core-boundaries.test.mjs +++ b/scripts/check-core-boundaries.test.mjs @@ -730,12 +730,13 @@ test('Services Core text runtime features keep independent exact owner profiles' ]); }); -test('image inspection and generation keep independent exact feature closures', async () => { +test('image inspection, image generation, and office documents keep independent exact feature closures', async () => { const manifestPath = 'src/crates/assembly/core/Cargo.toml'; const manifest = await readFile(new URL(`../${manifestPath}`, import.meta.url), 'utf8'); const features = parseManifestFeatures(manifest); for (const [name, refs] of [ ['tools-image-analysis', ['openbitfun-tool-packs/image-analysis']], + ['tools-office-documents', ['openbitfun-tool-packs/office-documents', 'dep:openbitfun-office-documents']], ['tools-image-generation', [ 'openbitfun-tool-packs/image-generation', 'ai-adapter-runtime', @@ -1526,6 +1527,7 @@ test('Core product-full explicitly assembles service and tool capability owners' 'tools-creation', 'tools-image-analysis', 'tools-image-generation', + 'tools-office-documents', 'tools-miniapp', 'tools-agent-control', ]) { @@ -1899,6 +1901,7 @@ const SDK_HOST_REVIEWED_CORE_FEATURES = [ 'tools-computer-use', 'tools-image-analysis', 'tools-image-generation', + 'tools-office-documents', 'tools-agent-control', ]; diff --git a/scripts/core-boundaries/cargo-dependency-boundaries.mjs b/scripts/core-boundaries/cargo-dependency-boundaries.mjs index 8f45cd2e80..39b6f8a44f 100644 --- a/scripts/core-boundaries/cargo-dependency-boundaries.mjs +++ b/scripts/core-boundaries/cargo-dependency-boundaries.mjs @@ -1458,6 +1458,7 @@ export function findProductEntrypointCoreFeatureViolations( 'tools-computer-use', 'tools-image-analysis', 'tools-image-generation', + 'tools-office-documents', 'tools-agent-control', ]; const CORE_TEST_SUPPORT_FEATURE = 'test-support'; @@ -1521,6 +1522,7 @@ export function findProductEntrypointCoreFeatureViolations( 'tools-git', 'tools-image-analysis', 'tools-image-generation', + 'tools-office-documents', 'tools-mcp', 'tools-miniapp', 'web-tools', diff --git a/scripts/core-boundaries/rules/crate-layout.mjs b/scripts/core-boundaries/rules/crate-layout.mjs index 5cd733d3e1..1c41d1776a 100644 --- a/scripts/core-boundaries/rules/crate-layout.mjs +++ b/scripts/core-boundaries/rules/crate-layout.mjs @@ -16,6 +16,7 @@ export const crateLayoutRules = [ { crateName: 'runtime-services', layer: 'execution', path: 'src/crates/execution/runtime-services' }, { crateName: 'tool-packs', layer: 'execution', path: 'src/crates/execution/tool-provider-groups' }, { crateName: 'tool-runtime', layer: 'execution', path: 'src/crates/execution/tool-execution' }, + { crateName: 'office-documents', layer: 'execution', path: 'src/crates/execution/office-documents' }, { crateName: 'agent-content', layer: 'assembly', path: 'src/crates/assembly/agent-content' }, { crateName: 'product-capabilities', layer: 'assembly', path: 'src/crates/assembly/product-capabilities' }, diff --git a/scripts/core-boundaries/rules/crate-rules.mjs b/scripts/core-boundaries/rules/crate-rules.mjs index 8e3667c7c4..8c76ad8579 100644 --- a/scripts/core-boundaries/rules/crate-rules.mjs +++ b/scripts/core-boundaries/rules/crate-rules.mjs @@ -72,6 +72,7 @@ export const noCoreDependencyCrates = [ 'external-sources', 'terminal', 'tool-runtime', + 'office-documents', 'transport', 'webdriver', ]; diff --git a/scripts/core-boundaries/rules/feature-rules.mjs b/scripts/core-boundaries/rules/feature-rules.mjs index fc13e5f281..2e5565cd0f 100644 --- a/scripts/core-boundaries/rules/feature-rules.mjs +++ b/scripts/core-boundaries/rules/feature-rules.mjs @@ -173,6 +173,7 @@ export const optionalDependencyFeatureOwnerRules = [ }, { depName: 'openbitfun-agent-runtime', ownerFeatures: ['agent-runtime', 'ai-adapter-runtime'] }, { depName: 'openbitfun-agent-workflows', ownerFeatures: ['deep-research'] }, + { depName: 'openbitfun-office-documents', ownerFeatures: ['tools-office-documents'] }, { depName: 'openbitfun-agent-stream', ownerFeatures: ['agent-runtime'] }, { depName: 'openbitfun-agent-tools', ownerFeatures: ['agent-runtime', 'local-storage', 'mcp-runtime'] }, { depName: 'openbitfun-claude-code-adapter', ownerFeatures: ['external-sources'] }, @@ -233,6 +234,7 @@ export const optionalDependencyFeatureOwnerRules = [ 'tools-git', 'tools-image-analysis', 'tools-image-generation', + 'tools-office-documents', 'tools-mcp', 'tools-miniapp', 'tools-pages', @@ -747,6 +749,7 @@ export const coreProductFullFeatureAssemblyRule = { 'tools-git', 'tools-image-analysis', 'tools-image-generation', + 'tools-office-documents', 'tools-mcp', 'tools-miniapp', 'tools-pages', @@ -791,6 +794,7 @@ export const acpServerCoreFeatures = [ 'tools-computer-use', 'tools-image-analysis', 'tools-image-generation', + 'tools-office-documents', 'tools-agent-control', ]; @@ -1395,6 +1399,16 @@ export const coreClosedFeatureProfileRules = [ exact: true, reason: 'tools-image-generation owns image generation with its configured AI client and wire adapter', }, + { + manifestPath: 'src/crates/assembly/core/Cargo.toml', + featureName: 'tools-office-documents', + requiredFeatureRefs: [ + 'openbitfun-tool-packs/office-documents', + 'dep:openbitfun-office-documents', + ], + exact: true, + reason: 'tools-office-documents owns Office file generation with only its portable OOXML engine', + }, { manifestPath: 'src/crates/assembly/core/Cargo.toml', featureName: 'tools-pages', @@ -1833,6 +1847,7 @@ export const ownerCrateFeatureAssemblyRules = [ 'computer-use', 'image-analysis', 'image-generation', + 'office-documents', 'miniapp', 'pages', 'creation', diff --git a/scripts/core-boundaries/self-test.mjs b/scripts/core-boundaries/self-test.mjs index 76ae223fc1..b3b701a635 100644 --- a/scripts/core-boundaries/self-test.mjs +++ b/scripts/core-boundaries/self-test.mjs @@ -629,6 +629,7 @@ export function runManifestParserSelfTest({ 'openbitfun-core/tools-computer-use', 'openbitfun-core/tools-image-analysis', 'openbitfun-core/tools-image-generation', + 'openbitfun-core/tools-office-documents', 'openbitfun-core/tools-agent-control', ], ], diff --git a/src/apps/cli/Cargo.toml b/src/apps/cli/Cargo.toml index 299ddb0d5d..7db90780c9 100644 --- a/src/apps/cli/Cargo.toml +++ b/src/apps/cli/Cargo.toml @@ -52,6 +52,7 @@ openbitfun-core = { path = "../../crates/assembly/core", features = [ "tools-computer-use", "tools-image-analysis", "tools-image-generation", + "tools-office-documents", "tools-agent-control", ] } openbitfun-events = { path = "../../crates/contracts/events" } diff --git a/src/apps/sdk-host/Cargo.toml b/src/apps/sdk-host/Cargo.toml index c5647c0cd1..e1f902e984 100644 --- a/src/apps/sdk-host/Cargo.toml +++ b/src/apps/sdk-host/Cargo.toml @@ -26,6 +26,7 @@ openbitfun-core = { path = "../../crates/assembly/core", features = [ "tools-computer-use", "tools-image-analysis", "tools-image-generation", + "tools-office-documents", "tools-agent-control", ] } openbitfun-sdk-host = { path = "../../crates/interfaces/sdk-host" } diff --git a/src/crates/assembly/core/AGENTS.md b/src/crates/assembly/core/AGENTS.md index 386d92ab05..02e71c3e41 100644 --- a/src/crates/assembly/core/AGENTS.md +++ b/src/crates/assembly/core/AGENTS.md @@ -116,6 +116,9 @@ SessionManager -> Session -> DialogTurn -> ModelRound Tool implementation groups use the matching `tools-*` owner feature. `tools-image-analysis` owns only image inspection; `tools-image-generation` separately selects the generation tool and its AI adapter client. + `tools-office-documents` owns `GenOfficeFile` and its portable OOXML engine + (`openbitfun-office-documents`); the tool moves bytes only through the + session's workspace file system, so remote workspaces need no extra owner. Product Assembly supplies the exact `ProductToolPlan`; Core materialization validates that requested owners were compiled and must not infer product capability from Cargo's feature union. The Agent Runtime baseline plan is @@ -261,6 +264,13 @@ cargo test --locked -p openbitfun-core --no-default-features --features agent-ru cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git,tools-image-analysis --lib agentic::tools::product_runtime::materialization::tests::image_tools_follow_independent_compiled_owners ``` +For Office file generation (`GenOfficeFile`); the engine itself is covered by +`cargo test -p openbitfun-office-documents`: + +```bash +cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git,tools-office-documents --lib agentic::tools::implementations::gen_office_file_tool::tests +``` + These fixtures do not call a provider or exercise live remote hosts. Image wire protocol and opt-in live probes belong to the AI adapters guide. diff --git a/src/crates/assembly/core/Cargo.toml b/src/crates/assembly/core/Cargo.toml index 6036df67c0..1efe32a679 100644 --- a/src/crates/assembly/core/Cargo.toml +++ b/src/crates/assembly/core/Cargo.toml @@ -78,6 +78,7 @@ openbitfun-agent-tools = { path = "../../execution/tool-contracts", optional = t # Tool pack provider plan openbitfun-tool-packs = { path = "../../execution/tool-provider-groups", optional = true } +openbitfun-office-documents = { path = "../../execution/office-documents", optional = true } # Core service owner crate openbitfun-services-core = { path = "../../services/services-core", features = ["json-io", "product-identity", "workspace-identity"] } @@ -171,6 +172,7 @@ product-full = [ "tools-computer-use", "tools-image-analysis", "tools-image-generation", + "tools-office-documents", "tools-miniapp", "tools-pages", "tools-creation", @@ -384,6 +386,10 @@ tools-image-generation = [ "ai-adapter-runtime", "openbitfun-ai-adapters/image-generation", ] +tools-office-documents = [ + "openbitfun-tool-packs/office-documents", + "dep:openbitfun-office-documents", +] tools-miniapp = [ "dep:openbitfun-product-domains", "openbitfun-tool-packs/miniapp", diff --git a/src/crates/assembly/core/builtin_skills/create-agent/references/tool-catalog.md b/src/crates/assembly/core/builtin_skills/create-agent/references/tool-catalog.md index 47a2b552d6..35fe54b65c 100644 --- a/src/crates/assembly/core/builtin_skills/create-agent/references/tool-catalog.md +++ b/src/crates/assembly/core/builtin_skills/create-agent/references/tool-catalog.md @@ -18,6 +18,7 @@ Use these tables to select tools for the user's tasks, then put their exact name | `Write` | Create or overwrite a file. | | `Edit` | Make targeted changes to existing file contents. | | `Delete` | Delete a file or directory. | +| `GenOfficeFile` | Create and incrementally edit Word (.docx), Excel (.xlsx), and PowerPoint (.pptx) files. | ## Command execution diff --git a/src/crates/assembly/core/src/agentic/agents/definitions/modes/claw.rs b/src/crates/assembly/core/src/agentic/agents/definitions/modes/claw.rs index dfa6b1b559..9f7cf7ea50 100644 --- a/src/crates/assembly/core/src/agentic/agents/definitions/modes/claw.rs +++ b/src/crates/assembly/core/src/agentic/agents/definitions/modes/claw.rs @@ -29,6 +29,7 @@ impl ClawMode { "Write".to_string(), "Edit".to_string(), "Delete".to_string(), + "GenOfficeFile".to_string(), "ExecCommand".to_string(), "WriteStdin".to_string(), "ExecControl".to_string(), diff --git a/src/crates/assembly/core/src/agentic/agents/definitions/modes/creative.rs b/src/crates/assembly/core/src/agentic/agents/definitions/modes/creative.rs index b81a94209f..79ea62076b 100644 --- a/src/crates/assembly/core/src/agentic/agents/definitions/modes/creative.rs +++ b/src/crates/assembly/core/src/agentic/agents/definitions/modes/creative.rs @@ -29,6 +29,7 @@ impl CreativeHarness { "FinalizeMiniApp", "PublishMiniApp", "FrontendWorkbench", + "GenOfficeFile", ] .into_iter() .map(str::to_string), diff --git a/src/crates/assembly/core/src/agentic/agents/definitions/modes/standard.rs b/src/crates/assembly/core/src/agentic/agents/definitions/modes/standard.rs index e22f31243f..a2ae48c322 100644 --- a/src/crates/assembly/core/src/agentic/agents/definitions/modes/standard.rs +++ b/src/crates/assembly/core/src/agentic/agents/definitions/modes/standard.rs @@ -23,6 +23,7 @@ impl StandardHarness { let mut default_tools = standard_harness_tools(); default_tools.push("ComputerUse".to_string()); default_tools.push("DesktopCard".to_string()); + default_tools.push("GenOfficeFile".to_string()); Self { default_tools } } } diff --git a/src/crates/assembly/core/src/agentic/agents/definitions/modes/ultimate.rs b/src/crates/assembly/core/src/agentic/agents/definitions/modes/ultimate.rs index caefccac2d..19ec229942 100644 --- a/src/crates/assembly/core/src/agentic/agents/definitions/modes/ultimate.rs +++ b/src/crates/assembly/core/src/agentic/agents/definitions/modes/ultimate.rs @@ -25,6 +25,7 @@ impl UltimateHarness { "Edit", "Write", "Delete", + "GenOfficeFile", "Grep", "Glob", "AskUserQuestion", diff --git a/src/crates/assembly/core/src/agentic/agents/mod.rs b/src/crates/assembly/core/src/agentic/agents/mod.rs index 667191ce0e..5c779625ce 100644 --- a/src/crates/assembly/core/src/agentic/agents/mod.rs +++ b/src/crates/assembly/core/src/agentic/agents/mod.rs @@ -319,6 +319,7 @@ mod tests { let mut expected = shared_tools; expected.push("ComputerUse".to_string()); expected.push("DesktopCard".to_string()); + expected.push("GenOfficeFile".to_string()); assert_eq!(StandardHarness::new().default_tools(), expected); } @@ -333,6 +334,25 @@ mod tests { #[cfg(test)] mod desktop_tool_tests { use super::*; + #[test] + fn document_producing_modes_include_office_file_generation() { + let modes: Vec> = vec![ + Box::new(StandardHarness::new()), + Box::new(UltimateHarness::new()), + Box::new(CreativeHarness::new()), + Box::new(ClawMode::new()), + ]; + for mode in modes { + assert!( + mode.default_tools() + .iter() + .any(|name| name == "GenOfficeFile"), + "{} should expose GenOfficeFile by default", + mode.id() + ); + } + } + #[test] fn main_desktop_modes_include_computer_use() { let modes: Vec> = vec![ diff --git a/src/crates/assembly/core/src/agentic/tools/agent-tool-exposure.md b/src/crates/assembly/core/src/agentic/tools/agent-tool-exposure.md index 207b1dd884..d14f44a8e7 100644 --- a/src/crates/assembly/core/src/agentic/tools/agent-tool-exposure.md +++ b/src/crates/assembly/core/src/agentic/tools/agent-tool-exposure.md @@ -37,6 +37,7 @@ Notes: | `Write` | Direct | None | - | | `Edit` | Direct | None | - | | `Delete` | Direct | None | - | +| `GenOfficeFile` | Direct | None | - | | `ExecCommand` | Direct | None | - | | `WriteStdin` | Direct | None | - | | `ExecControl` | Direct | None | - | diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/gen_office_file_tool.rs b/src/crates/assembly/core/src/agentic/tools/implementations/gen_office_file_tool.rs new file mode 100644 index 0000000000..338507925e --- /dev/null +++ b/src/crates/assembly/core/src/agentic/tools/implementations/gen_office_file_tool.rs @@ -0,0 +1,908 @@ +//! GenOfficeFile: incremental Word, Excel, and PowerPoint generation. +//! +//! The document model and package writers live in +//! `openbitfun-office-documents`; this tool resolves paths, loads referenced +//! images, and moves bytes through the session's workspace file system so it +//! works the same for local and remote workspaces. +//! GenOffice reference attribution and licenses are kept beside the engine +//! in `src/crates/execution/office-documents/README.md`. + +use crate::agentic::tools::file_permissions::file_permission_intents; +use crate::agentic::tools::framework::{ + PermissionIntent, Tool, ToolRenderOptions, ToolResult, ToolUseContext, ValidationResult, +}; +use crate::agentic::tools::ToolPathOperation; +use crate::util::errors::{OpenBitFunError, OpenBitFunResult}; +use async_trait::async_trait; +use openbitfun_office_documents::{ + collect_image_sources, guide, Detail, ImageSources, OfficeDocument, OfficeError, OfficeFormat, + OpenOptions, ReadRequest, +}; +use serde_json::{json, Value}; + +const TOOL_NAME: &str = "GenOfficeFile"; +const MAX_DOCUMENT_BYTES: usize = 200 * 1024 * 1024; +const MAX_IMAGE_BYTES: usize = 25 * 1024 * 1024; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Action { + Create, + Edit, + Read, + Guide, +} + +impl Action { + fn parse(input: &Value) -> Result { + match input.get("action").and_then(Value::as_str) { + Some("create") => Ok(Self::Create), + Some("edit") => Ok(Self::Edit), + Some("read") => Ok(Self::Read), + Some("guide") => Ok(Self::Guide), + Some(other) => Err(format!( + "unknown action `{other}`; use create, edit, read, or guide" + )), + None => Err("`action` is required: create, edit, read, or guide".to_string()), + } + } + + const fn as_str(self) -> &'static str { + match self { + Self::Create => "create", + Self::Edit => "edit", + Self::Read => "read", + Self::Guide => "guide", + } + } + + const fn writes(self) -> bool { + matches!(self, Self::Create | Self::Edit) + } +} + +pub struct GenOfficeFileTool; + +impl Default for GenOfficeFileTool { + fn default() -> Self { + Self::new() + } +} + +impl GenOfficeFileTool { + pub fn new() -> Self { + Self + } + + fn file_path(input: &Value) -> Option<&str> { + input + .get("file_path") + .and_then(Value::as_str) + .map(str::trim) + .filter(|path| !path.is_empty()) + } + + fn operations(input: &Value) -> Result, String> { + match input.get("operations") { + None | Some(Value::Null) => Ok(Vec::new()), + Some(Value::Array(items)) => { + if let Some(index) = items.iter().position(|item| !item.is_object()) { + return Err(format!( + "operations[{index}] must be an object with an `op` field" + )); + } + Ok(items.clone()) + } + Some(_) => Err("`operations` must be an array of operation objects".to_string()), + } + } + + fn format_for(input: &Value, action: Action) -> Result { + if action == Action::Guide { + if let Some(name) = input.get("format").and_then(Value::as_str) { + return OfficeFormat::from_name(name) + .ok_or_else(|| format!("unknown format `{name}`; use docx, xlsx, or pptx")); + } + } + let path = Self::file_path(input).ok_or_else(|| match action { + Action::Guide => "guide needs `format` (docx, xlsx, pptx) or a `file_path`".to_string(), + _ => "`file_path` is required".to_string(), + })?; + OfficeFormat::from_path(path) + .ok_or_else(|| format!("`{path}` must end in .docx, .xlsx, or .pptx")) + } + + /// Checks everything that does not need the file system. + fn check_input(input: &Value) -> Result<(Action, OfficeFormat), String> { + let action = Action::parse(input)?; + let format = Self::format_for(input, action)?; + let operations = Self::operations(input)?; + if action == Action::Edit && operations.is_empty() { + return Err("edit needs a non-empty `operations` array".to_string()); + } + if !action.writes() && !operations.is_empty() { + return Err(format!( + "`operations` is only used by create and edit, not {}", + action.as_str() + )); + } + if input + .get("settings") + .is_some_and(|settings| !settings.is_null()) + && action != Action::Create + { + return Err("`settings` is only used by create; change settings later with operations such as set_page_setup, set_styles, or set_theme".to_string()); + } + if let Some(detail) = input.get("detail").and_then(Value::as_str) { + if !matches!(detail, "outline" | "full") { + return Err("`detail` must be outline or full".to_string()); + } + } + if (input.get("sheet").is_some() || input.get("range").is_some()) + && format != OfficeFormat::Xlsx + { + return Err("`sheet` and `range` only apply to .xlsx files".to_string()); + } + Ok((action, format)) + } + + fn read_request(input: &Value) -> ReadRequest { + ReadRequest { + offset: input + .get("offset") + .and_then(Value::as_u64) + .map(|value| value as usize), + limit: input + .get("limit") + .and_then(Value::as_u64) + .map(|value| value as usize), + detail: match input.get("detail").and_then(Value::as_str) { + Some("full") => Detail::Full, + _ => Detail::Outline, + }, + sheet: input + .get("sheet") + .and_then(Value::as_str) + .map(str::to_string), + range: input + .get("range") + .and_then(Value::as_str) + .map(str::to_string), + } + } + + fn office_error(error: OfficeError) -> OpenBitFunError { + OpenBitFunError::tool(format!( + "{error}. Fix the reported problem and resend the whole batch; nothing was written. Use action=guide for the field reference." + )) + } + + /// Loads image files referenced by the operations through the workspace + /// file system, keyed by the exact source string the operations use. + async fn load_images( + context: &ToolUseContext, + operations: &[Value], + ) -> OpenBitFunResult { + let mut images = ImageSources::new(); + for source in collect_image_sources(operations) { + let lower = source.to_ascii_lowercase(); + if lower.starts_with("http://") || lower.starts_with("https://") { + return Err(OpenBitFunError::tool(format!( + "image `{source}` is a web URL; download it to a local file first (for example with ExecCommand) and pass the absolute file path" + ))); + } + let resolved = context.resolve_tool_path(&source)?; + context.enforce_path_operation(ToolPathOperation::Read, &resolved)?; + let bytes = context + .file_system_for_path(&resolved)? + .read_file_bounded(&resolved.resolved_path, MAX_IMAGE_BYTES) + .await + .map_err(|error| { + OpenBitFunError::tool(format!( + "cannot read image {}: {error:#}", + resolved.logical_path + )) + })? + .ok_or_else(|| { + OpenBitFunError::tool(format!( + "image {} is larger than {} MB", + resolved.logical_path, + MAX_IMAGE_BYTES / 1024 / 1024 + )) + })?; + images.insert(source, bytes); + } + Ok(images) + } + + fn now() -> String { + chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) + } + + fn parent_directory(path: &str, remote: bool) -> Option { + if remote { + return path + .rsplit_once('/') + .map(|(parent, _)| parent.to_string()) + .filter(|parent| !parent.is_empty()); + } + std::path::Path::new(path) + .parent() + .map(|parent| parent.to_string_lossy().into_owned()) + .filter(|parent| !parent.is_empty()) + } + + fn summary_text( + action: Action, + path: &str, + document: &OfficeDocument, + changes: &[String], + warnings: &[String], + ) -> String { + let format = document.format(); + let counts = document.summary(); + let count = match format { + OfficeFormat::Docx => format!("{} block(s)", counts["blocks"]), + OfficeFormat::Xlsx => format!("{} sheet(s)", counts["sheets"]), + OfficeFormat::Pptx => format!("{} slide(s)", counts["slides"]), + }; + let verb = if action == Action::Create { + "Created" + } else { + "Updated" + }; + let mut text = format!( + "{verb} {path} ({}, {count}, revision {}).", + format.as_str(), + document.revision() + ); + if !changes.is_empty() { + text.push_str("\nChanges:"); + for change in changes.iter().take(30) { + text.push_str("\n- "); + text.push_str(change); + } + } + if !warnings.is_empty() { + text.push_str("\nWarnings (fix them with a follow-up edit when they matter):"); + for warning in warnings { + text.push_str("\n- "); + text.push_str(warning); + } + } + text + } + + fn description_text() -> String { + r#"Create and incrementally edit real Office files: Word (.docx), Excel (.xlsx), and PowerPoint (.pptx). The format comes from the file extension. Use this instead of writing scripts when the user wants an Office document, report, spreadsheet, workbook, slide deck, or presentation. + +Build large documents over several calls instead of one: create the file with a first batch, then append or change content with `edit` (one section, a few slides, or a chunk of rows per call). Every call applies a batch of `operations` atomically (all or nothing) and rewrites the file. The editable source travels inside the file, so later calls can keep editing it. + +Actions: +- `create`: new file at `file_path` (absolute). Optional `settings` (document-level defaults) and `operations`. Refuses to replace an existing file unless `overwrite: true`. +- `edit`: apply `operations` to a file this tool created. +- `read`: page through the structure with `offset`/`limit`; `detail: "full"` returns the stored model of each unit (with indexes and embedded image `asset` names) for precise edits. For .xlsx, pass `sheet` to page rows or `range` (A1:D20) to read cells. +- `guide`: the complete field and operation reference for `format` (docx | xlsx | pptx). Call it before the first create or edit of a format in a session. + +Operations by format (each is `{"op": "...", ...}`): +- docx — blocks are 0-based: `insert_blocks` {index?, blocks | markdown}, `replace_blocks` {index, count?, blocks | markdown}, `delete_blocks` {index, count?}, `move_blocks` {index, count?, to}, `replace_text`, `set_page_setup`, `set_styles`, `set_header_footer` ({PAGE}/{NUMPAGES} fields), `set_properties`. Block types: heading, paragraph, list, table, image, code, quote, page_break, horizontal_rule, toc. Markdown (headings, lists, tables, code, quotes, links, images, [TOC]) is the fastest way to add content. +- xlsx — sheets by name: `add_sheet`, `delete_sheet`, `rename_sheet`, `move_sheet`, `set_cells` {sheet, start, rows}, `append_rows` {sheet, rows}, `insert_rows`/`delete_rows`/`insert_columns`/`delete_columns` (references shift), `clear_range`, `format_range` {range, style}, `set_column_widths`, `set_row_heights`, `merge_cells`, `unmerge_cells`, `freeze_panes`, `set_autofilter`, `set_sheet`, `set_properties`. Cell values: numbers, booleans, text, "=FORMULA", or {value, type: date|text|number, style}. +- pptx — slides are 0-based on a 1280×720 px canvas (16:9) with absolutely positioned elements (text, shape, image, table): `insert_slides` {index?, slides}, `replace_slide`, `update_slide` {index, update_elements/remove_elements/append_elements, background, notes}, `delete_slides`, `move_slides`, `duplicate_slide`, `set_theme`, `set_properties`. After each batch the touched slides are audited for text overflow and off-canvas elements. + +Images (docx image blocks, pptx image elements, Markdown images) take an absolute local path or a data URL (PNG, JPEG, GIF, BMP). Download web images first. + +Files this tool did not create cannot be edited; read them with the Read tool and create a new file. If another program changed a generated file, edit refuses unless `discard_external_changes: true` (which rebuilds from the last GenOfficeFile state and drops the outside changes)."# + .to_string() + } +} + +#[async_trait] +impl Tool for GenOfficeFileTool { + fn name(&self) -> &str { + TOOL_NAME + } + + async fn description(&self) -> OpenBitFunResult { + Ok(Self::description_text()) + } + + fn short_description(&self) -> String { + "Create and incrementally edit Word, Excel, and PowerPoint files.".to_string() + } + + fn input_schema(&self) -> Value { + json!({ + "type": "object", + "properties": { + "action": { + "type": "string", + "enum": ["create", "edit", "read", "guide"], + "description": "create a new file, edit a generated file, read its structure page by page, or get the field reference for a format." + }, + "file_path": { + "type": "string", + "description": "Absolute path of the .docx, .xlsx, or .pptx file. Required except for guide with `format`." + }, + "format": { + "type": "string", + "enum": ["docx", "xlsx", "pptx"], + "description": "guide only: which format's reference to return." + }, + "operations": { + "type": "array", + "description": "create/edit: ordered batch of operations, applied atomically. Each item is an object with `op` plus that operation's fields (see action=guide).", + "items": { + "type": "object", + "properties": { "op": { "type": "string" } }, + "required": ["op"], + "additionalProperties": true + } + }, + "settings": { + "type": "object", + "description": "create only: document-level defaults. docx: page, styles, header, footer, properties. pptx: slide_size (\"16:9\" | \"4:3\"), theme {font, east_asia_font, text_color}, properties. xlsx: properties.", + "additionalProperties": true + }, + "overwrite": { + "type": "boolean", + "description": "create only: replace an existing file at file_path." + }, + "discard_external_changes": { + "type": "boolean", + "description": "edit/read: proceed even though another program changed the file; edits rebuild from the last GenOfficeFile state." + }, + "offset": { "type": "integer", "minimum": 0, "description": "read: first unit (block, slide, sheet, or row) to return." }, + "limit": { "type": "integer", "minimum": 1, "maximum": 500, "description": "read: number of units to return." }, + "detail": { "type": "string", "enum": ["outline", "full"], "description": "read: outline (default) or the full stored model of each unit." }, + "sheet": { "type": "string", "description": "read, xlsx: sheet whose rows to return." }, + "range": { "type": "string", "description": "read, xlsx: A1 range of `sheet` to return, such as A1:F40." } + }, + "required": ["action"], + "additionalProperties": false + }) + } + + fn output_schema(&self) -> Value { + json!({ + "type": "object", + "properties": { + "action": { "type": "string" }, + "format": { "type": "string" }, + "file_path": { "type": "string" }, + "revision": { "type": "integer" }, + "bytes": { "type": "integer" }, + "counts": { "type": "object" }, + "changes": { "type": "array", "items": { "type": "string" } }, + "warnings": { "type": "array", "items": { "type": "string" } }, + "view": { "type": "object" }, + "guide": { "type": "string" } + }, + "required": ["action", "format"], + "additionalProperties": true + }) + } + + fn is_readonly(&self) -> bool { + false + } + + fn is_concurrency_safe(&self, input: Option<&Value>) -> bool { + input + .and_then(|input| Action::parse(input).ok()) + .is_some_and(|action| !action.writes()) + } + + fn permission_intents( + &self, + input: &Value, + context: &ToolUseContext, + ) -> OpenBitFunResult> { + let action = Action::parse(input).map_err(OpenBitFunError::validation)?; + let Some(file_path) = Self::file_path(input) else { + return Ok(Vec::new()); + }; + if action == Action::Guide { + return Ok(Vec::new()); + } + if !action.writes() { + return file_permission_intents("read", [file_path], context); + } + let mut intents = file_permission_intents("edit", [file_path], context)?; + let operations = Self::operations(input).unwrap_or_default(); + let images: Vec = collect_image_sources(&operations) + .into_iter() + .filter(|source| { + let lower = source.to_ascii_lowercase(); + !lower.starts_with("http://") && !lower.starts_with("https://") + }) + .collect(); + if !images.is_empty() { + intents.extend(file_permission_intents( + "read", + images.iter().map(String::as_str), + context, + )?); + } + Ok(intents) + } + + async fn validate_input( + &self, + input: &Value, + context: Option<&ToolUseContext>, + ) -> ValidationResult { + let reject = |message: String| ValidationResult { + result: false, + message: Some(message), + error_code: Some(400), + meta: None, + }; + let (action, _) = match Self::check_input(input) { + Ok(parsed) => parsed, + Err(message) => return reject(message), + }; + if !action.writes() { + return ValidationResult::default(); + } + let Some(file_path) = Self::file_path(input) else { + return reject("`file_path` is required".to_string()); + }; + if let Some(rejection) = crate::agentic::execution::edit_constraint_guard::check_write( + context, TOOL_NAME, "write", file_path, false, + ) + .await + { + return rejection; + } + if let Some(context) = context { + let resolved = match context.resolve_tool_path(file_path) { + Ok(resolved) => resolved, + Err(error) => return reject(error.to_string()), + }; + if let Err(error) = context.enforce_path_operation(ToolPathOperation::Write, &resolved) + { + return reject(error.to_string()); + } + } + ValidationResult::default() + } + + fn render_tool_use_message(&self, input: &Value, _options: &ToolRenderOptions) -> String { + let action = Action::parse(input).map(Action::as_str).unwrap_or("use"); + let operations = Self::operations(input).map(|ops| ops.len()).unwrap_or(0); + match (Self::file_path(input), operations) { + (Some(path), 0) => format!("GenOfficeFile {action} {path}"), + (Some(path), count) => format!("GenOfficeFile {action} {path} ({count} operation(s))"), + (None, _) => format!( + "GenOfficeFile {action} {}", + input.get("format").and_then(Value::as_str).unwrap_or("") + ), + } + } + + fn render_tool_result_message(&self, output: &Value) -> String { + let action = output.get("action").and_then(Value::as_str).unwrap_or(""); + let path = output + .get("file_path") + .and_then(Value::as_str) + .unwrap_or(""); + match action { + "create" => format!("Created {path}"), + "edit" => format!("Updated {path}"), + "read" => format!("Read {path}"), + _ => "Returned the GenOfficeFile guide".to_string(), + } + } + + async fn call_impl( + &self, + input: &Value, + context: &ToolUseContext, + ) -> OpenBitFunResult> { + let (action, format) = Self::check_input(input).map_err(OpenBitFunError::tool)?; + if action == Action::Guide { + let text = guide(format); + return Ok(vec![ToolResult::ok( + json!({ "action": "guide", "format": format.as_str(), "guide": text }), + Some(text.to_string()), + )]); + } + + let file_path = Self::file_path(input) + .ok_or_else(|| OpenBitFunError::tool("`file_path` is required".to_string()))?; + let resolved = context.resolve_tool_path(file_path)?; + let operation = if action.writes() { + ToolPathOperation::Write + } else { + ToolPathOperation::Read + }; + context.enforce_path_operation(operation, &resolved)?; + let fs = context.file_system_for_path(&resolved)?; + let exists = fs.exists(&resolved.resolved_path).await.map_err(|error| { + OpenBitFunError::tool(format!("cannot check {}: {error:#}", resolved.logical_path)) + })?; + let open_options = OpenOptions { + discard_external_changes: input + .get("discard_external_changes") + .and_then(Value::as_bool) + .unwrap_or(false), + }; + + let existing = if action == Action::Create { + if exists + && !input + .get("overwrite") + .and_then(Value::as_bool) + .unwrap_or(false) + { + return Err(OpenBitFunError::tool(format!( + "{} already exists. Use action=edit to change a file this tool created, pick another path, or pass overwrite=true to replace it.", + resolved.logical_path + ))); + } + None + } else { + if !exists { + return Err(OpenBitFunError::tool(format!( + "{} does not exist; use action=create first", + resolved.logical_path + ))); + } + let bytes = fs + .read_file_bounded(&resolved.resolved_path, MAX_DOCUMENT_BYTES) + .await + .map_err(|error| { + OpenBitFunError::tool(format!( + "cannot read {}: {error:#}", + resolved.logical_path + )) + })? + .ok_or_else(|| { + OpenBitFunError::tool(format!("{} is too large to edit", resolved.logical_path)) + })?; + Some(OfficeDocument::open(&bytes, &open_options).map_err(Self::office_error)?) + }; + + if action == Action::Read { + let document = existing.expect("read opens the existing document"); + let mut view = document + .read(&Self::read_request(input)) + .map_err(Self::office_error)?; + if document.format() == OfficeFormat::Pptx + && input.get("offset").and_then(Value::as_u64).unwrap_or(0) == 0 + { + let findings = document.audit(); + if !findings.is_empty() { + view["audit"] = json!(findings); + } + } + let text = serde_json::to_string_pretty(&view).unwrap_or_default(); + return Ok(vec![ToolResult::ok( + json!({ + "action": "read", + "format": format.as_str(), + "file_path": resolved.logical_path, + "view": view, + }), + Some(text), + )]); + } + + let mut document = match existing { + Some(document) => document, + None => { + OfficeDocument::new(format, input.get("settings")).map_err(Self::office_error)? + } + }; + if document.format() != format { + return Err(OpenBitFunError::tool(format!( + "{} holds a {} document; keep its original extension", + resolved.logical_path, + document.format().as_str() + ))); + } + let operations = Self::operations(input).map_err(OpenBitFunError::tool)?; + let images = Self::load_images(context, &operations).await?; + let report = document + .apply(&operations, &images) + .map_err(Self::office_error)?; + document.touch(&Self::now()); + let bytes = document.to_bytes().map_err(Self::office_error)?; + + context + .record_light_checkpoint( + TOOL_NAME, + &resolved.logical_path, + vec![resolved.logical_path.clone()], + ) + .await?; + if !exists { + if let Some(parent) = Self::parent_directory( + &resolved.resolved_path, + resolved.uses_remote_workspace_backend(), + ) { + // Providers without directory creation still create parents on write. + let _ = fs.create_dir_all(&parent).await; + } + } + fs.write_file(&resolved.resolved_path, &bytes) + .await + .map_err(|error| { + OpenBitFunError::tool(format!("cannot write {}: {error:#}", resolved.logical_path)) + })?; + crate::agentic::execution::edit_constraint_guard::record_mutation_applied( + context, + TOOL_NAME, + "write", + &resolved.logical_path, + ) + .await; + if !exists { + crate::agentic::execution::edit_constraint_guard::remember_agent_created_file( + context, + &resolved.logical_path, + ) + .await; + } + + let text = Self::summary_text( + action, + &resolved.logical_path, + &document, + &report.changes, + &report.warnings, + ); + Ok(vec![ToolResult::ok( + json!({ + "action": action.as_str(), + "format": format.as_str(), + "file_path": resolved.logical_path, + "revision": document.revision(), + "bytes": bytes.len(), + "counts": document.summary(), + "changes": report.changes, + "warnings": report.warnings, + }), + Some(text), + )]) + } +} + +#[cfg(test)] +mod tests { + use super::GenOfficeFileTool; + use crate::agentic::tools::framework::{Tool, ToolResult, ToolUseContext}; + use crate::agentic::tools::ToolRuntimeRestrictions; + use crate::agentic::WorkspaceBinding; + use async_trait::async_trait; + use openbitfun_runtime_ports::{ + ToolRuntimeHandles, WorkspaceCommandOptions, WorkspaceCommandResult, WorkspaceDirEntry, + WorkspaceFileSystem, WorkspaceServices, WorkspaceShell, + }; + use serde_json::{json, Value}; + use std::collections::HashMap; + use std::path::PathBuf; + use std::sync::{Arc, Mutex}; + + /// Workspace file system backed by a map, standing in for a local or SSH provider. + #[derive(Default)] + struct MemoryFs { + files: Mutex>>, + } + + #[async_trait] + impl WorkspaceFileSystem for MemoryFs { + async fn read_file(&self, path: &str) -> anyhow::Result> { + self.files + .lock() + .unwrap() + .get(path) + .cloned() + .ok_or_else(|| anyhow::anyhow!("no such file: {path}")) + } + + async fn read_file_text(&self, path: &str) -> anyhow::Result { + Ok(String::from_utf8(self.read_file(path).await?)?) + } + + async fn write_file(&self, path: &str, contents: &[u8]) -> anyhow::Result<()> { + self.files + .lock() + .unwrap() + .insert(path.to_string(), contents.to_vec()); + Ok(()) + } + + async fn exists(&self, path: &str) -> anyhow::Result { + Ok(self.files.lock().unwrap().contains_key(path)) + } + + async fn is_file(&self, path: &str) -> anyhow::Result { + self.exists(path).await + } + + async fn is_dir(&self, _path: &str) -> anyhow::Result { + Ok(false) + } + + async fn read_dir(&self, _path: &str) -> anyhow::Result> { + Ok(Vec::new()) + } + } + + struct UnusedShell; + + #[async_trait] + impl WorkspaceShell for UnusedShell { + async fn exec_with_options( + &self, + _command: &str, + _options: WorkspaceCommandOptions, + ) -> anyhow::Result { + panic!("GenOfficeFile must not run shell commands") + } + } + + fn context(fs: Arc, remote: bool) -> ToolUseContext { + let root = "/remote/workspace"; + let workspace = if remote { + let identity = crate::service::remote_ssh::workspace_state::workspace_session_identity( + root, + Some("office-test-ssh"), + Some("office-test-host"), + ) + .expect("remote identity"); + WorkspaceBinding::new_remote( + None, + PathBuf::from(root), + "office-test-ssh".to_string(), + "office-test-host".to_string(), + identity, + ) + } else { + WorkspaceBinding::new(None, PathBuf::from(root)) + }; + ToolUseContext { + tool_call_id: None, + agent_type: None, + session_id: None, + dialog_turn_id: None, + workspace: Some(workspace), + loaded_deferred_tool_specs: Vec::new(), + model_client: None, + primary_model_facts: tool_runtime::context::PrimaryModelFacts::default(), + custom_data: HashMap::new(), + computer_use_host: None, + runtime_tool_restrictions: ToolRuntimeRestrictions::default(), + runtime_handles: ToolRuntimeHandles::new( + Some(WorkspaceServices { + fs, + shell: Arc::new(UnusedShell), + }), + None, + ), + } + } + + fn data(results: Vec) -> Value { + match results.into_iter().next().expect("one result") { + ToolResult::Result { data, .. } => data, + other => panic!("unexpected result {other:?}"), + } + } + + fn png() -> Vec { + let mut bytes = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec(); + bytes.extend_from_slice(&64u32.to_be_bytes()); + bytes.extend_from_slice(&48u32.to_be_bytes()); + bytes.extend_from_slice(&[8, 6, 0, 0, 0]); + bytes + } + + #[cfg(unix)] + #[tokio::test] + async fn builds_a_deck_over_several_calls_through_the_workspace_file_system() { + for remote in [false, true] { + let fs = Arc::new(MemoryFs::default()); + fs.files + .lock() + .unwrap() + .insert("/remote/workspace/assets/logo.png".to_string(), png()); + let context = context(fs.clone(), remote); + let tool = GenOfficeFileTool::new(); + let path = "/remote/workspace/out/deck.pptx"; + + let created = data( + tool.call_impl( + &json!({"action": "create", "file_path": path, "operations": [ + {"op": "insert_slides", "slides": [{"title": "Cover", "elements": [ + {"type": "text", "x": 80, "y": 80, "w": 800, "h": 80, "text": "Hello", "size_pt": 36}, + {"type": "image", "src": "/remote/workspace/assets/logo.png", "x": 900, "y": 80, "w": 128, "h": 96} + ]}]} + ]}), + &context, + ) + .await + .expect("create"), + ); + assert_eq!(created["counts"]["slides"], json!(1)); + assert!(fs.files.lock().unwrap().contains_key(path)); + + let duplicate = tool + .call_impl(&json!({"action": "create", "file_path": path}), &context) + .await + .unwrap_err(); + assert!(duplicate.to_string().contains("already exists")); + + // The image file is gone; the embedded picture must still carry over. + fs.files + .lock() + .unwrap() + .remove("/remote/workspace/assets/logo.png"); + let edited = data( + tool.call_impl( + &json!({"action": "edit", "file_path": path, "operations": [ + {"op": "insert_slides", "slides": [{"title": "Agenda", "elements": [ + {"type": "text", "x": 80, "y": 80, "w": 800, "h": 300, "paragraphs": ["One", "Two"]} + ]}]} + ]}), + &context, + ) + .await + .expect("edit"), + ); + assert_eq!(edited["revision"], json!(2)); + + let read = data( + tool.call_impl( + &json!({"action": "read", "file_path": path, "offset": 1, "limit": 1}), + &context, + ) + .await + .expect("read"), + ); + assert_eq!(read["view"]["total_slides"], json!(2)); + assert_eq!(read["view"]["slides"][0]["label"], json!("Agenda")); + + let failed = tool + .call_impl( + &json!({"action": "edit", "file_path": path, "operations": [{"op": "delete_slides", "index": 7}]}), + &context, + ) + .await + .unwrap_err(); + assert!(failed.to_string().contains("delete_slides"), "{failed}"); + } + } + + #[test] + fn input_checks_catch_misuse_before_any_io() { + assert!(GenOfficeFileTool::check_input( + &json!({"action": "create", "file_path": "/a/b.docx"}) + ) + .is_ok()); + assert!( + GenOfficeFileTool::check_input(&json!({"action": "guide", "format": "pptx"})).is_ok() + ); + let cases = [ + json!({"action": "create", "file_path": "/a/b.doc"}), + json!({"action": "edit", "file_path": "/a/b.docx"}), + json!({"action": "edit", "file_path": "/a/b.docx", "operations": [{"op": "insert_blocks"}], "settings": {}}), + json!({"action": "read", "file_path": "/a/b.docx", "sheet": "S"}), + json!({"action": "read", "file_path": "/a/b.docx", "operations": [{"op": "x"}]}), + json!({"action": "write", "file_path": "/a/b.docx"}), + json!({"action": "guide"}), + ]; + for case in cases { + assert!(GenOfficeFileTool::check_input(&case).is_err(), "{case}"); + } + } + + #[test] + fn remote_parent_directories_use_posix_paths() { + assert_eq!( + GenOfficeFileTool::parent_directory("/home/u/docs/a.pptx", true).as_deref(), + Some("/home/u/docs") + ); + assert_eq!(GenOfficeFileTool::parent_directory("a.pptx", true), None); + } +} diff --git a/src/crates/assembly/core/src/agentic/tools/implementations/mod.rs b/src/crates/assembly/core/src/agentic/tools/implementations/mod.rs index b5a15244f9..5ec312a9e7 100644 --- a/src/crates/assembly/core/src/agentic/tools/implementations/mod.rs +++ b/src/crates/assembly/core/src/agentic/tools/implementations/mod.rs @@ -34,6 +34,8 @@ pub mod file_read_tool; pub mod file_write_tool; #[cfg(feature = "tools-creation")] pub mod frontend_workbench_tool; +#[cfg(feature = "tools-office-documents")] +pub mod gen_office_file_tool; #[cfg(feature = "tools-image-generation")] pub mod generate_image_tool; #[cfg(feature = "tools-miniapp")] @@ -114,6 +116,8 @@ pub use file_read_tool::FileReadTool; pub use file_write_tool::FileWriteTool; #[cfg(feature = "tools-creation")] pub use frontend_workbench_tool::FrontendWorkbenchTool; +#[cfg(feature = "tools-office-documents")] +pub use gen_office_file_tool::GenOfficeFileTool; #[cfg(feature = "tools-image-generation")] pub use generate_image_tool::GenerateImageTool; #[cfg(feature = "tools-miniapp")] diff --git a/src/crates/assembly/core/src/agentic/tools/product_runtime/materialization.rs b/src/crates/assembly/core/src/agentic/tools/product_runtime/materialization.rs index d1781d275f..4329c3f116 100644 --- a/src/crates/assembly/core/src/agentic/tools/product_runtime/materialization.rs +++ b/src/crates/assembly/core/src/agentic/tools/product_runtime/materialization.rs @@ -27,6 +27,7 @@ const PRODUCT_TOOL_REGISTRATION_ORDER: &[&str] = &[ "Write", "Edit", "Delete", + "GenOfficeFile", "ExecCommand", "WriteStdin", "ExecControl", @@ -117,6 +118,8 @@ impl StaticToolProviderFactory for ProductConcreteToolFactory { "Write" => Some(Arc::new(FileWriteTool::new())), "Edit" => Some(Arc::new(FileEditTool::new())), "Delete" => Some(Arc::new(DeleteFileTool::new())), + #[cfg(feature = "tools-office-documents")] + "GenOfficeFile" => Some(Arc::new(GenOfficeFileTool::new())), "ExecCommand" => Some(Arc::new(ExecCommandTool::new())), "WriteStdin" => Some(Arc::new(WriteStdinTool::new())), "ExecControl" => Some(Arc::new(ExecControlTool::new())), @@ -269,6 +272,11 @@ mod tests { &["view_image", "analyze_image"][..], cfg!(feature = "tools-image-analysis"), ), + ( + ToolPackFeatureGroup::OfficeDocuments, + &["GenOfficeFile"][..], + cfg!(feature = "tools-office-documents"), + ), ] { let result = create_product_tool_registry_from_plan( product_tool_provider_group_plan(), diff --git a/src/crates/assembly/core/src/agentic/tools/registry.rs b/src/crates/assembly/core/src/agentic/tools/registry.rs index 78e4ef68fc..98bdcef659 100644 --- a/src/crates/assembly/core/src/agentic/tools/registry.rs +++ b/src/crates/assembly/core/src/agentic/tools/registry.rs @@ -565,6 +565,7 @@ mod tests { "Write", "Edit", "Delete", + "GenOfficeFile", "ExecCommand", "WriteStdin", "ExecControl", diff --git a/src/crates/assembly/product-capabilities/src/lib.rs b/src/crates/assembly/product-capabilities/src/lib.rs index e13bbe2263..32761fe4bf 100644 --- a/src/crates/assembly/product-capabilities/src/lib.rs +++ b/src/crates/assembly/product-capabilities/src/lib.rs @@ -57,6 +57,7 @@ pub enum ProductFeatureGroup { ComputerUse, ImageAnalysis, ImageGeneration, + OfficeDocuments, MiniApp, Pages, Creation, @@ -73,6 +74,7 @@ impl ProductFeatureGroup { Self::ComputerUse => "computer-use", Self::ImageAnalysis => "image-analysis", Self::ImageGeneration => "image-generation", + Self::OfficeDocuments => "office-documents", Self::MiniApp => "miniapp", Self::Pages => "pages", Self::Creation => "creation", @@ -97,6 +99,7 @@ impl From for ProductFeatureGroup { ToolPackFeatureGroup::ComputerUse => Self::ComputerUse, ToolPackFeatureGroup::ImageAnalysis => Self::ImageAnalysis, ToolPackFeatureGroup::ImageGeneration => Self::ImageGeneration, + ToolPackFeatureGroup::OfficeDocuments => Self::OfficeDocuments, ToolPackFeatureGroup::MiniApp => Self::MiniApp, ToolPackFeatureGroup::Pages => Self::Pages, ToolPackFeatureGroup::Creation => Self::Creation, @@ -115,6 +118,7 @@ impl From for ToolPackFeatureGroup { ProductFeatureGroup::ComputerUse => Self::ComputerUse, ProductFeatureGroup::ImageAnalysis => Self::ImageAnalysis, ProductFeatureGroup::ImageGeneration => Self::ImageGeneration, + ProductFeatureGroup::OfficeDocuments => Self::OfficeDocuments, ProductFeatureGroup::MiniApp => Self::MiniApp, ProductFeatureGroup::Pages => Self::Pages, ProductFeatureGroup::Creation => Self::Creation, diff --git a/src/crates/assembly/product-capabilities/tests/product_capability_contracts/product_capabilities.rs b/src/crates/assembly/product-capabilities/tests/product_capability_contracts/product_capabilities.rs index 47441ea14d..0bf5c1f462 100644 --- a/src/crates/assembly/product-capabilities/tests/product_capability_contracts/product_capabilities.rs +++ b/src/crates/assembly/product-capabilities/tests/product_capability_contracts/product_capabilities.rs @@ -492,6 +492,7 @@ fn product_assembly_plan_exposes_build_feature_groups_explicitly() { ProductFeatureGroup::Basic, ProductFeatureGroup::ImageAnalysis, ProductFeatureGroup::ImageGeneration, + ProductFeatureGroup::OfficeDocuments, ProductFeatureGroup::AgentControl, ProductFeatureGroup::Git, ProductFeatureGroup::BrowserWeb, @@ -508,6 +509,7 @@ fn product_assembly_plan_exposes_build_feature_groups_explicitly() { "basic", "image-analysis", "image-generation", + "office-documents", "agent-control", "git", "browser-web", diff --git a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json index 2545feb82e..6a3785e076 100644 --- a/src/crates/contracts/product-domains/src/generated/product-control-catalog.json +++ b/src/crates/contracts/product-domains/src/generated/product-control-catalog.json @@ -4,9 +4,21 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "eac1f9fc6338c11451dfeb8ff17123dad2d8de1f1339de27eeaa17cb22e5ff66", + "digest": "8a02be2b328791ebb823e4b7a956bf0371c523caa7f881a6c778cbaa42d72575", "ownerDigest": "31d6371f7765bde7bee88e22a6a4f03c2c5370e138cf49975bdc88f3c5eeb052", "searchAcceptance": [ + { + "id": "native-office-generation", + "query": "GenOfficeFile", + "expectedFirstCapabilityId": "feature.ai-assistant", + "expectedCapabilityIds": [ + "feature.ai-assistant" + ], + "expectedItem": { + "capabilityId": "feature.ai-assistant", + "itemId": "office-document-generation" + } + }, { "id": "native-image-generation", "query": "generate_image", @@ -175,10 +187,10 @@ "features": 22, "settings": 22, "userFacing": 44, - "documentedItems": 333, + "documentedItems": 334, "controlCoverage": { "direct": 63, - "delegated": 70, + "delegated": 71, "interactive": 200, "unsupported": 0 } @@ -231,6 +243,7 @@ "model-mode-permissions", "creative-frontend-authoring", "image-generation", + "office-document-generation", "turn-control", "permission-mailbox", "history-search", @@ -517,6 +530,51 @@ "sceneId": "session" } }, + { + "id": "feature.ai-assistant:delegate:office-document-generation", + "capabilityId": "feature.ai-assistant", + "itemIds": [ + "office-document-generation" + ], + "kind": "delegate", + "risk": "execute", + "executionHost": "workspaceHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": true + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "delegateTools": [ + "GenOfficeFile" + ], + "presentationTarget": { + "kind": "scene", + "sceneId": "session" + } + }, { "id": "feature.ai-assistant:open:turn-control", "capabilityId": "feature.ai-assistant", @@ -20593,6 +20651,27 @@ ] } }, + { + "id": "office-document-generation", + "titleZh": "用 GenOfficeFile 创建并编辑 Word、Excel 和 PowerPoint 文件", + "titleEn": "Create and edit Word, Excel, and PowerPoint files with GenOfficeFile", + "control": { + "kind": "delegate", + "tools": [ + "GenOfficeFile" + ], + "workflowZh": [ + "先用 GenOfficeFile guide 读取格式指南,再通过 create 和 edit 分批生成或修改 .docx、.xlsx、.pptx 文件,无需安装 Office", + "用 read 分页查看文档结构;文件和引用图片通过当前工作区文件系统读写,支持本地或远程工作区", + "仅能继续编辑由该工具生成的文件;其他程序改过的内容默认拒绝覆盖,需要用户明确同意丢弃外部修改" + ], + "workflowEn": [ + "Read the format guide with GenOfficeFile guide, then use create and edit to build or revise .docx, .xlsx, and .pptx files in batches without installing Office", + "Use read to page through document structure; documents and referenced images use the active local or remote workspace filesystem", + "Only files generated by this tool can be reopened for editing; external changes are rejected by default and may be discarded only with the user's explicit agreement" + ] + } + }, { "id": "turn-control", "titleZh": "开始、引导、打断、取消或恢复一次智能体运行", @@ -20861,6 +20940,8 @@ "Extend client UI and runtime capabilities in Creative mode", "通过已配置的默认图像模型生成图片", "Generate images with the configured default image model", + "用 GenOfficeFile 创建并编辑 Word、Excel 和 PowerPoint 文件", + "Create and edit Word, Excel, and PowerPoint files with GenOfficeFile", "开始、引导、打断、取消或恢复一次智能体运行", "Start, steer, interrupt, cancel, or recover an agent turn", "查看并逐个或批量回答等待中的权限请求", @@ -20908,6 +20989,13 @@ "Use generate_image to create images from the user's description; omit service_id to use the configured default image model", "Specify count and size when needed and deliver the returned file paths; access remote workspace files through the active workspace data plane", "Report missing configuration, authentication failures, or quota limits explicitly without automatically switching services", + "GenOfficeFile", + "先用 GenOfficeFile guide 读取格式指南,再通过 create 和 edit 分批生成或修改 .docx、.xlsx、.pptx 文件,无需安装 Office", + "用 read 分页查看文档结构;文件和引用图片通过当前工作区文件系统读写,支持本地或远程工作区", + "仅能继续编辑由该工具生成的文件;其他程序改过的内容默认拒绝覆盖,需要用户明确同意丢弃外部修改", + "Read the format guide with GenOfficeFile guide, then use create and edit to build or revise .docx, .xlsx, and .pptx files in batches without installing Office", + "Use read to page through document structure; documents and referenced images use the active local or remote workspace filesystem", + "Only files generated by this tool can be reopened for editing; external changes are rejected by default and may be discarded only with the user's explicit agreement", "ListWorkspaces", "SessionControl", "SessionHistory", diff --git a/src/crates/execution/AGENTS-CN.md b/src/crates/execution/AGENTS-CN.md index 75da94a8c3..29e938c180 100644 --- a/src/crates/execution/AGENTS-CN.md +++ b/src/crates/execution/AGENTS-CN.md @@ -15,6 +15,7 @@ | `plugin-runtime-client` | `PluginRuntimeClient` 的默认实现,负责派发、重复请求结果和故障诊断;JS/TS Plugin Host 是经服务端口管理的子进程 | [AGENTS.md](plugin-runtime-client/AGENTS.md) | | `runtime-services` | Typed runtime service assembly 和 service availability facts | [AGENTS.md](runtime-services/AGENTS.md) | | `tool-provider-groups` | Tool provider group facts 和 product-full tool group composition;Cargo package 仍为 `openbitfun-tool-packs` | [AGENTS.md](tool-provider-groups/AGENTS.md) | +| `office-documents` | 可移植的 OOXML(docx、xlsx、pptx)文档模型、原子编辑操作和打包写出,供 `GenOfficeFile` 工具使用;只处理内存字节,不做 IO | [AGENTS.md](office-documents/AGENTS.md) | | `tool-execution` | 底层 file/search/tool IO helper、ExecCommand presentation facts、Computer Use loop/retry policy、prompt-safe tool context facts 和 provider-neutral tool runtime policy;Cargo package 仍为 `tool-runtime` | [AGENTS.md](tool-execution/AGENTS.md) | ## 放置规则 diff --git a/src/crates/execution/AGENTS.md b/src/crates/execution/AGENTS.md index e26550165d..26f4f5a8f2 100644 --- a/src/crates/execution/AGENTS.md +++ b/src/crates/execution/AGENTS.md @@ -19,6 +19,7 @@ delivery form. | `plugin-runtime-client` | Default `PluginRuntimeClient` implementation for dispatch, duplicate-request results, and fault diagnostics; the JS/TS Plugin Host remains a child process managed through service ports | [AGENTS.md](plugin-runtime-client/AGENTS.md) | | `runtime-services` | Typed runtime service assembly and service availability facts | [AGENTS.md](runtime-services/AGENTS.md) | | `tool-provider-groups` | Tool provider group facts and product-full tool group composition. Cargo package remains `openbitfun-tool-packs`. | [AGENTS.md](tool-provider-groups/AGENTS.md) | +| `office-documents` | Portable OOXML (docx, xlsx, pptx) document models, atomic edit operations, and package writers behind the `GenOfficeFile` tool; no IO beyond in-memory bytes | [AGENTS.md](office-documents/AGENTS.md) | | `tool-execution` | Low-level file/search/tool IO helpers, ExecCommand presentation facts, Computer Use loop/retry policies, prompt-safe tool context facts, and provider-neutral tool runtime policies. Cargo package remains `tool-runtime`. | [AGENTS.md](tool-execution/AGENTS.md) | ## Placement Rules diff --git a/src/crates/execution/office-documents/AGENTS.md b/src/crates/execution/office-documents/AGENTS.md new file mode 100644 index 0000000000..188ca50814 --- /dev/null +++ b/src/crates/execution/office-documents/AGENTS.md @@ -0,0 +1,42 @@ +# office-documents + +Cargo package: `openbitfun-office-documents`. Owns the portable OOXML engine +behind the `GenOfficeFile` tool: Word (`.docx`), Excel (`.xlsx`), and +PowerPoint (`.pptx`) document models, atomic edit operations, structure reads +with paging, and package writers. The models follow GenOffice's agent-facing +shapes (Markdown/blocks for Word, the workbook cell DSL for Excel, the +1280×720 px page spec for decks). + +## Boundaries + +- Pure in-memory bytes: no file, network, or process IO. The tool in + `assembly/core` resolves paths, loads referenced images through the + session's workspace file system (local or remote), and writes the result. +- Depends only on serialization, zip, Markdown parsing, and hashing crates. + Do not add Core, services, or runtime dependencies. + +## Contracts + +- Every package carries its editable model in `openbitfun/genoffice.json` + (package relationship type + `http://schemas.openbitfun.com/genoffice/2026/relationships/source`), with a + fingerprint of the rendered parts. Reopening refuses packages without the + part (`not_generated`) and packages another program changed + (`externally_modified`) unless the caller opts to discard those changes. +- The stored model is read by older and newer versions: model structs keep + unknown fields (`extra`) and round-trip them; new fields need defaults. The + envelope `version` gates incompatible changes. Operation input, in contrast, + reports unknown fields so a typo is not silently ignored. +- A batch is atomic: operations run on a clone, and an error names the failing + operation index. +- Embedded pictures are content-addressed assets kept in the media parts and + reused on later rebuilds without the original file. + +## Verification + +```bash +cargo test -p openbitfun-office-documents +``` + +`OFFICE_DOCUMENTS_SAMPLE_DIR=/some/dir cargo test -p openbitfun-office-documents --test end_to_end` +also writes the generated samples there for manual inspection in Office. diff --git a/src/crates/execution/office-documents/Cargo.toml b/src/crates/execution/office-documents/Cargo.toml new file mode 100644 index 0000000000..ffe79dd699 --- /dev/null +++ b/src/crates/execution/office-documents/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "openbitfun-office-documents" +version.workspace = true +authors.workspace = true +edition.workspace = true +license = "MIT AND Apache-2.0" +description = "Portable OOXML (docx, xlsx, pptx) document models, incremental edit operations, and package writers" + +[lib] +name = "openbitfun_office_documents" +crate-type = ["rlib"] + +[dependencies] +base64 = { workspace = true } +pulldown-cmark = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +sha2 = { workspace = true } +zip = { workspace = true } + +[dev-dependencies] +roxmltree = { workspace = true, features = ["std"] } + +[lints] +workspace = true diff --git a/src/crates/execution/office-documents/LICENSE-GENOFFICE.txt b/src/crates/execution/office-documents/LICENSE-GENOFFICE.txt new file mode 100644 index 0000000000..3017411926 --- /dev/null +++ b/src/crates/execution/office-documents/LICENSE-GENOFFICE.txt @@ -0,0 +1,202 @@ + + 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 2026 Mainfunc, Inc. + + 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. diff --git a/src/crates/execution/office-documents/NOTICE-GENOFFICE.txt b/src/crates/execution/office-documents/NOTICE-GENOFFICE.txt new file mode 100644 index 0000000000..34d8590f9b --- /dev/null +++ b/src/crates/execution/office-documents/NOTICE-GENOFFICE.txt @@ -0,0 +1,54 @@ +GenOffice +Copyright 2026 Mainfunc, Inc. + +This product includes software developed at Mainfunc, Inc. + +Bundled third-party components are listed in THIRD-PARTY-NOTICES.txt, which +tools/gen-third-party-notices.mjs generates at packaging time. It is not +checked into this repository; in a release build it ships inside the +application bundle (Contents/Resources on macOS, resources/ on Windows). +Run `node tools/gen-third-party-notices.mjs` to produce it from a source +checkout. + +Bundled fonts and their licenses are documented in +apps/docs/src/renderer/fonts/README.md. + +Downloadable fonts + +Any app can offer additional font families, at the reader's request, from the +build-injected font mirror. Those families are not in the bundle and so are not +in that README; the catalogue is +packages/electron-utils/src/font-catalog.ts, and every family there carries its +SPDX licence id in a `license` field, checked against a permissive allowlist by +packages/electron-utils/tests/font-store.test.ts. + +All of them are licensed under the SIL Open Font License, Version 1.1 +(https://openfontlicense.org), which permits the bundling and redistribution +this application performs. The families are: Open Sans, Roboto, Lato, +Montserrat, Poppins, Inter, Source Sans 3, Oswald, Raleway, Nunito, +Merriweather, Playfair Display, Work Sans, Rubik, Noto Sans JP, Noto Sans KR, +Noto Sans SC, Noto Sans TC, Nanum Gothic, Noto Serif SC, Noto Serif TC, +Noto Serif JP, Noto Serif KR, Nanum Myeongjo. + +Each downloaded file is verified against the sha256 recorded in the catalogue +before it is installed, and the catalogue states each family's size so an app +can ask before fetching tens of megabytes. + +Unicode Character Database + +apps/pdf/src/shared/radicals.ts contains a generated mapping derived from +Unicode Character Database 17.0.0, EquivalentUnifiedIdeograph.txt +(2025-08-01): +https://www.unicode.org/Public/17.0.0/ucd/EquivalentUnifiedIdeograph.txt + +Copyright © 1991-2026 Unicode, Inc. This data is distributed under Unicode +License v3. The complete copyright and permission notice is reproduced in +LICENSE-UNICODE.txt. + +Office Open XML schemas + +tools/ooxml-validate/schemas contains the ISO/IEC 29500-4:2016 (ECMA-376 +Part 4, Transitional) XML Schema files for PresentationML and DrawingML, as +distributed in the python-docx repository (ref/xsd), with one marked local +amendment (see tools/ooxml-validate/README.md). They are used only by tests +and development tooling and are not shipped in the application. diff --git a/src/crates/execution/office-documents/README.md b/src/crates/execution/office-documents/README.md new file mode 100644 index 0000000000..fd603f995e --- /dev/null +++ b/src/crates/execution/office-documents/README.md @@ -0,0 +1,41 @@ +# Office document engine + +Portable, in-memory Word, Excel, and PowerPoint generation for the +`GenOfficeFile` Agent tool. See [AGENTS.md](AGENTS.md) for ownership, stored +model compatibility, and focused verification. + +## GenOffice attribution and licensing + +This implementation was developed with reference to +[GenOffice](https://github.com/genspark-ai/genoffice), copyright 2026 +Mainfunc, Inc., licensed under Apache License 2.0. The reference revision +recorded for this attribution is +[`f8c17004fb730df11f0f743164ffd8b4281bb38c`](https://github.com/genspark-ai/genoffice/tree/f8c17004fb730df11f0f743164ffd8b4281bb38c). +It identifies the source reviewed for attribution, not a claim that all +OpenBitFun code was ported from that revision. + +The agent-facing designs used as references include: + +- Word Markdown/block operations: + [`packages/cli/src/formats/docx.ts`](https://github.com/genspark-ai/genoffice/blob/f8c17004fb730df11f0f743164ffd8b4281bb38c/packages/cli/src/formats/docx.ts). +- Excel cell DSL, styles, and workbook operations: + [`packages/cli/src/formats/xlsx-dsl.ts`](https://github.com/genspark-ai/genoffice/blob/f8c17004fb730df11f0f743164ffd8b4281bb38c/packages/cli/src/formats/xlsx-dsl.ts). +- PowerPoint 1280×720 page specs and positioned elements: + [`packages/pipelines/src/slides/page-spec.ts`](https://github.com/genspark-ai/genoffice/blob/f8c17004fb730df11f0f743164ffd8b4281bb38c/packages/pipelines/src/slides/page-spec.ts). + +OpenBitFun implements these capabilities in Rust with its own in-memory +models and OOXML package writers, atomic edit batches, embedded editable +source and integrity checks, paged reads, and workspace filesystem adapter. +The tool accepts a supported subset; it does not claim full GenOffice format +or operation compatibility. + +The complete upstream [license](LICENSE-GENOFFICE.txt) and +[NOTICE](NOTICE-GENOFFICE.txt) are preserved here. GenOffice-derived material +remains subject to Apache-2.0; OpenBitFun-authored additions use the repository's +MIT license. This attribution does not relicense the rest of OpenBitFun. +The upstream NOTICE describes components in GenOffice's own distribution; +those references do not mean OpenBitFun bundles those components. + +The applicable GenOffice attribution and complete Apache-2.0 license are also +included in the repository-level [third-party notices](../../../../THIRD_PARTY_NOTICES.md), +which existing Desktop and CLI packaging distributes with the binaries. diff --git a/src/crates/execution/office-documents/src/common.rs b/src/crates/execution/office-documents/src/common.rs new file mode 100644 index 0000000000..7a447e97a1 --- /dev/null +++ b/src/crates/execution/office-documents/src/common.rs @@ -0,0 +1,561 @@ +//! Types and helpers shared by the docx, xlsx, and pptx models. + +use crate::error::{OfficeError, OfficeResult}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use std::collections::BTreeMap; + +/// Fields the current schema does not know. Stored documents keep them so a +/// newer writer's data survives a round trip through this version; operation +/// input reports them so a typo is not silently ignored. +pub type Extra = BTreeMap; + +pub trait UnknownFields { + fn unknown_fields(&self, path: &str, out: &mut Vec); +} + +pub(crate) fn report_extra(extra: &Extra, path: &str, out: &mut Vec) { + for key in extra.keys() { + out.push(if path.is_empty() { + key.clone() + } else { + format!("{path}.{key}") + }); + } +} + +pub(crate) fn report_list(items: &[T], path: &str, out: &mut Vec) { + for (index, item) in items.iter().enumerate() { + item.unknown_fields(&format!("{path}[{index}]"), out); + } +} + +/// Parses one operation payload (without its `op` key) and rejects unknown +/// fields anywhere in it. +pub(crate) fn parse_operation( + value: &Value, +) -> OfficeResult { + let mut object = value + .as_object() + .cloned() + .ok_or_else(|| OfficeError::invalid("every operation must be a JSON object"))?; + object.remove("op"); + let parsed: T = serde_json::from_value(Value::Object(object)) + .map_err(|err| OfficeError::invalid(err.to_string()))?; + let mut unknown = Vec::new(); + parsed.unknown_fields("", &mut unknown); + if !unknown.is_empty() { + return Err(OfficeError::invalid(format!( + "unknown field(s): {}; see the guide for the fields this operation accepts", + unknown.join(", ") + ))); + } + Ok(parsed) +} + +pub(crate) fn operation_name(value: &Value) -> OfficeResult<&str> { + value + .get("op") + .and_then(Value::as_str) + .ok_or_else(|| OfficeError::invalid("every operation needs an `op` string")) +} + +pub(crate) fn unknown_operation(name: &str, supported: &[&str]) -> OfficeError { + let hint = did_you_mean(name, supported) + .map(|guess| format!(" Did you mean `{guess}`?")) + .unwrap_or_default(); + OfficeError::invalid(format!( + "unknown operation `{name}`.{hint} Supported: {}", + supported.join(", ") + )) +} + +pub(crate) fn did_you_mean<'a>(input: &str, candidates: &[&'a str]) -> Option<&'a str> { + let input = input.to_ascii_lowercase(); + candidates + .iter() + .map(|candidate| { + ( + levenshtein(&input, &candidate.to_ascii_lowercase()), + *candidate, + ) + }) + .filter(|(distance, candidate)| *distance <= 2.max(candidate.len() / 4)) + .min_by_key(|(distance, _)| *distance) + .map(|(_, candidate)| candidate) +} + +fn levenshtein(a: &str, b: &str) -> usize { + let b: Vec = b.chars().collect(); + let mut previous: Vec = (0..=b.len()).collect(); + for (i, ca) in a.chars().enumerate() { + let mut current = vec![i + 1; b.len() + 1]; + for (j, cb) in b.iter().enumerate() { + let cost = usize::from(ca != *cb); + current[j + 1] = (previous[j] + cost) + .min(previous[j + 1] + 1) + .min(current[j] + 1); + } + previous = current; + } + previous[b.len()] +} + +/// Core document metadata written to `docProps/core.xml`. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct DocumentProperties { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subject: Option, + #[serde(default, skip_serializing_if = "Option::is_none", alias = "creator")] + pub author: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub keywords: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub category: Option, + #[serde(flatten)] + pub extra: Extra, +} + +impl UnknownFields for DocumentProperties { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + } +} + +impl DocumentProperties { + /// Applies the provided fields; an empty string clears a field. + pub fn merge(&mut self, patch: &DocumentProperties) { + fn merge_field(target: &mut Option, value: &Option) { + if let Some(value) = value { + *target = (!value.is_empty()).then(|| value.clone()); + } + } + merge_field(&mut self.title, &patch.title); + merge_field(&mut self.subject, &patch.subject); + merge_field(&mut self.author, &patch.author); + merge_field(&mut self.keywords, &patch.keywords); + merge_field(&mut self.description, &patch.description); + merge_field(&mut self.category, &patch.category); + } +} + +/// One formatted span of text. Shared by Word paragraphs, slide paragraphs, +/// and table cells; each writer ignores the fields its format cannot show. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Run { + #[serde(default)] + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bold: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub italic: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub underline: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + alias = "strikethrough" + )] + pub strike: Option, + /// Monospace inline code. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub code: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub superscript: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub subscript: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub highlight: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + alias = "sizePt", + alias = "size" + )] + pub size_pt: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub font: Option, + /// External hyperlink target (http, https, or mailto). + #[serde(default, skip_serializing_if = "Option::is_none", alias = "url")] + pub link: Option, + #[serde(flatten)] + pub extra: Extra, +} + +impl Run { + pub fn plain(text: impl Into) -> Self { + Self { + text: text.into(), + ..Self::default() + } + } + + pub fn validate(&self, path: &str) -> OfficeResult<()> { + if let Some(color) = &self.color { + parse_color(color).map_err(|err| prefix(err, path, "color"))?; + } + if let Some(color) = &self.highlight { + parse_color(color).map_err(|err| prefix(err, path, "highlight"))?; + } + if let Some(size) = self.size_pt { + if !(1.0..=400.0).contains(&size) { + return Err(OfficeError::invalid(format!( + "{path}.size_pt must be between 1 and 400, got {size}" + ))); + } + } + if let Some(link) = &self.link { + validate_link(link).map_err(|err| prefix(err, path, "link"))?; + } + Ok(()) + } +} + +impl UnknownFields for Run { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + } +} + +pub(crate) fn validate_link(link: &str) -> OfficeResult<()> { + let lower = link.to_ascii_lowercase(); + if lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("mailto:") + { + Ok(()) + } else { + Err(OfficeError::invalid(format!( + "links must start with http://, https:// or mailto:, got `{link}`" + ))) + } +} + +pub(crate) fn prefix(mut error: OfficeError, path: &str, field: &str) -> OfficeError { + let location = if path.is_empty() { + field.to_string() + } else { + format!("{path}.{field}") + }; + error.message = format!("{location}: {}", error.message); + error +} + +/// Inline content accepted wherever text appears: either a plain `text` +/// string or explicit `runs`. Stored documents always keep `runs`. +pub(crate) fn canonical_runs(text: &mut Option, runs: &mut Vec) { + if let Some(text) = text.take() { + if runs.is_empty() { + runs.push(Run::plain(text)); + } + } +} + +pub(crate) fn runs_text(runs: &[Run]) -> String { + runs.iter().map(|run| run.text.as_str()).collect() +} + +pub(crate) fn validate_runs(runs: &[Run], path: &str) -> OfficeResult<()> { + for (index, run) in runs.iter().enumerate() { + run.validate(&format!("{path}.runs[{index}]"))?; + } + Ok(()) +} + +/// A table cell shared by Word and slide tables. Accepts a bare string, +/// number, boolean, or null as shorthand for `{ "text": ... }`. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(from = "TableCellInput")] +pub struct TableCell { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub runs: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bold: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fill: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub align: Option, + /// Number of grid columns this cell spans (Word tables only). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub colspan: Option, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Deserialize)] +#[serde(untagged)] +enum TableCellInput { + Text(String), + Number(serde_json::Number), + Bool(bool), + Null, + Full(TableCellFull), +} + +#[derive(Deserialize)] +struct TableCellFull { + #[serde(default)] + text: Option, + #[serde(default)] + runs: Vec, + #[serde(default)] + bold: Option, + #[serde(default)] + color: Option, + #[serde(default)] + fill: Option, + #[serde(default)] + align: Option, + #[serde(default)] + colspan: Option, + #[serde(flatten)] + extra: Extra, +} + +impl From for TableCell { + fn from(input: TableCellInput) -> Self { + let text_cell = |text: String| TableCell { + runs: if text.is_empty() { + Vec::new() + } else { + vec![Run::plain(text)] + }, + ..TableCell::default() + }; + match input { + TableCellInput::Text(text) => text_cell(text), + TableCellInput::Number(number) => text_cell(number.to_string()), + TableCellInput::Bool(value) => text_cell(value.to_string()), + TableCellInput::Null => TableCell::default(), + TableCellInput::Full(mut full) => { + canonical_runs(&mut full.text, &mut full.runs); + TableCell { + runs: full.runs, + bold: full.bold, + color: full.color, + fill: full.fill, + align: full.align, + colspan: full.colspan, + extra: full.extra, + } + } + } + } +} + +impl TableCell { + pub fn text(&self) -> String { + runs_text(&self.runs) + } + + pub fn validate(&self, path: &str) -> OfficeResult<()> { + validate_runs(&self.runs, path)?; + if let Some(color) = &self.color { + parse_color(color).map_err(|err| prefix(err, path, "color"))?; + } + if let Some(color) = &self.fill { + parse_color(color).map_err(|err| prefix(err, path, "fill"))?; + } + if self.colspan == Some(0) { + return Err(OfficeError::invalid(format!( + "{path}.colspan must be at least 1" + ))); + } + Ok(()) + } +} + +impl UnknownFields for TableCell { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + report_list(&self.runs, &format!("{path}.runs"), out); + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Align { + Left, + #[serde(alias = "centre", alias = "middle")] + Center, + Right, + Justify, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum VerticalAlign { + Top, + #[serde(alias = "center")] + Middle, + Bottom, +} + +/// `#RGB`, `#RRGGBB`, or `#RRGGBBAA` → (`RRGGBB`, alpha 0..=255). +pub fn parse_color(input: &str) -> OfficeResult<(String, Option)> { + let hex = input.trim().trim_start_matches('#').to_ascii_uppercase(); + let expanded = if hex.len() == 3 { + hex.chars().flat_map(|c| [c, c]).collect::() + } else { + hex + }; + let valid = matches!(expanded.len(), 6 | 8) && expanded.chars().all(|c| c.is_ascii_hexdigit()); + if !valid { + return Err(OfficeError::invalid(format!( + "invalid color `{input}`; use #RRGGBB or #RRGGBBAA" + ))); + } + let alpha = (expanded.len() == 8) + .then(|| u8::from_str_radix(&expanded[6..8], 16).ok()) + .flatten(); + Ok((expanded[..6].to_string(), alpha)) +} + +/// Normalizes an insertion point: `None` appends. +pub(crate) fn insertion_index(index: Option, len: usize, unit: &str) -> OfficeResult { + match index { + None => Ok(len), + Some(index) if index <= len => Ok(index), + Some(index) => Err(OfficeError::out_of_range(format!( + "{unit} index {index} is out of range; valid insertion points are 0..={len}" + ))), + } +} + +/// Validates `index..index+count` against a list length. +pub(crate) fn existing_span( + index: usize, + count: Option, + len: usize, + unit: &str, +) -> OfficeResult> { + let count = count.unwrap_or(1); + if count == 0 { + return Err(OfficeError::invalid("count must be at least 1")); + } + if len == 0 { + return Err(OfficeError::out_of_range(format!( + "the document has no {unit}s yet" + ))); + } + if index >= len || index + count > len { + return Err(OfficeError::out_of_range(format!( + "{unit} range {index}..{} is out of range; the document has {len} {unit}(s), indexes 0..={}", + index + count, + len - 1 + ))); + } + Ok(index..index + count) +} + +/// Moves `span` so that it starts at `to` in the list that results after the +/// span is removed. +pub(crate) fn move_span( + items: &mut Vec, + span: std::ops::Range, + to: usize, + unit: &str, +) -> OfficeResult<()> { + let limit = items.len() - span.len(); + if to > limit { + return Err(OfficeError::out_of_range(format!( + "target {unit} position {to} is out of range; after removing the moved {unit}(s) valid positions are 0..={limit}" + ))); + } + let moved: Vec = items.drain(span).collect(); + items.splice(to..to, moved); + Ok(()) +} + +/// RFC 7386 JSON merge patch. +pub(crate) fn merge_patch(target: &mut Value, patch: &Value) { + match patch { + Value::Object(patch_map) => { + if !target.is_object() { + *target = Value::Object(Map::new()); + } + let target_map = target.as_object_mut().expect("object ensured above"); + for (key, value) in patch_map { + if value.is_null() { + target_map.remove(key); + } else { + merge_patch(target_map.entry(key.clone()).or_insert(Value::Null), value); + } + } + } + other => *target = other.clone(), + } +} + +/// Shortens text for previews, counting characters rather than bytes. +pub(crate) fn preview(text: &str, limit: usize) -> String { + let flattened: String = text + .chars() + .map(|c| if c == '\n' { ' ' } else { c }) + .collect(); + let count = flattened.chars().count(); + if count <= limit { + flattened + } else { + let head: String = flattened.chars().take(limit).collect(); + format!("{head}…(+{} chars)", count - limit) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn parses_color_forms() { + assert_eq!(parse_color("#abc").unwrap(), ("AABBCC".to_string(), None)); + assert_eq!(parse_color("112233").unwrap(), ("112233".to_string(), None)); + assert_eq!( + parse_color("#11223380").unwrap(), + ("112233".to_string(), Some(0x80)) + ); + assert!(parse_color("red").is_err()); + } + + #[test] + fn table_cell_accepts_shorthand() { + let cells: Vec = + serde_json::from_value(json!(["a", 3, null, {"text": "b", "bold": true}])).unwrap(); + assert_eq!(cells[0].text(), "a"); + assert_eq!(cells[1].text(), "3"); + assert!(cells[2].runs.is_empty()); + assert_eq!(cells[3].bold, Some(true)); + } + + #[test] + fn unknown_fields_are_reported_with_paths() { + let cell: TableCell = + serde_json::from_value(json!({"text": "a", "colour": "#fff"})).unwrap(); + let mut out = Vec::new(); + cell.unknown_fields("cell", &mut out); + assert_eq!(out, vec!["cell.colour".to_string()]); + } + + #[test] + fn move_span_places_items_after_removal() { + let mut items = vec![0, 1, 2, 3, 4]; + move_span(&mut items, 0..2, 3, "item").unwrap(); + assert_eq!(items, vec![2, 3, 4, 0, 1]); + } + + #[test] + fn suggests_close_operation_names() { + assert_eq!( + did_you_mean("insert_block", &["insert_blocks", "delete_blocks"]), + Some("insert_blocks") + ); + } +} diff --git a/src/crates/execution/office-documents/src/docx/markdown.rs b/src/crates/execution/office-documents/src/docx/markdown.rs new file mode 100644 index 0000000000..dce38be320 --- /dev/null +++ b/src/crates/execution/office-documents/src/docx/markdown.rs @@ -0,0 +1,507 @@ +//! Markdown → Word blocks (CommonMark plus GFM tables, strikethrough, and +//! task lists). + +use super::model::{ + Block, CodeBlock, EmptyBlock, HeadingBlock, ImageBlock, ListBlock, ListItem, ParagraphBlock, + QuoteBlock, TableBlock, TocBlock, +}; +use crate::common::{Align, Extra, Run, TableCell}; +use pulldown_cmark::{Alignment, CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag, TagEnd}; + +#[derive(Default, Clone)] +struct InlineState { + bold: usize, + italic: usize, + strike: usize, + link: Option, +} + +impl InlineState { + fn run(&self, text: &str, code: bool) -> Run { + Run { + text: text.to_string(), + bold: (self.bold > 0).then_some(true), + italic: (self.italic > 0).then_some(true), + strike: (self.strike > 0).then_some(true), + code: code.then_some(true), + link: self.link.clone(), + ..Run::default() + } + } +} + +/// Appends a run, merging it into the previous one when the formatting matches. +fn push_run(runs: &mut Vec, run: Run) { + if run.text.is_empty() { + return; + } + if let Some(last) = runs.last_mut() { + let mut probe = last.clone(); + probe.text = run.text.clone(); + if probe == run { + last.text.push_str(&run.text); + return; + } + } + runs.push(run); +} + +enum Container { + Paragraph, + Heading(u8), + Quote { runs: Vec }, + List(ListFrame), + Table(TableFrame), +} + +struct ListFrame { + ordered: bool, + start: Option, + items: Vec, + depth: u8, +} + +#[derive(Default)] +struct TableFrame { + alignments: Vec, + rows: Vec>, + current_row: Vec, + in_cell: bool, + head: bool, +} + +/// Parses Markdown into blocks. Image references are returned as image +/// blocks whose `src` the caller resolves. +pub fn markdown_to_blocks(markdown: &str) -> Vec { + let options = + Options::ENABLE_TABLES | Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TASKLISTS; + let parser = Parser::new_ext(markdown, options); + + let mut blocks: Vec = Vec::new(); + let mut runs: Vec = Vec::new(); + let mut inline = InlineState::default(); + let mut stack: Vec = Vec::new(); + let mut code: Option<(String, Option)> = None; + let mut image: Option<(String, String)> = None; + let mut list_depth: u8 = 0; + + // Where completed inline content lands depends on the innermost container. + fn flush_paragraph(blocks: &mut Vec, stack: &mut [Container], runs: &mut Vec) { + trim_runs(runs); + if runs.is_empty() { + return; + } + let taken = std::mem::take(runs); + match stack + .iter_mut() + .rev() + .find(|c| !matches!(c, Container::Paragraph)) + { + Some(Container::Quote { runs: quote_runs }) => { + if !quote_runs.is_empty() { + quote_runs.push(Run::plain("\n")); + } + quote_runs.extend(taken); + } + Some(Container::List(frame)) => { + if let Some(item) = frame.items.last_mut() { + if !item.runs.is_empty() { + item.runs.push(Run::plain("\n")); + } + item.runs.extend(taken); + } + } + _ => { + if is_toc_marker(&taken) { + blocks.push(Block::Toc(TocBlock { + title: None, + levels: 3, + extra: Extra::default(), + })); + } else { + blocks.push(Block::Paragraph(ParagraphBlock { + runs: taken, + ..ParagraphBlock::default() + })); + } + } + } + } + + for event in parser { + if let Some((text, _)) = code.as_mut() { + match event { + Event::Text(value) => { + text.push_str(&value); + continue; + } + Event::End(TagEnd::CodeBlock) => { + let (text, language) = code.take().unwrap_or_default(); + blocks.push(Block::Code(CodeBlock { + text: text.trim_end_matches('\n').to_string(), + language, + extra: Extra::default(), + })); + continue; + } + _ => continue, + } + } + if let Some((_, alt)) = image.as_mut() { + match event { + Event::Text(value) | Event::Code(value) => { + alt.push_str(&value); + continue; + } + Event::End(TagEnd::Image) => { + let (src, alt) = image.take().unwrap_or_default(); + // Pictures are blocks: close the text before and continue after. + flush_paragraph(&mut blocks, &mut stack, &mut runs); + blocks.push(Block::Image(ImageBlock { + src: Some(src), + asset: None, + width_cm: None, + height_cm: None, + align: Some(Align::Center), + caption: None, + alt: (!alt.trim().is_empty()).then(|| alt.trim().to_string()), + extra: Extra::default(), + })); + continue; + } + _ => continue, + } + } + + match event { + Event::Start(tag) => match tag { + Tag::Paragraph => stack.push(Container::Paragraph), + Tag::Heading { level, .. } => { + stack.push(Container::Heading(heading_level(level))); + } + Tag::BlockQuote(_) => stack.push(Container::Quote { runs: Vec::new() }), + Tag::CodeBlock(kind) => { + flush_paragraph(&mut blocks, &mut stack, &mut runs); + let language = match kind { + CodeBlockKind::Fenced(info) => info + .split_whitespace() + .next() + .filter(|value| !value.is_empty()) + .map(str::to_string), + CodeBlockKind::Indented => None, + }; + code = Some((String::new(), language)); + } + Tag::List(start) => { + flush_paragraph(&mut blocks, &mut stack, &mut runs); + let nested = stack.iter().any(|c| matches!(c, Container::List(_))); + if nested { + list_depth = list_depth.saturating_add(1); + } else { + list_depth = 0; + stack.push(Container::List(ListFrame { + ordered: start.is_some(), + start: start.map(|value| value as u32).filter(|value| *value != 1), + items: Vec::new(), + depth: 0, + })); + } + } + Tag::Item => { + flush_paragraph(&mut blocks, &mut stack, &mut runs); + if let Some(Container::List(frame)) = stack + .iter_mut() + .rev() + .find(|c| matches!(c, Container::List(_))) + { + frame.depth = list_depth; + frame.items.push(ListItem { + runs: Vec::new(), + level: list_depth.min(8), + extra: Extra::default(), + }); + } + } + Tag::Table(alignments) => { + flush_paragraph(&mut blocks, &mut stack, &mut runs); + stack.push(Container::Table(TableFrame { + alignments, + ..TableFrame::default() + })); + } + Tag::TableHead => { + if let Some(Container::Table(frame)) = stack.last_mut() { + frame.head = true; + } + } + Tag::TableRow => {} + Tag::TableCell => { + if let Some(Container::Table(frame)) = stack.last_mut() { + frame.in_cell = true; + } + } + Tag::Emphasis => inline.italic += 1, + Tag::Strong => inline.bold += 1, + Tag::Strikethrough => inline.strike += 1, + Tag::Link { dest_url, .. } => { + let url = dest_url.to_string(); + let lower = url.to_ascii_lowercase(); + inline.link = (lower.starts_with("http://") + || lower.starts_with("https://") + || lower.starts_with("mailto:")) + .then_some(url); + } + Tag::Image { dest_url, .. } => { + image = Some((dest_url.to_string(), String::new())); + } + Tag::HtmlBlock | Tag::FootnoteDefinition(_) | Tag::MetadataBlock(_) => {} + }, + Event::End(tag_end) => match tag_end { + TagEnd::Paragraph => { + flush_paragraph(&mut blocks, &mut stack, &mut runs); + if matches!(stack.last(), Some(Container::Paragraph)) { + stack.pop(); + } + } + TagEnd::Heading(_) => { + if let Some(Container::Heading(level)) = stack.pop() { + trim_runs(&mut runs); + let taken = std::mem::take(&mut runs); + if !taken.is_empty() { + blocks.push(Block::Heading(HeadingBlock { + level, + text: None, + runs: taken, + align: None, + extra: Extra::default(), + })); + } + } + } + TagEnd::BlockQuote => { + flush_paragraph(&mut blocks, &mut stack, &mut runs); + if let Some(Container::Quote { runs: quote_runs }) = stack.pop() { + if !quote_runs.is_empty() { + blocks.push(Block::Quote(QuoteBlock { + text: None, + runs: quote_runs, + extra: Extra::default(), + })); + } + } + } + TagEnd::List(_) => { + flush_paragraph(&mut blocks, &mut stack, &mut runs); + if list_depth > 0 { + list_depth -= 1; + } else if let Some(Container::List(frame)) = stack.pop() { + let items: Vec = frame + .items + .into_iter() + .filter(|item| !item.runs.is_empty()) + .collect(); + if !items.is_empty() { + blocks.push(Block::List(ListBlock { + ordered: frame.ordered, + start: frame.start, + items, + extra: Extra::default(), + })); + } + } + } + TagEnd::Item => { + // Tight list items carry their text without a paragraph. + flush_paragraph(&mut blocks, &mut stack, &mut runs); + } + TagEnd::TableCell => { + if let Some(Container::Table(frame)) = stack.last_mut() { + trim_runs(&mut runs); + let column = frame.current_row.len(); + let align = match frame.alignments.get(column) { + Some(Alignment::Center) => Some(Align::Center), + Some(Alignment::Right) => Some(Align::Right), + Some(Alignment::Left) => Some(Align::Left), + _ => None, + }; + frame.current_row.push(TableCell { + runs: std::mem::take(&mut runs), + align, + ..TableCell::default() + }); + frame.in_cell = false; + } + } + TagEnd::TableHead | TagEnd::TableRow => { + if let Some(Container::Table(frame)) = stack.last_mut() { + let row = std::mem::take(&mut frame.current_row); + if !row.is_empty() { + frame.rows.push(row); + } + } + } + TagEnd::Table => { + if let Some(Container::Table(frame)) = stack.pop() { + if !frame.rows.is_empty() { + blocks.push(Block::Table(TableBlock { + rows: frame.rows, + header_rows: u32::from(frame.head), + column_widths_cm: None, + borders: true, + font_size_pt: None, + caption: None, + extra: Extra::default(), + })); + } + } + } + TagEnd::Emphasis => inline.italic = inline.italic.saturating_sub(1), + TagEnd::Strong => inline.bold = inline.bold.saturating_sub(1), + TagEnd::Strikethrough => inline.strike = inline.strike.saturating_sub(1), + TagEnd::Link => inline.link = None, + _ => {} + }, + Event::Text(text) => push_run(&mut runs, inline.run(&text, false)), + Event::Code(text) => push_run(&mut runs, inline.run(&text, true)), + Event::InlineMath(text) | Event::DisplayMath(text) => { + push_run(&mut runs, inline.run(&text, false)) + } + Event::SoftBreak => push_run(&mut runs, inline.run(" ", false)), + Event::HardBreak => push_run(&mut runs, inline.run("\n", false)), + Event::Rule => { + flush_paragraph(&mut blocks, &mut stack, &mut runs); + blocks.push(Block::HorizontalRule(EmptyBlock::default())); + } + Event::TaskListMarker(checked) => { + push_run(&mut runs, Run::plain(if checked { "☑ " } else { "☐ " })); + } + Event::Html(html) | Event::InlineHtml(html) => { + let lower = html.to_ascii_lowercase(); + if lower.contains("pagebreak") || lower.contains("page-break") { + flush_paragraph(&mut blocks, &mut stack, &mut runs); + blocks.push(Block::PageBreak(EmptyBlock::default())); + } else if lower.trim_start().starts_with(" {} + } + } + flush_paragraph(&mut blocks, &mut stack, &mut runs); + blocks +} + +fn heading_level(level: HeadingLevel) -> u8 { + match level { + HeadingLevel::H1 => 1, + HeadingLevel::H2 => 2, + HeadingLevel::H3 => 3, + HeadingLevel::H4 => 4, + HeadingLevel::H5 => 5, + HeadingLevel::H6 => 6, + } +} + +fn trim_runs(runs: &mut Vec) { + while runs + .last() + .is_some_and(|run| run.text.trim().is_empty() && run.text != "\n") + { + runs.pop(); + } + while runs.first().is_some_and(|run| run.text.trim().is_empty()) { + runs.remove(0); + } + if let Some(first) = runs.first_mut() { + first.text = first.text.trim_start().to_string(); + } + if let Some(last) = runs.last_mut() { + last.text = last.text.trim_end().to_string(); + } + runs.retain(|run| !run.text.is_empty()); +} + +fn is_toc_marker(runs: &[Run]) -> bool { + let text: String = runs.iter().map(|run| run.text.as_str()).collect(); + matches!( + text.trim().to_ascii_lowercase().as_str(), + "[toc]" | "[[toc]]" + ) +} + +/// Image sources referenced by Markdown, in document order. +pub fn markdown_image_sources(markdown: &str) -> Vec { + markdown_to_blocks(markdown) + .into_iter() + .filter_map(|block| match block { + Block::Image(image) => image.src, + _ => None, + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::common::runs_text; + + #[test] + fn converts_common_structures() { + let blocks = markdown_to_blocks( + "# Title\n\nSome **bold** and *it* with [link](https://a.b).\n\n- one\n- two\n - nested\n\n1. first\n2. second\n\n| A | B |\n|---|--:|\n| 1 | 2 |\n\n```rust\nfn main() {}\n```\n\n> quoted\n\n---\n\n![chart](./c.png)\n\n[TOC]\n", + ); + let kinds: Vec<&str> = blocks.iter().map(Block::kind).collect(); + assert_eq!( + kinds, + vec![ + "heading", + "paragraph", + "list", + "list", + "table", + "code", + "quote", + "horizontal_rule", + "image", + "toc" + ] + ); + let Block::Paragraph(paragraph) = &blocks[1] else { + panic!() + }; + assert!(paragraph + .runs + .iter() + .any(|run| run.bold == Some(true) && run.text == "bold")); + assert!(paragraph + .runs + .iter() + .any(|run| run.link.as_deref() == Some("https://a.b"))); + let Block::List(list) = &blocks[2] else { + panic!() + }; + assert_eq!(list.items.len(), 3); + assert_eq!(list.items[2].level, 1); + assert_eq!(runs_text(&list.items[2].runs), "nested"); + let Block::List(ordered) = &blocks[3] else { + panic!() + }; + assert!(ordered.ordered); + let Block::Table(table) = &blocks[4] else { + panic!() + }; + assert_eq!(table.header_rows, 1); + assert_eq!(table.rows[1][1].align, Some(Align::Right)); + assert_eq!( + markdown_image_sources("![x](a.png) text ![y](b.jpg)"), + vec!["a.png", "b.jpg"] + ); + } + + #[test] + fn splits_paragraph_around_inline_image() { + let blocks = markdown_to_blocks("before ![pic](p.png) after"); + let kinds: Vec<&str> = blocks.iter().map(Block::kind).collect(); + assert_eq!(kinds, vec!["paragraph", "image", "paragraph"]); + } +} diff --git a/src/crates/execution/office-documents/src/docx/mod.rs b/src/crates/execution/office-documents/src/docx/mod.rs new file mode 100644 index 0000000000..c7b42982ed --- /dev/null +++ b/src/crates/execution/office-documents/src/docx/mod.rs @@ -0,0 +1,90 @@ +//! Word documents (`.docx`). + +mod markdown; +pub(crate) mod model; +pub(crate) mod ops; +pub(crate) mod render; + +pub use markdown::{markdown_image_sources, markdown_to_blocks}; +pub use model::{Block, DocxDocument}; + +use crate::common::preview; +use crate::{Detail, ReadRequest}; +use serde_json::{json, Value}; + +pub(crate) fn read(doc: &DocxDocument, request: &ReadRequest) -> Value { + let total = doc.blocks.len(); + let (offset, limit) = request.window(total, 50); + let blocks: Vec = doc + .blocks + .iter() + .enumerate() + .skip(offset) + .take(limit) + .map(|(index, block)| { + if request.detail == Detail::Full { + let mut value = serde_json::to_value(block).unwrap_or(Value::Null); + if let Some(object) = value.as_object_mut() { + object.insert("index".to_string(), json!(index)); + } + return value; + } + let mut entry = json!({ + "index": index, + "type": block.kind(), + }); + let text = block.plain_text(); + if !text.is_empty() { + entry["text"] = json!(preview(&text, 160)); + } + match block { + Block::Heading(heading) => entry["level"] = json!(heading.level), + Block::List(list) => { + entry["items"] = json!(list.items.len()); + entry["ordered"] = json!(list.ordered); + } + Block::Table(table) => { + entry["rows"] = json!(table.rows.len()); + entry["columns"] = json!(table.rows.iter().map(Vec::len).max().unwrap_or(0)); + } + Block::Image(image) => entry["asset"] = json!(image.asset), + _ => {} + } + entry + }) + .collect(); + let headings: Vec = doc + .blocks + .iter() + .enumerate() + .filter_map(|(index, block)| match block { + Block::Heading(heading) => Some(json!({ + "index": index, + "level": heading.level, + "text": preview(&block.plain_text(), 80), + })), + _ => None, + }) + .take(200) + .collect(); + let mut view = json!({ + "total_blocks": total, + "offset": offset, + "limit": limit, + "blocks": blocks, + "headings": headings, + }); + if offset + limit < total { + view["next_offset"] = json!(offset + limit); + } + if offset == 0 { + view["settings"] = json!({ + "properties": doc.properties, + "page": doc.page, + "styles": doc.styles, + "header": doc.header, + "footer": doc.footer, + }); + } + view +} diff --git a/src/crates/execution/office-documents/src/docx/model.rs b/src/crates/execution/office-documents/src/docx/model.rs new file mode 100644 index 0000000000..df2d6c20ad --- /dev/null +++ b/src/crates/execution/office-documents/src/docx/model.rs @@ -0,0 +1,721 @@ +//! Word document model: page setup, styles, and an ordered list of blocks. + +use crate::common::{ + canonical_runs, parse_color, prefix, report_extra, report_list, runs_text, validate_runs, + Align, DocumentProperties, Extra, Run, TableCell, UnknownFields, +}; +use crate::error::{OfficeError, OfficeResult}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct DocxDocument { + #[serde(default)] + pub properties: DocumentProperties, + #[serde(default)] + pub page: PageSetup, + #[serde(default)] + pub styles: DocxStyles, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub header: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub footer: Option, + #[serde(default)] + pub blocks: Vec, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PaperSize { + #[default] + #[serde(alias = "A4")] + A4, + #[serde(alias = "Letter")] + Letter, + #[serde(alias = "Legal")] + Legal, + #[serde(alias = "A3")] + A3, + #[serde(alias = "A5")] + A5, +} + +impl PaperSize { + /// Portrait width and height in twentieths of a point. + pub const fn twips(self) -> (u32, u32) { + match self { + Self::A4 => (11906, 16838), + Self::Letter => (12240, 15840), + Self::Legal => (12240, 20160), + Self::A3 => (16838, 23811), + Self::A5 => (8391, 11906), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Orientation { + #[default] + Portrait, + Landscape, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Margins { + #[serde(default = "default_margin")] + pub top: f64, + #[serde(default = "default_margin")] + pub bottom: f64, + #[serde(default = "default_margin")] + pub left: f64, + #[serde(default = "default_margin")] + pub right: f64, + #[serde(flatten)] + pub extra: Extra, +} + +fn default_margin() -> f64 { + 2.54 +} + +impl Default for Margins { + fn default() -> Self { + Self { + top: default_margin(), + bottom: default_margin(), + left: default_margin(), + right: default_margin(), + extra: Extra::default(), + } + } +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct PageSetup { + #[serde(default)] + pub size: PaperSize, + #[serde(default)] + pub orientation: Orientation, + /// Margins in centimeters. + #[serde(default, alias = "margins")] + pub margins_cm: Margins, + #[serde(flatten)] + pub extra: Extra, +} + +impl PageSetup { + /// Page width and height in twips after orientation. + pub fn page_twips(&self) -> (u32, u32) { + let (width, height) = self.size.twips(); + match self.orientation { + Orientation::Portrait => (width, height), + Orientation::Landscape => (height, width), + } + } + + /// Width available to text, in twips. + pub fn text_width_twips(&self) -> u32 { + let (width, _) = self.page_twips(); + let margins = cm_to_twips(self.margins_cm.left) + cm_to_twips(self.margins_cm.right); + width.saturating_sub(margins).max(1440) + } + + pub fn validate(&self) -> OfficeResult<()> { + let m = &self.margins_cm; + for (name, value) in [ + ("top", m.top), + ("bottom", m.bottom), + ("left", m.left), + ("right", m.right), + ] { + if !(0.0..=10.0).contains(&value) { + return Err(OfficeError::invalid(format!( + "page.margins_cm.{name} must be between 0 and 10 cm, got {value}" + ))); + } + } + Ok(()) + } +} + +pub(crate) fn cm_to_twips(cm: f64) -> u32 { + (cm * 1440.0 / 2.54).round().max(0.0) as u32 +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct DocxStyles { + /// Latin body font; Word's default when absent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub font: Option, + /// Font for CJK text, such as "Microsoft YaHei" or "SimSun". + #[serde(default, skip_serializing_if = "Option::is_none")] + pub east_asia_font: Option, + #[serde(default = "default_body_size", alias = "size_pt")] + pub font_size_pt: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub heading_font: Option, + #[serde(default = "default_heading_color")] + pub heading_color: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text_color: Option, + /// Line spacing as a multiple of single spacing. + #[serde(default = "default_line_spacing")] + pub line_spacing: f64, + #[serde(default = "default_space_after")] + pub paragraph_space_after_pt: f64, + /// Fill of table header rows. + #[serde(default = "default_table_header_fill")] + pub table_header_fill: String, + #[serde(flatten)] + pub extra: Extra, +} + +fn default_body_size() -> f64 { + 11.0 +} +fn default_heading_color() -> String { + "#1F3864".to_string() +} +fn default_line_spacing() -> f64 { + 1.15 +} +fn default_space_after() -> f64 { + 8.0 +} +fn default_table_header_fill() -> String { + "#D9E2F3".to_string() +} + +impl Default for DocxStyles { + fn default() -> Self { + Self { + font: None, + east_asia_font: None, + font_size_pt: default_body_size(), + heading_font: None, + heading_color: default_heading_color(), + text_color: None, + line_spacing: default_line_spacing(), + paragraph_space_after_pt: default_space_after(), + table_header_fill: default_table_header_fill(), + extra: Extra::default(), + } + } +} + +impl DocxStyles { + pub fn validate(&self) -> OfficeResult<()> { + if !(6.0..=72.0).contains(&self.font_size_pt) { + return Err(OfficeError::invalid(format!( + "styles.font_size_pt must be between 6 and 72, got {}", + self.font_size_pt + ))); + } + if !(0.8..=3.0).contains(&self.line_spacing) { + return Err(OfficeError::invalid(format!( + "styles.line_spacing must be between 0.8 and 3.0, got {}", + self.line_spacing + ))); + } + if !(0.0..=72.0).contains(&self.paragraph_space_after_pt) { + return Err(OfficeError::invalid( + "styles.paragraph_space_after_pt must be between 0 and 72", + )); + } + parse_color(&self.heading_color).map_err(|err| prefix(err, "styles", "heading_color"))?; + parse_color(&self.table_header_fill) + .map_err(|err| prefix(err, "styles", "table_header_fill"))?; + if let Some(color) = &self.text_color { + parse_color(color).map_err(|err| prefix(err, "styles", "text_color"))?; + } + Ok(()) + } +} + +/// Header or footer text. `{PAGE}` and `{NUMPAGES}` become page fields. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct HeaderFooter { + pub text: String, + #[serde(default = "default_hf_align")] + pub align: Align, + #[serde(flatten)] + pub extra: Extra, +} + +fn default_hf_align() -> Align { + Align::Center +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Block { + Heading(HeadingBlock), + Paragraph(ParagraphBlock), + List(ListBlock), + Table(TableBlock), + Image(ImageBlock), + #[serde(alias = "code_block")] + Code(CodeBlock), + #[serde(alias = "blockquote")] + Quote(QuoteBlock), + PageBreak(EmptyBlock), + #[serde(alias = "rule", alias = "divider")] + HorizontalRule(EmptyBlock), + #[serde(alias = "table_of_contents")] + Toc(TocBlock), +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct HeadingBlock { + pub level: u8, + #[serde(default, skip_serializing)] + pub text: Option, + #[serde(default)] + pub runs: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub align: Option, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ParagraphStyle { + Normal, + Title, + Subtitle, + Caption, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct ParagraphBlock { + #[serde(default, skip_serializing)] + pub text: Option, + #[serde(default)] + pub runs: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub style: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub align: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub indent_cm: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub first_line_indent_cm: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub space_before_pt: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub space_after_pt: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub line_spacing: Option, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ListBlock { + #[serde(default)] + pub ordered: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start: Option, + pub items: Vec, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(from = "ListItemInput")] +pub struct ListItem { + #[serde(default)] + pub runs: Vec, + /// Nesting level, 0 for top-level items. + #[serde(default)] + pub level: u8, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Deserialize)] +#[serde(untagged)] +enum ListItemInput { + Text(String), + Full(ListItemFull), +} + +#[derive(Deserialize)] +struct ListItemFull { + #[serde(default)] + text: Option, + #[serde(default)] + runs: Vec, + #[serde(default)] + level: u8, + #[serde(flatten)] + extra: Extra, +} + +impl From for ListItem { + fn from(input: ListItemInput) -> Self { + match input { + ListItemInput::Text(text) => ListItem { + runs: vec![Run::plain(text)], + level: 0, + extra: Extra::default(), + }, + ListItemInput::Full(mut full) => { + canonical_runs(&mut full.text, &mut full.runs); + ListItem { + runs: full.runs, + level: full.level, + extra: full.extra, + } + } + } + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TableBlock { + pub rows: Vec>, + /// Leading rows styled as headers and repeated on every page. + #[serde(default = "default_header_rows")] + pub header_rows: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub column_widths_cm: Option>, + #[serde(default = "default_true")] + pub borders: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub font_size_pt: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub caption: Option, + #[serde(flatten)] + pub extra: Extra, +} + +fn default_header_rows() -> u32 { + 1 +} +fn default_true() -> bool { + true +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ImageBlock { + /// Source path or data URL given by the caller; informational once the + /// picture is embedded. + #[serde( + default, + skip_serializing_if = "Option::is_none", + alias = "url", + alias = "path" + )] + pub src: Option, + /// Name of the embedded picture. Echo it back to keep the same picture. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub asset: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub width_cm: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub height_cm: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub align: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub caption: Option, + #[serde(default, skip_serializing_if = "Option::is_none", alias = "alt_text")] + pub alt: Option, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct CodeBlock { + pub text: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub language: Option, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct QuoteBlock { + #[serde(default, skip_serializing)] + pub text: Option, + #[serde(default)] + pub runs: Vec, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct EmptyBlock { + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TocBlock { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + /// Deepest heading level listed. + #[serde(default = "default_toc_levels")] + pub levels: u8, + #[serde(flatten)] + pub extra: Extra, +} + +fn default_toc_levels() -> u8 { + 3 +} + +impl Block { + pub fn kind(&self) -> &'static str { + match self { + Block::Heading(_) => "heading", + Block::Paragraph(_) => "paragraph", + Block::List(_) => "list", + Block::Table(_) => "table", + Block::Image(_) => "image", + Block::Code(_) => "code", + Block::Quote(_) => "quote", + Block::PageBreak(_) => "page_break", + Block::HorizontalRule(_) => "horizontal_rule", + Block::Toc(_) => "toc", + } + } + + /// Moves `text` shorthands into `runs` so stored blocks have one shape. + pub fn canonicalize(&mut self) { + match self { + Block::Heading(block) => canonical_runs(&mut block.text, &mut block.runs), + Block::Paragraph(block) => canonical_runs(&mut block.text, &mut block.runs), + Block::Quote(block) => canonical_runs(&mut block.text, &mut block.runs), + _ => {} + } + } + + /// Plain text of the block, for previews and search. + pub fn plain_text(&self) -> String { + match self { + Block::Heading(block) => runs_text(&block.runs), + Block::Paragraph(block) => runs_text(&block.runs), + Block::Quote(block) => runs_text(&block.runs), + Block::List(block) => block + .items + .iter() + .map(|item| runs_text(&item.runs)) + .collect::>() + .join(" | "), + Block::Table(block) => block + .rows + .iter() + .map(|row| { + row.iter() + .map(TableCell::text) + .collect::>() + .join(" | ") + }) + .collect::>() + .join(" / "), + Block::Image(block) => block + .caption + .clone() + .or_else(|| block.alt.clone()) + .unwrap_or_default(), + Block::Code(block) => block.text.clone(), + Block::Toc(block) => block.title.clone().unwrap_or_default(), + Block::PageBreak(_) | Block::HorizontalRule(_) => String::new(), + } + } + + /// Every run of the block, for text replacement. + pub fn runs_mut(&mut self) -> Vec<&mut Run> { + match self { + Block::Heading(block) => block.runs.iter_mut().collect(), + Block::Paragraph(block) => block.runs.iter_mut().collect(), + Block::Quote(block) => block.runs.iter_mut().collect(), + Block::List(block) => block + .items + .iter_mut() + .flat_map(|item| item.runs.iter_mut()) + .collect(), + Block::Table(block) => block + .rows + .iter_mut() + .flat_map(|row| row.iter_mut()) + .flat_map(|cell| cell.runs.iter_mut()) + .collect(), + _ => Vec::new(), + } + } + + pub fn validate(&self, path: &str) -> OfficeResult<()> { + match self { + Block::Heading(block) => { + if !(1..=6).contains(&block.level) { + return Err(OfficeError::invalid(format!( + "{path}.level must be 1..=6, got {}", + block.level + ))); + } + if runs_text(&block.runs).trim().is_empty() { + return Err(OfficeError::invalid(format!("{path}: heading has no text"))); + } + validate_runs(&block.runs, path) + } + Block::Paragraph(block) => { + if let Some(spacing) = block.line_spacing { + if !(0.8..=3.0).contains(&spacing) { + return Err(OfficeError::invalid(format!( + "{path}.line_spacing must be between 0.8 and 3.0" + ))); + } + } + validate_runs(&block.runs, path) + } + Block::Quote(block) => validate_runs(&block.runs, path), + Block::List(block) => { + if block.items.is_empty() { + return Err(OfficeError::invalid(format!("{path}: list has no items"))); + } + for (index, item) in block.items.iter().enumerate() { + if item.level > 8 { + return Err(OfficeError::invalid(format!( + "{path}.items[{index}].level must be 0..=8" + ))); + } + validate_runs(&item.runs, &format!("{path}.items[{index}]"))?; + } + Ok(()) + } + Block::Table(block) => { + if block.rows.is_empty() || block.rows.iter().all(Vec::is_empty) { + return Err(OfficeError::invalid(format!("{path}: table has no cells"))); + } + if block.rows.len() > 2000 { + return Err(OfficeError::limit(format!( + "{path}: tables are limited to 2000 rows" + ))); + } + for (row_index, row) in block.rows.iter().enumerate() { + if row.len() > 63 { + return Err(OfficeError::limit(format!( + "{path}.rows[{row_index}]: Word tables are limited to 63 columns" + ))); + } + for (cell_index, cell) in row.iter().enumerate() { + cell.validate(&format!("{path}.rows[{row_index}][{cell_index}]"))?; + } + } + if let Some(widths) = &block.column_widths_cm { + if widths.iter().any(|width| !(0.2..=60.0).contains(width)) { + return Err(OfficeError::invalid(format!( + "{path}.column_widths_cm values must be between 0.2 and 60" + ))); + } + } + Ok(()) + } + Block::Image(block) => { + if block.src.is_none() && block.asset.is_none() { + return Err(OfficeError::invalid(format!( + "{path}: image needs `src` (a file path or data URL) or the `asset` of an embedded picture" + ))); + } + for (name, value) in [("width_cm", block.width_cm), ("height_cm", block.height_cm)] + { + if let Some(value) = value { + if !(0.1..=100.0).contains(&value) { + return Err(OfficeError::invalid(format!( + "{path}.{name} must be between 0.1 and 100" + ))); + } + } + } + Ok(()) + } + Block::Toc(block) => { + if !(1..=6).contains(&block.levels) { + return Err(OfficeError::invalid(format!("{path}.levels must be 1..=6"))); + } + Ok(()) + } + Block::Code(_) | Block::PageBreak(_) | Block::HorizontalRule(_) => Ok(()), + } + } +} + +impl UnknownFields for Block { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + match self { + Block::Heading(block) => { + report_extra(&block.extra, path, out); + report_list(&block.runs, &format!("{path}.runs"), out); + } + Block::Paragraph(block) => { + report_extra(&block.extra, path, out); + report_list(&block.runs, &format!("{path}.runs"), out); + } + Block::Quote(block) => { + report_extra(&block.extra, path, out); + report_list(&block.runs, &format!("{path}.runs"), out); + } + Block::List(block) => { + report_extra(&block.extra, path, out); + for (index, item) in block.items.iter().enumerate() { + let item_path = format!("{path}.items[{index}]"); + report_extra(&item.extra, &item_path, out); + report_list(&item.runs, &format!("{item_path}.runs"), out); + } + } + Block::Table(block) => { + report_extra(&block.extra, path, out); + for (row_index, row) in block.rows.iter().enumerate() { + report_list(row, &format!("{path}.rows[{row_index}]"), out); + } + } + Block::Image(block) => report_extra(&block.extra, path, out), + Block::Code(block) => report_extra(&block.extra, path, out), + Block::PageBreak(block) | Block::HorizontalRule(block) => { + report_extra(&block.extra, path, out) + } + Block::Toc(block) => report_extra(&block.extra, path, out), + } + } +} + +impl UnknownFields for PageSetup { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + report_extra(&self.margins_cm.extra, &format!("{path}.margins_cm"), out); + } +} + +impl UnknownFields for DocxStyles { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + } +} + +impl UnknownFields for HeaderFooter { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + } +} + +impl UnknownFields for DocxDocument { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + self.properties + .unknown_fields(&format!("{path}.properties"), out); + self.page.unknown_fields(&format!("{path}.page"), out); + self.styles.unknown_fields(&format!("{path}.styles"), out); + if let Some(header) = &self.header { + header.unknown_fields(&format!("{path}.header"), out); + } + if let Some(footer) = &self.footer { + footer.unknown_fields(&format!("{path}.footer"), out); + } + report_list(&self.blocks, &format!("{path}.blocks"), out); + } +} diff --git a/src/crates/execution/office-documents/src/docx/ops.rs b/src/crates/execution/office-documents/src/docx/ops.rs new file mode 100644 index 0000000000..162e75df83 --- /dev/null +++ b/src/crates/execution/office-documents/src/docx/ops.rs @@ -0,0 +1,408 @@ +//! Word edit operations. + +use super::markdown::markdown_to_blocks; +use super::model::{Block, DocxDocument, DocxStyles, HeaderFooter, PageSetup}; +use crate::common::{ + existing_span, insertion_index, merge_patch, move_span, parse_operation, report_extra, + report_list, unknown_operation, Align, DocumentProperties, Extra, UnknownFields, +}; +use crate::error::{OfficeError, OfficeResult}; +use crate::ApplyContext; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +pub(crate) const OPERATIONS: &[&str] = &[ + "insert_blocks", + "replace_blocks", + "delete_blocks", + "move_blocks", + "replace_text", + "set_page_setup", + "set_styles", + "set_header_footer", + "set_properties", +]; + +const MAX_BLOCKS: usize = 20_000; + +#[derive(Deserialize)] +struct BlockContent { + #[serde(default)] + blocks: Option>, + #[serde(default)] + markdown: Option, +} + +#[derive(Deserialize)] +struct InsertBlocks { + #[serde(default)] + index: Option, + #[serde(flatten)] + content: BlockContent, + #[serde(flatten)] + extra: Extra, +} + +#[derive(Deserialize)] +struct ReplaceBlocks { + index: usize, + #[serde(default)] + count: Option, + #[serde(flatten)] + content: BlockContent, + #[serde(flatten)] + extra: Extra, +} + +#[derive(Deserialize)] +struct DeleteBlocks { + index: usize, + #[serde(default)] + count: Option, + #[serde(flatten)] + extra: Extra, +} + +#[derive(Deserialize)] +struct MoveBlocks { + index: usize, + #[serde(default)] + count: Option, + to: usize, + #[serde(flatten)] + extra: Extra, +} + +#[derive(Deserialize)] +struct ReplaceText { + find: String, + replace: String, + #[serde(default = "default_true")] + match_case: bool, + #[serde(flatten)] + extra: Extra, +} + +fn default_true() -> bool { + true +} + +impl UnknownFields for BlockContent { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + if let Some(blocks) = &self.blocks { + report_list(blocks, &format!("{path}blocks"), out); + } + } +} + +impl UnknownFields for InsertBlocks { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_known_extra(&self.extra, &["blocks", "markdown"], path, out); + self.content.unknown_fields(path, out); + } +} + +impl UnknownFields for ReplaceBlocks { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_known_extra(&self.extra, &["blocks", "markdown"], path, out); + self.content.unknown_fields(path, out); + } +} + +impl UnknownFields for DeleteBlocks { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + } +} + +impl UnknownFields for MoveBlocks { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + } +} + +impl UnknownFields for ReplaceText { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + } +} + +/// Two flattened structs see the same keys; drop the ones the sibling owns. +fn report_known_extra(extra: &Extra, owned_elsewhere: &[&str], path: &str, out: &mut Vec) { + let filtered: Extra = extra + .iter() + .filter(|(key, _)| !owned_elsewhere.contains(&key.as_str())) + .map(|(key, value)| (key.clone(), value.clone())) + .collect(); + report_extra(&filtered, path, out); +} + +pub(crate) fn apply( + doc: &mut DocxDocument, + op: &str, + value: &Value, + ctx: &mut ApplyContext, +) -> OfficeResult<()> { + match op { + "insert_blocks" => { + let input: InsertBlocks = parse_operation(value)?; + let blocks = prepare_blocks(input.content, ctx)?; + let at = insertion_index(input.index, doc.blocks.len(), "block")?; + ensure_capacity(doc.blocks.len() + blocks.len())?; + let count = blocks.len(); + doc.blocks.splice(at..at, blocks); + ctx.note(format!("inserted {count} block(s) at index {at}")); + Ok(()) + } + "replace_blocks" => { + let input: ReplaceBlocks = parse_operation(value)?; + let span = existing_span(input.index, input.count, doc.blocks.len(), "block")?; + let blocks = prepare_blocks(input.content, ctx)?; + ensure_capacity(doc.blocks.len() - span.len() + blocks.len())?; + let (removed, added) = (span.len(), blocks.len()); + doc.blocks.splice(span.clone(), blocks); + ctx.note(format!( + "replaced {removed} block(s) at index {} with {added}", + span.start + )); + Ok(()) + } + "delete_blocks" => { + let input: DeleteBlocks = parse_operation(value)?; + let span = existing_span(input.index, input.count, doc.blocks.len(), "block")?; + let removed = span.len(); + doc.blocks.drain(span); + ctx.note(format!( + "deleted {removed} block(s) at index {}", + input.index + )); + Ok(()) + } + "move_blocks" => { + let input: MoveBlocks = parse_operation(value)?; + let span = existing_span(input.index, input.count, doc.blocks.len(), "block")?; + move_span(&mut doc.blocks, span, input.to, "block")?; + ctx.note(format!( + "moved block(s) from {} to {}", + input.index, input.to + )); + Ok(()) + } + "replace_text" => { + let input: ReplaceText = parse_operation(value)?; + if input.find.is_empty() { + return Err(OfficeError::invalid("`find` must not be empty")); + } + let mut replaced = 0; + for block in &mut doc.blocks { + for run in block.runs_mut() { + let (text, count) = + replace_all(&run.text, &input.find, &input.replace, input.match_case); + if count > 0 { + run.text = text; + replaced += count; + } + } + } + if replaced == 0 { + ctx.warn(format!( + "replace_text found no match for `{}` (a match split across differently formatted runs is not found)", + input.find + )); + } else { + ctx.note(format!( + "replaced {replaced} occurrence(s) of `{}`", + input.find + )); + } + Ok(()) + } + "set_page_setup" => { + patch_struct::(&mut doc.page, value)?; + doc.page.validate()?; + ctx.note("updated page setup".to_string()); + Ok(()) + } + "set_styles" => { + patch_struct::(&mut doc.styles, value)?; + doc.styles.validate()?; + ctx.note("updated document styles".to_string()); + Ok(()) + } + "set_header_footer" => { + let object = value.as_object().cloned().unwrap_or_default(); + for key in object.keys() { + if !matches!(key.as_str(), "op" | "header" | "footer") { + return Err(OfficeError::invalid(format!( + "unknown field `{key}`; set_header_footer accepts `header` and `footer`" + ))); + } + } + if let Some(header) = object.get("header") { + doc.header = header_footer(header, "header")?; + } + if let Some(footer) = object.get("footer") { + doc.footer = header_footer(footer, "footer")?; + } + ctx.note("updated header/footer".to_string()); + Ok(()) + } + "set_properties" => { + let input: DocumentProperties = parse_operation(value)?; + doc.properties.merge(&input); + ctx.note("updated document properties".to_string()); + Ok(()) + } + other => Err(unknown_operation(other, OPERATIONS)), + } +} + +fn ensure_capacity(count: usize) -> OfficeResult<()> { + if count > MAX_BLOCKS { + return Err(OfficeError::limit(format!( + "a document is limited to {MAX_BLOCKS} blocks" + ))); + } + Ok(()) +} + +fn header_footer(value: &Value, name: &str) -> OfficeResult> { + match value { + Value::Null => Ok(None), + Value::String(text) if text.trim().is_empty() => Ok(None), + Value::String(text) => Ok(Some(HeaderFooter { + text: text.clone(), + align: Align::Center, + extra: Extra::default(), + })), + Value::Object(_) => { + let parsed: HeaderFooter = serde_json::from_value(value.clone()) + .map_err(|err| OfficeError::invalid(format!("{name}: {err}")))?; + let mut unknown = Vec::new(); + parsed.unknown_fields(name, &mut unknown); + if !unknown.is_empty() { + return Err(OfficeError::invalid(format!( + "unknown field(s): {}", + unknown.join(", ") + ))); + } + Ok(Some(parsed)) + } + _ => Err(OfficeError::invalid(format!( + "{name} must be a string, an object {{text, align}}, or null" + ))), + } +} + +/// Applies a JSON merge patch (the operation minus `op`) to a settings struct. +pub(crate) fn patch_struct(target: &mut T, op_value: &Value) -> OfficeResult<()> +where + T: Serialize + DeserializeOwned + UnknownFields, +{ + let mut patch = op_value.clone(); + if let Some(object) = patch.as_object_mut() { + object.remove("op"); + } + let mut current = + serde_json::to_value(&*target).map_err(|err| OfficeError::invalid(err.to_string()))?; + merge_patch(&mut current, &patch); + let updated: T = + serde_json::from_value(current).map_err(|err| OfficeError::invalid(err.to_string()))?; + let mut unknown = Vec::new(); + updated.unknown_fields("", &mut unknown); + if !unknown.is_empty() { + return Err(OfficeError::invalid(format!( + "unknown field(s): {}", + unknown.join(", ") + ))); + } + *target = updated; + Ok(()) +} + +fn prepare_blocks(content: BlockContent, ctx: &mut ApplyContext) -> OfficeResult> { + let mut blocks = Vec::new(); + match (content.blocks, content.markdown) { + (Some(_), Some(_)) => { + return Err(OfficeError::invalid( + "pass either `blocks` or `markdown`, not both", + )) + } + (Some(list), None) => blocks.extend(list), + (None, Some(markdown)) => { + let parsed = markdown_to_blocks(&markdown); + if parsed.is_empty() && !markdown.trim().is_empty() { + ctx.warn("the markdown produced no blocks".to_string()); + } + blocks.extend(parsed); + } + (None, None) => { + return Err(OfficeError::invalid( + "pass `blocks` (an array of block objects) or `markdown` (a string)", + )) + } + } + if blocks.is_empty() { + return Err(OfficeError::invalid("no blocks to insert")); + } + for (index, block) in blocks.iter_mut().enumerate() { + block.canonicalize(); + let path = format!("blocks[{index}]"); + block.validate(&path)?; + if let Block::Image(image) = block { + let asset = ctx.resolve_image(image.src.as_deref(), image.asset.as_deref(), &path)?; + image.asset = Some(asset); + } + } + Ok(blocks) +} + +/// Replaces every occurrence, returning the new text and the match count. +pub(crate) fn replace_all( + text: &str, + find: &str, + replace: &str, + match_case: bool, +) -> (String, usize) { + if match_case { + let count = text.matches(find).count(); + return (text.replace(find, replace), count); + } + let lower_text = text.to_lowercase(); + let lower_find = find.to_lowercase(); + // Lowercasing can change byte lengths; fall back to exact matching then. + if lower_text.len() != text.len() || lower_find.len() != find.len() { + let count = text.matches(find).count(); + return (text.replace(find, replace), count); + } + let mut out = String::with_capacity(text.len()); + let mut count = 0; + let mut cursor = 0; + while let Some(position) = lower_text[cursor..].find(&lower_find) { + let start = cursor + position; + out.push_str(&text[cursor..start]); + out.push_str(replace); + cursor = start + find.len(); + count += 1; + } + out.push_str(&text[cursor..]); + (out, count) +} + +#[cfg(test)] +mod tests { + use super::replace_all; + + #[test] + fn replaces_case_insensitively() { + assert_eq!( + replace_all("Foo foo", "foo", "bar", false), + ("bar bar".to_string(), 2) + ); + assert_eq!( + replace_all("Foo foo", "foo", "bar", true), + ("Foo bar".to_string(), 1) + ); + } +} diff --git a/src/crates/execution/office-documents/src/docx/render.rs b/src/crates/execution/office-documents/src/docx/render.rs new file mode 100644 index 0000000000..f23b555f0c --- /dev/null +++ b/src/crates/execution/office-documents/src/docx/render.rs @@ -0,0 +1,807 @@ +//! WordprocessingML package writer. + +use super::model::{ + cm_to_twips, Block, DocxDocument, HeaderFooter, ImageBlock, ListBlock, Orientation, + ParagraphBlock, ParagraphStyle, TableBlock, TocBlock, +}; +use crate::common::{parse_color, runs_text, Align, Run, TableCell}; +use crate::error::{OfficeError, OfficeResult}; +use crate::image::{kind_of_asset, sniff}; +use crate::package::{add_common_parts, ContentTypes, Parts, Relationships}; +use crate::xml::{esc, needs_preserve, XML_HEADER}; +use std::collections::BTreeMap; + +const NS: &str = "xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:wp=\"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\""; +const REL_STYLES: &str = + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"; +const REL_SETTINGS: &str = + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings"; +const REL_NUMBERING: &str = + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering"; +const REL_HEADER: &str = + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header"; +const REL_FOOTER: &str = + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer"; +const REL_IMAGE: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"; +const REL_HYPERLINK: &str = + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"; +const EMU_PER_TWIP: u64 = 635; +const EMU_PER_CM: f64 = 360_000.0; +const EMU_PER_PX: u64 = 9525; + +struct Writer<'a> { + doc: &'a DocxDocument, + assets: &'a BTreeMap>, + rels: Relationships, + image_rels: BTreeMap, + link_rels: BTreeMap, + used_assets: Vec, + /// (numId, ordered, start) for every list block in order. + lists: Vec<(u32, bool, u32)>, + drawing_id: u32, + has_toc: bool, +} + +pub(crate) fn render( + doc: &DocxDocument, + assets: &BTreeMap>, + created: Option<&str>, + modified: Option<&str>, +) -> OfficeResult { + let mut writer = Writer { + doc, + assets, + rels: Relationships::default(), + image_rels: BTreeMap::new(), + link_rels: BTreeMap::new(), + used_assets: Vec::new(), + lists: Vec::new(), + drawing_id: 0, + has_toc: false, + }; + writer.rels.add(REL_STYLES, "styles.xml"); + writer.rels.add(REL_SETTINGS, "settings.xml"); + let body = writer.body()?; + + let mut types = ContentTypes::new(); + let mut parts = Parts::default(); + types.part( + "word/document.xml", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", + ); + types.part( + "word/styles.xml", + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", + ); + types.part( + "word/settings.xml", + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml", + ); + + if !writer.lists.is_empty() { + writer.rels.add(REL_NUMBERING, "numbering.xml"); + types.part( + "word/numbering.xml", + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml", + ); + parts.add_xml("word/numbering.xml", numbering_xml(&writer.lists)); + } + + let header_rel = doc.header.as_ref().map(|header| { + types.part( + "word/header1.xml", + "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml", + ); + parts.add_xml("word/header1.xml", header_footer_xml("hdr", header)); + writer.rels.add(REL_HEADER, "header1.xml") + }); + let footer_rel = doc.footer.as_ref().map(|footer| { + types.part( + "word/footer1.xml", + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml", + ); + parts.add_xml("word/footer1.xml", header_footer_xml("ftr", footer)); + writer.rels.add(REL_FOOTER, "footer1.xml") + }); + + let mut document = String::from(XML_HEADER); + document.push_str(&format!("")); + document.push_str(&body); + document.push_str(§ion_xml( + doc, + header_rel.as_deref(), + footer_rel.as_deref(), + )); + document.push_str(""); + + parts.add_xml("word/document.xml", document); + parts.add_xml("word/styles.xml", styles_xml(doc)); + parts.add_xml("word/settings.xml", settings_xml(writer.has_toc)); + parts.add_xml("word/_rels/document.xml.rels", writer.rels.xml()); + for asset in &writer.used_assets { + let bytes = assets + .get(asset) + .ok_or_else(|| OfficeError::corrupt(format!("embedded picture {asset} is missing")))?; + if let Some(kind) = kind_of_asset(asset) { + types.extension(kind.extension(), kind.content_type()); + } + parts.add(format!("word/media/{asset}"), bytes.clone()); + } + add_common_parts( + &mut parts, + &mut types, + "word/document.xml", + &doc.properties, + created, + modified, + "OpenBitFun GenOfficeFile", + ); + parts.add_xml("[Content_Types].xml", types.xml()); + Ok(parts) +} + +impl Writer<'_> { + fn body(&mut self) -> OfficeResult { + let mut out = String::new(); + let blocks = &self.doc.blocks; + for (index, block) in blocks.iter().enumerate() { + match block { + Block::Heading(heading) => { + let mut ppr = format!("", heading.level); + ppr.push_str(&jc(heading.align)); + out.push_str(&self.paragraph(&ppr, &heading.runs, None)); + } + Block::Paragraph(paragraph) => out.push_str(&self.plain_paragraph(paragraph)), + Block::List(list) => out.push_str(&self.list(list)), + Block::Table(table) => { + out.push_str(&self.table(table)); + let next_is_table = matches!(blocks.get(index + 1), Some(Block::Table(_)) | None); + if next_is_table { + // Word merges adjacent tables and wants a paragraph before sectPr. + out.push_str(""); + } + } + Block::Image(image) => out.push_str(&self.image(image)?), + Block::Code(code) => { + let run = Run { + text: code.text.clone(), + code: Some(true), + ..Run::default() + }; + out.push_str(&self.paragraph("", &[run], None)); + } + Block::Quote(quote) => { + out.push_str(&self.paragraph("", "e.runs, None)) + } + Block::PageBreak(_) => { + out.push_str(""); + } + Block::HorizontalRule(_) => out.push_str( + "", + ), + Block::Toc(toc) => out.push_str(&self.toc(toc)), + } + } + Ok(out) + } + + fn plain_paragraph(&mut self, paragraph: &ParagraphBlock) -> String { + let mut ppr = String::new(); + let style = match paragraph.style { + Some(ParagraphStyle::Title) => Some("Title"), + Some(ParagraphStyle::Subtitle) => Some("Subtitle"), + Some(ParagraphStyle::Caption) => Some("Caption"), + Some(ParagraphStyle::Normal) | None => None, + }; + if let Some(style) = style { + ppr.push_str(&format!("")); + } + if paragraph.space_before_pt.is_some() + || paragraph.space_after_pt.is_some() + || paragraph.line_spacing.is_some() + { + ppr.push_str(""); + } + if paragraph.indent_cm.is_some() || paragraph.first_line_indent_cm.is_some() { + ppr.push_str("= 0.0 { + ppr.push_str(&format!(" w:firstLine=\"{}\"", cm_to_twips(first))); + } else { + ppr.push_str(&format!(" w:hanging=\"{}\"", cm_to_twips(-first))); + } + } + ppr.push_str("/>"); + } + ppr.push_str(&jc(paragraph.align)); + self.paragraph(&ppr, ¶graph.runs, None) + } + + fn paragraph(&mut self, ppr: &str, runs: &[Run], defaults: Option<&RunDefaults>) -> String { + let mut out = String::from(""); + if !ppr.is_empty() { + out.push_str(&format!("{ppr}")); + } + for run in runs { + out.push_str(&self.run(run, defaults)); + } + out.push_str(""); + out + } + + fn run(&mut self, run: &Run, defaults: Option<&RunDefaults>) -> String { + let link = run.link.as_ref().map(|target| { + self.link_rels + .entry(target.clone()) + .or_insert_with(|| self.rels.add_external(REL_HYPERLINK, target)) + .clone() + }); + let mut rpr = String::new(); + if link.is_some() { + rpr.push_str(""); + } + let font = run + .font + .as_deref() + .or_else(|| (run.code == Some(true)).then_some("Consolas")); + if let Some(font) = font { + let font = esc(font); + rpr.push_str(&format!( + "" + )); + } + let bold = run.bold.or(defaults.and_then(|d| d.bold)); + if bold == Some(true) { + rpr.push_str(""); + } + if run.italic == Some(true) { + rpr.push_str(""); + } + if run.strike == Some(true) { + rpr.push_str(""); + } + let color = run + .color + .as_deref() + .or(defaults.and_then(|d| d.color.as_deref())); + if let Some(color) = color.and_then(|value| parse_color(value).ok()) { + rpr.push_str(&format!("", color.0)); + } + let size = run.size_pt.or(defaults.and_then(|d| d.size_pt)); + if let Some(size) = size { + let half_points = (size * 2.0).round() as i64; + rpr.push_str(&format!( + "" + )); + } + if run.underline == Some(true) { + rpr.push_str(""); + } + let shade = run + .highlight + .as_deref() + .and_then(|value| parse_color(value).ok()) + .map(|color| color.0) + .or_else(|| (run.code == Some(true)).then(|| "F2F2F2".to_string())); + if let Some(fill) = shade { + rpr.push_str(&format!( + "" + )); + } + if run.superscript == Some(true) { + rpr.push_str(""); + } else if run.subscript == Some(true) { + rpr.push_str(""); + } + let mut out = String::from(""); + if !rpr.is_empty() { + out.push_str(&format!("{rpr}")); + } + out.push_str(&text_content(&run.text)); + out.push_str(""); + match link { + Some(id) => format!("{out}"), + None => out, + } + } + + fn list(&mut self, list: &ListBlock) -> String { + let num_id = self.lists.len() as u32 + 1; + self.lists + .push((num_id, list.ordered, list.start.unwrap_or(1).max(1))); + let mut out = String::new(); + for item in &list.items { + let ppr = format!( + "", + item.level.min(8) + ); + out.push_str(&self.paragraph(&ppr, &item.runs, None)); + } + out + } + + fn table(&mut self, table: &TableBlock) -> String { + let columns = table + .rows + .iter() + .map(|row| { + row.iter() + .map(|cell| cell.colspan.unwrap_or(1) as usize) + .sum::() + }) + .max() + .unwrap_or(1) + .max(1); + let text_width = self.doc.page.text_width_twips() as f64; + let widths: Vec = match &table.column_widths_cm { + Some(widths) if !widths.is_empty() => (0..columns) + .map(|index| { + cm_to_twips( + *widths + .get(index) + .unwrap_or_else(|| widths.last().expect("non-empty")), + ) + }) + .collect(), + _ => vec![(text_width / columns as f64).floor() as u32; columns], + }; + let mut out = String::new(); + if let Some(caption) = &table.caption { + out.push_str(&self.paragraph( + "", + &[Run::plain(caption.clone())], + None, + )); + } + out.push_str(""); + let total: u32 = widths.iter().sum(); + out.push_str(&format!("")); + if table.borders { + out.push_str(""); + for side in ["top", "left", "bottom", "right", "insideH", "insideV"] { + out.push_str(&format!( + "" + )); + } + out.push_str(""); + } + out.push_str(""); + for width in &widths { + out.push_str(&format!("")); + } + out.push_str(""); + let header_fill = parse_color(&self.doc.styles.table_header_fill) + .map(|color| color.0) + .unwrap_or_else(|_| "D9E2F3".to_string()); + for (row_index, row) in table.rows.iter().enumerate() { + let is_header = (row_index as u32) < table.header_rows; + out.push_str(""); + if is_header { + out.push_str(""); + } + let mut column = 0; + for cell in row { + if column >= columns { + break; + } + let span = (cell.colspan.unwrap_or(1) as usize).clamp(1, columns - column); + let width: u32 = widths[column..column + span].iter().sum(); + out.push_str(&self.table_cell( + cell, + width, + span, + is_header, + &header_fill, + table.font_size_pt, + )); + column += span; + } + while column < columns { + out.push_str(&self.table_cell( + &TableCell::default(), + widths[column], + 1, + is_header, + &header_fill, + table.font_size_pt, + )); + column += 1; + } + out.push_str(""); + } + out.push_str(""); + out + } + + fn table_cell( + &mut self, + cell: &TableCell, + width: u32, + span: usize, + is_header: bool, + header_fill: &str, + font_size: Option, + ) -> String { + let mut out = format!(""); + if span > 1 { + out.push_str(&format!("")); + } + let fill = cell + .fill + .as_deref() + .and_then(|value| parse_color(value).ok()) + .map(|color| color.0) + .or_else(|| is_header.then(|| header_fill.to_string())); + if let Some(fill) = fill { + out.push_str(&format!( + "" + )); + } + out.push_str(""); + let defaults = RunDefaults { + bold: cell.bold.or(is_header.then_some(true)), + color: cell.color.clone(), + size_pt: font_size, + }; + let mut ppr = String::from(""); + ppr.push_str(&jc(cell.align)); + out.push_str(&self.paragraph(&ppr, &cell.runs, Some(&defaults))); + out.push_str(""); + out + } + + fn image(&mut self, image: &ImageBlock) -> OfficeResult { + let asset = image + .asset + .as_deref() + .ok_or_else(|| OfficeError::corrupt("image block without an embedded picture"))?; + let bytes = self + .assets + .get(asset) + .ok_or_else(|| OfficeError::corrupt(format!("embedded picture {asset} is missing")))?; + let info = sniff(bytes)?; + let rel = match self.image_rels.get(asset) { + Some(rel) => rel.clone(), + None => { + let rel = self.rels.add(REL_IMAGE, &format!("media/{asset}")); + self.image_rels.insert(asset.to_string(), rel.clone()); + self.used_assets.push(asset.to_string()); + rel + } + }; + let max_width = self.doc.page.text_width_twips() as u64 * EMU_PER_TWIP; + let aspect = info.height as f64 / info.width as f64; + let (cx, cy) = match (image.width_cm, image.height_cm) { + (Some(width), Some(height)) => (width * EMU_PER_CM, height * EMU_PER_CM), + (Some(width), None) => (width * EMU_PER_CM, width * EMU_PER_CM * aspect), + (None, Some(height)) => (height * EMU_PER_CM / aspect, height * EMU_PER_CM), + (None, None) => { + let natural = (info.width as u64 * EMU_PER_PX) as f64; + let width = natural.min(max_width as f64); + (width, width * aspect) + } + }; + let (cx, cy) = (cx.round().max(1.0) as u64, cy.round().max(1.0) as u64); + self.drawing_id += 1; + let id = self.drawing_id; + let descr = esc(image + .alt + .as_deref() + .or(image.caption.as_deref()) + .unwrap_or("")); + let mut out = format!("{}", + jc(image.align.or(Some(Align::Center))), + esc(asset), + ); + if let Some(caption) = &image.caption { + out.push_str(&self.paragraph( + &format!( + "{}", + jc(image.align.or(Some(Align::Center))) + ), + &[Run::plain(caption.clone())], + None, + )); + } + Ok(out) + } + + fn toc(&mut self, toc: &TocBlock) -> String { + self.has_toc = true; + let mut out = String::new(); + if let Some(title) = &toc.title { + out.push_str(&self.paragraph( + "", + &[Run::plain(title.clone())], + None, + )); + } + let tab = self.doc.page.text_width_twips(); + let entries: Vec<(u8, String)> = self + .doc + .blocks + .iter() + .filter_map(|block| match block { + Block::Heading(heading) if heading.level <= toc.levels => { + Some((heading.level, runs_text(&heading.runs))) + } + _ => None, + }) + .collect(); + let begin = format!( + " TOC \\o \"1-{}\" \\h \\z \\u ", + toc.levels + ); + let end = ""; + if entries.is_empty() { + out.push_str(&format!( + "{begin}Update this field to build the table of contents.{end}" + )); + return out; + } + let last = entries.len() - 1; + for (index, (level, text)) in entries.iter().enumerate() { + out.push_str(&format!( + "" + )); + if index == 0 { + out.push_str(&begin); + } + out.push_str(&format!("{}", text_content(text))); + if index == last { + out.push_str(end); + } + out.push_str(""); + } + out + } +} + +struct RunDefaults { + bold: Option, + color: Option, + size_pt: Option, +} + +fn pt_twips(points: f64) -> i64 { + (points.max(0.0) * 20.0).round() as i64 +} + +fn jc(align: Option) -> String { + match align { + Some(Align::Left) => "".to_string(), + Some(Align::Center) => "".to_string(), + Some(Align::Right) => "".to_string(), + Some(Align::Justify) => "".to_string(), + None => String::new(), + } +} + +/// Run content with line breaks and tabs as their own elements. +fn text_content(text: &str) -> String { + let mut out = String::new(); + for (line_index, line) in text.split('\n').enumerate() { + if line_index > 0 { + out.push_str(""); + } + for (tab_index, segment) in line.split('\t').enumerate() { + if tab_index > 0 { + out.push_str(""); + } + if segment.is_empty() { + continue; + } + if needs_preserve(segment) { + out.push_str(&format!( + "{}", + esc(segment) + )); + } else { + out.push_str(&format!("{}", esc(segment))); + } + } + } + out +} + +fn section_xml(doc: &DocxDocument, header: Option<&str>, footer: Option<&str>) -> String { + let (width, height) = doc.page.page_twips(); + let margins = &doc.page.margins_cm; + let mut out = String::from(""); + if let Some(id) = header { + out.push_str(&format!( + "" + )); + } + if let Some(id) = footer { + out.push_str(&format!( + "" + )); + } + let orient = match doc.page.orientation { + Orientation::Landscape => " w:orient=\"landscape\"", + Orientation::Portrait => "", + }; + out.push_str(&format!( + "" + )); + out.push_str(&format!( + "", + cm_to_twips(margins.top), + cm_to_twips(margins.right), + cm_to_twips(margins.bottom), + cm_to_twips(margins.left) + )); + out.push_str(""); + out +} + +fn header_footer_xml(tag: &str, part: &HeaderFooter) -> String { + let style = if tag == "hdr" { "Header" } else { "Footer" }; + let mut content = String::new(); + let mut rest = part.text.as_str(); + while !rest.is_empty() { + let next = ["{PAGE}", "{NUMPAGES}"] + .iter() + .filter_map(|token| rest.find(token).map(|position| (position, *token))) + .min_by_key(|(position, _)| *position); + match next { + Some((position, token)) => { + if position > 0 { + content.push_str(&format!("{}", text_content(&rest[..position]))); + } + let field = token.trim_matches(|c| c == '{' || c == '}'); + content.push_str(&format!( + "1" + )); + rest = &rest[position + token.len()..]; + } + None => { + content.push_str(&format!("{}", text_content(rest))); + rest = ""; + } + } + } + format!( + "{XML_HEADER}{}{content}", + jc(Some(part.align)) + ) +} + +fn numbering_xml(lists: &[(u32, bool, u32)]) -> String { + let mut out = String::from(XML_HEADER); + out.push_str( + "", + ); + let bullets = ["•", "◦", "▪"]; + out.push_str( + "", + ); + for level in 0..9u32 { + out.push_str(&format!( + "", + bullets[level as usize % 3], + 720 + level * 360 + )); + } + out.push_str(""); + let formats = ["decimal", "lowerLetter", "lowerRoman"]; + out.push_str( + "", + ); + for level in 0..9u32 { + out.push_str(&format!( + "", + formats[level as usize % 3], + level + 1, + 720 + level * 360 + )); + } + out.push_str(""); + for (num_id, ordered, start) in lists { + let abstract_id = u32::from(*ordered); + out.push_str(&format!( + "" + )); + } + out.push_str(""); + out +} + +fn settings_xml(update_fields: bool) -> String { + format!( + "{XML_HEADER}{}", + if update_fields { + "" + } else { + "" + } + ) +} + +fn styles_xml(doc: &DocxDocument) -> String { + let styles = &doc.styles; + let font = esc(styles.font.as_deref().unwrap_or("Calibri")); + let heading_font = esc(styles + .heading_font + .as_deref() + .unwrap_or(styles.font.as_deref().unwrap_or("Calibri"))); + let east_asia = styles + .east_asia_font + .as_deref() + .map(|value| format!(" w:eastAsia=\"{}\"", esc(value))) + .unwrap_or_default(); + let body_size = (styles.font_size_pt * 2.0).round() as i64; + let heading_color = parse_color(&styles.heading_color) + .map(|color| color.0) + .unwrap_or_else(|_| "1F3864".to_string()); + let text_color = styles + .text_color + .as_deref() + .and_then(|value| parse_color(value).ok()) + .map(|color| format!("", color.0)) + .unwrap_or_default(); + let line = (styles.line_spacing * 240.0).round() as i64; + let after = pt_twips(styles.paragraph_space_after_pt); + + let mut out = String::from(XML_HEADER); + out.push_str( + "", + ); + out.push_str(&format!( + "{text_color}" + )); + out.push_str(""); + out.push_str(""); + out.push_str(""); + out.push_str(""); + let heading_sizes: [f64; 6] = [18.0, 15.0, 13.0, 12.0, 11.0, 11.0]; + let spacing_before = [360, 240, 200, 160, 120, 120]; + for level in 1..=6usize { + let size = (heading_sizes[level - 1].max(styles.font_size_pt) * 2.0).round() as i64; + let italic = if level >= 5 { "" } else { "" }; + out.push_str(&format!( + "{italic}", + spacing_before[level - 1], + level - 1 + )); + } + out.push_str(&format!( + "" + )); + out.push_str(""); + out.push_str(""); + out.push_str(""); + out.push_str(""); + out.push_str(""); + out.push_str(&format!( + "" + )); + for level in 1..=6u32 { + out.push_str(&format!( + "", + (level - 1) * 220 + )); + } + out.push_str(""); + out.push_str(""); + out.push_str(""); + out.push_str(""); + out +} diff --git a/src/crates/execution/office-documents/src/error.rs b/src/crates/execution/office-documents/src/error.rs new file mode 100644 index 0000000000..d7af636aae --- /dev/null +++ b/src/crates/execution/office-documents/src/error.rs @@ -0,0 +1,109 @@ +//! Error type shared by every office format. + +use std::fmt; + +/// Stable, machine-readable failure classes. The tool layer forwards +/// [`OfficeErrorKind::code`] to the model so it can branch on the reason +/// instead of parsing the message. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OfficeErrorKind { + /// An operation or its fields are malformed. + InvalidOperation, + /// An index, cell address, or range lies outside the document. + OutOfRange, + /// A named target (sheet, element) does not exist. + NotFound, + /// The file extension or package is not a supported office format. + UnsupportedFormat, + /// The package carries no editable source model. + NotGenerated, + /// The package changed after this engine last wrote it. + ExternallyModified, + /// The package cannot be read as a zip/OOXML container. + CorruptPackage, + /// An image source could not be decoded. + InvalidImage, + /// A size or count limit was exceeded. + LimitExceeded, +} + +impl OfficeErrorKind { + pub const fn code(self) -> &'static str { + match self { + Self::InvalidOperation => "invalid_operation", + Self::OutOfRange => "out_of_range", + Self::NotFound => "not_found", + Self::UnsupportedFormat => "unsupported_format", + Self::NotGenerated => "not_generated", + Self::ExternallyModified => "externally_modified", + Self::CorruptPackage => "corrupt_package", + Self::InvalidImage => "invalid_image", + Self::LimitExceeded => "limit_exceeded", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OfficeError { + pub kind: OfficeErrorKind, + pub message: String, + /// Zero-based position of the failing operation inside its batch. + pub operation_index: Option, + pub operation: Option, +} + +impl OfficeError { + pub fn new(kind: OfficeErrorKind, message: impl Into) -> Self { + Self { + kind, + message: message.into(), + operation_index: None, + operation: None, + } + } + + pub fn invalid(message: impl Into) -> Self { + Self::new(OfficeErrorKind::InvalidOperation, message) + } + + pub fn out_of_range(message: impl Into) -> Self { + Self::new(OfficeErrorKind::OutOfRange, message) + } + + pub fn not_found(message: impl Into) -> Self { + Self::new(OfficeErrorKind::NotFound, message) + } + + pub fn limit(message: impl Into) -> Self { + Self::new(OfficeErrorKind::LimitExceeded, message) + } + + pub fn corrupt(message: impl Into) -> Self { + Self::new(OfficeErrorKind::CorruptPackage, message) + } + + /// Pins the error to one operation of a batch. + pub fn at_operation(mut self, index: usize, operation: &str) -> Self { + self.operation_index = Some(index); + self.operation = Some(operation.to_string()); + self + } +} + +impl fmt::Display for OfficeError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match (&self.operation_index, &self.operation) { + (Some(index), Some(operation)) => write!( + formatter, + "operation #{index} `{operation}` failed ({}): {}", + self.kind.code(), + self.message + ), + _ => write!(formatter, "{} ({})", self.message, self.kind.code()), + } + } +} + +impl std::error::Error for OfficeError {} + +pub type OfficeResult = Result; diff --git a/src/crates/execution/office-documents/src/guide.rs b/src/crates/execution/office-documents/src/guide.rs new file mode 100644 index 0000000000..5d15b722ce --- /dev/null +++ b/src/crates/execution/office-documents/src/guide.rs @@ -0,0 +1,16 @@ +//! Operation references returned by the tool's `guide` action. + +use crate::OfficeFormat; + +const DOCX: &str = include_str!("guides/docx.md"); +const XLSX: &str = include_str!("guides/xlsx.md"); +const PPTX: &str = include_str!("guides/pptx.md"); + +/// The full operation and field reference for one format. +pub fn guide(format: OfficeFormat) -> &'static str { + match format { + OfficeFormat::Docx => DOCX, + OfficeFormat::Xlsx => XLSX, + OfficeFormat::Pptx => PPTX, + } +} diff --git a/src/crates/execution/office-documents/src/guides/docx.md b/src/crates/execution/office-documents/src/guides/docx.md new file mode 100644 index 0000000000..ed670f7856 --- /dev/null +++ b/src/crates/execution/office-documents/src/guides/docx.md @@ -0,0 +1,60 @@ +# GenOfficeFile — Word (.docx) + +A Word document is an ordered list of **blocks** (0-based indexes) plus document settings. Build it over several `edit` calls: write the skeleton first, then insert sections one or a few at a time. `read` pages over blocks with `offset`/`limit` and returns the heading outline, so you can find where to insert next. + +## Blocks + +Every block is an object with `type`. Text fields take either `text` (plain string) or `runs` (formatted spans). Inside text, `\n` is a line break. + +| type | fields | +|---|---| +| `heading` | `level` 1–6, `text`/`runs`, `align` | +| `paragraph` | `text`/`runs`, `style` (`normal` `title` `subtitle` `caption`), `align` (`left` `center` `right` `justify`), `indent_cm`, `first_line_indent_cm` (negative = hanging), `space_before_pt`, `space_after_pt`, `line_spacing` (multiple, e.g. 1.5) | +| `list` | `ordered` (bool), `start`, `items`: strings or `{text/runs, level}` (level 0–8 nests) | +| `table` | `rows`: array of rows; a cell is a string/number or `{text/runs, bold, color, fill, align, colspan}`; `header_rows` (default 1), `column_widths_cm`, `borders` (default true), `font_size_pt`, `caption` | +| `image` | `src` (absolute local path or data URL; PNG/JPEG/GIF/BMP), `width_cm` and/or `height_cm` (aspect kept when one is given; default = natural size capped at the text width), `align`, `caption`, `alt`. After embedding, `read` shows `asset`; pass `asset` instead of `src` to reuse an embedded picture | +| `code` | `text`, `language` | +| `quote` | `text`/`runs` | +| `page_break` | — | +| `horizontal_rule` | — | +| `toc` | `title`, `levels` (default 3). Lists the headings; Word refreshes page numbers on open | + +**Run** fields: `text`, `bold`, `italic`, `underline`, `strike`, `code`, `superscript`, `subscript`, `color` (`#RRGGBB`), `highlight` (`#RRGGBB`), `size_pt`, `font`, `link` (http/https/mailto URL). + +### Markdown + +`insert_blocks` and `replace_blocks` accept `markdown` instead of `blocks`. Supported: headings, paragraphs with `**bold**` / `*italic*` / `~~strike~~` / `` `code` `` / `[links](https://…)`, bullet / numbered / nested / task lists, GFM tables (with column alignment), fenced code, block quotes, `---` rules, images `![alt](/abs/path.png)`, `[TOC]` on its own line, and ``. + +## Operations + +| op | fields | effect | +|---|---|---| +| `insert_blocks` | `index` (insert before; omit to append), `blocks` or `markdown` | adds blocks | +| `replace_blocks` | `index`, `count` (default 1), `blocks` or `markdown` | replaces `count` blocks with the new ones (any number) | +| `delete_blocks` | `index`, `count` (default 1) | removes blocks | +| `move_blocks` | `index`, `count` (default 1), `to` | moves blocks; `to` is the position in the list after they are removed | +| `replace_text` | `find`, `replace`, `match_case` (default true) | replaces inside every run (text split across differently formatted runs is not matched) | +| `set_page_setup` | `size` (`a4` `letter` `legal` `a3` `a5`), `orientation` (`portrait` `landscape`), `margins_cm` `{top,bottom,left,right}` | partial update | +| `set_styles` | `font`, `east_asia_font`, `font_size_pt`, `heading_font`, `heading_color`, `text_color`, `line_spacing`, `paragraph_space_after_pt`, `table_header_fill` | partial update of document-wide styles | +| `set_header_footer` | `header`, `footer`: a string, `{text, align}`, or `null` to remove. `{PAGE}` and `{NUMPAGES}` become page fields | | +| `set_properties` | `title`, `subject`, `author`, `keywords`, `description`, `category` | document metadata | + +Indexes inside one batch are live: after inserting two blocks at index 3, the old block 3 is block 5 for the next operation in the same batch. A batch is atomic — if any operation fails, nothing is written and the error names the operation. + +## Settings at create + +`settings` may carry `page`, `styles`, `header`, `footer`, `properties` (same fields as above). For Chinese documents set `styles.east_asia_font` (for example `Microsoft YaHei`, `SimSun`, `PingFang SC`). + +## Example + +```json +{"action": "create", "file_path": "/abs/report.docx", + "settings": {"styles": {"east_asia_font": "Microsoft YaHei"}}, + "operations": [ + {"op": "set_properties", "title": "Q3 Report"}, + {"op": "insert_blocks", "markdown": "# Q3 Report\n\n[TOC]\n\n## Summary\n\nRevenue grew **23%**."}, + {"op": "set_header_footer", "footer": "Page {PAGE} of {NUMPAGES}"} + ]} +``` + +Then append sections with `{"action": "edit", "file_path": "/abs/report.docx", "operations": [{"op": "insert_blocks", "markdown": "## Details\n\n..."}]}`. diff --git a/src/crates/execution/office-documents/src/guides/pptx.md b/src/crates/execution/office-documents/src/guides/pptx.md new file mode 100644 index 0000000000..a6548a83ba --- /dev/null +++ b/src/crates/execution/office-documents/src/guides/pptx.md @@ -0,0 +1,65 @@ +# GenOfficeFile — PowerPoint (.pptx) + +A deck is a list of **slides** (0-based). Each slide is a fixed canvas — **1280 × 720 px** for `16:9` (default) or 960 × 720 for `4:3` — with absolutely positioned elements: origin top-left, `x` `y` `w` `h` in px, painted in array order (first = bottom). Build one slide (or a few) per `edit` call; `read` pages over slides, and `detail: "full"` returns a slide's elements with their indexes for targeted edits. + +## Slide + +`{ "title", "layout", "background": "#RRGGBB", "notes": "speaker notes", "elements": [ … ] }`. `title` and `layout` are planning labels shown by `read` (not drawn). + +## Elements + +Colors are `#RRGGBB` or `#RRGGBBAA` (alpha). Text-bearing elements accept `text` (string, `\n` = new paragraph) or `paragraphs`, plus element-level run defaults `size_pt`, `bold`, `italic`, `color`, `font`, `align` that apply wherever a run or paragraph does not set its own. + +**text** — `{type: "text", x, y, w, h, text | paragraphs, valign (top|middle|bottom, default top), rotation, …defaults}`. Zero inner padding; the box wraps at `w` and does not grow, so size it for its content. + +**shape** — `{type: "shape", shape, x, y, w, h, fill, stroke: {color, width_pt, dash: solid|dash|dot}, text | paragraphs, valign (default middle), padding (px), flip_h, flip_v, rotation, …defaults}`. `shape` is one of `rect` `roundRect` `ellipse` `triangle` `rtTriangle` `rightArrow` `leftArrow` `upArrow` `downArrow` `chevron` `diamond` `parallelogram` `trapezoid` `hexagon` `pentagon` `octagon` `plus` `pie` `donut` `star5` `heart` `cloud` `line` `lineArrow`. A shape needs a fill, a stroke, or text. `line`/`lineArrow` draw the box diagonal (use `h: 0` for a horizontal rule, `flip_v` for bottom-left → top-right) and need a `stroke`. + +**image** — `{type: "image", src, x, y, w, h, fit: cover|contain|stretch (default cover), alt, rotation}`. `src` is an absolute local path or a data URL (PNG/JPEG/GIF/BMP; download web images to a local file first). `cover` center-crops to fill the box, so give the box roughly the picture's aspect ratio. After embedding, `read` shows `asset`; keep it to reuse the picture. + +**table** — `{type: "table", x, y, w, h, rows, header (default true), column_widths (px, scaled to w), font_size_pt (default 14), font, header_fill, header_color, fill, band_fill ("" disables banding), border_color, text_color}`. Cells are strings/numbers or `{text/runs, bold, color, fill, align}`. Rows share `h` equally. At most 60 rows × 30 columns. + +**Paragraph** — a string, or `{text | runs, align (left|center|right|justify), line_spacing_pct, space_before_pt, space_after_pt, bullet, numbered, level, size_pt, bold, italic, color, font}`. + +**Run** — `{text, size_pt, bold, italic, underline, strike, superscript, subscript, color, highlight, font, link}`. + +GenOffice spec spellings are accepted as aliases: `sizePt`, `lineSpacingPct`, `spaceBeforePt`, `spaceAfterPt`, `widthPt`, `flipH`, `flipV`, `url`. + +## Operations + +| op | fields | effect | +|---|---|---| +| `insert_slides` | `index` (omit to append), `slides` | adds slides | +| `replace_slide` | `index`, `slide` | rebuilds one slide | +| `update_slide` | `index`, then any of `title` `layout` `background` `notes` (null clears), `elements` (replace all), or `update_elements` `[{index, …changed fields}]`, `remove_elements` `[indexes]`, `append_elements` `[elements]` (applied in that order) | partial slide edit | +| `delete_slides` | `index`, `count` (default 1) | | +| `move_slides` | `index`, `count`, `to` | `to` is the position after the moved slides are removed | +| `duplicate_slide` | `index`, `to` (default right after) | | +| `set_theme` | `font`, `east_asia_font`, `text_color` | deck-wide defaults | +| `set_properties` | `title`, `subject`, `author`, `keywords`, `description`, `category` | | + +After a batch the tool audits the touched slides and reports elements outside the canvas and text that likely overflows its box; fix those with `update_slide`. + +## Design rules (from GenOffice's deck pipeline) + +- Decide the style first: background per page type, main text color, one or two accent colors, title and body fonts. Re-use them on every slide; never give each item its own color. +- Plan the deck before writing slides: a cover, content/data pages with varied layouts (three cards, big number, two-column comparison, timeline, KPI row, chart + insight), and a closing page. Do not repeat the same content layout back to back. +- Sizing text: one line ≈ `size_pt × 1.6` px tall; a CJK character ≈ `size_pt × 1.33` px wide, a Latin character ≈ `size_pt × 0.7` px. Count the wrapped lines and make the box that tall plus a spare line. +- Type scale (pt): titles 32–48, subtitles 18–24, body 12–16, hero numbers up to 80. +- Spacing: ≥ 8 px between text and a card edge, ≥ 20 px between a title and its subtitle. Keep everything inside the canvas and spread content over the whole slide. +- Only use photos you actually have (local files, generated or downloaded images). Without photos, use typography, color blocks and shapes; never fake a photo with a grey box. Data visuals can be built from `rect`, `donut` and `line` shapes sized proportionally to real values. +- Avoid: a thin accent bar on every card, rainbow cards, a header bar repeated on every slide, two text boxes that say the same thing, placeholder copy ("XX%", "lorem"). + +## Example + +```json +{"action": "edit", "file_path": "/abs/deck.pptx", "operations": [ + {"op": "insert_slides", "slides": [{ + "title": "Cover", "background": "#0E1A2B", "notes": "Open with the 40% figure.", + "elements": [ + {"type": "shape", "shape": "rect", "x": 0, "y": 0, "w": 560, "h": 720, "fill": "#1F3A5F"}, + {"type": "text", "x": 80, "y": 240, "w": 440, "h": 150, "paragraphs": [ + {"runs": [{"text": "Margins fell ", "size_pt": 40, "bold": true, "color": "#FFFFFF"}, {"text": "40%", "size_pt": 54, "bold": true, "color": "#FFC000"}]}]}, + {"type": "image", "src": "/abs/assets/port.jpg", "x": 640, "y": 120, "w": 560, "h": 480} + ]}]} +]} +``` diff --git a/src/crates/execution/office-documents/src/guides/xlsx.md b/src/crates/execution/office-documents/src/guides/xlsx.md new file mode 100644 index 0000000000..69df0cf144 --- /dev/null +++ b/src/crates/execution/office-documents/src/guides/xlsx.md @@ -0,0 +1,60 @@ +# GenOfficeFile — Excel (.xlsx) + +A workbook is a list of **sheets**; each sheet holds sparse cells addressed A1-style. Add data in chunks (`append_rows` is the natural way to page a large table across calls), then format. `read` without `sheet` lists the sheets; with `sheet` it pages over rows (`offset`/`limit`, default 100 rows) or reads an A1 `range`. + +Range reads also honor `offset`/`limit` (at most 500 rows per call); pass the same range and the returned `next_offset` to continue. `detail: "full"` preserves complete cell text; outline reads shorten long text. + +## Cell values + +Rows are arrays of cell values: + +- number or boolean → stored as such +- string → text; a string starting with `=` is a formula (`"=SUM(B2:B9)"`) +- `null` → leave that cell unchanged (skip) +- object → `{"value": …, "formula": "…", "type": "text" | "number" | "boolean" | "date", "style": {…}}`. `type: "text"` keeps a leading `=` literal; `type: "date"` turns `"2024-03-31"` or `"2024-03-31 09:30"` into a real date with a date format. + +Formula results are computed and cached for arithmetic, comparisons, `&`, cell and range references (including other sheets), and SUM, AVERAGE, MIN, MAX, COUNT, COUNTA, PRODUCT, ROUND, ROUNDUP, ROUNDDOWN, ABS, IF, IFERROR, AND, OR, NOT, CONCAT(ENATE), LEN, UPPER, LOWER, TRIM, so `read` and simple viewers show values. Other functions (VLOOKUP, SUMIF, FILTER, …) are stored without a cached value; Excel, WPS and LibreOffice compute every formula when the file opens, and the tool lists the uncached cells. Write numbers as numbers (not `"1,200"`) so formulas and number formats work. + +## Styles + +`style` objects (in `format_range` or a cell object) take: `bold`, `italic`, `underline`, `strike`, `font_color`, `font_size`, `font_name`, `fill_color`, `number_format` (`"#,##0.00"`, `"0.0%"`, `"yyyy-mm-dd"`, `"¥#,##0"` …), `align` (`left` `center` `right` `justify` `general`), `valign` (`top` `center` `bottom`), `wrap`, `indent`, `border` (`thin` `medium` `thick` `dashed` `dotted` `double` `none`), `border_color`. Colors are `#RRGGBB`. Formatting merges into a cell's existing style. + +## Operations + +`sheet` is a sheet name (or 0-based index); it may be omitted when the workbook has exactly one sheet. Rows and columns are 1-based in `row`, letters in `column`. + +| op | fields | effect | +|---|---|---| +| `add_sheet` | `name`, `index`, `rows`, `start` (default `A1`) | new sheet, optionally with data | +| `delete_sheet` | `sheet` | | +| `rename_sheet` | `sheet`, `name` | formulas that reference the sheet are updated | +| `move_sheet` | `sheet`, `to` | reorder tabs | +| `set_cells` | `sheet`, `start` (default `A1`), `rows` | writes a 2-D block anchored at `start` | +| `append_rows` | `sheet`, `rows`, `column` (default `A`) | writes below the last used row | +| `insert_rows` | `sheet`, `row`, `count`, `rows` | inserts empty rows before `row` (optionally filled); references below shift | +| `delete_rows` | `sheet`, `row`, `count` | references shift; references to deleted cells become `#REF!` | +| `insert_columns` / `delete_columns` | `sheet`, `column`, `count` | same for columns | +| `clear_range` | `sheet`, `range`, `what` (`all` `contents` `formats`) | | +| `format_range` | `sheet`, `range`, `style` | | +| `set_column_widths` | `sheet`, `widths` `{ "A": 18, "B:D": 12 }` (characters; 0 hides) | | +| `set_row_heights` | `sheet`, `heights` `{ "1": 28, "2:10": 18 }` (points; 0 hides) | | +| `merge_cells` / `unmerge_cells` | `sheet`, `range` | | +| `freeze_panes` | `sheet`, `rows`, `columns` (0, 0 removes) | | +| `set_autofilter` | `sheet`, `range` (`null` removes) | | +| `set_sheet` | `sheet`, `tab_color` | | +| `set_properties` | `title`, `subject`, `author`, `keywords`, `description`, `category` | | + +Operations run in order and each sees the previous result: after `insert_rows`, later operations in the same batch address the shifted grid. A batch is atomic. + +## Example + +```json +{"action": "create", "file_path": "/abs/sales.xlsx", "operations": [ + {"op": "add_sheet", "name": "Sales", "rows": [["Item", "Qty", "Price", "Total"], ["Apple", 2, 1.5, "=B2*C2"]]}, + {"op": "append_rows", "sheet": "Sales", "rows": [["Pear", 3, 2, "=B3*C3"], ["Total", "=SUM(B2:B3)", null, "=SUM(D2:D3)"]]}, + {"op": "format_range", "sheet": "Sales", "range": "A1:D1", "style": {"bold": true, "fill_color": "#1F4E79", "font_color": "#FFFFFF"}}, + {"op": "format_range", "sheet": "Sales", "range": "C2:D4", "style": {"number_format": "#,##0.00"}}, + {"op": "set_column_widths", "sheet": "Sales", "widths": {"A": 16, "B:D": 12}}, + {"op": "freeze_panes", "sheet": "Sales", "rows": 1} +]} +``` diff --git a/src/crates/execution/office-documents/src/image.rs b/src/crates/execution/office-documents/src/image.rs new file mode 100644 index 0000000000..b773267b0f --- /dev/null +++ b/src/crates/execution/office-documents/src/image.rs @@ -0,0 +1,210 @@ +//! Image sniffing for embedding: format, natural size, and data URLs. + +use crate::error::{OfficeError, OfficeErrorKind, OfficeResult}; +use base64::Engine; +use sha2::{Digest, Sha256}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ImageKind { + Png, + Jpeg, + Gif, + Bmp, +} + +impl ImageKind { + pub const fn extension(self) -> &'static str { + match self { + Self::Png => "png", + Self::Jpeg => "jpeg", + Self::Gif => "gif", + Self::Bmp => "bmp", + } + } + + pub const fn content_type(self) -> &'static str { + match self { + Self::Png => "image/png", + Self::Jpeg => "image/jpeg", + Self::Gif => "image/gif", + Self::Bmp => "image/bmp", + } + } + + pub fn from_extension(extension: &str) -> Option { + match extension.to_ascii_lowercase().as_str() { + "png" => Some(Self::Png), + "jpg" | "jpeg" => Some(Self::Jpeg), + "gif" => Some(Self::Gif), + "bmp" => Some(Self::Bmp), + _ => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ImageInfo { + pub kind: ImageKind, + pub width: u32, + pub height: u32, +} + +fn invalid(message: impl Into) -> OfficeError { + OfficeError::new(OfficeErrorKind::InvalidImage, message) +} + +/// Reads the format and pixel size from the file header. +pub fn sniff(bytes: &[u8]) -> OfficeResult { + if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { + if bytes.len() < 24 { + return Err(invalid("truncated PNG header")); + } + let width = u32::from_be_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]); + let height = u32::from_be_bytes([bytes[20], bytes[21], bytes[22], bytes[23]]); + return checked(ImageKind::Png, width, height); + } + if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") { + if bytes.len() < 10 { + return Err(invalid("truncated GIF header")); + } + let width = u16::from_le_bytes([bytes[6], bytes[7]]) as u32; + let height = u16::from_le_bytes([bytes[8], bytes[9]]) as u32; + return checked(ImageKind::Gif, width, height); + } + if bytes.starts_with(b"BM") { + if bytes.len() < 26 { + return Err(invalid("truncated BMP header")); + } + let width = i32::from_le_bytes([bytes[18], bytes[19], bytes[20], bytes[21]]); + let height = i32::from_le_bytes([bytes[22], bytes[23], bytes[24], bytes[25]]); + return checked(ImageKind::Bmp, width.unsigned_abs(), height.unsigned_abs()); + } + if bytes.starts_with(&[0xFF, 0xD8]) { + let (width, height) = + jpeg_size(bytes).ok_or_else(|| invalid("JPEG without a frame header"))?; + return checked(ImageKind::Jpeg, width, height); + } + if bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { + return Err(invalid( + "WebP images are not supported by Office; convert the picture to PNG or JPEG first", + )); + } + if bytes.starts_with(b" OfficeResult { + if width == 0 || height == 0 { + return Err(invalid("image has zero width or height")); + } + Ok(ImageInfo { + kind, + width, + height, + }) +} + +fn jpeg_size(bytes: &[u8]) -> Option<(u32, u32)> { + let mut index = 2; + while index + 4 <= bytes.len() { + if bytes[index] != 0xFF { + index += 1; + continue; + } + let marker = bytes[index + 1]; + if marker == 0xFF { + index += 1; + continue; + } + if marker == 0xD8 || marker == 0x01 || (0xD0..=0xD7).contains(&marker) { + index += 2; + continue; + } + let length = u16::from_be_bytes([bytes[index + 2], bytes[index + 3]]) as usize; + let is_frame = (0xC0..=0xCF).contains(&marker) && !matches!(marker, 0xC4 | 0xC8 | 0xCC); + if is_frame { + if index + 9 > bytes.len() { + return None; + } + let height = u16::from_be_bytes([bytes[index + 5], bytes[index + 6]]) as u32; + let width = u16::from_be_bytes([bytes[index + 7], bytes[index + 8]]) as u32; + return Some((width, height)); + } + if length < 2 { + return None; + } + index += 2 + length; + } + None +} + +/// Decodes `data:image/...;base64,...`; `None` when the source is not a data URL. +pub fn decode_data_url(source: &str) -> Option>> { + let rest = source.strip_prefix("data:")?; + let Some((meta, payload)) = rest.split_once(',') else { + return Some(Err(invalid("malformed data URL"))); + }; + if !meta.ends_with(";base64") { + return Some(Err(invalid("data URLs must be base64 encoded"))); + } + let cleaned: String = payload.chars().filter(|c| !c.is_whitespace()).collect(); + Some( + base64::engine::general_purpose::STANDARD + .decode(cleaned.as_bytes()) + .map_err(|err| invalid(format!("invalid base64 in data URL: {err}"))), + ) +} + +/// Content-addressed asset name: the same picture is stored once. +pub fn asset_name(bytes: &[u8], kind: ImageKind) -> String { + let digest = Sha256::digest(bytes); + let hex: String = digest.iter().take(8).map(|b| format!("{b:02x}")).collect(); + format!("img-{hex}.{}", kind.extension()) +} + +pub fn kind_of_asset(name: &str) -> Option { + name.rsplit_once('.') + .and_then(|(_, extension)| ImageKind::from_extension(extension)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_support::tiny_png; + + #[test] + fn sniffs_png_size_and_rejects_webp() { + let info = sniff(&tiny_png(640, 480)).unwrap(); + assert_eq!( + (info.kind, info.width, info.height), + (ImageKind::Png, 640, 480) + ); + let error = sniff(b"RIFF\0\0\0\0WEBPVP8 ").unwrap_err(); + assert_eq!(error.kind, OfficeErrorKind::InvalidImage); + } + + #[test] + fn reads_jpeg_frame_size() { + let jpeg = [ + 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00, 0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, + 0x20, 0x00, 0x40, + ]; + let info = sniff(&jpeg).unwrap(); + assert_eq!((info.width, info.height), (64, 32)); + } + + #[test] + fn decodes_data_urls() { + let decoded = decode_data_url("data:image/png;base64,aGk=") + .unwrap() + .unwrap(); + assert_eq!(decoded, b"hi"); + assert!(decode_data_url("/tmp/a.png").is_none()); + } +} diff --git a/src/crates/execution/office-documents/src/lib.rs b/src/crates/execution/office-documents/src/lib.rs new file mode 100644 index 0000000000..0caa37af87 --- /dev/null +++ b/src/crates/execution/office-documents/src/lib.rs @@ -0,0 +1,564 @@ +//! Portable OOXML document engine for agent tools. +//! +//! Agent-facing formats were developed with reference to GenOffice +//! (Copyright 2026 Mainfunc, Inc.; Apache-2.0). See this crate's README.md, +//! LICENSE-GENOFFICE.txt, and NOTICE-GENOFFICE.txt for sources and attribution. +//! +//! A document is an editable JSON model (Word blocks, workbook sheets, or a +//! slide deck of positioned elements). Operations edit the model atomically, +//! and the whole package is re-rendered from it. The model travels inside the +//! package, so a later call can reopen the file and keep editing it one batch +//! at a time instead of producing everything in a single call. + +pub mod common; +pub mod docx; +mod error; +mod guide; +pub mod image; +mod package; +pub mod pptx; +pub mod xlsx; +mod xml; + +pub use error::{OfficeError, OfficeErrorKind, OfficeResult}; +pub use guide::guide; + +use common::{merge_patch, operation_name, UnknownFields}; +use docx::DocxDocument; +use package::{read_source, read_zip, SourceEnvelope, SOURCE_PART, SOURCE_SCHEMA, SOURCE_VERSION}; +use pptx::PptxDocument; +use serde::de::DeserializeOwned; +use serde::Serialize; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use xlsx::XlsxDocument; + +/// Bytes of image sources referenced by operations, keyed by the exact +/// source string. Data URLs are decoded by the engine and need no entry. +pub type ImageSources = HashMap>; + +const MAX_OPERATIONS_PER_BATCH: usize = 200; +const MAX_IMAGE_BYTES: usize = 25 * 1024 * 1024; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum OfficeFormat { + Docx, + Xlsx, + Pptx, +} + +impl OfficeFormat { + pub fn from_path(path: &str) -> Option { + let extension = path.rsplit_once('.')?.1; + Self::from_name(extension) + } + + pub fn from_name(name: &str) -> Option { + match name + .trim() + .trim_start_matches('.') + .to_ascii_lowercase() + .as_str() + { + "docx" | "word" => Some(Self::Docx), + "xlsx" | "excel" => Some(Self::Xlsx), + "pptx" | "powerpoint" => Some(Self::Pptx), + _ => None, + } + } + + pub const fn as_str(self) -> &'static str { + match self { + Self::Docx => "docx", + Self::Xlsx => "xlsx", + Self::Pptx => "pptx", + } + } + + /// The unit `read` pages over and structural operations address. + pub const fn unit(self) -> &'static str { + match self { + Self::Docx => "block", + Self::Xlsx => "sheet", + Self::Pptx => "slide", + } + } + + pub fn operations(self) -> &'static [&'static str] { + match self { + Self::Docx => docx::ops::OPERATIONS, + Self::Xlsx => xlsx::ops::OPERATIONS, + Self::Pptx => pptx::ops::OPERATIONS, + } + } +} + +#[derive(Debug, Clone, PartialEq)] +enum Model { + Docx(Box), + Xlsx(Box), + Pptx(Box), +} + +impl Model { + fn format(&self) -> OfficeFormat { + match self { + Model::Docx(_) => OfficeFormat::Docx, + Model::Xlsx(_) => OfficeFormat::Xlsx, + Model::Pptx(_) => OfficeFormat::Pptx, + } + } + + fn referenced_assets(&self) -> BTreeSet { + match self { + Model::Docx(doc) => doc + .blocks + .iter() + .filter_map(|block| match block { + docx::Block::Image(image) => image.asset.clone(), + _ => None, + }) + .collect(), + Model::Pptx(deck) => deck.referenced_assets(), + Model::Xlsx(_) => BTreeSet::new(), + } + } + + fn media_dir(&self) -> &'static str { + match self { + Model::Docx(_) => "word/media/", + Model::Pptx(_) => "ppt/media/", + Model::Xlsx(_) => "xl/media/", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Detail { + /// Compact listing: kind, preview text, and counts. + #[default] + Outline, + /// The stored model of each unit, suitable for editing and echoing back. + Full, +} + +#[derive(Debug, Clone, Default)] +pub struct ReadRequest { + pub offset: Option, + pub limit: Option, + pub detail: Detail, + /// Workbook only: page over rows of this sheet instead of the sheet list. + pub sheet: Option, + /// Workbook only: an A1 range of `sheet` to read. + pub range: Option, +} + +impl ReadRequest { + pub(crate) fn window(&self, total: usize, default_limit: usize) -> (usize, usize) { + let offset = self.offset.unwrap_or(0).min(total); + let limit = self.limit.unwrap_or(default_limit).clamp(1, 500); + (offset, limit) + } +} + +#[derive(Debug, Clone, Default)] +pub struct OpenOptions { + /// Rebuild from the embedded source even when another program changed + /// the rendered parts since this engine last wrote them. + pub discard_external_changes: bool, +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct ApplyReport { + pub applied: usize, + pub changes: Vec, + pub warnings: Vec, +} + +/// Mutable state shared by the operations of one batch. +pub(crate) struct ApplyContext<'a> { + images: &'a ImageSources, + assets: &'a mut BTreeMap>, + changes: Vec, + warnings: Vec, + /// Units (slides) whose layout should be audited after the batch. + pub(crate) touched: BTreeSet, +} + +impl ApplyContext<'_> { + pub(crate) fn note(&mut self, change: String) { + self.changes.push(change); + } + + pub(crate) fn warn(&mut self, warning: String) { + self.warnings.push(warning); + } + + /// Embeds an image and returns its asset name. An `asset` that is already + /// embedded wins over `src`, so echoing a read result back keeps working + /// after the original file is gone. + pub(crate) fn resolve_image( + &mut self, + src: Option<&str>, + asset: Option<&str>, + path: &str, + ) -> OfficeResult { + if let Some(asset) = asset { + if self.assets.contains_key(asset) { + return Ok(asset.to_string()); + } + if src.is_none() { + return Err(OfficeError::not_found(format!( + "{path}: asset `{asset}` is not embedded in this document; pass `src` with a file path or data URL instead" + ))); + } + } + let src = src.ok_or_else(|| { + OfficeError::invalid(format!("{path}: image needs `src` or an embedded `asset`")) + })?; + let bytes = match image::decode_data_url(src) { + Some(decoded) => decoded?, + None => self.images.get(src).cloned().ok_or_else(|| { + OfficeError::new( + OfficeErrorKind::InvalidImage, + format!("{path}: image `{src}` was not loaded; use an absolute local file path or a data URL"), + ) + })?, + }; + if bytes.len() > MAX_IMAGE_BYTES { + return Err(OfficeError::limit(format!( + "{path}: image `{src}` is larger than {} MB", + MAX_IMAGE_BYTES / 1024 / 1024 + ))); + } + let info = image::sniff(&bytes).map_err(|err| common::prefix(err, path, "src"))?; + let name = image::asset_name(&bytes, info.kind); + self.assets.entry(name.clone()).or_insert(bytes); + Ok(name) + } +} + +/// An open, editable office document. +#[derive(Debug, Clone)] +pub struct OfficeDocument { + model: Model, + assets: BTreeMap>, + revision: u64, + created: Option, + modified: Option, + envelope_extra: BTreeMap, +} + +impl OfficeDocument { + /// A new empty document. `settings` is a partial document-level object + /// (page/styles for Word, slide size/theme for decks, properties for all). + pub fn new(format: OfficeFormat, settings: Option<&Value>) -> OfficeResult { + let model = match format { + OfficeFormat::Docx => { + let mut doc: DocxDocument = + with_settings(DocxDocument::default(), settings, "blocks")?; + doc.page.validate()?; + doc.styles.validate()?; + doc.blocks.clear(); + Model::Docx(Box::new(doc)) + } + OfficeFormat::Xlsx => { + let mut book: XlsxDocument = + with_settings(XlsxDocument::default(), settings, "sheets")?; + book.sheets.clear(); + Model::Xlsx(Box::new(book)) + } + OfficeFormat::Pptx => { + let mut deck: PptxDocument = + with_settings(PptxDocument::default(), settings, "slides")?; + deck.validate_settings()?; + deck.slides.clear(); + Model::Pptx(Box::new(deck)) + } + }; + Ok(Self { + model, + assets: BTreeMap::new(), + revision: 0, + created: None, + modified: None, + envelope_extra: BTreeMap::new(), + }) + } + + /// Reopens a package written by this engine. + pub fn open(bytes: &[u8], options: &OpenOptions) -> OfficeResult { + let entries = read_zip(bytes)?; + let envelope = read_source(&entries, options.discard_external_changes)?; + let format = OfficeFormat::from_name(&envelope.format).ok_or_else(|| { + OfficeError::new( + OfficeErrorKind::UnsupportedFormat, + format!("unknown embedded format `{}`", envelope.format), + ) + })?; + let model = match format { + OfficeFormat::Docx => Model::Docx(Box::new(from_source(envelope.document.clone())?)), + OfficeFormat::Xlsx => Model::Xlsx(Box::new(from_source(envelope.document.clone())?)), + OfficeFormat::Pptx => Model::Pptx(Box::new(from_source(envelope.document.clone())?)), + }; + let mut assets = BTreeMap::new(); + for name in model.referenced_assets() { + let path = format!("{}{name}", model.media_dir()); + let bytes = entries.get(&path).ok_or_else(|| { + OfficeError::corrupt(format!( + "embedded picture {path} is missing from the package" + )) + })?; + assets.insert(name, bytes.clone()); + } + Ok(Self { + model, + assets, + revision: envelope.revision, + created: envelope.created, + modified: envelope.modified, + envelope_extra: envelope.extra, + }) + } + + pub fn format(&self) -> OfficeFormat { + self.model.format() + } + + pub fn revision(&self) -> u64 { + self.revision + } + + /// Records the write time (RFC 3339) for the document properties. + pub fn touch(&mut self, now: &str) { + if self.created.is_none() { + self.created = Some(now.to_string()); + } + self.modified = Some(now.to_string()); + } + + /// Applies a batch atomically: either every operation succeeds or the + /// document is left unchanged. + pub fn apply( + &mut self, + operations: &[Value], + images: &ImageSources, + ) -> OfficeResult { + if operations.len() > MAX_OPERATIONS_PER_BATCH { + return Err(OfficeError::limit(format!( + "a batch is limited to {MAX_OPERATIONS_PER_BATCH} operations; split it across calls" + ))); + } + let mut model = self.model.clone(); + let mut assets = self.assets.clone(); + let mut ctx = ApplyContext { + images, + assets: &mut assets, + changes: Vec::new(), + warnings: Vec::new(), + touched: BTreeSet::new(), + }; + for (index, operation) in operations.iter().enumerate() { + let name = operation_name(operation) + .map_err(|err| err.at_operation(index, "?"))? + .to_string(); + let result = match &mut model { + Model::Docx(doc) => docx::ops::apply(doc, &name, operation, &mut ctx), + Model::Xlsx(book) => xlsx::ops::apply(book, &name, operation, &mut ctx), + Model::Pptx(deck) => pptx::ops::apply(deck, &name, operation, &mut ctx), + }; + result.map_err(|err| err.at_operation(index, &name))?; + } + let mut warnings = ctx.warnings; + let changes = ctx.changes; + if let Model::Pptx(deck) = &model { + warnings.extend(deck.audit(Some(&ctx.touched))); + } + if let Model::Xlsx(book) = &model { + warnings.extend(book.warnings()); + } + let referenced = model.referenced_assets(); + assets.retain(|name, _| referenced.contains(name)); + self.model = model; + self.assets = assets; + self.revision += 1; + Ok(ApplyReport { + applied: operations.len(), + changes, + warnings, + }) + } + + /// Renders the complete package, including the embedded source. + pub fn to_bytes(&self) -> OfficeResult> { + let created = self.created.as_deref(); + let modified = self.modified.as_deref(); + let (mut parts, document) = match &self.model { + Model::Docx(doc) => ( + docx::render::render(doc, &self.assets, created, modified)?, + to_source(doc)?, + ), + Model::Xlsx(book) => ( + xlsx::render::render(book, created, modified)?, + to_source(book)?, + ), + Model::Pptx(deck) => ( + pptx::render::render(deck, &self.assets, created, modified)?, + to_source(deck)?, + ), + }; + let envelope = SourceEnvelope { + schema: SOURCE_SCHEMA.to_string(), + version: SOURCE_VERSION, + format: self.format().as_str().to_string(), + revision: self.revision, + fingerprint: parts.fingerprint(), + created: self.created.clone(), + modified: self.modified.clone(), + document, + extra: self.envelope_extra.clone(), + }; + let source = serde_json::to_vec(&envelope) + .map_err(|err| OfficeError::corrupt(format!("cannot serialize the source: {err}")))?; + parts.add(SOURCE_PART, source); + parts.into_zip() + } + + /// A page of the document's structure. + pub fn read(&self, request: &ReadRequest) -> OfficeResult { + let mut view = match &self.model { + Model::Docx(doc) => docx::read(doc, request), + Model::Xlsx(book) => xlsx::read(book, request)?, + Model::Pptx(deck) => pptx::read(deck, request), + }; + if let Some(object) = view.as_object_mut() { + object.insert("format".to_string(), json!(self.format().as_str())); + object.insert("revision".to_string(), json!(self.revision)); + } + Ok(view) + } + + /// Unit counts for tool results. + pub fn summary(&self) -> Value { + match &self.model { + Model::Docx(doc) => json!({ "blocks": doc.blocks.len() }), + Model::Xlsx(book) => json!({ + "sheets": book.sheets.len(), + "sheet_names": book.sheets.iter().map(|sheet| sheet.name.clone()).collect::>(), + }), + Model::Pptx(deck) => json!({ "slides": deck.slides.len() }), + } + } + + /// Layout findings for the whole document (decks: geometry and overflow). + pub fn audit(&self) -> Vec { + match &self.model { + Model::Pptx(deck) => deck.audit(None), + Model::Xlsx(book) => book.warnings(), + Model::Docx(_) => Vec::new(), + } + } +} + +fn to_source(model: &T) -> OfficeResult { + serde_json::to_value(model) + .map_err(|err| OfficeError::corrupt(format!("cannot serialize the document model: {err}"))) +} + +fn from_source(value: Value) -> OfficeResult { + serde_json::from_value(value).map_err(|err| { + OfficeError::corrupt(format!("the embedded document model is invalid: {err}")) + }) +} + +fn with_settings(base: T, settings: Option<&Value>, content_key: &str) -> OfficeResult +where + T: Serialize + DeserializeOwned + UnknownFields, +{ + let Some(settings) = settings.filter(|value| !value.is_null()) else { + return Ok(base); + }; + if !settings.is_object() { + return Err(OfficeError::invalid("settings must be an object")); + } + if settings.get(content_key).is_some() { + return Err(OfficeError::invalid(format!( + "settings cannot carry `{content_key}`; add content with operations" + ))); + } + let mut value = to_source(&base)?; + merge_patch(&mut value, settings); + let parsed: T = serde_json::from_value(value) + .map_err(|err| OfficeError::invalid(format!("settings: {err}")))?; + let mut unknown = Vec::new(); + parsed.unknown_fields("settings", &mut unknown); + if !unknown.is_empty() { + return Err(OfficeError::invalid(format!( + "unknown settings field(s): {}", + unknown.join(", ") + ))); + } + Ok(parsed) +} + +/// Image sources the host must load before [`OfficeDocument::apply`]: +/// `src`/`url`/`path` of image objects that carry no embedded `asset`, plus +/// pictures referenced from Markdown. Data URLs are excluded. +pub fn collect_image_sources(operations: &[Value]) -> Vec { + fn push_source(object: &serde_json::Map, out: &mut Vec) { + if object.get("asset").and_then(Value::as_str).is_some() { + return; + } + for key in ["src", "url", "path"] { + if let Some(src) = object.get(key).and_then(Value::as_str) { + out.push(src.to_string()); + return; + } + } + } + fn walk(value: &Value, out: &mut Vec) { + match value { + Value::Object(object) => { + let is_image = object.get("type").and_then(Value::as_str) == Some("image"); + if is_image { + push_source(object, out); + } + // Element patches carry no `type`; a new `src` replaces the picture. + if let Some(patches) = object.get("update_elements").and_then(Value::as_array) { + for patch in patches.iter().filter_map(Value::as_object) { + push_source(patch, out); + } + } + if let Some(markdown) = object.get("markdown").and_then(Value::as_str) { + out.extend(docx::markdown_image_sources(markdown)); + } + for child in object.values() { + walk(child, out); + } + } + Value::Array(items) => items.iter().for_each(|item| walk(item, out)), + _ => {} + } + } + let mut found = Vec::new(); + for operation in operations { + walk(operation, &mut found); + } + let mut seen = BTreeSet::new(); + found + .into_iter() + .filter(|src| !src.starts_with("data:")) + .filter(|src| seen.insert(src.clone())) + .collect() +} + +#[cfg(test)] +pub(crate) mod test_support { + pub(crate) fn tiny_png(width: u32, height: u32) -> Vec { + let mut bytes = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec(); + bytes.extend_from_slice(&width.to_be_bytes()); + bytes.extend_from_slice(&height.to_be_bytes()); + bytes.extend_from_slice(&[8, 6, 0, 0, 0]); + bytes + } +} diff --git a/src/crates/execution/office-documents/src/package.rs b/src/crates/execution/office-documents/src/package.rs new file mode 100644 index 0000000000..b8b59aff41 --- /dev/null +++ b/src/crates/execution/office-documents/src/package.rs @@ -0,0 +1,430 @@ +//! OPC package plumbing: zip IO, shared parts, and the embedded source model. +//! +//! Every package this crate writes carries its editable model in a private +//! part (`openbitfun/genoffice.json`) reached through a package-level +//! relationship. Office applications ignore unknown relationships, so the file +//! opens normally; this crate reads the part back to apply later edits. + +use crate::common::DocumentProperties; +use crate::error::{OfficeError, OfficeErrorKind, OfficeResult}; +use crate::xml::{esc, XML_HEADER}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::io::{Cursor, Read, Write}; + +pub(crate) const SOURCE_PART: &str = "openbitfun/genoffice.json"; +pub(crate) const SOURCE_REL_TYPE: &str = + "http://schemas.openbitfun.com/genoffice/2026/relationships/source"; +pub(crate) const SOURCE_CONTENT_TYPE: &str = "application/vnd.openbitfun.genoffice+json"; +pub(crate) const SOURCE_SCHEMA: &str = "openbitfun.genoffice"; +pub(crate) const SOURCE_VERSION: u32 = 1; + +const MAX_PACKAGE_ENTRIES: usize = 4096; +const MAX_ENTRY_BYTES: u64 = 256 * 1024 * 1024; +const MAX_TOTAL_BYTES: u64 = 512 * 1024 * 1024; + +const REL_OFFICE_DOCUMENT: &str = + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; +const REL_CORE: &str = + "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"; +const REL_APP: &str = + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"; + +/// The JSON stored in [`SOURCE_PART`]. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub(crate) struct SourceEnvelope { + pub schema: String, + pub version: u32, + pub format: String, + #[serde(default)] + pub revision: u64, + /// Hash of the rendered parts; a mismatch means another program changed + /// the document after this engine wrote it. + #[serde(default)] + pub fingerprint: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub created: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub modified: Option, + pub document: Value, + /// Forward-compatible envelope fields written by newer versions. + #[serde(flatten)] + pub extra: BTreeMap, +} + +/// Rendered package parts in write order. +#[derive(Debug, Default)] +pub(crate) struct Parts { + entries: Vec<(String, Vec)>, +} + +impl Parts { + pub(crate) fn add(&mut self, name: impl Into, bytes: impl Into>) { + self.entries.push((name.into(), bytes.into())); + } + + pub(crate) fn add_xml(&mut self, name: impl Into, xml: String) { + self.add(name, xml.into_bytes()); + } + + pub(crate) fn fingerprint(&self) -> String { + fingerprint( + self.entries + .iter() + .map(|(name, bytes)| (name.as_str(), bytes.as_slice())), + ) + } + + pub(crate) fn into_zip(self) -> OfficeResult> { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default() + .compression_method(zip::CompressionMethod::Deflated) + .last_modified_time(zip::DateTime::default()); + for (name, bytes) in self.entries { + writer + .start_file(name.as_str(), options) + .map_err(|err| OfficeError::corrupt(format!("cannot write {name}: {err}")))?; + writer + .write_all(&bytes) + .map_err(|err| OfficeError::corrupt(format!("cannot write {name}: {err}")))?; + } + let cursor = writer + .finish() + .map_err(|err| OfficeError::corrupt(format!("cannot finish package: {err}")))?; + Ok(cursor.into_inner()) + } +} + +/// Parts that count toward the fingerprint: everything this engine renders +/// except the source part itself and document properties, which Office +/// applications rewrite on every save. +fn fingerprinted(name: &str) -> bool { + name != SOURCE_PART && !name.starts_with("docProps/") +} + +pub(crate) fn fingerprint<'a>(entries: impl Iterator) -> String { + let mut selected: Vec<(&str, &[u8])> = + entries.filter(|(name, _)| fingerprinted(name)).collect(); + selected.sort_by(|a, b| a.0.cmp(b.0)); + let mut hasher = Sha256::new(); + for (name, bytes) in selected { + hasher.update(name.as_bytes()); + hasher.update([0]); + hasher.update((bytes.len() as u64).to_le_bytes()); + hasher.update(bytes); + } + hasher + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +/// Reads every entry of a package, refusing archives that inflate past the +/// limits before materializing them. +pub(crate) fn read_zip(bytes: &[u8]) -> OfficeResult>> { + let mut archive = zip::ZipArchive::new(Cursor::new(bytes)) + .map_err(|err| OfficeError::corrupt(format!("not a zip package: {err}")))?; + if archive.len() > MAX_PACKAGE_ENTRIES { + return Err(OfficeError::limit(format!( + "package has {} entries; the limit is {MAX_PACKAGE_ENTRIES}", + archive.len() + ))); + } + let mut total = 0u64; + let mut entries = BTreeMap::new(); + for index in 0..archive.len() { + let mut file = archive + .by_index(index) + .map_err(|err| OfficeError::corrupt(format!("unreadable zip entry: {err}")))?; + if file.is_dir() { + continue; + } + let name = file.name().to_string(); + if file.size() > MAX_ENTRY_BYTES { + return Err(OfficeError::limit(format!( + "package entry {name} is too large" + ))); + } + let mut buffer = Vec::with_capacity(file.size() as usize); + (&mut file) + .take(MAX_ENTRY_BYTES + 1) + .read_to_end(&mut buffer) + .map_err(|err| OfficeError::corrupt(format!("cannot read {name}: {err}")))?; + if buffer.len() as u64 > MAX_ENTRY_BYTES { + return Err(OfficeError::limit(format!( + "package entry {name} is too large" + ))); + } + total += buffer.len() as u64; + if total > MAX_TOTAL_BYTES { + return Err(OfficeError::limit("package inflates past the size limit")); + } + entries.insert(name, buffer); + } + Ok(entries) +} + +/// Extracts and verifies the embedded source of an opened package. +pub(crate) fn read_source( + entries: &BTreeMap>, + discard_external_changes: bool, +) -> OfficeResult { + let Some(source) = entries.get(SOURCE_PART) else { + return Err(OfficeError::new( + OfficeErrorKind::NotGenerated, + "this file was not created by GenOfficeFile (or another program re-saved it and dropped the editable source); read it with the Read tool and create a new file instead", + )); + }; + let envelope: SourceEnvelope = serde_json::from_slice(source).map_err(|err| { + OfficeError::corrupt(format!("the embedded source is not valid JSON: {err}")) + })?; + if envelope.schema != SOURCE_SCHEMA { + return Err(OfficeError::corrupt(format!( + "unexpected source schema `{}`", + envelope.schema + ))); + } + if envelope.version > SOURCE_VERSION { + return Err(OfficeError::new( + OfficeErrorKind::UnsupportedFormat, + format!( + "the file was written by a newer GenOfficeFile (source version {}); this version understands up to {SOURCE_VERSION}", + envelope.version + ), + )); + } + let actual = fingerprint( + entries + .iter() + .map(|(name, bytes)| (name.as_str(), bytes.as_slice())), + ); + if !discard_external_changes + && !envelope.fingerprint.is_empty() + && actual != envelope.fingerprint + { + return Err(OfficeError::new( + OfficeErrorKind::ExternallyModified, + "the file was changed by another program after GenOfficeFile last wrote it; editing would discard those changes. Read it with the Read tool and recreate it, or pass discard_external_changes=true to rebuild from the last GenOfficeFile state", + )); + } + Ok(envelope) +} + +/// `[Content_Types].xml` builder. +#[derive(Debug, Default)] +pub(crate) struct ContentTypes { + defaults: BTreeMap, + overrides: Vec<(String, String)>, +} + +impl ContentTypes { + pub(crate) fn new() -> Self { + let mut types = Self { + defaults: BTreeMap::new(), + overrides: Vec::new(), + }; + types.extension( + "rels", + "application/vnd.openxmlformats-package.relationships+xml", + ); + types.extension("xml", "application/xml"); + types + } + + pub(crate) fn extension(&mut self, extension: &str, content_type: &str) { + self.defaults + .insert(extension.to_string(), content_type.to_string()); + } + + pub(crate) fn part(&mut self, part_name: &str, content_type: &str) { + self.overrides + .push((format!("/{part_name}"), content_type.to_string())); + } + + pub(crate) fn xml(&self) -> String { + let mut xml = String::from(XML_HEADER); + xml.push_str( + "", + ); + for (extension, content_type) in &self.defaults { + xml.push_str(&format!( + "" + )); + } + for (part, content_type) in &self.overrides { + xml.push_str(&format!( + "", + esc(part) + )); + } + xml.push_str(""); + xml + } +} + +/// Relationship part builder; ids are assigned in insertion order. +#[derive(Debug, Default)] +pub(crate) struct Relationships { + entries: Vec<(String, String, String, bool)>, +} + +impl Relationships { + pub(crate) fn add(&mut self, rel_type: &str, target: &str) -> String { + self.push(rel_type, target, false) + } + + pub(crate) fn add_external(&mut self, rel_type: &str, target: &str) -> String { + self.push(rel_type, target, true) + } + + fn push(&mut self, rel_type: &str, target: &str, external: bool) -> String { + let id = format!("rId{}", self.entries.len() + 1); + self.entries.push(( + id.clone(), + rel_type.to_string(), + target.to_string(), + external, + )); + id + } + + pub(crate) fn xml(&self) -> String { + let mut xml = String::from(XML_HEADER); + xml.push_str( + "", + ); + for (id, rel_type, target, external) in &self.entries { + xml.push_str(&format!( + "", + esc(target), + if *external { + " TargetMode=\"External\"" + } else { + "" + } + )); + } + xml.push_str(""); + xml + } +} + +/// Adds the parts every package shares: package relationships, document +/// properties, and the embedded source part with its content type. +pub(crate) fn add_common_parts( + parts: &mut Parts, + types: &mut ContentTypes, + main_part: &str, + properties: &DocumentProperties, + created: Option<&str>, + modified: Option<&str>, + application: &str, +) { + let mut rels = Relationships::default(); + rels.add(REL_OFFICE_DOCUMENT, main_part); + rels.add(REL_CORE, "docProps/core.xml"); + rels.add(REL_APP, "docProps/app.xml"); + rels.add(SOURCE_REL_TYPE, SOURCE_PART); + parts.add_xml("_rels/.rels", rels.xml()); + + types.part( + "docProps/core.xml", + "application/vnd.openxmlformats-package.core-properties+xml", + ); + types.part( + "docProps/app.xml", + "application/vnd.openxmlformats-officedocument.extended-properties+xml", + ); + types.part(SOURCE_PART, SOURCE_CONTENT_TYPE); + parts.add_xml("docProps/core.xml", core_xml(properties, created, modified)); + parts.add_xml("docProps/app.xml", app_xml(application)); +} + +fn core_xml( + properties: &DocumentProperties, + created: Option<&str>, + modified: Option<&str>, +) -> String { + let mut xml = String::from(XML_HEADER); + xml.push_str(""); + let mut field = |tag: &str, value: &Option| { + if let Some(value) = value { + xml.push_str(&format!("<{tag}>{}", esc(value))); + } + }; + field("dc:title", &properties.title); + field("dc:subject", &properties.subject); + field("dc:creator", &properties.author); + field("cp:keywords", &properties.keywords); + field("dc:description", &properties.description); + field("cp:category", &properties.category); + if let Some(author) = &properties.author { + xml.push_str(&format!( + "{}", + esc(author) + )); + } + if let Some(created) = created { + xml.push_str(&format!( + "{}", + esc(created) + )); + } + if let Some(modified) = modified { + xml.push_str(&format!( + "{}", + esc(modified) + )); + } + xml.push_str(""); + xml +} + +fn app_xml(application: &str) -> String { + format!( + "{XML_HEADER}{}", + esc(application) + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fingerprint_ignores_source_and_properties() { + let a = fingerprint( + [ + ("word/document.xml", b"a".as_slice()), + (SOURCE_PART, b"x".as_slice()), + ] + .into_iter(), + ); + let b = fingerprint( + [ + ("docProps/core.xml", b"changed".as_slice()), + ("word/document.xml", b"a".as_slice()), + (SOURCE_PART, b"y".as_slice()), + ] + .into_iter(), + ); + assert_eq!(a, b); + let c = fingerprint([("word/document.xml", b"b".as_slice())].into_iter()); + assert_ne!(a, c); + } + + #[test] + fn zip_round_trip() { + let mut parts = Parts::default(); + parts.add("a.xml", b"".to_vec()); + let bytes = parts.into_zip().unwrap(); + let entries = read_zip(&bytes).unwrap(); + assert_eq!( + entries.get("a.xml").map(Vec::as_slice), + Some(b"".as_slice()) + ); + } +} diff --git a/src/crates/execution/office-documents/src/pptx/mod.rs b/src/crates/execution/office-documents/src/pptx/mod.rs new file mode 100644 index 0000000000..4897560636 --- /dev/null +++ b/src/crates/execution/office-documents/src/pptx/mod.rs @@ -0,0 +1,198 @@ +//! Slide decks (`.pptx`). + +pub(crate) mod model; +pub(crate) mod ops; +pub(crate) mod render; + +pub use model::{Element, PptxDocument, Slide, SHAPE_KINDS}; + +use crate::common::{preview, runs_text}; +use crate::{Detail, ReadRequest}; +use model::{Paragraph, TextDefaults}; +use serde_json::{json, Value}; +use std::collections::BTreeSet; + +pub(crate) fn read(deck: &PptxDocument, request: &ReadRequest) -> Value { + let total = deck.slides.len(); + let default_limit = if request.detail == Detail::Full { + 5 + } else { + 30 + }; + let (offset, limit) = request.window(total, default_limit); + let slides: Vec = deck + .slides + .iter() + .enumerate() + .skip(offset) + .take(limit) + .map(|(index, slide)| { + if request.detail == Detail::Full { + let mut value = serde_json::to_value(slide).unwrap_or(Value::Null); + if let Some(elements) = value.get_mut("elements").and_then(Value::as_array_mut) { + for (element_index, element) in elements.iter_mut().enumerate() { + if let Some(object) = element.as_object_mut() { + object.insert("index".to_string(), json!(element_index)); + } + } + } + if let Some(object) = value.as_object_mut() { + object.insert("index".to_string(), json!(index)); + } + return value; + } + let text: Vec = slide + .elements + .iter() + .map(|element| element.plain_text()) + .filter(|text| !text.trim().is_empty()) + .collect(); + let mut kinds = std::collections::BTreeMap::<&str, usize>::new(); + for element in &slide.elements { + *kinds.entry(element.kind()).or_default() += 1; + } + let mut entry = json!({ + "index": index, + "label": preview(&slide.label(), 80), + "elements": slide.elements.len(), + "element_kinds": kinds, + "text": preview(&text.join(" | "), 240), + }); + if let Some(layout) = &slide.layout { + entry["layout"] = json!(layout); + } + if let Some(background) = &slide.background { + entry["background"] = json!(background); + } + if let Some(notes) = &slide.notes { + entry["notes"] = json!(preview(notes, 120)); + } + entry + }) + .collect(); + let (width, height) = deck.slide_size.canvas(); + let mut view = json!({ + "total_slides": total, + "offset": offset, + "limit": limit, + "canvas": { "width": width, "height": height, "unit": "px" }, + "slides": slides, + }); + if offset + limit < total { + view["next_offset"] = json!(offset + limit); + } + if offset == 0 { + view["settings"] = json!({ + "properties": deck.properties, + "slide_size": deck.slide_size, + "theme": deck.theme, + }); + } + view +} + +impl PptxDocument { + /// Geometry findings: elements off the canvas and text that likely + /// overflows its box. `only` limits the audit to some slides. + pub fn audit(&self, only: Option<&BTreeSet>) -> Vec { + let (canvas_w, canvas_h) = self.slide_size.canvas(); + let mut findings = Vec::new(); + for (index, slide) in self.slides.iter().enumerate() { + if only.is_some_and(|set| !set.contains(&index)) { + continue; + } + if slide.elements.is_empty() { + findings.push(format!("slide {index}: the slide has no elements")); + } + for (element_index, element) in slide.elements.iter().enumerate() { + let (x, y, w, h) = element.bounds(); + let path = format!("slide {index} element {element_index} ({})", element.kind()); + if x < -1.0 || y < -1.0 || x + w > canvas_w + 1.0 || y + h > canvas_h + 1.0 { + findings.push(format!( + "{path}: box {x:.0},{y:.0} {w:.0}×{h:.0} extends past the {canvas_w:.0}×{canvas_h:.0} canvas" + )); + } + let (paragraphs, defaults, inset) = match element { + Element::Text(text) => (&text.paragraphs, &text.defaults, 0.0), + Element::Shape(shape) => ( + &shape.paragraphs, + &shape.defaults, + shape.padding.unwrap_or(0.0), + ), + _ => continue, + }; + let available_w = (w - inset * 2.0).max(1.0); + let needed = estimate_text_height(paragraphs, defaults, available_w) + inset * 2.0; + if needed > h * 1.08 + 4.0 { + findings.push(format!( + "{path}: text needs about {needed:.0}px of height but the box is {h:.0}px; enlarge h, shorten the text, or lower size_pt" + )); + } + } + } + findings.truncate(40); + findings + } +} + +/// Rough text height in px using average glyph widths: CJK ≈ 1 em, +/// Latin ≈ 0.55 em, line height ≈ 1.2 em × line spacing. +pub(crate) fn estimate_text_height( + paragraphs: &[Paragraph], + defaults: &TextDefaults, + width: f64, +) -> f64 { + let mut height = 0.0; + for paragraph in paragraphs { + let size = paragraph + .runs + .iter() + .filter_map(|run| run.size_pt) + .fold(None, |max: Option, size| { + Some(max.map_or(size, |current| current.max(size))) + }) + .or(defaults.size_pt) + .unwrap_or(18.0); + let em = size * 96.0 / 72.0; + let spacing = paragraph.line_spacing_pct.unwrap_or(100.0) / 100.0; + let line_height = em * 1.2 * spacing; + let indent = if paragraph.bullet || paragraph.numbered { + em * 1.1 * (paragraph.level as f64 + 1.0) + } else { + 0.0 + }; + let usable = (width - indent).max(em); + let mut lines = 0.0; + for line in runs_text(¶graph.runs).split('\n') { + let line_width: f64 = line + .chars() + .map(|c| { + if c == ' ' { + 0.28 + } else if is_wide(c) { + 1.0 + } else if c.is_ascii_uppercase() || c.is_ascii_digit() { + 0.62 + } else { + 0.52 + } + }) + .sum::() + * em; + lines += (line_width / usable).ceil().max(1.0); + } + height += lines * line_height; + height += (paragraph.space_before_pt.unwrap_or(0.0) + + paragraph.space_after_pt.unwrap_or(0.0)) + * 96.0 + / 72.0; + } + height +} + +fn is_wide(c: char) -> bool { + matches!(c as u32, + 0x1100..=0x115F | 0x2E80..=0x303E | 0x3041..=0x33FF | 0x3400..=0x4DBF | 0x4E00..=0x9FFF + | 0xA000..=0xA4CF | 0xAC00..=0xD7A3 | 0xF900..=0xFAFF | 0xFE30..=0xFE4F | 0xFF00..=0xFF60 + | 0xFFE0..=0xFFE6 | 0x1F300..=0x1FAFF | 0x20000..=0x3FFFD) +} diff --git a/src/crates/execution/office-documents/src/pptx/model.rs b/src/crates/execution/office-documents/src/pptx/model.rs new file mode 100644 index 0000000000..080006315b --- /dev/null +++ b/src/crates/execution/office-documents/src/pptx/model.rs @@ -0,0 +1,767 @@ +//! Slide deck model: a fixed px canvas of absolutely positioned elements, +//! following GenOffice's page spec (`x`/`y`/`w`/`h` in px, paint order = +//! array order). + +use crate::common::{ + canonical_runs, parse_color, prefix, report_extra, report_list, runs_text, validate_runs, + Align, DocumentProperties, Extra, Run, TableCell, UnknownFields, VerticalAlign, +}; +use crate::error::{OfficeError, OfficeResult}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; + +pub const SHAPE_KINDS: &[&str] = &[ + "rect", + "roundRect", + "ellipse", + "triangle", + "rtTriangle", + "rightArrow", + "leftArrow", + "upArrow", + "downArrow", + "chevron", + "diamond", + "parallelogram", + "trapezoid", + "hexagon", + "pentagon", + "octagon", + "plus", + "pie", + "donut", + "star5", + "heart", + "cloud", + "line", + "lineArrow", +]; + +pub(crate) const MAX_ELEMENTS_PER_SLIDE: usize = 200; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +pub enum SlideSize { + #[default] + #[serde(rename = "16:9", alias = "wide", alias = "widescreen")] + Wide, + #[serde(rename = "4:3", alias = "standard")] + Standard, +} + +impl SlideSize { + /// Canvas size in px; one px is 9525 EMU in both sizes. + pub const fn canvas(self) -> (f64, f64) { + match self { + Self::Wide => (1280.0, 720.0), + Self::Standard => (960.0, 720.0), + } + } +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct DeckTheme { + /// Latin font for all text unless a run names its own. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub font: Option, + /// Font for CJK text. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub east_asia_font: Option, + /// Default text color. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text_color: Option, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct PptxDocument { + #[serde(default)] + pub properties: DocumentProperties, + #[serde(default)] + pub slide_size: SlideSize, + #[serde(default)] + pub theme: DeckTheme, + #[serde(default)] + pub slides: Vec, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Slide { + /// Planning label echoed from an outline; also the slide's name in read results. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub layout: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub background: Option, + /// Speaker notes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub notes: Option, + #[serde(default)] + pub elements: Vec, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Element { + Shape(ShapeElement), + #[serde(alias = "textbox")] + Text(TextElement), + #[serde(alias = "picture")] + Image(ImageElement), + Table(TableElement), +} + +/// Run defaults shared by text-bearing elements: a run or paragraph that +/// does not set a field inherits it from here. +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct TextDefaults { + #[serde(default, skip_serializing_if = "Option::is_none", alias = "sizePt")] + pub size_pt: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bold: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub italic: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub color: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub font: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub align: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Stroke { + pub color: String, + #[serde(default = "default_stroke_width", alias = "widthPt", alias = "width")] + pub width_pt: f64, + /// `solid` (default), `dash`, or `dot`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub dash: Option, + #[serde(flatten)] + pub extra: Extra, +} + +fn default_stroke_width() -> f64 { + 1.0 +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ShapeElement { + #[serde(default = "default_shape")] + pub shape: String, + pub x: f64, + pub y: f64, + pub w: f64, + pub h: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fill: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stroke: Option, + #[serde(default, skip_serializing)] + pub text: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub paragraphs: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub valign: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub padding: Option, + #[serde(default, skip_serializing_if = "is_false", alias = "flipH")] + pub flip_h: bool, + #[serde(default, skip_serializing_if = "is_false", alias = "flipV")] + pub flip_v: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rotation: Option, + #[serde(flatten)] + pub defaults: TextDefaults, + #[serde(flatten)] + pub extra: Extra, +} + +fn default_shape() -> String { + "rect".to_string() +} + +fn is_false(value: &bool) -> bool { + !*value +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TextElement { + pub x: f64, + pub y: f64, + pub w: f64, + pub h: f64, + #[serde(default, skip_serializing)] + pub text: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub paragraphs: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub valign: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rotation: Option, + #[serde(flatten)] + pub defaults: TextDefaults, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ImageFit { + /// Center-crop to fill the box (object-fit: cover). + #[default] + Cover, + /// Fit inside the box, keeping the whole picture. + Contain, + /// Stretch to the box, ignoring the aspect ratio. + Stretch, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ImageElement { + pub x: f64, + pub y: f64, + pub w: f64, + pub h: f64, + #[serde( + default, + skip_serializing_if = "Option::is_none", + alias = "url", + alias = "path" + )] + pub src: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub asset: Option, + #[serde(default)] + pub fit: ImageFit, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rotation: Option, + #[serde(default, skip_serializing_if = "Option::is_none", alias = "alt_text")] + pub alt: Option, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TableElement { + pub x: f64, + pub y: f64, + pub w: f64, + pub h: f64, + pub rows: Vec>, + /// Style the first row as a header. + #[serde(default = "default_true")] + pub header: bool, + /// Column widths in px; scaled to `w` when they do not add up. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub column_widths: Option>, + #[serde(default = "default_table_font_size", alias = "fontSizePt")] + pub font_size_pt: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub font: Option, + #[serde(default = "default_header_fill")] + pub header_fill: String, + #[serde(default = "default_header_color")] + pub header_color: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fill: Option, + /// Alternate row fill; empty string disables banding. + #[serde(default = "default_band_fill")] + pub band_fill: String, + #[serde(default = "default_border_color")] + pub border_color: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub text_color: Option, + #[serde(flatten)] + pub extra: Extra, +} + +fn default_true() -> bool { + true +} +fn default_table_font_size() -> f64 { + 14.0 +} +fn default_header_fill() -> String { + "#1F3864".to_string() +} +fn default_header_color() -> String { + "#FFFFFF".to_string() +} +fn default_band_fill() -> String { + "#F2F2F2".to_string() +} +fn default_border_color() -> String { + "#BFBFBF".to_string() +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +#[serde(from = "ParagraphInput")] +pub struct Paragraph { + #[serde(default)] + pub runs: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub align: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub line_spacing_pct: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub space_before_pt: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub space_after_pt: Option, + #[serde(default, skip_serializing_if = "is_false")] + pub bullet: bool, + #[serde(default, skip_serializing_if = "is_false")] + pub numbered: bool, + #[serde(default, skip_serializing_if = "is_zero")] + pub level: u8, + #[serde(flatten)] + pub extra: Extra, +} + +fn is_zero(value: &u8) -> bool { + *value == 0 +} + +#[derive(Deserialize)] +#[serde(untagged)] +enum ParagraphInput { + Text(String), + Full(ParagraphFull), +} + +#[derive(Deserialize)] +struct ParagraphFull { + #[serde(default)] + text: Option, + #[serde(default)] + runs: Vec, + #[serde(default)] + align: Option, + #[serde(default, alias = "lineSpacingPct")] + line_spacing_pct: Option, + #[serde(default, alias = "spaceBeforePt")] + space_before_pt: Option, + #[serde(default, alias = "spaceAfterPt")] + space_after_pt: Option, + #[serde(default)] + bullet: bool, + #[serde(default)] + numbered: bool, + #[serde(default)] + level: u8, + /// Run defaults at paragraph level, folded into the runs. + #[serde(default, alias = "sizePt")] + size_pt: Option, + #[serde(default)] + bold: Option, + #[serde(default)] + italic: Option, + #[serde(default)] + color: Option, + #[serde(default)] + font: Option, + #[serde(flatten)] + extra: Extra, +} + +impl From for Paragraph { + fn from(input: ParagraphInput) -> Self { + match input { + ParagraphInput::Text(text) => Paragraph { + runs: vec![Run::plain(text)], + ..Paragraph::default() + }, + ParagraphInput::Full(mut full) => { + canonical_runs(&mut full.text, &mut full.runs); + for run in &mut full.runs { + run.size_pt = run.size_pt.or(full.size_pt); + run.bold = run.bold.or(full.bold); + run.italic = run.italic.or(full.italic); + if run.color.is_none() { + run.color = full.color.clone(); + } + if run.font.is_none() { + run.font = full.font.clone(); + } + } + Paragraph { + runs: full.runs, + align: full.align, + line_spacing_pct: full.line_spacing_pct, + space_before_pt: full.space_before_pt, + space_after_pt: full.space_after_pt, + bullet: full.bullet, + numbered: full.numbered, + level: full.level, + extra: full.extra, + } + } + } + } +} + +impl Paragraph { + fn validate(&self, path: &str) -> OfficeResult<()> { + validate_runs(&self.runs, path)?; + if let Some(value) = self.line_spacing_pct { + if !(50.0..=300.0).contains(&value) { + return Err(OfficeError::invalid(format!( + "{path}.line_spacing_pct must be 50..=300" + ))); + } + } + for (name, value) in [ + ("space_before_pt", self.space_before_pt), + ("space_after_pt", self.space_after_pt), + ] { + if value.is_some_and(|value| !(0.0..=200.0).contains(&value)) { + return Err(OfficeError::invalid(format!( + "{path}.{name} must be 0..=200" + ))); + } + } + if self.level > 8 { + return Err(OfficeError::invalid(format!("{path}.level must be 0..=8"))); + } + Ok(()) + } +} + +impl UnknownFields for Paragraph { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + report_list(&self.runs, &format!("{path}.runs"), out); + } +} + +impl TextDefaults { + fn validate(&self, path: &str) -> OfficeResult<()> { + if let Some(color) = &self.color { + parse_color(color).map_err(|err| prefix(err, path, "color"))?; + } + if self + .size_pt + .is_some_and(|size| !(1.0..=400.0).contains(&size)) + { + return Err(OfficeError::invalid(format!( + "{path}.size_pt must be 1..=400" + ))); + } + Ok(()) + } +} + +fn check_geometry( + x: f64, + y: f64, + w: f64, + h: f64, + allow_flat: bool, + path: &str, +) -> OfficeResult<()> { + for (name, value) in [("x", x), ("y", y), ("w", w), ("h", h)] { + if !value.is_finite() || value.abs() > 20_000.0 { + return Err(OfficeError::invalid(format!( + "{path}.{name} must be a finite px value" + ))); + } + } + let minimum = if allow_flat { 0.0 } else { 1.0 }; + if w < minimum || h < minimum || (w <= 0.0 && h <= 0.0) { + return Err(OfficeError::invalid(format!( + "{path}: w and h must be at least {minimum} px (got {w}×{h})" + ))); + } + Ok(()) +} + +impl Element { + pub fn kind(&self) -> &'static str { + match self { + Element::Shape(_) => "shape", + Element::Text(_) => "text", + Element::Image(_) => "image", + Element::Table(_) => "table", + } + } + + pub fn bounds(&self) -> (f64, f64, f64, f64) { + match self { + Element::Shape(e) => (e.x, e.y, e.w, e.h), + Element::Text(e) => (e.x, e.y, e.w, e.h), + Element::Image(e) => (e.x, e.y, e.w, e.h), + Element::Table(e) => (e.x, e.y, e.w, e.h), + } + } + + pub fn canonicalize(&mut self) { + let shorthand = |text: &mut Option, paragraphs: &mut Vec| { + if let Some(text) = text.take() { + if paragraphs.is_empty() { + paragraphs.extend(text.split('\n').map(|line| Paragraph { + runs: vec![Run::plain(line)], + ..Paragraph::default() + })); + } + } + }; + match self { + Element::Shape(e) => shorthand(&mut e.text, &mut e.paragraphs), + Element::Text(e) => shorthand(&mut e.text, &mut e.paragraphs), + _ => {} + } + } + + pub fn plain_text(&self) -> String { + let paragraphs_text = |paragraphs: &[Paragraph]| { + paragraphs + .iter() + .map(|paragraph| runs_text(¶graph.runs)) + .collect::>() + .join("\n") + }; + match self { + Element::Shape(e) => paragraphs_text(&e.paragraphs), + Element::Text(e) => paragraphs_text(&e.paragraphs), + Element::Image(e) => e.alt.clone().unwrap_or_default(), + Element::Table(e) => e + .rows + .iter() + .map(|row| { + row.iter() + .map(TableCell::text) + .collect::>() + .join(" | ") + }) + .collect::>() + .join(" / "), + } + } + + pub fn validate(&self, path: &str) -> OfficeResult<()> { + match self { + Element::Shape(e) => { + if !SHAPE_KINDS.contains(&e.shape.as_str()) { + let hint = crate::common::did_you_mean(&e.shape, SHAPE_KINDS) + .map(|guess| format!(" Did you mean `{guess}`?")) + .unwrap_or_default(); + return Err(OfficeError::invalid(format!( + "{path}.shape `{}` is unknown.{hint} Supported: {}", + e.shape, + SHAPE_KINDS.join(", ") + ))); + } + let is_line = e.shape == "line" || e.shape == "lineArrow"; + check_geometry(e.x, e.y, e.w, e.h, is_line, path)?; + if let Some(fill) = &e.fill { + parse_color(fill).map_err(|err| prefix(err, path, "fill"))?; + } + if let Some(stroke) = &e.stroke { + parse_color(&stroke.color).map_err(|err| prefix(err, path, "stroke.color"))?; + if !(0.0..=50.0).contains(&stroke.width_pt) { + return Err(OfficeError::invalid(format!( + "{path}.stroke.width_pt must be 0..=50" + ))); + } + if let Some(dash) = &stroke.dash { + if !matches!(dash.as_str(), "solid" | "dash" | "dot") { + return Err(OfficeError::invalid(format!( + "{path}.stroke.dash must be solid, dash, or dot" + ))); + } + } + } + if is_line && e.stroke.is_none() { + return Err(OfficeError::invalid(format!( + "{path}: `{}` shapes need a `stroke`", + e.shape + ))); + } + if !is_line && e.fill.is_none() && e.stroke.is_none() && e.paragraphs.is_empty() { + return Err(OfficeError::invalid(format!( + "{path}: a shape needs a `fill`, a `stroke`, or text" + ))); + } + e.defaults.validate(path)?; + for (index, paragraph) in e.paragraphs.iter().enumerate() { + paragraph.validate(&format!("{path}.paragraphs[{index}]"))?; + } + Ok(()) + } + Element::Text(e) => { + check_geometry(e.x, e.y, e.w, e.h, false, path)?; + if e.paragraphs + .iter() + .all(|paragraph| runs_text(¶graph.runs).trim().is_empty()) + { + return Err(OfficeError::invalid(format!( + "{path}: text element has no text (use `text` or `paragraphs`)" + ))); + } + e.defaults.validate(path)?; + for (index, paragraph) in e.paragraphs.iter().enumerate() { + paragraph.validate(&format!("{path}.paragraphs[{index}]"))?; + } + Ok(()) + } + Element::Image(e) => { + check_geometry(e.x, e.y, e.w, e.h, false, path)?; + if e.src.is_none() && e.asset.is_none() { + return Err(OfficeError::invalid(format!( + "{path}: image needs `src` (an absolute file path or data URL) or the `asset` of an embedded picture" + ))); + } + Ok(()) + } + Element::Table(e) => { + check_geometry(e.x, e.y, e.w, e.h, false, path)?; + if e.rows.is_empty() || e.rows.iter().all(Vec::is_empty) { + return Err(OfficeError::invalid(format!("{path}: table has no cells"))); + } + if e.rows.len() > 60 || e.rows.iter().any(|row| row.len() > 30) { + return Err(OfficeError::limit(format!( + "{path}: slide tables are limited to 60 rows and 30 columns; split the data across slides" + ))); + } + for (row_index, row) in e.rows.iter().enumerate() { + for (cell_index, cell) in row.iter().enumerate() { + cell.validate(&format!("{path}.rows[{row_index}][{cell_index}]"))?; + } + } + for (name, color) in [ + ("header_fill", Some(&e.header_fill)), + ("header_color", Some(&e.header_color)), + ("border_color", Some(&e.border_color)), + ("fill", e.fill.as_ref()), + ("text_color", e.text_color.as_ref()), + ] { + if let Some(color) = color { + parse_color(color).map_err(|err| prefix(err, path, name))?; + } + } + if !e.band_fill.is_empty() { + parse_color(&e.band_fill).map_err(|err| prefix(err, path, "band_fill"))?; + } + if !(4.0..=96.0).contains(&e.font_size_pt) { + return Err(OfficeError::invalid(format!( + "{path}.font_size_pt must be 4..=96" + ))); + } + if let Some(widths) = &e.column_widths { + if widths + .iter() + .any(|width| !width.is_finite() || *width <= 0.0) + { + return Err(OfficeError::invalid(format!( + "{path}.column_widths must be positive px" + ))); + } + } + Ok(()) + } + } + } +} + +impl UnknownFields for Element { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + match self { + Element::Shape(e) => { + report_extra(&e.extra, path, out); + if let Some(stroke) = &e.stroke { + report_extra(&stroke.extra, &format!("{path}.stroke"), out); + } + report_list(&e.paragraphs, &format!("{path}.paragraphs"), out); + } + Element::Text(e) => { + report_extra(&e.extra, path, out); + report_list(&e.paragraphs, &format!("{path}.paragraphs"), out); + } + Element::Image(e) => report_extra(&e.extra, path, out), + Element::Table(e) => { + report_extra(&e.extra, path, out); + for (index, row) in e.rows.iter().enumerate() { + report_list(row, &format!("{path}.rows[{index}]"), out); + } + } + } + } +} + +impl Slide { + pub fn canonicalize(&mut self) { + for element in &mut self.elements { + element.canonicalize(); + } + } + + pub fn validate(&self, path: &str) -> OfficeResult<()> { + if self.elements.len() > MAX_ELEMENTS_PER_SLIDE { + return Err(OfficeError::limit(format!( + "{path}: a slide is limited to {MAX_ELEMENTS_PER_SLIDE} elements" + ))); + } + if let Some(background) = &self.background { + parse_color(background).map_err(|err| prefix(err, path, "background"))?; + } + for (index, element) in self.elements.iter().enumerate() { + element.validate(&format!("{path}.elements[{index}]"))?; + } + Ok(()) + } + + /// A short label: the planning title, else the first line of text. + pub fn label(&self) -> String { + if let Some(title) = &self.title { + return title.clone(); + } + self.elements + .iter() + .map(Element::plain_text) + .find(|text| !text.trim().is_empty()) + .map(|text| text.lines().next().unwrap_or("").to_string()) + .unwrap_or_default() + } +} + +impl UnknownFields for Slide { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + report_list(&self.elements, &format!("{path}.elements"), out); + } +} + +impl UnknownFields for PptxDocument { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + self.properties + .unknown_fields(&format!("{path}.properties"), out); + report_extra(&self.theme.extra, &format!("{path}.theme"), out); + report_list(&self.slides, &format!("{path}.slides"), out); + } +} + +impl PptxDocument { + pub fn validate_settings(&self) -> OfficeResult<()> { + if let Some(color) = &self.theme.text_color { + parse_color(color).map_err(|err| prefix(err, "theme", "text_color"))?; + } + Ok(()) + } + + pub fn referenced_assets(&self) -> BTreeSet { + self.slides + .iter() + .flat_map(|slide| slide.elements.iter()) + .filter_map(|element| match element { + Element::Image(image) => image.asset.clone(), + _ => None, + }) + .collect() + } +} diff --git a/src/crates/execution/office-documents/src/pptx/ops.rs b/src/crates/execution/office-documents/src/pptx/ops.rs new file mode 100644 index 0000000000..b7e9486572 --- /dev/null +++ b/src/crates/execution/office-documents/src/pptx/ops.rs @@ -0,0 +1,414 @@ +//! Slide deck edit operations. + +use super::model::{DeckTheme, Element, ImageFit, PptxDocument, Slide}; +use crate::common::{ + existing_span, insertion_index, move_span, parse_operation, report_extra, report_list, + unknown_operation, DocumentProperties, Extra, UnknownFields, +}; +use crate::docx::ops::patch_struct; +use crate::error::{OfficeError, OfficeResult}; +use crate::image::sniff; +use crate::ApplyContext; +use serde::Deserialize; +use serde_json::{Map, Value}; + +pub(crate) const OPERATIONS: &[&str] = &[ + "insert_slides", + "replace_slide", + "update_slide", + "delete_slides", + "move_slides", + "duplicate_slide", + "set_theme", + "set_properties", +]; + +const MAX_SLIDES: usize = 500; + +#[derive(Deserialize)] +struct InsertSlides { + #[serde(default)] + index: Option, + slides: Vec, + #[serde(flatten)] + extra: Extra, +} + +#[derive(Deserialize)] +struct ReplaceSlide { + index: usize, + slide: Slide, + #[serde(flatten)] + extra: Extra, +} + +#[derive(Deserialize)] +struct SlideSpan { + index: usize, + #[serde(default)] + count: Option, + #[serde(default)] + to: Option, + #[serde(flatten)] + extra: Extra, +} + +impl UnknownFields for InsertSlides { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + report_list(&self.slides, "slides", out); + } +} + +impl UnknownFields for ReplaceSlide { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + self.slide.unknown_fields("slide", out); + } +} + +impl UnknownFields for SlideSpan { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + } +} + +impl UnknownFields for DeckTheme { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + } +} + +pub(crate) fn apply( + deck: &mut PptxDocument, + op: &str, + value: &Value, + ctx: &mut ApplyContext, +) -> OfficeResult<()> { + match op { + "insert_slides" => { + let input: InsertSlides = parse_operation(value)?; + if input.slides.is_empty() { + return Err(OfficeError::invalid( + "`slides` must contain at least one slide", + )); + } + let at = insertion_index(input.index, deck.slides.len(), "slide")?; + if deck.slides.len() + input.slides.len() > MAX_SLIDES { + return Err(OfficeError::limit(format!( + "a deck is limited to {MAX_SLIDES} slides" + ))); + } + let mut slides = input.slides; + for (offset, slide) in slides.iter_mut().enumerate() { + prepare_slide(slide, deck, &format!("slides[{offset}]"), ctx)?; + } + let count = slides.len(); + shift_touched(ctx, at, count as i64); + deck.slides.splice(at..at, slides); + ctx.touched.extend(at..at + count); + ctx.note(format!("inserted {count} slide(s) at index {at}")); + Ok(()) + } + "replace_slide" => { + let input: ReplaceSlide = parse_operation(value)?; + existing_span(input.index, None, deck.slides.len(), "slide")?; + let mut slide = input.slide; + prepare_slide(&mut slide, deck, "slide", ctx)?; + deck.slides[input.index] = slide; + ctx.touched.insert(input.index); + ctx.note(format!("replaced slide {}", input.index)); + Ok(()) + } + "update_slide" => update_slide(deck, value, ctx), + "delete_slides" => { + let input: SlideSpan = parse_operation(value)?; + if input.to.is_some() { + return Err(OfficeError::invalid("delete_slides does not take `to`")); + } + let span = existing_span(input.index, input.count, deck.slides.len(), "slide")?; + let count = span.len(); + deck.slides.drain(span.clone()); + ctx.touched.retain(|index| !span.contains(index)); + shift_touched(ctx, span.end, -(count as i64)); + ctx.note(format!("deleted {count} slide(s) at index {}", input.index)); + Ok(()) + } + "move_slides" => { + let input: SlideSpan = parse_operation(value)?; + let to = input + .to + .ok_or_else(|| OfficeError::invalid("move_slides needs `to`"))?; + let span = existing_span(input.index, input.count, deck.slides.len(), "slide")?; + move_span(&mut deck.slides, span, to, "slide")?; + ctx.touched.clear(); + ctx.note(format!("moved slide(s) from {} to {to}", input.index)); + Ok(()) + } + "duplicate_slide" => { + let input: SlideSpan = parse_operation(value)?; + if input.count.is_some() { + return Err(OfficeError::invalid( + "duplicate_slide copies one slide; it does not take `count`", + )); + } + existing_span(input.index, None, deck.slides.len(), "slide")?; + if deck.slides.len() >= MAX_SLIDES { + return Err(OfficeError::limit(format!( + "a deck is limited to {MAX_SLIDES} slides" + ))); + } + let at = insertion_index( + Some(input.to.unwrap_or(input.index + 1)), + deck.slides.len(), + "slide", + )?; + let copy = deck.slides[input.index].clone(); + shift_touched(ctx, at, 1); + deck.slides.insert(at, copy); + ctx.note(format!("duplicated slide {} to index {at}", input.index)); + Ok(()) + } + "set_theme" => { + patch_struct::(&mut deck.theme, value)?; + deck.validate_settings()?; + ctx.note("updated the deck theme".to_string()); + Ok(()) + } + "set_properties" => { + let input: DocumentProperties = parse_operation(value)?; + deck.properties.merge(&input); + ctx.note("updated document properties".to_string()); + Ok(()) + } + other => Err(unknown_operation(other, OPERATIONS)), + } +} + +/// Keeps audit targets pointing at the same slides after a structural edit. +fn shift_touched(ctx: &mut ApplyContext, from: usize, delta: i64) { + let shifted = std::mem::take(&mut ctx.touched) + .into_iter() + .map(|index| { + if index >= from { + (index as i64 + delta).max(0) as usize + } else { + index + } + }) + .collect(); + ctx.touched = shifted; +} + +fn prepare_slide( + slide: &mut Slide, + deck: &PptxDocument, + path: &str, + ctx: &mut ApplyContext, +) -> OfficeResult<()> { + slide.canonicalize(); + slide.validate(path)?; + for (index, element) in slide.elements.iter_mut().enumerate() { + prepare_element(element, deck, &format!("{path}.elements[{index}]"), ctx)?; + } + Ok(()) +} + +fn prepare_element( + element: &mut Element, + _deck: &PptxDocument, + path: &str, + ctx: &mut ApplyContext, +) -> OfficeResult<()> { + if let Element::Image(image) = element { + let asset = ctx.resolve_image(image.src.as_deref(), image.asset.as_deref(), path)?; + image.asset = Some(asset.clone()); + if image.fit == ImageFit::Cover { + if let Some(info) = ctx.assets.get(&asset).and_then(|bytes| sniff(bytes).ok()) { + let picture = info.width as f64 / info.height as f64; + let frame = image.w / image.h.max(1.0); + let kept = (picture / frame).min(frame / picture); + if kept < 0.5 { + ctx.warn(format!( + "{path}: the {:.0}×{:.0} box shows only {:.0}% of the {}×{} picture (center crop); size the box nearer the picture's aspect ratio or use fit=contain", + image.w, + image.h, + kept * 100.0, + info.width, + info.height + )); + } + } + } + } + Ok(()) +} + +/// Partial slide edit: slide fields, element patches by index, removals, +/// and appended elements, applied in that order. +fn update_slide( + deck: &mut PptxDocument, + value: &Value, + ctx: &mut ApplyContext, +) -> OfficeResult<()> { + let object = value + .as_object() + .ok_or_else(|| OfficeError::invalid("update_slide must be an object"))?; + const KEYS: &[&str] = &[ + "op", + "index", + "title", + "layout", + "background", + "notes", + "elements", + "update_elements", + "remove_elements", + "append_elements", + ]; + for key in object.keys() { + if !KEYS.contains(&key.as_str()) { + return Err(OfficeError::invalid(format!( + "unknown field `{key}`; update_slide accepts {}", + KEYS[1..].join(", ") + ))); + } + } + let index = object + .get("index") + .and_then(Value::as_u64) + .ok_or_else(|| OfficeError::invalid("update_slide needs a numeric `index`"))? + as usize; + existing_span(index, None, deck.slides.len(), "slide")?; + if object.contains_key("elements") + && ["update_elements", "remove_elements", "append_elements"] + .iter() + .any(|key| object.contains_key(*key)) + { + return Err(OfficeError::invalid( + "`elements` replaces the whole element list; do not combine it with update/remove/append_elements", + )); + } + + let mut slide = deck.slides[index].clone(); + let set_text = + |target: &mut Option, key: &str, object: &Map| -> OfficeResult<()> { + match object.get(key) { + None => Ok(()), + Some(Value::Null) => { + *target = None; + Ok(()) + } + Some(Value::String(text)) => { + *target = (!text.is_empty()).then(|| text.clone()); + Ok(()) + } + Some(_) => Err(OfficeError::invalid(format!( + "`{key}` must be a string or null" + ))), + } + }; + set_text(&mut slide.title, "title", object)?; + set_text(&mut slide.layout, "layout", object)?; + set_text(&mut slide.background, "background", object)?; + set_text(&mut slide.notes, "notes", object)?; + + if let Some(elements) = object.get("elements") { + slide.elements = parse_elements(elements, "elements")?; + } + if let Some(patches) = object.get("update_elements") { + let patches = patches.as_array().ok_or_else(|| { + OfficeError::invalid("`update_elements` must be an array of {index, ...fields}") + })?; + for (patch_index, patch) in patches.iter().enumerate() { + let path = format!("update_elements[{patch_index}]"); + let mut patch = patch + .as_object() + .cloned() + .ok_or_else(|| OfficeError::invalid(format!("{path} must be an object")))?; + let target = patch + .remove("index") + .and_then(|value| value.as_u64()) + .ok_or_else(|| OfficeError::invalid(format!("{path} needs a numeric `index`")))? + as usize; + if target >= slide.elements.len() { + return Err(OfficeError::out_of_range(format!( + "{path}: element index {target} is out of range; the slide has {} element(s)", + slide.elements.len() + ))); + } + let mut current = serde_json::to_value(&slide.elements[target]) + .map_err(|err| OfficeError::invalid(err.to_string()))?; + crate::common::merge_patch(&mut current, &Value::Object(patch)); + let mut updated = parse_element(¤t, &path)?; + // A changed picture source must be embedded again. + if let (Element::Image(new), Element::Image(old)) = + (&mut updated, &slide.elements[target]) + { + if new.src != old.src && new.asset == old.asset { + new.asset = None; + } + } + slide.elements[target] = updated; + } + } + if let Some(remove) = object.get("remove_elements") { + let mut indexes: Vec = remove + .as_array() + .ok_or_else(|| { + OfficeError::invalid("`remove_elements` must be an array of element indexes") + })? + .iter() + .map(|value| value.as_u64().map(|index| index as usize)) + .collect::>>() + .ok_or_else(|| { + OfficeError::invalid("`remove_elements` must contain non-negative integers") + })?; + indexes.sort_unstable(); + indexes.dedup(); + if let Some(bad) = indexes.iter().find(|index| **index >= slide.elements.len()) { + return Err(OfficeError::out_of_range(format!( + "remove_elements: element index {bad} is out of range; the slide has {} element(s)", + slide.elements.len() + ))); + } + for index in indexes.into_iter().rev() { + slide.elements.remove(index); + } + } + if let Some(append) = object.get("append_elements") { + slide + .elements + .extend(parse_elements(append, "append_elements")?); + } + prepare_slide(&mut slide, deck, &format!("slides[{index}]"), ctx)?; + deck.slides[index] = slide; + ctx.touched.insert(index); + ctx.note(format!("updated slide {index}")); + Ok(()) +} + +fn parse_elements(value: &Value, path: &str) -> OfficeResult> { + let items = value + .as_array() + .ok_or_else(|| OfficeError::invalid(format!("`{path}` must be an array of elements")))?; + items + .iter() + .enumerate() + .map(|(index, item)| parse_element(item, &format!("{path}[{index}]"))) + .collect() +} + +fn parse_element(value: &Value, path: &str) -> OfficeResult { + let element: Element = serde_json::from_value(value.clone()) + .map_err(|err| OfficeError::invalid(format!("{path}: {err}")))?; + let mut unknown = Vec::new(); + element.unknown_fields(path, &mut unknown); + if !unknown.is_empty() { + return Err(OfficeError::invalid(format!( + "unknown field(s): {}", + unknown.join(", ") + ))); + } + Ok(element) +} diff --git a/src/crates/execution/office-documents/src/pptx/render.rs b/src/crates/execution/office-documents/src/pptx/render.rs new file mode 100644 index 0000000000..9b346759da --- /dev/null +++ b/src/crates/execution/office-documents/src/pptx/render.rs @@ -0,0 +1,769 @@ +//! PresentationML package writer. + +use super::model::{ + Element, ImageElement, ImageFit, Paragraph, PptxDocument, ShapeElement, Slide, SlideSize, + TableElement, TextDefaults, TextElement, +}; +use crate::common::{parse_color, Align, Run, VerticalAlign}; +use crate::error::{OfficeError, OfficeResult}; +use crate::image::{kind_of_asset, sniff}; +use crate::package::{add_common_parts, ContentTypes, Parts, Relationships}; +use crate::xml::{esc, XML_HEADER}; +use std::collections::BTreeMap; + +const NS: &str = "xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\""; +const REL_BASE: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"; +const EMU_PER_PX: f64 = 9525.0; +const EMU_PER_PT: f64 = 12700.0; +const GROUP_HEADER: &str = ""; +const CLR_MAP: &str = ""; + +fn rel(kind: &str) -> String { + format!("{REL_BASE}{kind}") +} + +fn emu(px: f64) -> i64 { + (px * EMU_PER_PX).round() as i64 +} + +pub(crate) fn render( + deck: &PptxDocument, + assets: &BTreeMap>, + created: Option<&str>, + modified: Option<&str>, +) -> OfficeResult { + let mut parts = Parts::default(); + let mut types = ContentTypes::new(); + let mut presentation_rels = Relationships::default(); + let (slide_cx, slide_cy) = slide_emu(deck.slide_size); + let has_notes = deck.slides.iter().any(|slide| { + slide + .notes + .as_deref() + .is_some_and(|notes| !notes.is_empty()) + }); + + let master_rel = presentation_rels.add(&rel("slideMaster"), "slideMasters/slideMaster1.xml"); + let mut slide_ids = String::new(); + let mut used_assets: Vec = Vec::new(); + for (index, slide) in deck.slides.iter().enumerate() { + let number = index + 1; + let id = presentation_rels.add(&rel("slide"), &format!("slides/slide{number}.xml")); + slide_ids.push_str(&format!("", 256 + index)); + let mut slide_rels = Relationships::default(); + slide_rels.add(&rel("slideLayout"), "../slideLayouts/slideLayout1.xml"); + let body = SlideWriter { + deck, + assets, + rels: &mut slide_rels, + used_assets: &mut used_assets, + image_rels: BTreeMap::new(), + link_rels: BTreeMap::new(), + next_id: 2, + } + .slide(slide)?; + if slide + .notes + .as_deref() + .is_some_and(|notes| !notes.is_empty()) + { + slide_rels.add( + &rel("notesSlide"), + &format!("../notesSlides/notesSlide{number}.xml"), + ); + let mut notes_rels = Relationships::default(); + notes_rels.add(&rel("notesMaster"), "../notesMasters/notesMaster1.xml"); + notes_rels.add(&rel("slide"), &format!("../slides/slide{number}.xml")); + parts.add_xml( + format!("ppt/notesSlides/notesSlide{number}.xml"), + notes_xml(slide.notes.as_deref().unwrap_or("")), + ); + parts.add_xml( + format!("ppt/notesSlides/_rels/notesSlide{number}.xml.rels"), + notes_rels.xml(), + ); + types.part( + &format!("ppt/notesSlides/notesSlide{number}.xml"), + "application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml", + ); + } + parts.add_xml(format!("ppt/slides/slide{number}.xml"), body); + parts.add_xml( + format!("ppt/slides/_rels/slide{number}.xml.rels"), + slide_rels.xml(), + ); + types.part( + &format!("ppt/slides/slide{number}.xml"), + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml", + ); + } + let notes_master_rel = has_notes + .then(|| presentation_rels.add(&rel("notesMaster"), "notesMasters/notesMaster1.xml")); + presentation_rels.add(&rel("presProps"), "presProps.xml"); + presentation_rels.add(&rel("viewProps"), "viewProps.xml"); + presentation_rels.add(&rel("theme"), "theme/theme1.xml"); + presentation_rels.add(&rel("tableStyles"), "tableStyles.xml"); + + let mut presentation = format!("{XML_HEADER}"); + if let Some(id) = ¬es_master_rel { + presentation.push_str(&format!( + "" + )); + } + if !slide_ids.is_empty() { + presentation.push_str(&format!("{slide_ids}")); + } + let size_type = match deck.slide_size { + SlideSize::Wide => "", + SlideSize::Standard => " type=\"screen4x3\"", + }; + presentation.push_str(&format!("")); + presentation.push_str(&format!("{}", level_styles(1800))); + + parts.add_xml("ppt/presentation.xml", presentation); + parts.add_xml("ppt/_rels/presentation.xml.rels", presentation_rels.xml()); + parts.add_xml( + "ppt/presProps.xml", + format!("{XML_HEADER}"), + ); + parts.add_xml("ppt/viewProps.xml", format!("{XML_HEADER}")); + parts.add_xml("ppt/tableStyles.xml", format!("{XML_HEADER}")); + parts.add_xml("ppt/theme/theme1.xml", theme_xml(deck)); + parts.add_xml("ppt/slideMasters/slideMaster1.xml", master_xml()); + let mut master_rels = Relationships::default(); + master_rels.add(&rel("slideLayout"), "../slideLayouts/slideLayout1.xml"); + master_rels.add(&rel("theme"), "../theme/theme1.xml"); + parts.add_xml( + "ppt/slideMasters/_rels/slideMaster1.xml.rels", + master_rels.xml(), + ); + parts.add_xml("ppt/slideLayouts/slideLayout1.xml", format!("{XML_HEADER}{GROUP_HEADER}")); + let mut layout_rels = Relationships::default(); + layout_rels.add(&rel("slideMaster"), "../slideMasters/slideMaster1.xml"); + parts.add_xml( + "ppt/slideLayouts/_rels/slideLayout1.xml.rels", + layout_rels.xml(), + ); + + types.part( + "ppt/presentation.xml", + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml", + ); + types.part( + "ppt/presProps.xml", + "application/vnd.openxmlformats-officedocument.presentationml.presProps+xml", + ); + types.part( + "ppt/viewProps.xml", + "application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml", + ); + types.part( + "ppt/tableStyles.xml", + "application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml", + ); + types.part( + "ppt/theme/theme1.xml", + "application/vnd.openxmlformats-officedocument.theme+xml", + ); + types.part( + "ppt/slideMasters/slideMaster1.xml", + "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml", + ); + types.part( + "ppt/slideLayouts/slideLayout1.xml", + "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml", + ); + + if has_notes { + parts.add_xml("ppt/notesMasters/notesMaster1.xml", notes_master_xml()); + let mut notes_master_rels = Relationships::default(); + notes_master_rels.add(&rel("theme"), "../theme/theme2.xml"); + parts.add_xml( + "ppt/notesMasters/_rels/notesMaster1.xml.rels", + notes_master_rels.xml(), + ); + parts.add_xml("ppt/theme/theme2.xml", theme_xml(deck)); + types.part( + "ppt/notesMasters/notesMaster1.xml", + "application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml", + ); + types.part( + "ppt/theme/theme2.xml", + "application/vnd.openxmlformats-officedocument.theme+xml", + ); + } + + for asset in &used_assets { + let bytes = assets + .get(asset) + .ok_or_else(|| OfficeError::corrupt(format!("embedded picture {asset} is missing")))?; + if let Some(kind) = kind_of_asset(asset) { + types.extension(kind.extension(), kind.content_type()); + } + parts.add(format!("ppt/media/{asset}"), bytes.clone()); + } + add_common_parts( + &mut parts, + &mut types, + "ppt/presentation.xml", + &deck.properties, + created, + modified, + "OpenBitFun GenOfficeFile", + ); + parts.add_xml("[Content_Types].xml", types.xml()); + Ok(parts) +} + +fn slide_emu(size: SlideSize) -> (i64, i64) { + let (width, height) = size.canvas(); + (emu(width), emu(height)) +} + +struct SlideWriter<'a> { + deck: &'a PptxDocument, + assets: &'a BTreeMap>, + rels: &'a mut Relationships, + used_assets: &'a mut Vec, + image_rels: BTreeMap, + link_rels: BTreeMap, + next_id: u32, +} + +impl SlideWriter<'_> { + fn id(&mut self) -> u32 { + let id = self.next_id; + self.next_id += 1; + id + } + + fn slide(mut self, slide: &Slide) -> OfficeResult { + let mut xml = format!("{XML_HEADER}"); + if let Some((rgb, _)) = slide + .background + .as_deref() + .and_then(|color| parse_color(color).ok()) + { + xml.push_str(&format!("")); + } + xml.push_str(&format!("{GROUP_HEADER}")); + for element in &slide.elements { + let shape = match element { + Element::Shape(shape) => self.shape(shape), + Element::Text(text) => self.text(text), + Element::Image(image) => self.image(image)?, + Element::Table(table) => self.table(table), + }; + xml.push_str(&shape); + } + xml.push_str( + "", + ); + Ok(xml) + } + + fn link(&mut self, target: &str) -> String { + if let Some(id) = self.link_rels.get(target) { + return id.clone(); + } + let id = self.rels.add_external(&rel("hyperlink"), target); + self.link_rels.insert(target.to_string(), id.clone()); + id + } + + fn shape(&mut self, shape: &ShapeElement) -> String { + let id = self.id(); + let is_line = shape.shape == "line" || shape.shape == "lineArrow"; + let preset = if is_line { + "line" + } else { + shape.shape.as_str() + }; + let mut xml = format!("", esc(&shape.shape)); + xml.push_str(&xfrm( + shape.x, + shape.y, + shape.w, + shape.h, + shape.rotation, + shape.flip_h, + shape.flip_v, + )); + xml.push_str(&format!( + "" + )); + xml.push_str(&match &shape.fill { + Some(fill) => solid_fill(fill), + None => "".to_string(), + }); + match &shape.stroke { + Some(stroke) => { + let width = (stroke.width_pt * EMU_PER_PT).round() as i64; + xml.push_str(&format!( + "{}", + solid_fill(&stroke.color) + )); + match stroke.dash.as_deref() { + Some("dash") => xml.push_str(""), + Some("dot") => xml.push_str(""), + _ => {} + } + if shape.shape == "lineArrow" { + xml.push_str(""); + } + xml.push_str(""); + } + None => xml.push_str(""), + } + xml.push_str(""); + if !shape.paragraphs.is_empty() { + let inset = shape.padding.map(emu).unwrap_or(0); + xml.push_str(&self.text_body( + &shape.paragraphs, + &shape.defaults, + shape.valign.unwrap_or(VerticalAlign::Middle), + inset, + )); + } + xml.push_str(""); + xml + } + + fn text(&mut self, text: &TextElement) -> String { + let id = self.id(); + let mut xml = format!(""); + xml.push_str(&xfrm( + text.x, + text.y, + text.w, + text.h, + text.rotation, + false, + false, + )); + xml.push_str(""); + xml.push_str(&self.text_body( + &text.paragraphs, + &text.defaults, + text.valign.unwrap_or(VerticalAlign::Top), + 0, + )); + xml.push_str(""); + xml + } + + fn text_body( + &mut self, + paragraphs: &[Paragraph], + defaults: &TextDefaults, + valign: VerticalAlign, + inset: i64, + ) -> String { + let anchor = match valign { + VerticalAlign::Top => "t", + VerticalAlign::Middle => "ctr", + VerticalAlign::Bottom => "b", + }; + let mut xml = format!( + "" + ); + for paragraph in paragraphs { + xml.push_str(&self.paragraph(paragraph, defaults)); + } + xml.push_str(""); + xml + } + + fn paragraph(&mut self, paragraph: &Paragraph, defaults: &TextDefaults) -> String { + let mut ppr = String::new(); + let align = paragraph.align.or(defaults.align); + let mut attributes = String::new(); + if let Some(align) = align { + let value = match align { + Align::Left => "l", + Align::Center => "ctr", + Align::Right => "r", + Align::Justify => "just", + }; + attributes.push_str(&format!(" algn=\"{value}\"")); + } + let size = paragraph + .runs + .iter() + .filter_map(|run| run.size_pt) + .fold(None, |max: Option, size| { + Some(max.map_or(size, |current| current.max(size))) + }) + .or(defaults.size_pt) + .unwrap_or(18.0); + if paragraph.bullet || paragraph.numbered { + let indent = emu(size * 1.333 * 1.1).max(emu(16.0)); + let margin = indent * (paragraph.level as i64 + 1); + attributes.push_str(&format!(" marL=\"{margin}\" indent=\"-{indent}\"")); + } else if paragraph.level > 0 { + attributes.push_str(&format!(" marL=\"{}\"", emu(24.0) * paragraph.level as i64)); + } + if paragraph.level > 0 { + attributes.push_str(&format!(" lvl=\"{}\"", paragraph.level.min(8))); + } + if let Some(spacing) = paragraph.line_spacing_pct { + ppr.push_str(&format!( + "", + (spacing * 1000.0).round() as i64 + )); + } + if let Some(before) = paragraph.space_before_pt { + ppr.push_str(&format!( + "", + (before * 100.0).round() as i64 + )); + } + if let Some(after) = paragraph.space_after_pt { + ppr.push_str(&format!( + "", + (after * 100.0).round() as i64 + )); + } + if paragraph.numbered { + ppr.push_str(""); + } else if paragraph.bullet { + ppr.push_str(""); + } else { + ppr.push_str(""); + } + let mut xml = format!("{ppr}"); + for run in ¶graph.runs { + for (index, line) in run.text.split('\n').enumerate() { + if index > 0 { + xml.push_str(&format!( + "{}", + self.run_properties(run, defaults, "a:rPr") + )); + } + if line.is_empty() { + continue; + } + xml.push_str(&format!( + "{}{}", + self.run_properties(run, defaults, "a:rPr"), + esc(line) + )); + } + } + let end = Run { + size_pt: Some(size), + ..Run::default() + }; + xml.push_str(&self.run_properties(&end, defaults, "a:endParaRPr")); + xml.push_str(""); + xml + } + + fn run_properties(&mut self, run: &Run, defaults: &TextDefaults, tag: &str) -> String { + let mut attributes = String::from(" lang=\"en-US\""); + if let Some(size) = run.size_pt.or(defaults.size_pt) { + attributes.push_str(&format!(" sz=\"{}\"", (size * 100.0).round() as i64)); + } + if run.bold.or(defaults.bold) == Some(true) { + attributes.push_str(" b=\"1\""); + } + if run.italic.or(defaults.italic) == Some(true) { + attributes.push_str(" i=\"1\""); + } + if run.underline == Some(true) { + attributes.push_str(" u=\"sng\""); + } + if run.strike == Some(true) { + attributes.push_str(" strike=\"sngStrike\""); + } + if run.superscript == Some(true) { + attributes.push_str(" baseline=\"30000\""); + } else if run.subscript == Some(true) { + attributes.push_str(" baseline=\"-25000\""); + } + attributes.push_str(" dirty=\"0\""); + let mut children = String::new(); + let color = run.color.as_deref().or(defaults.color.as_deref()).or(self + .deck + .theme + .text_color + .as_deref()); + if let Some(color) = color { + children.push_str(&solid_fill(color)); + } + if let Some((rgb, _)) = run + .highlight + .as_deref() + .and_then(|color| parse_color(color).ok()) + { + children.push_str(&format!( + "" + )); + } + let font = run + .font + .as_deref() + .or(defaults.font.as_deref()) + .or_else(|| (run.code == Some(true)).then_some("Consolas")); + if let Some(font) = font { + let font = esc(font); + children.push_str(&format!("")); + } + if let Some(link) = &run.link { + let id = self.link(link); + children.push_str(&format!("")); + } + if children.is_empty() { + format!("<{tag}{attributes}/>") + } else { + format!("<{tag}{attributes}>{children}") + } + } + + fn image(&mut self, image: &ImageElement) -> OfficeResult { + let asset = image + .asset + .as_deref() + .ok_or_else(|| OfficeError::corrupt("image element without an embedded picture"))?; + let bytes = self + .assets + .get(asset) + .ok_or_else(|| OfficeError::corrupt(format!("embedded picture {asset} is missing")))?; + let info = sniff(bytes)?; + let rel_id = match self.image_rels.get(asset) { + Some(id) => id.clone(), + None => { + let id = self.rels.add(&rel("image"), &format!("../media/{asset}")); + self.image_rels.insert(asset.to_string(), id.clone()); + if !self.used_assets.iter().any(|used| used == asset) { + self.used_assets.push(asset.to_string()); + } + id + } + }; + let picture = info.width as f64 / info.height as f64; + let frame = image.w / image.h.max(0.01); + let (mut x, mut y, mut w, mut h) = (image.x, image.y, image.w, image.h); + let mut crop = String::new(); + match image.fit { + ImageFit::Cover => { + if picture > frame * 1.001 { + let keep = frame / picture; + let side = ((1.0 - keep) / 2.0 * 100_000.0).round() as i64; + crop = format!(""); + } else if frame > picture * 1.001 { + let keep = picture / frame; + let side = ((1.0 - keep) / 2.0 * 100_000.0).round() as i64; + crop = format!(""); + } + } + ImageFit::Contain => { + if picture > frame { + let height = w / picture; + y += (h - height) / 2.0; + h = height; + } else { + let width = h * picture; + x += (w - width) / 2.0; + w = width; + } + } + ImageFit::Stretch => {} + } + let id = self.id(); + let descr = esc(image.alt.as_deref().unwrap_or("")); + let mut xml = format!("{crop}"); + xml.push_str(&xfrm(x, y, w, h, image.rotation, false, false)); + xml.push_str(""); + Ok(xml) + } + + fn table(&mut self, table: &TableElement) -> String { + let id = self.id(); + let columns = table.rows.iter().map(Vec::len).max().unwrap_or(1).max(1); + let widths: Vec = match &table.column_widths { + Some(widths) if !widths.is_empty() => { + let raw: Vec = (0..columns) + .map(|index| { + *widths + .get(index) + .unwrap_or_else(|| widths.last().expect("non-empty")) + }) + .collect(); + let sum: f64 = raw.iter().sum(); + raw.iter().map(|width| width * table.w / sum).collect() + } + _ => vec![table.w / columns as f64; columns], + }; + let row_height = table.h / table.rows.len().max(1) as f64; + let mut xml = format!("", + emu(table.x), emu(table.y), emu(table.w), emu(table.h), u8::from(table.header)); + for width in &widths { + xml.push_str(&format!("", emu(*width))); + } + xml.push_str(""); + let border = solid_fill(&table.border_color); + for (row_index, row) in table.rows.iter().enumerate() { + let is_header = table.header && row_index == 0; + xml.push_str(&format!("", emu(row_height))); + for column in 0..columns { + let cell = row.get(column).cloned().unwrap_or_default(); + let defaults = TextDefaults { + size_pt: Some(table.font_size_pt), + bold: cell.bold.or(is_header.then_some(true)), + italic: None, + color: cell + .color + .clone() + .or_else(|| is_header.then(|| table.header_color.clone())) + .or_else(|| table.text_color.clone()), + font: table.font.clone(), + align: cell.align, + }; + let paragraph = Paragraph { + runs: cell.runs.clone(), + ..Paragraph::default() + }; + xml.push_str(""); + xml.push_str(&self.paragraph(¶graph, &defaults)); + xml.push_str(""); + for side in ["lnL", "lnR", "lnT", "lnB"] { + xml.push_str(&format!("{border}")); + } + let body_index = if table.header { + row_index.saturating_sub(1) + } else { + row_index + }; + let fill = cell.fill.clone().or_else(|| { + if is_header { + Some(table.header_fill.clone()) + } else if !table.band_fill.is_empty() && body_index % 2 == 1 { + Some(table.band_fill.clone()) + } else { + table.fill.clone() + } + }); + xml.push_str(&match fill { + Some(fill) => solid_fill(&fill), + None => "".to_string(), + }); + xml.push_str(""); + } + xml.push_str(""); + } + xml.push_str(""); + xml + } +} + +fn xfrm( + x: f64, + y: f64, + w: f64, + h: f64, + rotation: Option, + flip_h: bool, + flip_v: bool, +) -> String { + let mut attributes = String::new(); + if let Some(rotation) = rotation.filter(|rotation| *rotation != 0.0) { + let normalized = rotation.rem_euclid(360.0); + attributes.push_str(&format!( + " rot=\"{}\"", + (normalized * 60_000.0).round() as i64 + )); + } + if flip_h { + attributes.push_str(" flipH=\"1\""); + } + if flip_v { + attributes.push_str(" flipV=\"1\""); + } + format!( + "", + emu(x), + emu(y), + emu(w).max(0), + emu(h).max(0) + ) +} + +fn solid_fill(color: &str) -> String { + match parse_color(color) { + Ok((rgb, Some(alpha))) => format!( + "", + (alpha as f64 / 255.0 * 100_000.0).round() as i64 + ), + Ok((rgb, None)) => format!(""), + Err(_) => "".to_string(), + } +} + +fn level_styles(size: u32) -> String { + (1..=9) + .map(|level| { + format!( + "", + (level - 1) * 457200 + ) + }) + .collect() +} + +fn master_xml() -> String { + format!( + "{XML_HEADER}{GROUP_HEADER}{CLR_MAP}{}{}", + level_styles(1800), + level_styles(1800) + ) +} + +fn notes_master_xml() -> String { + format!( + "{XML_HEADER}{GROUP_HEADER}{CLR_MAP}{}", + level_styles(1200) + ) +} + +fn notes_xml(notes: &str) -> String { + let paragraphs: String = notes + .split('\n') + .map(|line| { + if line.is_empty() { + "".to_string() + } else { + format!( + "{}", + esc(line) + ) + } + }) + .collect(); + format!( + "{XML_HEADER}{GROUP_HEADER}{paragraphs}" + ) +} + +fn theme_xml(deck: &PptxDocument) -> String { + let latin = esc(deck.theme.font.as_deref().unwrap_or("Calibri")); + let east_asia = esc(deck.theme.east_asia_font.as_deref().unwrap_or("")); + let dark = deck + .theme + .text_color + .as_deref() + .and_then(|color| parse_color(color).ok()) + .map(|(rgb, _)| format!("")) + .unwrap_or_else(|| "".to_string()); + let font_set = |name: &str| { + format!( + "" + ) + }; + let fill_variants = ""; + format!( + "{XML_HEADER}{dark}{}{}{fill_variants}{fill_variants}", + font_set("majorFont"), + font_set("minorFont") + ) +} diff --git a/src/crates/execution/office-documents/src/xlsx/address.rs b/src/crates/execution/office-documents/src/xlsx/address.rs new file mode 100644 index 0000000000..7b5cae3536 --- /dev/null +++ b/src/crates/execution/office-documents/src/xlsx/address.rs @@ -0,0 +1,161 @@ +//! A1-style cell addressing. + +use crate::error::{OfficeError, OfficeResult}; +use std::fmt; + +pub(crate) const MAX_ROWS: u32 = 1_048_576; +pub(crate) const MAX_COLUMNS: u32 = 16_384; + +/// One-based row and column. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct CellRef { + pub row: u32, + pub col: u32, +} + +impl CellRef { + pub fn new(row: u32, col: u32) -> Self { + Self { row, col } + } +} + +impl fmt::Display for CellRef { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "{}{}", column_letters(self.col), self.row) + } +} + +/// Inclusive rectangle. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct CellRange { + pub start: CellRef, + pub end: CellRef, +} + +impl CellRange { + pub(crate) fn contains(&self, cell: CellRef) -> bool { + (self.start.row..=self.end.row).contains(&cell.row) + && (self.start.col..=self.end.col).contains(&cell.col) + } + + pub(crate) fn intersects(&self, other: &CellRange) -> bool { + self.start.row <= other.end.row + && other.start.row <= self.end.row + && self.start.col <= other.end.col + && other.start.col <= self.end.col + } + + pub(crate) fn cell_count(&self) -> u64 { + (self.end.row - self.start.row + 1) as u64 * (self.end.col - self.start.col + 1) as u64 + } + + pub(crate) fn is_single(&self) -> bool { + self.start == self.end + } +} + +impl fmt::Display for CellRange { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.is_single() { + write!(formatter, "{}", self.start) + } else { + write!(formatter, "{}:{}", self.start, self.end) + } + } +} + +pub(crate) fn column_letters(mut col: u32) -> String { + let mut letters = Vec::new(); + while col > 0 { + let remainder = ((col - 1) % 26) as u8; + letters.push((b'A' + remainder) as char); + col = (col - 1) / 26; + } + letters.iter().rev().collect() +} + +pub(crate) fn column_number(letters: &str) -> Option { + if letters.is_empty() || letters.len() > 3 || !letters.chars().all(|c| c.is_ascii_alphabetic()) + { + return None; + } + let mut value: u32 = 0; + for character in letters.chars() { + value = value * 26 + (character.to_ascii_uppercase() as u32 - 'A' as u32 + 1); + } + (value <= MAX_COLUMNS).then_some(value) +} + +pub(crate) fn parse_column(input: &str) -> OfficeResult { + column_number(input.trim().trim_start_matches('$')).ok_or_else(|| { + OfficeError::invalid(format!( + "invalid column `{input}`; use letters such as A or AB" + )) + }) +} + +pub(crate) fn parse_cell(input: &str) -> OfficeResult { + let cleaned: String = input.trim().chars().filter(|c| *c != '$').collect(); + let split = cleaned + .find(|c: char| c.is_ascii_digit()) + .ok_or_else(|| invalid_cell(input))?; + let (letters, digits) = cleaned.split_at(split); + let col = column_number(letters).ok_or_else(|| invalid_cell(input))?; + let row: u32 = digits.parse().map_err(|_| invalid_cell(input))?; + if row == 0 || row > MAX_ROWS { + return Err(OfficeError::out_of_range(format!( + "row {row} in `{input}` is outside 1..={MAX_ROWS}" + ))); + } + Ok(CellRef { row, col }) +} + +fn invalid_cell(input: &str) -> OfficeError { + OfficeError::invalid(format!( + "invalid cell address `{input}`; use A1 style such as B3" + )) +} + +/// Parses `A1` or `A1:C9` (either corner order). +pub(crate) fn parse_range(input: &str) -> OfficeResult { + let (first, second) = match input.split_once(':') { + Some((a, b)) => (parse_cell(a)?, parse_cell(b)?), + None => { + let cell = parse_cell(input)?; + (cell, cell) + } + }; + Ok(CellRange { + start: CellRef::new(first.row.min(second.row), first.col.min(second.col)), + end: CellRef::new(first.row.max(second.row), first.col.max(second.col)), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn converts_columns_both_ways() { + for (number, letters) in [ + (1, "A"), + (26, "Z"), + (27, "AA"), + (702, "ZZ"), + (703, "AAA"), + (16384, "XFD"), + ] { + assert_eq!(column_letters(number), letters); + assert_eq!(column_number(letters), Some(number)); + } + assert_eq!(column_number("XFE"), None); + } + + #[test] + fn parses_ranges_in_any_corner_order() { + let range = parse_range("$C$5:A1").unwrap(); + assert_eq!(range.to_string(), "A1:C5"); + assert!(parse_cell("A0").is_err()); + assert!(parse_cell("1A").is_err()); + } +} diff --git a/src/crates/execution/office-documents/src/xlsx/eval.rs b/src/crates/execution/office-documents/src/xlsx/eval.rs new file mode 100644 index 0000000000..95750deeb8 --- /dev/null +++ b/src/crates/execution/office-documents/src/xlsx/eval.rs @@ -0,0 +1,960 @@ +//! Small formula evaluator that fills cached results (``) so viewers that +//! do not recalculate (previewers, text extractors, the agent's own Read) +//! see values. Anything outside the supported subset is left uncached and +//! the spreadsheet application computes it on open (`fullCalcOnLoad`). + +use super::address::{column_number, CellRef, MAX_ROWS}; +use super::model::XlsxDocument; +use serde_json::Value; +use std::collections::{HashMap, HashSet}; + +const MAX_RANGE_CELLS: u64 = 1_000_000; +const MAX_DEPTH: usize = 256; + +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Computed { + Number(f64), + Text(String), + Bool(bool), + Error(&'static str), + Empty, +} + +/// The formula cannot be evaluated locally. +#[derive(Debug)] +struct Unsupported; + +type EvalResult = Result; + +#[derive(Debug, Clone)] +enum Expr { + Number(f64), + Text(String), + Bool(bool), + Error(&'static str), + Cell(Option, CellRef), + Range(Option, CellRef, CellRef), + Negate(Box), + Percent(Box), + Binary(char, Box, Box), + Compare(&'static str, Box, Box), + Call(String, Vec), +} + +#[derive(Debug, Clone, PartialEq)] +enum Token { + Number(f64), + Text(String), + Ident(String), + Ref(Option, CellRef), + Error(&'static str), + Op(&'static str), +} + +const ERRORS: &[&str] = &[ + "#DIV/0!", "#N/A", "#NAME?", "#NULL!", "#NUM!", "#REF!", "#VALUE!", +]; + +fn tokenize(formula: &str) -> EvalResult> { + let chars: Vec = formula.chars().collect(); + let mut tokens = Vec::new(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + if c.is_whitespace() { + i += 1; + continue; + } + if c == '"' { + let mut text = String::new(); + i += 1; + loop { + match chars.get(i) { + Some('"') if chars.get(i + 1) == Some(&'"') => { + text.push('"'); + i += 2; + } + Some('"') => { + i += 1; + break; + } + Some(other) => { + text.push(*other); + i += 1; + } + None => return Err(Unsupported), + } + } + tokens.push(Token::Text(text)); + continue; + } + if c == '#' { + let rest: String = chars[i..].iter().collect(); + let error = ERRORS + .iter() + .find(|error| rest.starts_with(**error)) + .ok_or(Unsupported)?; + tokens.push(Token::Error(error)); + i += error.chars().count(); + continue; + } + if c.is_ascii_digit() || (c == '.' && chars.get(i + 1).is_some_and(char::is_ascii_digit)) { + let start = i; + while i < chars.len() && (chars[i].is_ascii_digit() || chars[i] == '.') { + i += 1; + } + if i < chars.len() && (chars[i] == 'e' || chars[i] == 'E') { + let mut j = i + 1; + if j < chars.len() && (chars[j] == '+' || chars[j] == '-') { + j += 1; + } + if j < chars.len() && chars[j].is_ascii_digit() { + i = j; + while i < chars.len() && chars[i].is_ascii_digit() { + i += 1; + } + } + } + let text: String = chars[start..i].iter().collect(); + tokens.push(Token::Number(text.parse().map_err(|_| Unsupported)?)); + continue; + } + if c == '\'' || c == '$' || c.is_alphabetic() || c == '_' { + let (token, next) = lex_name_or_ref(&chars, i)?; + tokens.push(token); + i = next; + continue; + } + let two: String = chars[i..(i + 2).min(chars.len())].iter().collect(); + let op = match two.as_str() { + "<>" => Some("<>"), + "<=" => Some("<="), + ">=" => Some(">="), + _ => None, + }; + if let Some(op) = op { + tokens.push(Token::Op(op)); + i += 2; + continue; + } + let op = match c { + '+' => "+", + '-' => "-", + '*' => "*", + '/' => "/", + '^' => "^", + '&' => "&", + '=' => "=", + '<' => "<", + '>' => ">", + '%' => "%", + ',' => ",", + '(' => "(", + ')' => ")", + ':' => ":", + _ => return Err(Unsupported), + }; + tokens.push(Token::Op(op)); + i += 1; + } + Ok(tokens) +} + +fn lex_name_or_ref(chars: &[char], start: usize) -> EvalResult<(Token, usize)> { + let mut i = start; + let mut sheet = None; + if chars[i] == '\'' { + let mut name = String::new(); + i += 1; + loop { + match chars.get(i) { + Some('\'') if chars.get(i + 1) == Some(&'\'') => { + name.push('\''); + i += 2; + } + Some('\'') => { + i += 1; + break; + } + Some(c) => { + name.push(*c); + i += 1; + } + None => return Err(Unsupported), + } + } + if chars.get(i) != Some(&'!') { + return Err(Unsupported); + } + sheet = Some(name); + i += 1; + } else { + let mut j = i; + while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_' || chars[j] == '.') + { + j += 1; + } + if j > i && chars.get(j) == Some(&'!') { + sheet = Some(chars[i..j].iter().collect()); + i = j + 1; + } + } + if let Some((cell, next)) = lex_cell(chars, i) { + let followed_by_name = chars + .get(next) + .is_some_and(|c| c.is_alphanumeric() || *c == '_' || *c == '('); + if !followed_by_name { + return Ok((Token::Ref(sheet, cell), next)); + } + } + if sheet.is_some() { + // Whole-row/column ranges and names on other sheets are out of scope. + return Err(Unsupported); + } + let mut j = i; + while j < chars.len() && (chars[j].is_alphanumeric() || chars[j] == '_' || chars[j] == '.') { + j += 1; + } + if j == i { + return Err(Unsupported); + } + Ok(( + Token::Ident(chars[i..j].iter().collect::().to_ascii_uppercase()), + j, + )) +} + +fn lex_cell(chars: &[char], start: usize) -> Option<(CellRef, usize)> { + let mut i = start; + if chars.get(i) == Some(&'$') { + i += 1; + } + let letters_start = i; + while i < chars.len() && chars[i].is_ascii_alphabetic() && i - letters_start < 3 { + i += 1; + } + let col = column_number(&chars[letters_start..i].iter().collect::())?; + if chars.get(i) == Some(&'$') { + i += 1; + } + let digits_start = i; + while i < chars.len() && chars[i].is_ascii_digit() { + i += 1; + } + let row: u32 = chars[digits_start..i] + .iter() + .collect::() + .parse() + .ok()?; + (1..=MAX_ROWS) + .contains(&row) + .then_some((CellRef::new(row, col), i)) +} + +struct Parser { + tokens: Vec, + position: usize, +} + +impl Parser { + fn peek(&self) -> Option<&Token> { + self.tokens.get(self.position) + } + + fn eat(&mut self, op: &str) -> bool { + if self.peek() + == Some(&Token::Op(match op { + "(" => "(", + ")" => ")", + "," => ",", + ":" => ":", + "%" => "%", + _ => return false, + })) + { + self.position += 1; + return true; + } + false + } + + fn peek_op(&self) -> Option<&'static str> { + match self.peek() { + Some(Token::Op(op)) => Some(op), + _ => None, + } + } + + fn comparison(&mut self) -> EvalResult { + let mut left = self.concat()?; + while let Some(op @ ("=" | "<>" | "<" | ">" | "<=" | ">=")) = self.peek_op() { + self.position += 1; + let right = self.concat()?; + left = Expr::Compare(op, Box::new(left), Box::new(right)); + } + Ok(left) + } + + fn concat(&mut self) -> EvalResult { + let mut left = self.additive()?; + while self.peek_op() == Some("&") { + self.position += 1; + left = Expr::Binary('&', Box::new(left), Box::new(self.additive()?)); + } + Ok(left) + } + + fn additive(&mut self) -> EvalResult { + let mut left = self.multiplicative()?; + while let Some(op @ ("+" | "-")) = self.peek_op() { + self.position += 1; + let right = self.multiplicative()?; + left = Expr::Binary( + op.chars().next().unwrap_or('+'), + Box::new(left), + Box::new(right), + ); + } + Ok(left) + } + + fn multiplicative(&mut self) -> EvalResult { + let mut left = self.power()?; + while let Some(op @ ("*" | "/")) = self.peek_op() { + self.position += 1; + let right = self.power()?; + left = Expr::Binary( + op.chars().next().unwrap_or('*'), + Box::new(left), + Box::new(right), + ); + } + Ok(left) + } + + fn power(&mut self) -> EvalResult { + let mut left = self.unary()?; + while self.peek_op() == Some("^") { + self.position += 1; + left = Expr::Binary('^', Box::new(left), Box::new(self.unary()?)); + } + Ok(left) + } + + fn unary(&mut self) -> EvalResult { + match self.peek_op() { + Some("-") => { + self.position += 1; + Ok(Expr::Negate(Box::new(self.unary()?))) + } + Some("+") => { + self.position += 1; + self.unary() + } + _ => { + let mut expr = self.primary()?; + while self.eat("%") { + expr = Expr::Percent(Box::new(expr)); + } + Ok(expr) + } + } + } + + fn primary(&mut self) -> EvalResult { + let token = self.peek().cloned().ok_or(Unsupported)?; + self.position += 1; + match token { + Token::Number(value) => Ok(Expr::Number(value)), + Token::Text(text) => Ok(Expr::Text(text)), + Token::Error(error) => Ok(Expr::Error(error)), + Token::Ref(sheet, cell) => { + if self.eat(":") { + match self.peek().cloned() { + Some(Token::Ref(None, end)) => { + self.position += 1; + Ok(Expr::Range(sheet, cell, end)) + } + _ => Err(Unsupported), + } + } else { + Ok(Expr::Cell(sheet, cell)) + } + } + Token::Ident(name) => { + if self.eat("(") { + let mut args = Vec::new(); + if !self.eat(")") { + loop { + args.push(self.comparison()?); + if self.eat(",") { + continue; + } + if self.eat(")") { + break; + } + return Err(Unsupported); + } + } + Ok(Expr::Call( + name.trim_start_matches("_XLFN.").to_string(), + args, + )) + } else { + match name.as_str() { + "TRUE" => Ok(Expr::Bool(true)), + "FALSE" => Ok(Expr::Bool(false)), + _ => Err(Unsupported), + } + } + } + Token::Op("(") => { + let inner = self.comparison()?; + if !self.eat(")") { + return Err(Unsupported); + } + Ok(inner) + } + Token::Op(_) => Err(Unsupported), + } + } +} + +fn parse(formula: &str) -> EvalResult { + let mut parser = Parser { + tokens: tokenize(formula)?, + position: 0, + }; + let expr = parser.comparison()?; + if parser.position != parser.tokens.len() { + return Err(Unsupported); + } + Ok(expr) +} + +/// Computed results of every formula the evaluator understands, keyed by +/// sheet index and cell. +pub(crate) fn evaluate_workbook(book: &XlsxDocument) -> HashMap<(usize, CellRef), Computed> { + let mut evaluator = Evaluator { + book, + memo: HashMap::new(), + visiting: HashSet::new(), + depth: 0, + }; + for (sheet_index, sheet) in book.sheets.iter().enumerate() { + for (cell, value) in &sheet.cells { + if value.formula.is_some() { + let _ = evaluator.cell(sheet_index, *cell); + } + } + } + evaluator + .memo + .into_iter() + .filter_map(|(key, value)| value.map(|value| (key, value))) + .collect() +} + +struct Evaluator<'a> { + book: &'a XlsxDocument, + memo: HashMap<(usize, CellRef), Option>, + visiting: HashSet<(usize, CellRef)>, + depth: usize, +} + +impl Evaluator<'_> { + fn sheet_index(&self, current: usize, name: &Option) -> Option { + match name { + None => Some(current), + Some(name) => self.book.sheet_index(name), + } + } + + fn cell(&mut self, sheet: usize, cell: CellRef) -> EvalResult { + let Some(stored) = self.book.sheets[sheet].cells.get(&cell) else { + return Ok(Computed::Empty); + }; + let Some(formula) = &stored.formula else { + return Ok(match &stored.value { + Value::Number(number) => Computed::Number(number.as_f64().unwrap_or(0.0)), + Value::String(text) => Computed::Text(text.clone()), + Value::Bool(value) => Computed::Bool(*value), + _ => Computed::Empty, + }); + }; + let key = (sheet, cell); + if let Some(known) = self.memo.get(&key) { + return known.clone().ok_or(Unsupported); + } + if !self.visiting.insert(key) || self.depth > MAX_DEPTH { + return Err(Unsupported); + } + self.depth += 1; + let result = parse(formula).and_then(|expr| self.scalar(sheet, &expr)); + self.depth -= 1; + self.visiting.remove(&key); + let stored = result.as_ref().ok().cloned(); + self.memo.insert(key, stored); + result + } + + /// Values of a reference or range argument, row-major. + fn values(&mut self, sheet: usize, expr: &Expr) -> EvalResult> { + match expr { + Expr::Range(name, start, end) => { + let Some(target) = self.sheet_index(sheet, name) else { + return Ok(vec![Computed::Error("#REF!")]); + }; + let (top, bottom) = (start.row.min(end.row), start.row.max(end.row)); + let (left, right) = (start.col.min(end.col), start.col.max(end.col)); + if (bottom - top + 1) as u64 * (right - left + 1) as u64 > MAX_RANGE_CELLS { + return Err(Unsupported); + } + // Visit only stored cells: empty cells contribute nothing. + let cells: Vec = self.book.sheets[target] + .cells + .range(CellRef::new(top, 0)..=CellRef::new(bottom, u32::MAX)) + .map(|(cell, _)| *cell) + .filter(|cell| (left..=right).contains(&cell.col)) + .collect(); + cells + .into_iter() + .map(|cell| self.cell(target, cell)) + .collect() + } + other => Ok(vec![self.scalar(sheet, other)?]), + } + } + + fn scalar(&mut self, sheet: usize, expr: &Expr) -> EvalResult { + Ok(match expr { + Expr::Number(value) => Computed::Number(*value), + Expr::Text(text) => Computed::Text(text.clone()), + Expr::Bool(value) => Computed::Bool(*value), + Expr::Error(error) => Computed::Error(error), + Expr::Cell(name, cell) => match self.sheet_index(sheet, name) { + Some(target) => self.cell(target, *cell)?, + None => Computed::Error("#REF!"), + }, + Expr::Range(_, start, end) if start == end => { + let values = self.values(sheet, expr)?; + values.into_iter().next().unwrap_or(Computed::Empty) + } + Expr::Range(..) => return Err(Unsupported), + Expr::Negate(inner) => match number(self.scalar(sheet, inner)?) { + Ok(value) => Computed::Number(-value), + Err(error) => error, + }, + Expr::Percent(inner) => match number(self.scalar(sheet, inner)?) { + Ok(value) => Computed::Number(value / 100.0), + Err(error) => error, + }, + Expr::Binary('&', left, right) => { + let left = self.scalar(sheet, left)?; + let right = self.scalar(sheet, right)?; + if let Computed::Error(error) = left { + return Ok(Computed::Error(error)); + } + if let Computed::Error(error) = right { + return Ok(Computed::Error(error)); + } + Computed::Text(format!("{}{}", text(&left), text(&right))) + } + Expr::Binary(op, left, right) => { + let left = number(self.scalar(sheet, left)?); + let right = number(self.scalar(sheet, right)?); + match (left, right) { + (Err(error), _) | (_, Err(error)) => error, + (Ok(a), Ok(b)) => match op { + '+' => finite(a + b), + '-' => finite(a - b), + '*' => finite(a * b), + '/' if b == 0.0 => Computed::Error("#DIV/0!"), + '/' => finite(a / b), + '^' => finite(a.powf(b)), + _ => return Err(Unsupported), + }, + } + } + Expr::Compare(op, left, right) => { + let left = self.scalar(sheet, left)?; + let right = self.scalar(sheet, right)?; + if let Computed::Error(error) = left { + return Ok(Computed::Error(error)); + } + if let Computed::Error(error) = right { + return Ok(Computed::Error(error)); + } + let ordering = compare(&left, &right); + Computed::Bool(match *op { + "=" => ordering == std::cmp::Ordering::Equal, + "<>" => ordering != std::cmp::Ordering::Equal, + "<" => ordering == std::cmp::Ordering::Less, + ">" => ordering == std::cmp::Ordering::Greater, + "<=" => ordering != std::cmp::Ordering::Greater, + _ => ordering != std::cmp::Ordering::Less, + }) + } + Expr::Call(name, args) => self.call(sheet, name, args)?, + }) + } + + /// Numbers from arguments: ranges contribute only their numeric cells, + /// direct arguments are coerced. + fn numbers(&mut self, sheet: usize, args: &[Expr]) -> EvalResult, Computed>> { + let mut out = Vec::new(); + for arg in args { + let is_range = matches!(arg, Expr::Range(..)); + for value in self.values(sheet, arg)? { + match value { + Computed::Error(error) => return Ok(Err(Computed::Error(error))), + Computed::Number(number) => out.push(number), + other if !is_range => match number(other) { + Ok(number) => out.push(number), + Err(error) => return Ok(Err(error)), + }, + _ => {} + } + } + } + Ok(Ok(out)) + } + + fn call(&mut self, sheet: usize, name: &str, args: &[Expr]) -> EvalResult { + let arity = |min: usize, max: usize| -> EvalResult<()> { + if args.len() < min || args.len() > max { + Err(Unsupported) + } else { + Ok(()) + } + }; + Ok(match name { + "SUM" | "AVERAGE" | "MIN" | "MAX" | "COUNT" | "PRODUCT" => { + if name == "COUNT" { + let mut count = 0usize; + for arg in args { + count += self + .values(sheet, arg)? + .iter() + .filter(|value| matches!(value, Computed::Number(_))) + .count(); + } + return Ok(Computed::Number(count as f64)); + } + let values = match self.numbers(sheet, args)? { + Ok(values) => values, + Err(error) => return Ok(error), + }; + match name { + "SUM" => finite(values.iter().sum()), + "PRODUCT" => finite(values.iter().product()), + "AVERAGE" if values.is_empty() => Computed::Error("#DIV/0!"), + "AVERAGE" => finite(values.iter().sum::() / values.len() as f64), + _ if values.is_empty() => Computed::Number(0.0), + "MIN" => Computed::Number(values.iter().copied().fold(f64::INFINITY, f64::min)), + _ => Computed::Number(values.iter().copied().fold(f64::NEG_INFINITY, f64::max)), + } + } + "COUNTA" => { + let mut count = 0usize; + for arg in args { + count += self + .values(sheet, arg)? + .iter() + .filter(|value| !matches!(value, Computed::Empty)) + .count(); + } + Computed::Number(count as f64) + } + "ROUND" | "ROUNDUP" | "ROUNDDOWN" => { + arity(1, 2)?; + let value = number(self.scalar(sheet, &args[0])?); + let digits = match args.get(1) { + Some(arg) => number(self.scalar(sheet, arg)?), + None => Ok(0.0), + }; + match (value, digits) { + (Err(error), _) | (_, Err(error)) => error, + (Ok(value), Ok(digits)) => { + let factor = 10f64.powi(digits.trunc() as i32); + // Strip binary noise first so 2.345 rounds like Excel (to 2.35). + let scaled: f64 = format!("{:.9}", value * factor) + .parse() + .unwrap_or(value * factor); + let rounded = match name { + "ROUND" => scaled.abs().round().copysign(scaled), + "ROUNDUP" => scaled.abs().ceil().copysign(scaled), + _ => scaled.trunc(), + }; + finite(rounded / factor) + } + } + } + "ABS" => { + arity(1, 1)?; + match number(self.scalar(sheet, &args[0])?) { + Ok(value) => Computed::Number(value.abs()), + Err(error) => error, + } + } + "IF" => { + arity(2, 3)?; + match truthy(self.scalar(sheet, &args[0])?) { + Err(error) => error, + Ok(true) => self.scalar(sheet, &args[1])?, + Ok(false) => match args.get(2) { + Some(arg) => self.scalar(sheet, arg)?, + None => Computed::Bool(false), + }, + } + } + "IFERROR" => { + arity(2, 2)?; + match self.scalar(sheet, &args[0])? { + Computed::Error(_) => self.scalar(sheet, &args[1])?, + value => value, + } + } + "AND" | "OR" => { + let mut results = Vec::new(); + for arg in args { + for value in self.values(sheet, arg)? { + if matches!(value, Computed::Empty | Computed::Text(_)) + && matches!(arg, Expr::Range(..)) + { + continue; + } + match truthy(value) { + Ok(flag) => results.push(flag), + Err(error) => return Ok(error), + } + } + } + if results.is_empty() { + Computed::Error("#VALUE!") + } else if name == "AND" { + Computed::Bool(results.iter().all(|flag| *flag)) + } else { + Computed::Bool(results.iter().any(|flag| *flag)) + } + } + "NOT" => { + arity(1, 1)?; + match truthy(self.scalar(sheet, &args[0])?) { + Ok(flag) => Computed::Bool(!flag), + Err(error) => error, + } + } + "CONCATENATE" | "CONCAT" => { + let mut out = String::new(); + for arg in args { + for value in self.values(sheet, arg)? { + if let Computed::Error(error) = value { + return Ok(Computed::Error(error)); + } + out.push_str(&text(&value)); + } + } + Computed::Text(out) + } + "LEN" | "UPPER" | "LOWER" | "TRIM" => { + arity(1, 1)?; + let value = self.scalar(sheet, &args[0])?; + if let Computed::Error(error) = value { + return Ok(Computed::Error(error)); + } + let value = text(&value); + match name { + "LEN" => Computed::Number(value.chars().count() as f64), + "UPPER" => Computed::Text(value.to_uppercase()), + "LOWER" => Computed::Text(value.to_lowercase()), + _ => Computed::Text(value.split_whitespace().collect::>().join(" ")), + } + } + _ => return Err(Unsupported), + }) + } +} + +fn finite(value: f64) -> Computed { + if value.is_finite() { + Computed::Number(value) + } else { + Computed::Error("#NUM!") + } +} + +fn number(value: Computed) -> Result { + match value { + Computed::Number(value) => Ok(value), + Computed::Bool(value) => Ok(if value { 1.0 } else { 0.0 }), + Computed::Empty => Ok(0.0), + Computed::Text(text) if text.trim().is_empty() => Err(Computed::Error("#VALUE!")), + Computed::Text(text) => text.trim().parse().map_err(|_| Computed::Error("#VALUE!")), + Computed::Error(error) => Err(Computed::Error(error)), + } +} + +fn truthy(value: Computed) -> Result { + match value { + Computed::Bool(value) => Ok(value), + Computed::Number(value) => Ok(value != 0.0), + Computed::Empty => Ok(false), + Computed::Text(text) => match text.to_ascii_uppercase().as_str() { + "TRUE" => Ok(true), + "FALSE" => Ok(false), + _ => Err(Computed::Error("#VALUE!")), + }, + Computed::Error(error) => Err(Computed::Error(error)), + } +} + +/// Excel's general-format rendering of a value used as text. +pub(crate) fn text(value: &Computed) -> String { + match value { + Computed::Number(value) => format_number(*value), + Computed::Text(text) => text.clone(), + Computed::Bool(value) => if *value { "TRUE" } else { "FALSE" }.to_string(), + Computed::Error(error) => (*error).to_string(), + Computed::Empty => String::new(), + } +} + +pub(crate) fn format_number(value: f64) -> String { + // Round to 15 significant digits without trimming integer zeroes or + // rounding small nonzero values to zero with fixed decimal precision. + format!("{value:.14e}") + .parse::() + .unwrap_or(value) + .to_string() +} + +fn compare(left: &Computed, right: &Computed) -> std::cmp::Ordering { + use std::cmp::Ordering; + let rank = |value: &Computed| match value { + Computed::Number(_) | Computed::Empty => 0, + Computed::Text(_) => 1, + Computed::Bool(_) => 2, + Computed::Error(_) => 3, + }; + match (left, right) { + (Computed::Text(a), Computed::Text(b)) => a.to_lowercase().cmp(&b.to_lowercase()), + (Computed::Text(a), Computed::Empty) => { + if a.is_empty() { + Ordering::Equal + } else { + Ordering::Greater + } + } + (Computed::Empty, Computed::Text(b)) => { + if b.is_empty() { + Ordering::Equal + } else { + Ordering::Less + } + } + (Computed::Bool(a), Computed::Bool(b)) => a.cmp(b), + _ if rank(left) == 0 && rank(right) == 0 => { + let a = number(left.clone()).unwrap_or(0.0); + let b = number(right.clone()).unwrap_or(0.0); + a.partial_cmp(&b).unwrap_or(Ordering::Equal) + } + _ => rank(left).cmp(&rank(right)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::xlsx::model::{Cell, Sheet}; + use serde_json::json; + + fn book(cells: &[(&str, Value)]) -> XlsxDocument { + let mut sheet = Sheet { + name: "Data".to_string(), + ..Sheet::default() + }; + for (address, value) in cells { + let cell = crate::xlsx::address::parse_cell(address).unwrap(); + let entry = match value { + Value::String(text) if text.starts_with('=') => Cell { + formula: Some(text[1..].to_string()), + ..Cell::default() + }, + other => Cell { + value: other.clone(), + ..Cell::default() + }, + }; + sheet.cells.insert(cell, entry); + } + XlsxDocument { + sheets: vec![ + sheet, + Sheet { + name: "Other Sheet".to_string(), + ..Sheet::default() + }, + ], + ..XlsxDocument::default() + } + } + + fn eval(cells: &[(&str, Value)], target: &str) -> Option { + let book = book(cells); + let cell = crate::xlsx::address::parse_cell(target).unwrap(); + evaluate_workbook(&book).get(&(0, cell)).cloned() + } + + #[test] + fn evaluates_arithmetic_functions_and_references() { + let cells = [ + ("A1", json!(2)), + ("A2", json!(3.5)), + ("A3", json!("x")), + ("B1", json!("=A1*A2+10%")), + ("B2", json!("=SUM(A1:A3)")), + ("B3", json!("=AVERAGE(A1:A2)")), + ("B4", json!("=IF(B2>5,\"big\",\"small\")&\"!\"")), + ("B5", json!("=A1/0")), + ("B6", json!("=IFERROR(B5,0)")), + ("B7", json!("=ROUND(2.345,2)")), + ("B8", json!("=-2^2")), + ("B9", json!("=COUNT(A1:A3)+COUNTA(A1:A3)")), + ("C1", json!("=FILTER(A1:A3,A1:A3>0)")), + ("C2", json!("=C3")), + ("C3", json!("=C2")), + ("C4", json!("='Other Sheet'!A1+1")), + ]; + assert_eq!(eval(&cells, "B1"), Some(Computed::Number(7.1))); + assert_eq!(eval(&cells, "B2"), Some(Computed::Number(5.5))); + assert_eq!(eval(&cells, "B3"), Some(Computed::Number(2.75))); + assert_eq!(eval(&cells, "B4"), Some(Computed::Text("big!".to_string()))); + assert_eq!(eval(&cells, "B5"), Some(Computed::Error("#DIV/0!"))); + assert_eq!(eval(&cells, "B6"), Some(Computed::Number(0.0))); + assert_eq!(eval(&cells, "B7"), Some(Computed::Number(2.35))); + assert_eq!(eval(&cells, "B8"), Some(Computed::Number(4.0))); + assert_eq!(eval(&cells, "B9"), Some(Computed::Number(5.0))); + assert_eq!( + eval(&cells, "C1"), + None, + "unsupported functions stay uncached" + ); + assert_eq!(eval(&cells, "C2"), None, "cycles stay uncached"); + assert_eq!(eval(&cells, "C4"), Some(Computed::Number(1.0))); + } + + #[test] + fn formats_numbers_like_general_format() { + assert_eq!(format_number(3.0), "3"); + assert_eq!(format_number(0.1 + 0.2), "0.3"); + assert_eq!(format_number(-2.5), "-2.5"); + for value in [1e15, -1e15, 1.2e20, 1e-20, -1.23456789e-12] { + assert_eq!(format_number(value).parse::().unwrap(), value); + } + assert_eq!( + eval(&[("A1", json!("=1000000000000000&\" units\""))], "A1"), + Some(Computed::Text("1000000000000000 units".to_string())) + ); + } +} diff --git a/src/crates/execution/office-documents/src/xlsx/formula.rs b/src/crates/execution/office-documents/src/xlsx/formula.rs new file mode 100644 index 0000000000..a0aef4c1e4 --- /dev/null +++ b/src/crates/execution/office-documents/src/xlsx/formula.rs @@ -0,0 +1,488 @@ +//! Reference rewriting in formulas when rows/columns move or sheets are renamed. +//! +//! The scanner understands string literals, quoted and bare sheet prefixes, +//! cell references, and whole-column (`A:C`) and whole-row (`2:5`) ranges. +//! Everything else is copied verbatim. + +use super::address::{column_letters, column_number, MAX_COLUMNS, MAX_ROWS}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Axis { + Row, + Column, +} + +/// Insertion (`delta > 0`) or deletion (`delta < 0`) of whole rows or +/// columns starting at the one-based index `at` of `sheet`. +#[derive(Debug, Clone)] +pub(crate) struct Shift { + pub sheet: String, + pub axis: Axis, + pub at: u32, + pub delta: i64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum PartKind { + Cell, + Column, + Row, +} + +#[derive(Debug, Clone, Copy)] +struct Part { + kind: PartKind, + col_abs: bool, + col: u32, + row_abs: bool, + row: u32, +} + +impl Part { + fn render(&self) -> String { + let col = || { + format!( + "{}{}", + if self.col_abs { "$" } else { "" }, + column_letters(self.col) + ) + }; + let row = || format!("{}{}", if self.row_abs { "$" } else { "" }, self.row); + match self.kind { + PartKind::Cell => format!("{}{}", col(), row()), + PartKind::Column => col(), + PartKind::Row => row(), + } + } +} + +#[derive(Debug, Clone)] +struct Reference { + /// Raw prefix including the `!`, kept verbatim unless renamed. + prefix: Option, + sheet: Option, + first: Part, + second: Option, +} + +enum Token { + Text(String), + Ref(Reference), +} + +fn is_name_char(c: char) -> bool { + c.is_alphanumeric() || c == '_' || c == '.' +} + +fn tokenize(formula: &str) -> Vec { + let chars: Vec = formula.chars().collect(); + let mut tokens = Vec::new(); + let mut text = String::new(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + if c == '"' { + text.push(c); + i += 1; + while i < chars.len() { + text.push(chars[i]); + if chars[i] == '"' { + if chars.get(i + 1) == Some(&'"') { + text.push('"'); + i += 2; + continue; + } + i += 1; + break; + } + i += 1; + } + continue; + } + let boundary = + i == 0 || !(is_name_char(chars[i - 1]) || chars[i - 1] == '$' || chars[i - 1] == '!'); + if boundary { + if let Some((reference, next)) = parse_reference(&chars, i) { + if !text.is_empty() { + tokens.push(Token::Text(std::mem::take(&mut text))); + } + tokens.push(Token::Ref(reference)); + i = next; + continue; + } + } + text.push(c); + i += 1; + } + if !text.is_empty() { + tokens.push(Token::Text(text)); + } + tokens +} + +fn parse_reference(chars: &[char], start: usize) -> Option<(Reference, usize)> { + let (prefix, sheet, mut i) = parse_sheet_prefix(chars, start).unwrap_or((None, None, start)); + let (first, next) = parse_part(chars, i)?; + i = next; + let mut second = None; + if chars.get(i) == Some(&':') { + if let Some((part, after)) = parse_part(chars, i + 1) { + if part.kind == first.kind { + second = Some(part); + i = after; + } + } + } + // Whole-row and whole-column references only exist as ranges. + if first.kind != PartKind::Cell && second.is_none() { + return None; + } + if let Some(&next_char) = chars.get(i) { + if is_name_char(next_char) || next_char == '(' || next_char == '!' || next_char == '$' { + return None; + } + } + Some(( + Reference { + prefix, + sheet, + first, + second, + }, + i, + )) +} + +fn parse_sheet_prefix( + chars: &[char], + start: usize, +) -> Option<(Option, Option, usize)> { + let mut i = start; + if chars.get(i) == Some(&'\'') { + let mut name = String::new(); + i += 1; + loop { + match chars.get(i) { + Some('\'') if chars.get(i + 1) == Some(&'\'') => { + name.push('\''); + i += 2; + } + Some('\'') => { + i += 1; + break; + } + Some(c) => { + name.push(*c); + i += 1; + } + None => return None, + } + } + if chars.get(i) != Some(&'!') { + return None; + } + let raw: String = chars[start..=i].iter().collect(); + return Some((Some(raw), Some(name), i + 1)); + } + while i < chars.len() && is_name_char(chars[i]) { + i += 1; + } + if i > start && chars.get(i) == Some(&'!') { + let name: String = chars[start..i].iter().collect(); + let raw: String = chars[start..=i].iter().collect(); + return Some((Some(raw), Some(name), i + 1)); + } + None +} + +fn parse_part(chars: &[char], start: usize) -> Option<(Part, usize)> { + let mut i = start; + let col_abs = chars.get(i) == Some(&'$'); + if col_abs { + i += 1; + } + let letters_start = i; + while i < chars.len() && chars[i].is_ascii_alphabetic() && i - letters_start < 4 { + i += 1; + } + let letters: String = chars[letters_start..i].iter().collect(); + if !letters.is_empty() { + let col = column_number(&letters)?; + let row_abs = chars.get(i) == Some(&'$'); + let mut j = if row_abs { i + 1 } else { i }; + let digits_start = j; + while j < chars.len() && chars[j].is_ascii_digit() { + j += 1; + } + if j > digits_start { + let row: u32 = chars[digits_start..j] + .iter() + .collect::() + .parse() + .ok()?; + if row == 0 || row > MAX_ROWS { + return None; + } + return Some(( + Part { + kind: PartKind::Cell, + col_abs, + col, + row_abs, + row, + }, + j, + )); + } + if row_abs { + return None; + } + return Some(( + Part { + kind: PartKind::Column, + col_abs, + col, + row_abs: false, + row: 0, + }, + i, + )); + } + // A row part: `$5` or `5` (only meaningful inside a row range). + let digits_start = i; + while i < chars.len() && chars[i].is_ascii_digit() { + i += 1; + } + if i == digits_start { + return None; + } + let row: u32 = chars[digits_start..i] + .iter() + .collect::() + .parse() + .ok()?; + if row == 0 || row > MAX_ROWS || chars.get(i) == Some(&'.') { + return None; + } + Some(( + Part { + kind: PartKind::Row, + col_abs: false, + col: 0, + row_abs: col_abs, + row, + }, + i, + )) +} + +#[derive(Clone, Copy)] +enum End { + Single, + Start, + Finish, +} + +/// Shifts one coordinate; `None` means it was deleted and cannot be kept. +fn shift_index(value: u32, shift: &Shift, end: End) -> Option { + let at = shift.at; + if shift.delta >= 0 { + if value >= at { + let shifted = value as i64 + shift.delta; + let limit = match shift.axis { + Axis::Row => MAX_ROWS, + Axis::Column => MAX_COLUMNS, + }; + return (shifted <= limit as i64).then_some(shifted as u32); + } + return Some(value); + } + let count = (-shift.delta) as u32; + let last = at + count - 1; + if value < at { + Some(value) + } else if value > last { + Some(value - count) + } else { + match end { + End::Single => None, + End::Start => Some(at), + End::Finish => (at > 1).then(|| at - 1), + } + } +} + +fn shift_part(part: &mut Part, shift: &Shift, end: End) -> bool { + match (shift.axis, part.kind) { + (Axis::Row, PartKind::Cell | PartKind::Row) => match shift_index(part.row, shift, end) { + Some(row) => { + part.row = row; + true + } + None => false, + }, + (Axis::Column, PartKind::Cell | PartKind::Column) => { + match shift_index(part.col, shift, end) { + Some(col) => { + part.col = col; + true + } + None => false, + } + } + _ => true, + } +} + +/// Rewrites `formula` (stored on `formula_sheet`) for a row/column shift. +pub(crate) fn shift_formula(formula: &str, formula_sheet: &str, shift: &Shift) -> String { + let mut out = String::new(); + for token in tokenize(formula) { + match token { + Token::Text(text) => out.push_str(&text), + Token::Ref(mut reference) => { + let target = reference.sheet.as_deref().unwrap_or(formula_sheet); + if !target.eq_ignore_ascii_case(&shift.sheet) { + out.push_str(&render(&reference)); + continue; + } + let ok = match reference.second.as_mut() { + None => shift_part(&mut reference.first, shift, End::Single), + Some(second) => { + let a = shift_part(&mut reference.first, shift, End::Start); + let b = shift_part(second, shift, End::Finish); + let ordered = match shift.axis { + Axis::Row => reference.first.row <= second.row, + Axis::Column => reference.first.col <= second.col, + }; + a && b && ordered + } + }; + if ok { + out.push_str(&render(&reference)); + } else { + out.push_str(reference.prefix.as_deref().unwrap_or("")); + out.push_str("#REF!"); + } + } + } + } + out +} + +/// Points sheet-qualified references at a renamed sheet. +pub(crate) fn rename_sheet_in_formula(formula: &str, old: &str, new: &str) -> String { + let mut out = String::new(); + for token in tokenize(formula) { + match token { + Token::Text(text) => out.push_str(&text), + Token::Ref(mut reference) => { + if reference + .sheet + .as_deref() + .is_some_and(|sheet| sheet.eq_ignore_ascii_case(old)) + { + reference.prefix = Some(format!("{}!", quote_sheet_name(new))); + reference.sheet = Some(new.to_string()); + } + out.push_str(&render(&reference)); + } + } + } + out +} + +/// Sheet names referenced with an explicit prefix. +pub(crate) fn referenced_sheets(formula: &str) -> Vec { + tokenize(formula) + .into_iter() + .filter_map(|token| match token { + Token::Ref(reference) => reference.sheet, + Token::Text(_) => None, + }) + .collect() +} + +pub(crate) fn quote_sheet_name(name: &str) -> String { + let plain = name.chars().all(|c| c.is_alphanumeric() || c == '_') + && !name.starts_with(|c: char| c.is_ascii_digit()) + && super::address::parse_cell(name).is_err(); + if plain { + name.to_string() + } else { + format!("'{}'", name.replace('\'', "''")) + } +} + +fn render(reference: &Reference) -> String { + let mut out = reference.prefix.clone().unwrap_or_default(); + out.push_str(&reference.first.render()); + if let Some(second) = &reference.second { + out.push(':'); + out.push_str(&second.render()); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn rows(sheet: &str, at: u32, delta: i64) -> Shift { + Shift { + sheet: sheet.to_string(), + axis: Axis::Row, + at, + delta, + } + } + + #[test] + fn inserting_rows_shifts_references_below() { + let shift = rows("Data", 3, 2); + assert_eq!( + shift_formula("SUM(A1:A10)+B3*$C$4", "Data", &shift), + "SUM(A1:A12)+B5*$C$6" + ); + assert_eq!(shift_formula("A2+\"A5\"", "Data", &shift), "A2+\"A5\""); + assert_eq!( + shift_formula("Data!A5+'Other Sheet'!A5", "Summary", &shift), + "Data!A7+'Other Sheet'!A5" + ); + assert_eq!(shift_formula("LOG10(A9)", "Data", &shift), "LOG10(A11)"); + assert_eq!( + shift_formula("SUM(4:6)+SUM(A:A)", "Data", &shift), + "SUM(6:8)+SUM(A:A)" + ); + } + + #[test] + fn deleting_rows_shrinks_ranges_and_breaks_single_refs() { + let shift = rows("S", 3, -2); + assert_eq!(shift_formula("SUM(A1:A10)", "S", &shift), "SUM(A1:A8)"); + assert_eq!(shift_formula("A3+A5", "S", &shift), "#REF!+A3"); + assert_eq!(shift_formula("SUM(A3:A4)", "S", &shift), "SUM(#REF!)"); + } + + #[test] + fn column_shift_and_rename() { + let shift = Shift { + sheet: "S".to_string(), + axis: Axis::Column, + at: 2, + delta: 1, + }; + assert_eq!( + shift_formula("A1+B1+SUM(B:C)", "S", &shift), + "A1+C1+SUM(C:D)" + ); + assert_eq!( + rename_sheet_in_formula("Old!A1+'Old'!B2+X!C3", "Old", "New Name"), + "'New Name'!A1+'New Name'!B2+X!C3" + ); + assert_eq!( + referenced_sheets("Sales!A1+'Q 2'!B2+C3"), + vec!["Sales", "Q 2"] + ); + } +} diff --git a/src/crates/execution/office-documents/src/xlsx/mod.rs b/src/crates/execution/office-documents/src/xlsx/mod.rs new file mode 100644 index 0000000000..8f46c3ec7a --- /dev/null +++ b/src/crates/execution/office-documents/src/xlsx/mod.rs @@ -0,0 +1,191 @@ +//! Workbooks (`.xlsx`). + +pub(crate) mod address; +pub(crate) mod eval; +pub(crate) mod formula; +pub(crate) mod model; +pub(crate) mod ops; +pub(crate) mod render; + +pub use model::{Cell, CellStyle, Sheet, XlsxDocument}; + +use crate::common::preview; +use crate::error::{OfficeError, OfficeResult}; +use crate::{Detail, ReadRequest}; +use address::{column_letters, parse_range, CellRange, CellRef}; +use serde_json::{json, Value}; + +const MAX_READ_COLUMNS: u32 = 60; + +pub(crate) fn read(book: &XlsxDocument, request: &ReadRequest) -> OfficeResult { + let Some(name) = &request.sheet else { + return Ok(list_sheets(book, request)); + }; + let index = book.sheet_index(name).ok_or_else(|| { + OfficeError::not_found(format!( + "no sheet named `{name}`; sheets: {}", + book.sheets + .iter() + .map(|sheet| sheet.name.as_str()) + .collect::>() + .join(", ") + )) + })?; + let sheet = &book.sheets[index]; + let computed = eval::evaluate_workbook(book); + let used = used_range(sheet); + let Some(used) = used else { + return Ok(json!({ "sheet": sheet.name, "used_range": null, "rows": [], "total_rows": 0 })); + }; + let requested = match &request.range { + Some(range) => parse_range(range)?, + None => used, + }; + let total_rows = (requested.end.row - requested.start.row + 1) as usize; + let (offset, limit) = request.window(total_rows, 100); + let row_count = limit.min(total_rows - offset); + let first = requested.start.row + offset as u32; + let window = CellRange { + start: CellRef::new(first, requested.start.col), + end: CellRef::new( + first + row_count.saturating_sub(1) as u32, + requested.end.col, + ), + }; + let last_col = window.end.col.min(window.start.col + MAX_READ_COLUMNS - 1); + let columns: Vec = (window.start.col..=last_col).map(column_letters).collect(); + let mut rows = Vec::new(); + let mut styles = serde_json::Map::new(); + for row in first..first + row_count as u32 { + let mut values = Vec::new(); + let mut any = false; + for col in window.start.col..=last_col { + let address = CellRef::new(row, col); + let value = match sheet.cells.get(&address) { + Some(cell) => { + if request.detail == Detail::Full { + if let Some(style) = &cell.style { + styles.insert( + address.to_string(), + serde_json::to_value(style).unwrap_or(Value::Null), + ); + } + } + match (&cell.formula, &cell.value) { + (Some(formula), _) => match computed.get(&(index, address)) { + Some(value) => { + json!({ "formula": format!("={formula}"), "value": computed_json(value) }) + } + None => json!({ "formula": format!("={formula}"), "value": null }), + }, + (None, Value::String(text)) if request.detail == Detail::Outline => { + json!(preview(text, 200)) + } + (None, other) => other.clone(), + } + } + None => Value::Null, + }; + any |= !value.is_null(); + values.push(value); + } + if any { + rows.push(json!({ "row": row, "cells": values })); + } + } + let mut view = json!({ + "sheet": sheet.name, + "used_range": used.to_string(), + "window": (row_count > 0).then(|| CellRange { start: window.start, end: CellRef::new(window.end.row, last_col) }.to_string()), + "offset": offset, + "limit": limit, + "total_rows": total_rows, + "columns": columns, + "rows": rows, + "merges": sheet.merges, + "freeze": sheet.freeze, + "autofilter": sheet.autofilter, + "note": "formula cells show {formula, value}; a null value means the formula uses functions only the spreadsheet application computes (on open)", + }); + if window.end.col > last_col { + view["columns_truncated"] = json!(true); + } + if offset + row_count < total_rows { + view["next_offset"] = json!(offset + row_count); + } + if request.detail == Detail::Full { + view["styles"] = Value::Object(styles); + view["column_widths"] = json!(sheet + .column_widths + .iter() + .map(|(column, width)| (column_letters(*column), *width)) + .collect::>()); + view["row_heights"] = json!(sheet.row_heights); + } + Ok(view) +} + +fn list_sheets(book: &XlsxDocument, request: &ReadRequest) -> Value { + let total = book.sheets.len(); + let (offset, limit) = request.window(total, 50); + let sheets: Vec = book + .sheets + .iter() + .enumerate() + .skip(offset) + .take(limit) + .map(|(index, sheet)| { + json!({ + "index": index, + "name": sheet.name, + "used_range": used_range(sheet).map(|range| range.to_string()), + "cells": sheet.cells.values().filter(|cell| !cell.value.is_null() || cell.formula.is_some()).count(), + "formulas": sheet.cells.values().filter(|cell| cell.formula.is_some()).count(), + "merges": sheet.merges.len(), + "freeze": sheet.freeze, + "autofilter": sheet.autofilter, + }) + }) + .collect(); + let mut view = json!({ + "total_sheets": total, + "offset": offset, + "limit": limit, + "sheets": sheets, + "properties": book.properties, + "hint": "pass `sheet` (and optionally `range` or offset/limit over rows) to read cell values", + }); + if offset + limit < total { + view["next_offset"] = json!(offset + limit); + } + view +} + +fn used_range(sheet: &Sheet) -> Option { + let mut cells = sheet + .cells + .iter() + .filter(|(_, cell)| !cell.value.is_null() || cell.formula.is_some()) + .map(|(address, _)| *address) + .peekable(); + cells.peek()?; + let mut start = CellRef::new(u32::MAX, u32::MAX); + let mut end = CellRef::new(0, 0); + for cell in cells { + start.row = start.row.min(cell.row); + start.col = start.col.min(cell.col); + end.row = end.row.max(cell.row); + end.col = end.col.max(cell.col); + } + Some(CellRange { start, end }) +} + +fn computed_json(value: &eval::Computed) -> Value { + match value { + eval::Computed::Number(number) => json!(number), + eval::Computed::Text(text) => json!(text), + eval::Computed::Bool(flag) => json!(flag), + eval::Computed::Error(error) => json!(error), + eval::Computed::Empty => json!(0), + } +} diff --git a/src/crates/execution/office-documents/src/xlsx/model.rs b/src/crates/execution/office-documents/src/xlsx/model.rs new file mode 100644 index 0000000000..092af02887 --- /dev/null +++ b/src/crates/execution/office-documents/src/xlsx/model.rs @@ -0,0 +1,430 @@ +//! Workbook model: sheets of sparse cells with styles and sheet layout. + +use super::address::{parse_range, CellRef}; +use super::formula::referenced_sheets; +use crate::common::{ + parse_color, prefix, report_extra, report_list, DocumentProperties, Extra, UnknownFields, +}; +use crate::error::{OfficeError, OfficeResult}; +use serde::de::{MapAccess, Visitor}; +use serde::ser::SerializeMap; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde_json::Value; +use std::collections::BTreeMap; +use std::fmt; + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct XlsxDocument { + #[serde(default)] + pub properties: DocumentProperties, + #[serde(default)] + pub sheets: Vec, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Sheet { + pub name: String, + #[serde(default, with = "cell_map")] + pub cells: BTreeMap, + /// Column widths in characters, keyed by one-based column number. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub column_widths: BTreeMap, + /// Row heights in points, keyed by one-based row number. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub row_heights: BTreeMap, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub merges: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub freeze: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub autofilter: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tab_color: Option, + #[serde(flatten)] + pub extra: Extra, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Freeze { + #[serde(default)] + pub rows: u32, + #[serde(default, alias = "cols")] + pub columns: u32, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct Cell { + /// Literal value: string, number, boolean, or null for formula/style-only cells. + #[serde(default, skip_serializing_if = "Value::is_null")] + pub value: Value, + /// Formula without the leading `=`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub formula: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub style: Option, + #[serde(flatten)] + pub extra: Extra, +} + +impl Cell { + pub fn is_empty(&self) -> bool { + self.value.is_null() && self.formula.is_none() && self.style.is_none() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum BorderStyle { + None, + Thin, + Medium, + Thick, + Dashed, + Dotted, + Double, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum HorizontalAlign { + General, + Left, + #[serde(alias = "centre", alias = "middle")] + Center, + Right, + Justify, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum VerticalAlignment { + Top, + #[serde(alias = "middle")] + Center, + Bottom, +} + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct CellStyle { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub bold: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub italic: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub underline: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub strike: Option, + #[serde(default, skip_serializing_if = "Option::is_none", alias = "color")] + pub font_color: Option, + #[serde(default, skip_serializing_if = "Option::is_none", alias = "size_pt")] + pub font_size: Option, + #[serde(default, skip_serializing_if = "Option::is_none", alias = "font")] + pub font_name: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + alias = "fill", + alias = "background" + )] + pub fill_color: Option, + /// Excel number format code, such as `#,##0.00`, `0.0%`, or `yyyy-mm-dd`. + #[serde(default, skip_serializing_if = "Option::is_none", alias = "format")] + pub number_format: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + alias = "horizontal_align" + )] + pub align: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + alias = "vertical_align" + )] + pub valign: Option, + #[serde(default, skip_serializing_if = "Option::is_none", alias = "wrap_text")] + pub wrap: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub indent: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub border: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub border_color: Option, + #[serde(flatten)] + pub extra: Extra, +} + +impl CellStyle { + /// Overlays the fields set in `patch`. + pub fn merge(&mut self, patch: &CellStyle) { + macro_rules! take { + ($($field:ident),*) => { + $(if patch.$field.is_some() { self.$field = patch.$field.clone(); })* + }; + } + take!( + bold, + italic, + underline, + strike, + font_color, + font_size, + font_name, + fill_color, + number_format, + align, + valign, + wrap, + indent, + border, + border_color + ); + } + + pub fn is_default(&self) -> bool { + *self == CellStyle::default() + } + + pub fn validate(&self, path: &str) -> OfficeResult<()> { + for (name, color) in [ + ("font_color", &self.font_color), + ("fill_color", &self.fill_color), + ("border_color", &self.border_color), + ] { + if let Some(color) = color { + parse_color(color).map_err(|err| prefix(err, path, name))?; + } + } + if let Some(size) = self.font_size { + if !(1.0..=409.0).contains(&size) { + return Err(OfficeError::invalid(format!( + "{path}.font_size must be 1..=409" + ))); + } + } + if self.indent.is_some_and(|indent| indent > 250) { + return Err(OfficeError::invalid(format!( + "{path}.indent must be 0..=250" + ))); + } + if self + .number_format + .as_ref() + .is_some_and(|format| format.len() > 255) + { + return Err(OfficeError::invalid(format!( + "{path}.number_format is too long" + ))); + } + Ok(()) + } +} + +impl UnknownFields for CellStyle { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + } +} + +impl UnknownFields for XlsxDocument { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + self.properties + .unknown_fields(&format!("{path}.properties"), out); + report_list(&self.sheets, &format!("{path}.sheets"), out); + } +} + +impl UnknownFields for Sheet { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + } +} + +pub(crate) fn validate_sheet_name(name: &str) -> OfficeResult<()> { + let length = name.chars().count(); + if name.trim().is_empty() || length > 31 { + return Err(OfficeError::invalid(format!( + "sheet name `{name}` must be 1 to 31 characters" + ))); + } + if name.contains(['[', ']', ':', '*', '?', '/', '\\']) { + return Err(OfficeError::invalid(format!( + "sheet name `{name}` cannot contain [ ] : * ? / \\" + ))); + } + if name.starts_with('\'') || name.ends_with('\'') { + return Err(OfficeError::invalid(format!( + "sheet name `{name}` cannot start or end with an apostrophe" + ))); + } + if name.eq_ignore_ascii_case("history") { + return Err(OfficeError::invalid("`History` is a reserved sheet name")); + } + Ok(()) +} + +impl XlsxDocument { + pub fn sheet_index(&self, name: &str) -> Option { + self.sheets + .iter() + .position(|sheet| sheet.name.eq_ignore_ascii_case(name)) + } + + /// Problems worth reporting after a batch. + pub fn warnings(&self) -> Vec { + let mut warnings = Vec::new(); + for sheet in &self.sheets { + let mut missing: Vec = Vec::new(); + for (cell, value) in &sheet.cells { + let Some(formula) = &value.formula else { + continue; + }; + if formula.contains("#REF!") { + warnings.push(format!( + "sheet `{}` {cell}: formula contains #REF! (a referenced row, column, or sheet was deleted)", + sheet.name + )); + } + for referenced in referenced_sheets(formula) { + if self.sheet_index(&referenced).is_none() && !missing.contains(&referenced) { + missing.push(referenced); + } + } + } + for name in missing { + warnings.push(format!( + "sheet `{}` has formulas that reference sheet `{name}`, which does not exist", + sheet.name + )); + } + let ranges: Vec<_> = sheet + .merges + .iter() + .filter_map(|merge| parse_range(merge).ok()) + .collect(); + for (index, range) in ranges.iter().enumerate() { + if ranges[index + 1..] + .iter() + .any(|other| other.intersects(range)) + { + warnings.push(format!( + "sheet `{}`: merged range {range} overlaps another merged range", + sheet.name + )); + } + } + } + let computed = super::eval::evaluate_workbook(self); + let mut uncached: Vec = Vec::new(); + for (sheet_index, sheet) in self.sheets.iter().enumerate() { + for (cell, value) in &sheet.cells { + if value.formula.is_some() && !computed.contains_key(&(sheet_index, *cell)) { + uncached.push(format!("{}!{cell}", sheet.name)); + } + } + } + if !uncached.is_empty() { + let sample: Vec<&str> = uncached.iter().take(5).map(String::as_str).collect(); + warnings.push(format!( + "{} formula cell(s) ({}{}) use functions or references the local evaluator does not compute; they show values once Excel, WPS, or LibreOffice opens the file", + uncached.len(), + sample.join(", "), + if uncached.len() > sample.len() { ", …" } else { "" } + )); + } + for (sheet_index, sheet) in self.sheets.iter().enumerate() { + for (cell, value) in &sheet.cells { + if value.formula.is_none() { + continue; + } + if let Some(super::eval::Computed::Error(error)) = + computed.get(&(sheet_index, *cell)) + { + if *error != "#REF!" { + warnings.push(format!( + "sheet `{}` {cell}: formula evaluates to {error}", + sheet.name + )); + } + } + } + } + warnings.truncate(30); + warnings + } +} + +/// Serializes the sparse cell map as `{ "A1": {...}, ... }` in row-major order. +mod cell_map { + use super::*; + use crate::xlsx::address::parse_cell; + + pub(crate) fn serialize( + cells: &BTreeMap, + serializer: S, + ) -> Result { + let mut map = serializer.serialize_map(Some(cells.len()))?; + for (cell, value) in cells { + map.serialize_entry(&cell.to_string(), value)?; + } + map.end() + } + + pub(crate) fn deserialize<'de, D: Deserializer<'de>>( + deserializer: D, + ) -> Result, D::Error> { + struct CellMapVisitor; + impl<'de> Visitor<'de> for CellMapVisitor { + type Value = BTreeMap; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a map of A1 addresses to cells") + } + + fn visit_map>(self, mut access: M) -> Result { + let mut cells = BTreeMap::new(); + while let Some((key, value)) = access.next_entry::()? { + let cell = parse_cell(&key).map_err(serde::de::Error::custom)?; + cells.insert(cell, value); + } + Ok(cells) + } + } + deserializer.deserialize_map(CellMapVisitor) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn cells_round_trip_as_a1_map() { + let mut sheet = Sheet { + name: "S".to_string(), + ..Sheet::default() + }; + sheet.cells.insert( + CellRef::new(2, 1), + Cell { + value: json!(5), + ..Cell::default() + }, + ); + let value = serde_json::to_value(&sheet).unwrap(); + assert_eq!(value["cells"]["A2"]["value"], json!(5)); + let back: Sheet = serde_json::from_value(value).unwrap(); + assert_eq!(back, sheet); + } + + #[test] + fn rejects_invalid_sheet_names() { + assert!(validate_sheet_name("Q1/Q2").is_err()); + assert!(validate_sheet_name("").is_err()); + assert!(validate_sheet_name("营收 2024").is_ok()); + } +} diff --git a/src/crates/execution/office-documents/src/xlsx/ops.rs b/src/crates/execution/office-documents/src/xlsx/ops.rs new file mode 100644 index 0000000000..1853012890 --- /dev/null +++ b/src/crates/execution/office-documents/src/xlsx/ops.rs @@ -0,0 +1,1077 @@ +//! Workbook edit operations. + +use super::address::{ + column_letters, parse_cell, parse_column, parse_range, CellRange, CellRef, MAX_COLUMNS, + MAX_ROWS, +}; +use super::formula::{rename_sheet_in_formula, shift_formula, Axis, Shift}; +use super::model::{validate_sheet_name, CellStyle, Freeze, Sheet, XlsxDocument}; +use crate::common::{ + parse_color, parse_operation, report_extra, unknown_operation, DocumentProperties, Extra, + UnknownFields, +}; +use crate::error::{OfficeError, OfficeResult}; +use crate::ApplyContext; +use serde::Deserialize; +use serde_json::{Map, Value}; +use std::collections::BTreeMap; + +pub(crate) const OPERATIONS: &[&str] = &[ + "add_sheet", + "delete_sheet", + "rename_sheet", + "move_sheet", + "set_cells", + "append_rows", + "insert_rows", + "delete_rows", + "insert_columns", + "delete_columns", + "clear_range", + "format_range", + "set_column_widths", + "set_row_heights", + "merge_cells", + "unmerge_cells", + "freeze_panes", + "set_autofilter", + "set_sheet", + "set_properties", +]; + +const MAX_SHEETS: usize = 255; +const MAX_CELLS: usize = 2_000_000; +const MAX_FORMAT_CELLS: u64 = 1_000_000; + +macro_rules! op_struct { + ($name:ident { $($body:tt)* }) => { + #[derive(Deserialize)] + struct $name { + $($body)* + #[serde(flatten)] + extra: Extra, + } + impl UnknownFields for $name { + fn unknown_fields(&self, path: &str, out: &mut Vec) { + report_extra(&self.extra, path, out); + } + } + }; +} + +op_struct!(AddSheet { + name: String, + #[serde(default)] + index: Option, + #[serde(default, alias = "values")] + rows: Option>>, + #[serde(default)] + start: Option, +}); +op_struct!(DeleteSheet { + #[serde(default)] + sheet: Option, +}); +op_struct!(RenameSheet { + #[serde(default)] + sheet: Option, + name: String, +}); +op_struct!(MoveSheet { + #[serde(default)] + sheet: Option, + to: usize, +}); +op_struct!(SetCells { + #[serde(default)] + sheet: Option, + #[serde(default, alias = "cell", alias = "anchor")] + start: Option, + #[serde(alias = "values")] + rows: Vec>, +}); +op_struct!(AppendRows { + #[serde(default)] + sheet: Option, + #[serde(alias = "values")] + rows: Vec>, + #[serde(default)] + column: Option, +}); +op_struct!(InsertRows { + #[serde(default)] + sheet: Option, + row: u32, + #[serde(default)] + count: Option, + #[serde(default, alias = "values")] + rows: Option>>, +}); +op_struct!(DeleteRows { + #[serde(default)] + sheet: Option, + row: u32, + #[serde(default)] + count: Option, +}); +op_struct!(InsertColumns { + #[serde(default)] + sheet: Option, + column: String, + #[serde(default)] + count: Option, +}); +op_struct!(DeleteColumns { + #[serde(default)] + sheet: Option, + column: String, + #[serde(default)] + count: Option, +}); +op_struct!(ClearRange { + #[serde(default)] + sheet: Option, + range: String, + #[serde(default)] + what: Option, +}); +op_struct!(FormatRange { + #[serde(default)] + sheet: Option, + range: String, + style: CellStyle, +}); +op_struct!(SetColumnWidths { + #[serde(default)] + sheet: Option, + widths: BTreeMap, +}); +op_struct!(SetRowHeights { + #[serde(default)] + sheet: Option, + heights: BTreeMap, +}); +op_struct!(RangeOnly { + #[serde(default)] + sheet: Option, + range: String, +}); +op_struct!(FreezePanes { + #[serde(default)] + sheet: Option, + #[serde(default)] + rows: u32, + #[serde(default, alias = "cols")] + columns: u32, +}); +op_struct!(SetAutofilter { + #[serde(default)] + sheet: Option, + #[serde(default)] + range: Option, +}); +op_struct!(SetSheet { + #[serde(default)] + sheet: Option, + #[serde(default)] + tab_color: Option, +}); + +pub(crate) fn apply( + book: &mut XlsxDocument, + op: &str, + value: &Value, + ctx: &mut ApplyContext, +) -> OfficeResult<()> { + match op { + "add_sheet" => { + let input: AddSheet = parse_operation(value)?; + validate_sheet_name(&input.name)?; + if book.sheet_index(&input.name).is_some() { + return Err(OfficeError::invalid(format!( + "a sheet named `{}` already exists", + input.name + ))); + } + if book.sheets.len() >= MAX_SHEETS { + return Err(OfficeError::limit(format!( + "a workbook is limited to {MAX_SHEETS} sheets" + ))); + } + let at = crate::common::insertion_index(input.index, book.sheets.len(), "sheet")?; + let mut sheet = Sheet { + name: input.name.clone(), + ..Sheet::default() + }; + if let Some(rows) = input.rows { + let start = parse_cell(input.start.as_deref().unwrap_or("A1"))?; + write_rows(&mut sheet, start, &rows)?; + } + book.sheets.insert(at, sheet); + ensure_cell_budget(book)?; + ctx.note(format!("added sheet `{}` at position {at}", input.name)); + Ok(()) + } + "delete_sheet" => { + let input: DeleteSheet = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + let removed = book.sheets.remove(index); + ctx.note(format!("deleted sheet `{}`", removed.name)); + Ok(()) + } + "rename_sheet" => { + let input: RenameSheet = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + validate_sheet_name(&input.name)?; + if let Some(existing) = book.sheet_index(&input.name) { + if existing != index { + return Err(OfficeError::invalid(format!( + "a sheet named `{}` already exists", + input.name + ))); + } + } + let old = std::mem::replace(&mut book.sheets[index].name, input.name.clone()); + for sheet in &mut book.sheets { + for cell in sheet.cells.values_mut() { + if let Some(formula) = &mut cell.formula { + *formula = rename_sheet_in_formula(formula, &old, &input.name); + } + } + } + ctx.note(format!("renamed sheet `{old}` to `{}`", input.name)); + Ok(()) + } + "move_sheet" => { + let input: MoveSheet = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + crate::common::move_span(&mut book.sheets, index..index + 1, input.to, "sheet")?; + ctx.note(format!("moved sheet to position {}", input.to)); + Ok(()) + } + "set_cells" => { + let input: SetCells = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + let start = parse_cell(input.start.as_deref().unwrap_or("A1"))?; + let written = write_rows(&mut book.sheets[index], start, &input.rows)?; + ensure_cell_budget(book)?; + ctx.note(format!( + "wrote {written} cell(s) on `{}` from {start}", + book.sheets[index].name + )); + Ok(()) + } + "append_rows" => { + let input: AppendRows = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + let sheet = &mut book.sheets[index]; + let next_row = sheet.cells.keys().map(|cell| cell.row).max().unwrap_or(0) + 1; + let column = match &input.column { + Some(column) => parse_column(column)?, + None => 1, + }; + let start = CellRef::new(next_row, column); + write_rows(sheet, start, &input.rows)?; + let name = sheet.name.clone(); + ensure_cell_budget(book)?; + ctx.note(format!( + "appended {} row(s) to `{name}` at row {next_row}", + input.rows.len() + )); + Ok(()) + } + "insert_rows" => { + let input: InsertRows = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + let count = input + .count + .or_else(|| input.rows.as_ref().map(|rows| rows.len() as u32)) + .unwrap_or(1) + .max(1); + if input + .rows + .as_ref() + .is_some_and(|rows| rows.len() > count as usize) + { + return Err(OfficeError::invalid( + "insert_rows: `rows` cannot contain more rows than `count`", + )); + } + check_index(input.row, MAX_ROWS, "row")?; + shift_sheet(book, index, Axis::Row, input.row, count as i64)?; + if let Some(rows) = &input.rows { + write_rows(&mut book.sheets[index], CellRef::new(input.row, 1), rows)?; + } + ensure_cell_budget(book)?; + ctx.note(format!("inserted {count} row(s) at row {}", input.row)); + Ok(()) + } + "delete_rows" => { + let input: DeleteRows = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + let count = input.count.unwrap_or(1).max(1); + check_index(input.row, MAX_ROWS, "row")?; + shift_sheet(book, index, Axis::Row, input.row, -(count as i64))?; + ctx.note(format!("deleted {count} row(s) at row {}", input.row)); + Ok(()) + } + "insert_columns" => { + let input: InsertColumns = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + let column = parse_column(&input.column)?; + let count = input.count.unwrap_or(1).max(1); + shift_sheet(book, index, Axis::Column, column, count as i64)?; + ctx.note(format!( + "inserted {count} column(s) at {}", + column_letters(column) + )); + Ok(()) + } + "delete_columns" => { + let input: DeleteColumns = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + let column = parse_column(&input.column)?; + let count = input.count.unwrap_or(1).max(1); + shift_sheet(book, index, Axis::Column, column, -(count as i64))?; + ctx.note(format!( + "deleted {count} column(s) at {}", + column_letters(column) + )); + Ok(()) + } + "clear_range" => { + let input: ClearRange = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + let range = parse_range(&input.range)?; + let what = input.what.as_deref().unwrap_or("all"); + if !matches!(what, "all" | "contents" | "formats") { + return Err(OfficeError::invalid( + "`what` must be all, contents, or formats", + )); + } + let sheet = &mut book.sheets[index]; + let mut cleared = 0; + sheet.cells.retain(|cell, value| { + if !range.contains(*cell) { + return true; + } + cleared += 1; + match what { + "contents" => { + value.value = Value::Null; + value.formula = None; + } + "formats" => value.style = None, + _ => return false, + } + !value.is_empty() + }); + ctx.note(format!("cleared {what} of {cleared} cell(s) in {range}")); + Ok(()) + } + "format_range" => { + let input: FormatRange = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + let range = parse_range(&input.range)?; + let mut unknown = Vec::new(); + input.style.unknown_fields("style", &mut unknown); + if !unknown.is_empty() { + return Err(OfficeError::invalid(format!( + "unknown field(s): {}", + unknown.join(", ") + ))); + } + input.style.validate("style")?; + if range.cell_count() > MAX_FORMAT_CELLS { + return Err(OfficeError::limit(format!( + "format_range is limited to {MAX_FORMAT_CELLS} cells; format the used rows instead of whole columns" + ))); + } + let sheet = &mut book.sheets[index]; + for row in range.start.row..=range.end.row { + for col in range.start.col..=range.end.col { + let cell = sheet.cells.entry(CellRef::new(row, col)).or_default(); + let mut style = cell.style.take().unwrap_or_default(); + style.merge(&input.style); + cell.style = (!style.is_default()).then_some(style); + } + } + sheet.cells.retain(|_, cell| !cell.is_empty()); + ensure_cell_budget(book)?; + ctx.note(format!("formatted {range}")); + Ok(()) + } + "set_column_widths" => { + let input: SetColumnWidths = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + let sheet = &mut book.sheets[index]; + for (key, width) in &input.widths { + if !(0.0..=255.0).contains(width) { + return Err(OfficeError::invalid(format!( + "column width for `{key}` must be 0..=255 characters" + ))); + } + let (first, last) = match key.split_once(':') { + Some((a, b)) => (parse_column(a)?, parse_column(b)?), + None => { + let column = parse_column(key)?; + (column, column) + } + }; + for column in first.min(last)..=first.max(last) { + sheet.column_widths.insert(column, *width); + } + } + ctx.note("set column widths".to_string()); + Ok(()) + } + "set_row_heights" => { + let input: SetRowHeights = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + let sheet = &mut book.sheets[index]; + for (key, height) in &input.heights { + if !(0.0..=409.0).contains(height) { + return Err(OfficeError::invalid(format!( + "row height for `{key}` must be 0..=409 points" + ))); + } + let parse = |text: &str| -> OfficeResult { + let row: u32 = text + .trim() + .parse() + .map_err(|_| OfficeError::invalid(format!("invalid row `{text}`")))?; + check_index(row, MAX_ROWS, "row")?; + Ok(row) + }; + let (first, last) = match key.split_once(':') { + Some((a, b)) => (parse(a)?, parse(b)?), + None => (parse(key)?, parse(key)?), + }; + if last.max(first) - first.min(last) > 100_000 { + return Err(OfficeError::limit( + "set_row_heights spans at most 100000 rows per entry", + )); + } + for row in first.min(last)..=first.max(last) { + sheet.row_heights.insert(row, *height); + } + } + ctx.note("set row heights".to_string()); + Ok(()) + } + "merge_cells" => { + let input: RangeOnly = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + let range = parse_range(&input.range)?; + if range.is_single() { + return Err(OfficeError::invalid( + "merge_cells needs a range of at least two cells", + )); + } + let sheet = &mut book.sheets[index]; + if let Some(existing) = sheet + .merges + .iter() + .filter_map(|merge| parse_range(merge).ok()) + .find(|other| other.intersects(&range)) + { + return Err(OfficeError::invalid(format!( + "{range} overlaps the merged range {existing}; unmerge it first" + ))); + } + sheet.merges.push(range.to_string()); + ctx.note(format!("merged {range}")); + Ok(()) + } + "unmerge_cells" => { + let input: RangeOnly = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + let range = parse_range(&input.range)?; + let sheet = &mut book.sheets[index]; + let before = sheet.merges.len(); + sheet.merges.retain(|merge| { + parse_range(merge) + .map(|other| !other.intersects(&range)) + .unwrap_or(false) + }); + let removed = before - sheet.merges.len(); + if removed == 0 { + ctx.warn(format!("unmerge_cells: no merged range intersects {range}")); + } + ctx.note(format!("unmerged {removed} range(s)")); + Ok(()) + } + "freeze_panes" => { + let input: FreezePanes = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + if input.rows > 1000 || input.columns > 100 { + return Err(OfficeError::invalid( + "freeze at most 1000 rows and 100 columns", + )); + } + book.sheets[index].freeze = (input.rows > 0 || input.columns > 0).then_some(Freeze { + rows: input.rows, + columns: input.columns, + }); + ctx.note(format!( + "froze {} row(s) and {} column(s)", + input.rows, input.columns + )); + Ok(()) + } + "set_autofilter" => { + let input: SetAutofilter = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + book.sheets[index].autofilter = match &input.range { + Some(range) => Some(parse_range(range)?.to_string()), + None => None, + }; + ctx.note("updated the auto filter".to_string()); + Ok(()) + } + "set_sheet" => { + let input: SetSheet = parse_operation(value)?; + let index = resolve_sheet(book, input.sheet.as_ref())?; + if let Some(color) = &input.tab_color { + if color.is_empty() { + book.sheets[index].tab_color = None; + } else { + parse_color(color)?; + book.sheets[index].tab_color = Some(color.clone()); + } + } + ctx.note("updated sheet settings".to_string()); + Ok(()) + } + "set_properties" => { + let input: DocumentProperties = parse_operation(value)?; + book.properties.merge(&input); + ctx.note("updated document properties".to_string()); + Ok(()) + } + other => Err(unknown_operation(other, OPERATIONS)), + } +} + +fn check_index(value: u32, max: u32, unit: &str) -> OfficeResult<()> { + if value == 0 || value > max { + return Err(OfficeError::out_of_range(format!( + "{unit} {value} is outside 1..={max}" + ))); + } + Ok(()) +} + +fn ensure_cell_budget(book: &XlsxDocument) -> OfficeResult<()> { + let total: usize = book.sheets.iter().map(|sheet| sheet.cells.len()).sum(); + if total > MAX_CELLS { + return Err(OfficeError::limit(format!( + "a workbook is limited to {MAX_CELLS} stored cells" + ))); + } + Ok(()) +} + +/// Finds the target sheet by name or zero-based index; optional when the +/// workbook has exactly one sheet. +fn resolve_sheet(book: &XlsxDocument, selector: Option<&Value>) -> OfficeResult { + let names = || { + book.sheets + .iter() + .map(|sheet| format!("`{}`", sheet.name)) + .collect::>() + .join(", ") + }; + match selector { + None | Some(Value::Null) => { + if book.sheets.len() == 1 { + Ok(0) + } else if book.sheets.is_empty() { + Err(OfficeError::not_found( + "the workbook has no sheets yet; add one with add_sheet", + )) + } else { + Err(OfficeError::invalid(format!( + "`sheet` is required when the workbook has several sheets: {}", + names() + ))) + } + } + Some(Value::String(name)) => book.sheet_index(name).ok_or_else(|| { + let candidates: Vec<&str> = book + .sheets + .iter() + .map(|sheet| sheet.name.as_str()) + .collect(); + let hint = crate::common::did_you_mean(name, &candidates) + .map(|guess| format!(" Did you mean `{guess}`?")) + .unwrap_or_default(); + OfficeError::not_found(format!( + "no sheet named `{name}`.{hint} Sheets: {}", + names() + )) + }), + Some(Value::Number(number)) => { + let index = number + .as_u64() + .ok_or_else(|| OfficeError::invalid("sheet index must be a non-negative integer"))? + as usize; + if index < book.sheets.len() { + Ok(index) + } else { + Err(OfficeError::out_of_range(format!( + "sheet index {index} is out of range; sheets: {}", + names() + ))) + } + } + Some(_) => Err(OfficeError::invalid( + "`sheet` must be a sheet name or a zero-based index", + )), + } +} + +/// Writes a 2-D block of cell inputs; `null` leaves a cell unchanged. +fn write_rows(sheet: &mut Sheet, start: CellRef, rows: &[Vec]) -> OfficeResult { + let mut written = 0; + for (row_offset, row) in rows.iter().enumerate() { + let row_number = start.row as u64 + row_offset as u64; + if row_number > MAX_ROWS as u64 { + return Err(OfficeError::out_of_range(format!( + "data runs past row {MAX_ROWS}" + ))); + } + for (col_offset, input) in row.iter().enumerate() { + let col_number = start.col as u64 + col_offset as u64; + if col_number > MAX_COLUMNS as u64 { + return Err(OfficeError::out_of_range(format!( + "data runs past column {}", + column_letters(MAX_COLUMNS) + ))); + } + let address = CellRef::new(row_number as u32, col_number as u32); + let path = address.to_string(); + let Some(update) = parse_cell_input(input, &path)? else { + continue; + }; + let cell = sheet.cells.entry(address).or_default(); + cell.value = update.value; + cell.formula = update.formula; + if let Some(style) = update.style { + let mut merged = cell.style.take().unwrap_or_default(); + merged.merge(&style); + cell.style = (!merged.is_default()).then_some(merged); + } + if cell.is_empty() { + sheet.cells.remove(&address); + } + written += 1; + } + } + Ok(written) +} + +struct CellUpdate { + value: Value, + formula: Option, + style: Option, +} + +fn parse_cell_input(input: &Value, path: &str) -> OfficeResult> { + let simple = |value: Value, formula: Option| { + Ok(Some(CellUpdate { + value, + formula, + style: None, + })) + }; + match input { + Value::Null => Ok(None), + Value::Bool(_) | Value::Number(_) => simple(input.clone(), None), + Value::String(text) => { + if let Some(formula) = text + .strip_prefix('=') + .filter(|rest| !rest.trim().is_empty()) + { + check_formula(formula, path)?; + simple(Value::Null, Some(formula.to_string())) + } else { + simple(Value::String(text.clone()), None) + } + } + Value::Object(object) => parse_cell_object(object, path).map(Some), + Value::Array(_) => Err(OfficeError::invalid(format!( + "{path}: a cell cannot be an array; rows are arrays of cell values" + ))), + } +} + +fn parse_cell_object(object: &Map, path: &str) -> OfficeResult { + for key in object.keys() { + if !matches!(key.as_str(), "value" | "formula" | "type" | "style") { + return Err(OfficeError::invalid(format!( + "{path}: unknown cell field `{key}`; cells accept value, formula, type, style" + ))); + } + } + let style = match object.get("style") { + None | Some(Value::Null) => None, + Some(value) => { + let style: CellStyle = serde_json::from_value(value.clone()) + .map_err(|err| OfficeError::invalid(format!("{path}.style: {err}")))?; + let mut unknown = Vec::new(); + style.unknown_fields(&format!("{path}.style"), &mut unknown); + if !unknown.is_empty() { + return Err(OfficeError::invalid(format!( + "unknown field(s): {}", + unknown.join(", ") + ))); + } + style.validate(&format!("{path}.style"))?; + Some(style) + } + }; + let kind = object.get("type").and_then(Value::as_str); + let raw = object.get("value").cloned().unwrap_or(Value::Null); + if let Some(formula) = object.get("formula").and_then(Value::as_str) { + let formula = formula.strip_prefix('=').unwrap_or(formula); + check_formula(formula, path)?; + return Ok(CellUpdate { + value: Value::Null, + formula: Some(formula.to_string()), + style, + }); + } + let (value, formula, style) = match kind { + None => match &raw { + Value::String(text) if text.starts_with('=') && text.len() > 1 => { + check_formula(&text[1..], path)?; + (Value::Null, Some(text[1..].to_string()), style) + } + Value::Array(_) | Value::Object(_) => { + return Err(OfficeError::invalid(format!( + "{path}.value must be a string, number, or boolean" + ))) + } + _ => (raw, None, style), + }, + Some("text" | "string") => ( + match raw { + Value::Null => Value::Null, + Value::String(text) => Value::String(text), + other => Value::String(other.to_string()), + }, + None, + style, + ), + Some("number") => { + let number = match &raw { + Value::Number(_) => raw.clone(), + Value::String(text) => text + .trim() + .replace(',', "") + .parse::() + .ok() + .and_then(serde_json::Number::from_f64) + .map(Value::Number) + .ok_or_else(|| { + OfficeError::invalid(format!("{path}: `{text}` is not a number")) + })?, + _ => { + return Err(OfficeError::invalid(format!( + "{path}: type number needs a numeric value" + ))) + } + }; + (number, None, style) + } + Some("boolean" | "bool") => match raw { + Value::Bool(_) => (raw, None, style), + _ => { + return Err(OfficeError::invalid(format!( + "{path}: type boolean needs true or false" + ))) + } + }, + Some("date" | "datetime") => { + let text = raw.as_str().ok_or_else(|| { + OfficeError::invalid(format!( + "{path}: type date needs a string such as 2024-03-31" + )) + })?; + let (serial, has_time) = date_serial(text).ok_or_else(|| { + OfficeError::invalid(format!( + "{path}: `{text}` is not YYYY-MM-DD or YYYY-MM-DD HH:MM[:SS]" + )) + })?; + let mut style = style.unwrap_or_default(); + if style.number_format.is_none() { + style.number_format = Some( + if has_time { + "yyyy-mm-dd hh:mm" + } else { + "yyyy-mm-dd" + } + .to_string(), + ); + } + let number = serde_json::Number::from_f64(serial) + .map(Value::Number) + .ok_or_else(|| OfficeError::invalid(format!("{path}: invalid date")))?; + (number, None, Some(style)) + } + Some(other) => { + return Err(OfficeError::invalid(format!( + "{path}: unknown cell type `{other}`; use text, number, boolean, or date" + ))) + } + }; + Ok(CellUpdate { + value, + formula, + style, + }) +} + +/// Catches the most common formula slips before Excel reports a repair. +fn check_formula(formula: &str, path: &str) -> OfficeResult<()> { + let mut depth: i64 = 0; + let mut in_string = false; + for character in formula.chars() { + match character { + '"' => in_string = !in_string, + '(' if !in_string => depth += 1, + ')' if !in_string => { + depth -= 1; + if depth < 0 { + break; + } + } + _ => {} + } + } + if in_string { + return Err(OfficeError::invalid(format!( + "{path}: formula `={formula}` has an unterminated string" + ))); + } + if depth != 0 { + return Err(OfficeError::invalid(format!( + "{path}: formula `={formula}` has unbalanced parentheses" + ))); + } + if formula.len() > 8192 { + return Err(OfficeError::invalid(format!( + "{path}: formulas are limited to 8192 characters" + ))); + } + Ok(()) +} + +/// Excel serial date (1900 system) for `YYYY-MM-DD[ HH:MM[:SS]]`. +fn date_serial(text: &str) -> Option<(f64, bool)> { + let text = text.trim(); + let (date, time) = match text.split_once([' ', 'T']) { + Some((date, time)) => (date, Some(time)), + None => (text, None), + }; + let mut parts = date.split('-'); + let year: i64 = parts.next()?.parse().ok()?; + let month: i64 = parts.next()?.parse().ok()?; + let day: i64 = parts.next()?.parse().ok()?; + if parts.next().is_some() + || !(1900..=9999).contains(&year) + || !(1..=12).contains(&month) + || !(1..=31).contains(&day) + { + return None; + } + let leap_year = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + let days_in_month = match month { + 2 if leap_year => 29, + 2 => 28, + 4 | 6 | 9 | 11 => 30, + _ => 31, + }; + if day > days_in_month { + return None; + } + // Excel reserves serial 60 for its fictitious 1900-02-29. Real dates + // before March 1900 must not include that extra day. + let days = days_from_civil(year, month, day) - days_from_civil(1899, 12, 31) + + i64::from((year, month) >= (1900, 3)); + let mut fraction = 0.0; + if let Some(time) = time { + let mut pieces = time.trim_end_matches('Z').split(':'); + let hours: u32 = pieces.next()?.parse().ok()?; + let minutes: u32 = pieces.next()?.parse().ok()?; + let seconds: f64 = pieces.next().unwrap_or("0").parse().ok()?; + if pieces.next().is_some() + || hours >= 24 + || minutes >= 60 + || !(0.0..60.0).contains(&seconds) + { + return None; + } + fraction = (hours as f64 * 3600.0 + minutes as f64 * 60.0 + seconds) / 86400.0; + } + Some((days as f64 + fraction, time.is_some())) +} + +fn days_from_civil(year: i64, month: i64, day: i64) -> i64 { + let year = if month <= 2 { year - 1 } else { year }; + let era = if year >= 0 { year } else { year - 399 } / 400; + let yoe = year - era * 400; + let mp = (month + 9) % 12; + let doy = (153 * mp + 2) / 5 + day - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + era * 146_097 + doe - 719_468 +} + +/// Inserts or deletes rows/columns on one sheet and rewrites every +/// reference to it across the workbook. +fn shift_sheet( + book: &mut XlsxDocument, + index: usize, + axis: Axis, + at: u32, + delta: i64, +) -> OfficeResult<()> { + let limit = match axis { + Axis::Row => MAX_ROWS, + Axis::Column => MAX_COLUMNS, + }; + check_index(at, limit, if axis == Axis::Row { "row" } else { "column" })?; + if delta < 0 && at as i64 - delta - 1 > limit as i64 { + return Err(OfficeError::out_of_range( + "the deleted span runs past the sheet edge", + )); + } + let shift = Shift { + sheet: book.sheets[index].name.clone(), + axis, + at, + delta, + }; + let coordinate = |cell: &CellRef| match axis { + Axis::Row => cell.row, + Axis::Column => cell.col, + }; + let moved = |value: u32| -> Option { + if delta >= 0 { + if value >= at { + let shifted = value as i64 + delta; + return (shifted <= limit as i64).then_some(shifted as u32); + } + return Some(value); + } + let count = (-delta) as u32; + if value < at { + Some(value) + } else if value >= at + count { + Some(value - count) + } else { + None + } + }; + + let sheet = &mut book.sheets[index]; + if delta > 0 { + let overflow = sheet + .cells + .keys() + .any(|cell| coordinate(cell) >= at && coordinate(cell) as i64 + delta > limit as i64); + if overflow { + return Err(OfficeError::out_of_range( + "inserting would push cells past the sheet edge", + )); + } + } + let cells = std::mem::take(&mut sheet.cells); + for (cell, value) in cells { + let Some(new) = moved(coordinate(&cell)) else { + continue; + }; + let key = match axis { + Axis::Row => CellRef::new(new, cell.col), + Axis::Column => CellRef::new(cell.row, new), + }; + sheet.cells.insert(key, value); + } + let remap = |map: &mut BTreeMap| { + let old = std::mem::take(map); + for (key, value) in old { + if let Some(new) = moved(key) { + map.insert(new, value); + } + } + }; + match axis { + Axis::Row => remap(&mut sheet.row_heights), + Axis::Column => remap(&mut sheet.column_widths), + } + let sheet_name = sheet.name.clone(); + let shift_range = |text: &str| -> Option { + let shifted = shift_formula(text, &sheet_name, &shift); + (!shifted.contains("#REF!")).then_some(shifted) + }; + sheet.merges = sheet + .merges + .iter() + .filter_map(|merge| shift_range(merge)) + .filter(|merge| { + parse_range(merge) + .map(|range: CellRange| !range.is_single()) + .unwrap_or(false) + }) + .collect(); + sheet.autofilter = sheet.autofilter.as_deref().and_then(shift_range); + + for other in &mut book.sheets { + let host = other.name.clone(); + for cell in other.cells.values_mut() { + if let Some(formula) = &mut cell.formula { + *formula = shift_formula(formula, &host, &shift); + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn date_serials_match_excel() { + assert_eq!(date_serial("1900-01-01"), Some((1.0, false))); + assert_eq!(date_serial("1900-02-28"), Some((59.0, false))); + assert_eq!(date_serial("1900-03-01"), Some((61.0, false))); + assert_eq!(date_serial("2024-01-01"), Some((45292.0, false))); + let (serial, has_time) = date_serial("2024-01-01 12:00").unwrap(); + assert!(has_time); + assert!((serial - 45292.5).abs() < 1e-9); + assert_eq!(date_serial("2024-13-01"), None); + } + + #[test] + fn rejects_impossible_dates_and_malformed_times() { + for date in [ + "1900-02-29", + "2023-02-29", + "2024-04-31", + "2024-01-01 12:00:00:01", + "2024-01-01 12:00:60", + "2024-01-01 1.5:00", + ] { + assert_eq!(date_serial(date), None, "{date}"); + } + assert_eq!(date_serial("2024-02-29"), Some((45351.0, false))); + } + + #[test] + fn formula_check_catches_unbalanced_input() { + assert!(check_formula("SUM(A1:A3", "A4").is_err()); + assert!(check_formula("\"(\"&A1", "A4").is_ok()); + } +} diff --git a/src/crates/execution/office-documents/src/xlsx/render.rs b/src/crates/execution/office-documents/src/xlsx/render.rs new file mode 100644 index 0000000000..cca6c3355e --- /dev/null +++ b/src/crates/execution/office-documents/src/xlsx/render.rs @@ -0,0 +1,572 @@ +//! SpreadsheetML package writer. + +use super::address::{column_letters, parse_range, CellRef}; +use super::eval::{evaluate_workbook, Computed}; +use super::model::{ + BorderStyle, Cell, CellStyle, HorizontalAlign, Sheet, VerticalAlignment, XlsxDocument, +}; +use crate::common::parse_color; +use crate::error::OfficeResult; +use crate::package::{add_common_parts, ContentTypes, Parts, Relationships}; +use crate::xml::{esc, needs_preserve, XML_HEADER}; +use serde_json::Value; +use std::collections::HashMap; + +const NS_MAIN: &str = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; +const NS_REL: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; +const REL_WORKSHEET: &str = + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"; +const REL_STYLES: &str = + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"; +const REL_SHARED_STRINGS: &str = + "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings"; + +pub(crate) fn render( + book: &XlsxDocument, + created: Option<&str>, + modified: Option<&str>, +) -> OfficeResult { + let placeholder; + let sheets: &[Sheet] = if book.sheets.is_empty() { + placeholder = [Sheet { + name: "Sheet1".to_string(), + ..Sheet::default() + }]; + &placeholder + } else { + &book.sheets + }; + + let computed = evaluate_workbook(book); + let mut styles = StyleRegistry::new(); + let mut strings = SharedStrings::default(); + let mut parts = Parts::default(); + let mut types = ContentTypes::new(); + let mut rels = Relationships::default(); + let mut workbook_sheets = String::new(); + let mut defined_names = String::new(); + + for (index, sheet) in sheets.iter().enumerate() { + let number = index + 1; + let part = format!("xl/worksheets/sheet{number}.xml"); + let rel = rels.add(REL_WORKSHEET, &format!("worksheets/sheet{number}.xml")); + workbook_sheets.push_str(&format!( + "", + esc(&sheet.name) + )); + if let Some(range) = sheet + .autofilter + .as_deref() + .and_then(|range| parse_range(range).ok()) + { + defined_names.push_str(&format!( + "", + esc(&super::formula::quote_sheet_name(&sheet.name)), + absolute(&range.start, &range.end) + )); + } + types.part( + &part, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml", + ); + parts.add_xml( + part, + worksheet_xml(sheet, index, &computed, &mut styles, &mut strings), + ); + } + rels.add(REL_STYLES, "styles.xml"); + rels.add(REL_SHARED_STRINGS, "sharedStrings.xml"); + + let mut workbook = format!( + "{XML_HEADER}{workbook_sheets}" + ); + if !defined_names.is_empty() { + workbook.push_str(&format!("{defined_names}")); + } + workbook.push_str(""); + + types.part( + "xl/workbook.xml", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", + ); + types.part( + "xl/styles.xml", + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml", + ); + types.part( + "xl/sharedStrings.xml", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml", + ); + parts.add_xml("xl/workbook.xml", workbook); + parts.add_xml("xl/_rels/workbook.xml.rels", rels.xml()); + parts.add_xml("xl/styles.xml", styles.xml()); + parts.add_xml("xl/sharedStrings.xml", strings.xml()); + add_common_parts( + &mut parts, + &mut types, + "xl/workbook.xml", + &book.properties, + created, + modified, + "OpenBitFun GenOfficeFile", + ); + parts.add_xml("[Content_Types].xml", types.xml()); + Ok(parts) +} + +fn absolute(start: &CellRef, end: &CellRef) -> String { + format!( + "${}${}:${}${}", + column_letters(start.col), + start.row, + column_letters(end.col), + end.row + ) +} + +fn worksheet_xml( + sheet: &Sheet, + sheet_index: usize, + computed: &HashMap<(usize, CellRef), Computed>, + styles: &mut StyleRegistry, + strings: &mut SharedStrings, +) -> String { + let selected = sheet_index == 0; + let mut xml = format!("{XML_HEADER}"); + if let Some((rgb, _)) = sheet + .tab_color + .as_deref() + .and_then(|color| parse_color(color).ok()) + { + xml.push_str(&format!("")); + } + let dimension = match (sheet.cells.keys().next(), sheet.cells.keys().last()) { + (Some(_), Some(_)) => { + let min_col = sheet.cells.keys().map(|cell| cell.col).min().unwrap_or(1); + let max_col = sheet.cells.keys().map(|cell| cell.col).max().unwrap_or(1); + let min_row = sheet.cells.keys().map(|cell| cell.row).min().unwrap_or(1); + let max_row = sheet.cells.keys().map(|cell| cell.row).max().unwrap_or(1); + let start = CellRef::new(min_row, min_col); + let end = CellRef::new(max_row, max_col); + if start == end { + start.to_string() + } else { + format!("{start}:{end}") + } + } + _ => "A1".to_string(), + }; + xml.push_str(&format!("")); + xml.push_str(&format!( + "", + if selected { " tabSelected=\"1\"" } else { "" } + )); + if let Some(freeze) = sheet + .freeze + .filter(|freeze| freeze.rows > 0 || freeze.columns > 0) + { + let top_left = CellRef::new(freeze.rows + 1, freeze.columns + 1); + let pane = match (freeze.rows > 0, freeze.columns > 0) { + (true, true) => "bottomRight", + (true, false) => "bottomLeft", + _ => "topRight", + }; + xml.push_str(" 0 { + xml.push_str(&format!(" xSplit=\"{}\"", freeze.columns)); + } + if freeze.rows > 0 { + xml.push_str(&format!(" ySplit=\"{}\"", freeze.rows)); + } + xml.push_str(&format!( + " topLeftCell=\"{top_left}\" activePane=\"{pane}\" state=\"frozen\"/>" + )); + } + xml.push_str(""); + if !sheet.column_widths.is_empty() { + xml.push_str(""); + for (column, width) in &sheet.column_widths { + xml.push_str(&format!( + "", + number(*width), + if *width == 0.0 { " hidden=\"1\"" } else { "" } + )); + } + xml.push_str(""); + } + xml.push_str(""); + let mut rows: Vec = sheet.cells.keys().map(|cell| cell.row).collect(); + rows.extend(sheet.row_heights.keys().copied()); + rows.sort_unstable(); + rows.dedup(); + let mut cells = sheet.cells.iter().peekable(); + for row in rows { + xml.push_str(&format!(""); + } + xml.push_str(""); + if let Some(range) = sheet + .autofilter + .as_deref() + .and_then(|range| parse_range(range).ok()) + { + xml.push_str(&format!("")); + } + let merges: Vec = sheet + .merges + .iter() + .filter_map(|merge| parse_range(merge).ok()) + .map(|range| range.to_string()) + .collect(); + if !merges.is_empty() { + xml.push_str(&format!("", merges.len())); + for merge in merges { + xml.push_str(&format!("")); + } + xml.push_str(""); + } + xml.push_str(""); + xml +} + +fn number(value: f64) -> String { + if value.fract() == 0.0 && value.abs() < 1e15 { + format!("{}", value as i64) + } else { + format!("{value}") + } +} + +fn cell_xml( + address: &CellRef, + cell: &Cell, + computed: Option<&Computed>, + styles: &mut StyleRegistry, + strings: &mut SharedStrings, +) -> String { + let style = cell + .style + .as_ref() + .map(|style| styles.xf(style)) + .unwrap_or(0); + let style_attr = if style > 0 { + format!(" s=\"{style}\"") + } else { + String::new() + }; + if let Some(formula) = &cell.formula { + // Cached results let viewers that do not recalculate show values; + // Excel recomputes everything on open (fullCalcOnLoad). + let f = format!("{}", esc(formula)); + return match computed { + Some(Computed::Number(value)) => format!( + "{f}{}", + number(*value) + ), + Some(Computed::Empty) => format!("{f}0"), + Some(Computed::Text(text)) => format!( + "{f}{}", + esc(text) + ), + Some(Computed::Bool(value)) => format!( + "{f}{}", + u8::from(*value) + ), + Some(Computed::Error(error)) => format!( + "{f}{}", + esc(error) + ), + None => format!("{f}"), + }; + } + match &cell.value { + Value::Number(value) => format!( + "{}", + value + .as_f64() + .map(number) + .unwrap_or_else(|| value.to_string()) + ), + Value::Bool(value) => format!( + "{}", + u8::from(*value) + ), + Value::String(text) => { + let index = strings.index(text); + format!("{index}") + } + _ => format!(""), + } +} + +#[derive(Default)] +struct SharedStrings { + list: Vec, + map: HashMap, + count: usize, +} + +impl SharedStrings { + fn index(&mut self, text: &str) -> usize { + self.count += 1; + if let Some(index) = self.map.get(text) { + return *index; + } + let index = self.list.len(); + self.list.push(text.to_string()); + self.map.insert(text.to_string(), index); + index + } + + fn xml(&self) -> String { + let mut xml = format!( + "{XML_HEADER}", + self.count, + self.list.len() + ); + for text in &self.list { + if needs_preserve(text) || text.contains('\n') { + xml.push_str(&format!( + "{}", + esc(text) + )); + } else { + xml.push_str(&format!("{}", esc(text))); + } + } + xml.push_str(""); + xml + } +} + +/// Deduplicating registry of fonts, fills, borders, number formats, and +/// cell formats (`cellXfs`). +struct StyleRegistry { + fonts: Vec, + fills: Vec, + borders: Vec, + num_fmts: Vec<(u32, String)>, + xfs: Vec, + xf_index: HashMap, +} + +impl StyleRegistry { + fn new() -> Self { + Self { + fonts: vec![ + "" + .to_string(), + ], + fills: vec![ + "".to_string(), + "".to_string(), + ], + borders: vec!["".to_string()], + num_fmts: Vec::new(), + xfs: vec![ + "" + .to_string(), + ], + xf_index: HashMap::new(), + } + } + + fn intern(list: &mut Vec, xml: String) -> usize { + if let Some(index) = list.iter().position(|existing| *existing == xml) { + return index; + } + list.push(xml); + list.len() - 1 + } + + fn number_format(&mut self, code: &str) -> u32 { + let builtin = match code { + "General" | "general" => Some(0), + "0" => Some(1), + "0.00" => Some(2), + "#,##0" => Some(3), + "#,##0.00" => Some(4), + "0%" => Some(9), + "0.00%" => Some(10), + "0.00E+00" => Some(11), + "@" => Some(49), + _ => None, + }; + if let Some(id) = builtin { + return id; + } + if let Some((id, _)) = self.num_fmts.iter().find(|(_, existing)| existing == code) { + return *id; + } + let id = 164 + self.num_fmts.len() as u32; + self.num_fmts.push((id, code.to_string())); + id + } + + fn xf(&mut self, style: &CellStyle) -> u32 { + let font = { + let mut xml = String::from(""); + if style.bold == Some(true) { + xml.push_str(""); + } + if style.italic == Some(true) { + xml.push_str(""); + } + if style.strike == Some(true) { + xml.push_str(""); + } + if style.underline == Some(true) { + xml.push_str(""); + } + xml.push_str(&format!( + "", + number(style.font_size.unwrap_or(11.0)) + )); + if let Some((rgb, _)) = style + .font_color + .as_deref() + .and_then(|color| parse_color(color).ok()) + { + xml.push_str(&format!("")); + } + xml.push_str(&format!( + "", + esc(style.font_name.as_deref().unwrap_or("Calibri")) + )); + Self::intern(&mut self.fonts, xml) + }; + let fill = match style.fill_color.as_deref().and_then(|color| parse_color(color).ok()) { + Some((rgb, _)) => Self::intern( + &mut self.fills, + format!(""), + ), + None => 0, + }; + let border = match style.border.filter(|border| *border != BorderStyle::None) { + Some(border) => { + let kind = match border { + BorderStyle::Thin => "thin", + BorderStyle::Medium => "medium", + BorderStyle::Thick => "thick", + BorderStyle::Dashed => "dashed", + BorderStyle::Dotted => "dotted", + BorderStyle::Double => "double", + BorderStyle::None => "none", + }; + let color = style + .border_color + .as_deref() + .and_then(|color| parse_color(color).ok()) + .map(|(rgb, _)| format!("")) + .unwrap_or_else(|| "".to_string()); + let side = |name: &str| format!("<{name} style=\"{kind}\">{color}"); + Self::intern( + &mut self.borders, + format!( + "{}{}{}{}", + side("left"), + side("right"), + side("top"), + side("bottom") + ), + ) + } + None => 0, + }; + let num_fmt = style + .number_format + .as_deref() + .map(|code| self.number_format(code)) + .unwrap_or(0); + let mut alignment = String::new(); + if let Some(align) = style.align { + let value = match align { + HorizontalAlign::General => "general", + HorizontalAlign::Left => "left", + HorizontalAlign::Center => "center", + HorizontalAlign::Right => "right", + HorizontalAlign::Justify => "justify", + }; + alignment.push_str(&format!(" horizontal=\"{value}\"")); + } + if let Some(valign) = style.valign { + let value = match valign { + VerticalAlignment::Top => "top", + VerticalAlignment::Center => "center", + VerticalAlignment::Bottom => "bottom", + }; + alignment.push_str(&format!(" vertical=\"{value}\"")); + } + if style.wrap == Some(true) { + alignment.push_str(" wrapText=\"1\""); + } + if let Some(indent) = style.indent.filter(|indent| *indent > 0) { + alignment.push_str(&format!(" indent=\"{indent}\"")); + } + let mut xf = format!( + ""); + } else { + xf.push_str(&format!( + " applyAlignment=\"1\">" + )); + } + if let Some(index) = self.xf_index.get(&xf) { + return *index; + } + let index = self.xfs.len() as u32; + self.xfs.push(xf.clone()); + self.xf_index.insert(xf, index); + index + } + + fn xml(&self) -> String { + let mut xml = format!("{XML_HEADER}"); + if !self.num_fmts.is_empty() { + xml.push_str(&format!("", self.num_fmts.len())); + for (id, code) in &self.num_fmts { + xml.push_str(&format!( + "", + esc(code) + )); + } + xml.push_str(""); + } + let section = |tag: &str, items: &[String]| { + format!( + "<{tag} count=\"{}\">{}", + items.len(), + items.concat() + ) + }; + xml.push_str(§ion("fonts", &self.fonts)); + xml.push_str(§ion("fills", &self.fills)); + xml.push_str(§ion("borders", &self.borders)); + xml.push_str(""); + xml.push_str(§ion("cellXfs", &self.xfs)); + xml.push_str(""); + xml + } +} diff --git a/src/crates/execution/office-documents/src/xml.rs b/src/crates/execution/office-documents/src/xml.rs new file mode 100644 index 0000000000..1ce5eb71c0 --- /dev/null +++ b/src/crates/execution/office-documents/src/xml.rs @@ -0,0 +1,44 @@ +//! Minimal XML text helpers for the package writers. + +/// Escapes text for element content and attribute values, dropping the +/// control characters XML 1.0 cannot carry. +pub(crate) fn esc(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + for character in text.chars() { + match character { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + '\t' | '\n' | '\r' => out.push(character), + c if (c as u32) < 0x20 => {} + '\u{FFFE}' | '\u{FFFF}' => {} + c => out.push(c), + } + } + out +} + +/// Whether a text node needs `xml:space="preserve"` to keep its whitespace. +pub(crate) fn needs_preserve(text: &str) -> bool { + text.starts_with(char::is_whitespace) + || text.ends_with(char::is_whitespace) + || text.contains(" ") + || text.contains('\t') +} + +pub(crate) const XML_HEADER: &str = + "\n"; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn escapes_markup_and_drops_control_characters() { + assert_eq!(esc("a&\"c'\u{1}"), "a<b>&"c'"); + assert!(needs_preserve(" lead")); + assert!(!needs_preserve("plain text")); + } +} diff --git a/src/crates/execution/office-documents/tests/end_to_end.rs b/src/crates/execution/office-documents/tests/end_to_end.rs new file mode 100644 index 0000000000..8f0b0ab402 --- /dev/null +++ b/src/crates/execution/office-documents/tests/end_to_end.rs @@ -0,0 +1,465 @@ +//! End-to-end: build each format over several batches, reopen it, and check +//! that every XML part is well formed and carries the expected content. + +use openbitfun_office_documents::{ + collect_image_sources, Detail, ImageSources, OfficeDocument, OfficeErrorKind, OfficeFormat, + OpenOptions, ReadRequest, +}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::io::{Cursor, Read, Write}; + +// A complete PNG keeps exported samples suitable for real Office viewers. +fn sample_png() -> Vec { + include_bytes!("fixtures/chart.png").to_vec() +} + +fn entries(bytes: &[u8]) -> BTreeMap> { + let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).expect("zip"); + let mut out = BTreeMap::new(); + for index in 0..archive.len() { + let mut file = archive.by_index(index).expect("entry"); + let mut buffer = Vec::new(); + file.read_to_end(&mut buffer).expect("read"); + out.insert(file.name().to_string(), buffer); + } + out +} + +fn assert_well_formed(bytes: &[u8]) -> BTreeMap> { + let parts = entries(bytes); + for (name, content) in &parts { + if name.ends_with(".xml") || name.ends_with(".rels") { + let text = std::str::from_utf8(content).expect("utf8"); + roxmltree::Document::parse(text) + .unwrap_or_else(|err| panic!("{name} is not well formed: {err}")); + } + } + assert!(parts.contains_key("[Content_Types].xml")); + assert!(parts.contains_key("openbitfun/genoffice.json")); + parts +} + +fn text_of(parts: &BTreeMap>, name: &str) -> String { + String::from_utf8( + parts + .get(name) + .unwrap_or_else(|| panic!("missing {name}")) + .clone(), + ) + .unwrap() +} + +fn ops(value: Value) -> Vec { + value.as_array().cloned().unwrap() +} + +/// Writes samples for manual inspection when OFFICE_DOCUMENTS_SAMPLE_DIR is set. +fn keep_sample(name: &str, bytes: &[u8]) { + if let Ok(dir) = std::env::var("OFFICE_DOCUMENTS_SAMPLE_DIR") { + let path = std::path::Path::new(&dir).join(name); + std::fs::File::create(path) + .unwrap() + .write_all(bytes) + .unwrap(); + } +} + +#[test] +fn docx_built_incrementally_and_reopened() { + let mut doc = OfficeDocument::new( + OfficeFormat::Docx, + Some(&json!({"page": {"size": "a4", "margins_cm": {"left": 2.0, "right": 2.0}}, "styles": {"east_asia_font": "Microsoft YaHei"}})), + ) + .unwrap(); + doc.touch("2026-11-05T10:00:00Z"); + let mut images = ImageSources::new(); + images.insert("/tmp/chart.png".to_string(), sample_png()); + let first = ops(json!([ + {"op": "set_properties", "title": "季度报告", "author": "Agent"}, + {"op": "insert_blocks", "markdown": "# 季度报告\n\n[TOC]\n\n## 概览\n\n收入增长 **23%**,详见 [官网](https://example.com)。\n\n- 第一点\n- 第二点\n - 子项\n\n| 指标 | 数值 |\n|---|---:|\n| 收入 | 120 |\n\n![图表](/tmp/chart.png)"}, + {"op": "set_header_footer", "header": "内部资料", "footer": {"text": "第 {PAGE} 页 / 共 {NUMPAGES} 页", "align": "right"}} + ])); + assert_eq!(collect_image_sources(&first), vec!["/tmp/chart.png"]); + let report = doc.apply(&first, &images).unwrap(); + assert_eq!(report.applied, 3); + let bytes = doc.to_bytes().unwrap(); + keep_sample("sample.docx", &bytes); + let parts = assert_well_formed(&bytes); + let document = text_of(&parts, "word/document.xml"); + assert!(document.contains("季度报告")); + assert!(document.contains("w:numId")); + assert!(document.contains("TOC \\o")); + assert!(document.contains("")); + assert!(parts.keys().any(|name| name.starts_with("word/media/img-"))); + assert!(text_of(&parts, "word/footer1.xml").contains("NUMPAGES")); + + // Second call: reopen without the original image file and keep editing. + let mut reopened = OfficeDocument::open(&bytes, &OpenOptions::default()).unwrap(); + let outline = reopened.read(&ReadRequest::default()).unwrap(); + let total = outline["total_blocks"].as_u64().unwrap() as usize; + assert!(total >= 6); + reopened + .apply( + &ops(json!([ + {"op": "insert_blocks", "blocks": [ + {"type": "heading", "level": 2, "text": "风险"}, + {"type": "paragraph", "runs": [{"text": "汇率波动", "bold": true}, {"text": " 可能影响利润。"}], "align": "justify"}, + {"type": "page_break"}, + {"type": "table", "rows": [["A", "B"], [1, {"text": "x", "fill": "#FFF2CC", "colspan": 1}]], "column_widths_cm": [4, 6]} + ]}, + {"op": "replace_text", "find": "收入", "replace": "营收"}, + {"op": "move_blocks", "index": 0, "count": 1, "to": 1}, + {"op": "delete_blocks", "index": 1} + ])), + &ImageSources::new(), + ) + .unwrap(); + let bytes = reopened.to_bytes().unwrap(); + let parts = assert_well_formed(&bytes); + let document = text_of(&parts, "word/document.xml"); + assert!(document.contains("营收")); + assert!(document.contains("汇率波动")); + assert!(document.contains("w:type=\"page\"")); + // The picture embedded by the first call survived without its source file. + assert!(parts.keys().any(|name| name.starts_with("word/media/img-"))); + + let page = reopened + .read(&ReadRequest { + offset: Some(0), + limit: Some(2), + detail: Detail::Full, + ..ReadRequest::default() + }) + .unwrap(); + assert_eq!(page["blocks"].as_array().unwrap().len(), 2); + assert!(page["next_offset"].is_number()); +} + +#[test] +fn docx_batches_are_atomic_and_report_the_failing_operation() { + let mut doc = OfficeDocument::new(OfficeFormat::Docx, None).unwrap(); + doc.apply( + &ops(json!([{"op": "insert_blocks", "markdown": "hello"}])), + &ImageSources::new(), + ) + .unwrap(); + let error = doc + .apply( + &ops(json!([ + {"op": "insert_blocks", "markdown": "second"}, + {"op": "delete_blocks", "index": 9} + ])), + &ImageSources::new(), + ) + .unwrap_err(); + assert_eq!(error.kind, OfficeErrorKind::OutOfRange); + assert_eq!(error.operation_index, Some(1)); + let view = doc.read(&ReadRequest::default()).unwrap(); + assert_eq!( + view["total_blocks"], + json!(1), + "the failed batch must not leave partial edits" + ); + + let typo = doc + .apply(&ops(json!([{"op": "insert_blocks", "blocks": [{"type": "paragraph", "text": "x", "colour": "#000"}]}])), &ImageSources::new()) + .unwrap_err(); + assert!(typo.message.contains("colour"), "{}", typo.message); + let unknown = doc + .apply( + &ops(json!([{"op": "insert_block", "markdown": "x"}])), + &ImageSources::new(), + ) + .unwrap_err(); + assert!( + unknown.message.contains("insert_blocks"), + "{}", + unknown.message + ); +} + +#[test] +fn xlsx_rows_formulas_and_structure() { + let mut book = OfficeDocument::new(OfficeFormat::Xlsx, None).unwrap(); + book.apply( + &ops(json!([ + {"op": "add_sheet", "name": "Sales", "rows": [["Item", "Qty", "Price", "Total"], ["Apple", 2, 1.5, "=B2*C2"], ["Pear", 3, 2, "=B3*C3"]]}, + {"op": "append_rows", "sheet": "Sales", "rows": [["Sum", "=SUM(B2:B3)", null, "=SUM(D2:D3)"]]}, + {"op": "format_range", "sheet": "Sales", "range": "A1:D1", "style": {"bold": true, "fill_color": "#DDEBF7", "border": "thin"}}, + {"op": "format_range", "sheet": "Sales", "range": "C2:D4", "style": {"number_format": "#,##0.00"}}, + {"op": "set_column_widths", "sheet": "Sales", "widths": {"A": 16, "B:D": 12}}, + {"op": "freeze_panes", "sheet": "Sales", "rows": 1}, + {"op": "set_autofilter", "sheet": "Sales", "range": "A1:D3"}, + {"op": "add_sheet", "name": "Summary", "rows": [["Total", "=Sales!D4"], ["Date", {"value": "2024-03-31", "type": "date"}]]}, + {"op": "set_column_widths", "sheet": "Summary", "widths": {"A:B": 16}} + ])), + &ImageSources::new(), + ) + .unwrap(); + // Inserting a row above the totals shifts every reference to it. + book.apply( + &ops(json!([ + {"op": "insert_rows", "sheet": "Sales", "row": 3, "rows": [["Fig", 1, 4, "=B3*C3"]]}, + {"op": "merge_cells", "sheet": "Sales", "range": "A6:D6"}, + {"op": "rename_sheet", "sheet": "Sales", "name": "Sales 2024"} + ])), + &ImageSources::new(), + ) + .unwrap(); + let bytes = book.to_bytes().unwrap(); + keep_sample("sample.xlsx", &bytes); + let parts = assert_well_formed(&bytes); + let sheet1 = text_of(&parts, "xl/worksheets/sheet1.xml"); + assert!(sheet1.contains("SUM(B2:B4)"), "{sheet1}"); + assert!( + sheet1.contains("B4*C4"), + "the Pear row moved down: {sheet1}" + ); + assert!(sheet1.contains("state=\"frozen\"")); + assert!(sheet1.contains("")); + let sheet2 = text_of(&parts, "xl/worksheets/sheet2.xml"); + assert!( + sheet2.contains("'Sales 2024'!D5"), + "{sheet2}" + ); + assert!(sheet2.contains("45382"), "date serial: {sheet2}"); + assert!(text_of(&parts, "xl/workbook.xml").contains("fullCalcOnLoad")); + + let reopened = OfficeDocument::open(&bytes, &OpenOptions::default()).unwrap(); + let rows = reopened + .read(&ReadRequest { + sheet: Some("Sales 2024".to_string()), + limit: Some(2), + ..ReadRequest::default() + }) + .unwrap(); + assert_eq!(rows["rows"].as_array().unwrap().len(), 2); + assert_eq!(rows["next_offset"], json!(2)); + assert_eq!( + rows["rows"][1]["cells"][3], + json!({"formula": "=B2*C2", "value": 3.0}) + ); +} + +#[test] +fn pptx_slides_with_notes_tables_and_images() { + let mut deck = OfficeDocument::new( + OfficeFormat::Pptx, + Some(&json!({"theme": {"font": "Arial", "east_asia_font": "Microsoft YaHei"}})), + ) + .unwrap(); + let mut images = ImageSources::new(); + images.insert("/tmp/hero.png".to_string(), sample_png()); + deck.apply( + &ops(json!([ + {"op": "insert_slides", "slides": [ + {"title": "Cover", "background": "#0E1A2B", "notes": "Open with the 40% figure.", "elements": [ + {"type": "shape", "shape": "rect", "x": 0, "y": 0, "w": 520, "h": 720, "fill": "#1F3A5F"}, + {"type": "text", "x": 80, "y": 220, "w": 760, "h": 120, "text": "The 40% squeeze", "sizePt": 48, "bold": true, "color": "#FFFFFF"}, + {"type": "image", "url": "/tmp/hero.png", "x": 660, "y": 80, "w": 540, "h": 560} + ]}, + {"title": "Data", "elements": [ + {"type": "text", "x": 80, "y": 40, "w": 1120, "h": 70, "paragraphs": [{"runs": [{"text": "Where the margin went", "sizePt": 32, "bold": true}]}]}, + {"type": "table", "x": 80, "y": 140, "w": 1120, "h": 240, "rows": [["Cost", "Change"], ["Fuel", "+31%"], ["Wages", "+18%"]]}, + {"type": "shape", "shape": "lineArrow", "x": 80, "y": 420, "w": 400, "h": 0, "stroke": {"color": "#C00000", "widthPt": 2}}, + {"type": "text", "x": 80, "y": 460, "w": 300, "h": 30, "paragraphs": [{"text": "A long bullet that will not fit in this tiny box at all because it keeps going", "bullet": true}]} + ]} + ]} + ])), + &images, + ) + .map(|report| { + assert!(report.warnings.iter().any(|warning| warning.contains("text needs about")), "{:?}", report.warnings); + }) + .unwrap(); + let bytes = deck.to_bytes().unwrap(); + keep_sample("sample.pptx", &bytes); + let parts = assert_well_formed(&bytes); + let slide1 = text_of(&parts, "ppt/slides/slide1.xml"); + assert!(slide1.contains("The 40% squeeze")); + assert!(slide1.contains("")); + + let mut reopened = OfficeDocument::open(&bytes, &OpenOptions::default()).unwrap(); + let full = reopened + .read(&ReadRequest { + offset: Some(0), + limit: Some(1), + detail: Detail::Full, + ..ReadRequest::default() + }) + .unwrap(); + let image = &full["slides"][0]["elements"][2]; + assert!(image["asset"].as_str().unwrap().starts_with("img-")); + reopened + .apply( + &ops(json!([ + {"op": "update_slide", "index": 0, "update_elements": [{"index": 1, "color": "#FFD966"}], "remove_elements": [0]}, + {"op": "duplicate_slide", "index": 1}, + {"op": "move_slides", "index": 2, "to": 0}, + {"op": "delete_slides", "index": 2} + ])), + &ImageSources::new(), + ) + .unwrap(); + let view = reopened.read(&ReadRequest::default()).unwrap(); + assert_eq!(view["total_slides"], json!(2)); + assert_eq!(view["slides"][0]["label"], json!("Data")); + assert_eq!(view["slides"][1]["label"], json!("Cover")); + let parts = assert_well_formed(&reopened.to_bytes().unwrap()); + assert!(text_of(&parts, "ppt/slides/slide2.xml").contains("FFD966")); +} + +#[test] +fn xlsx_range_reads_are_paged_and_full_text_is_lossless() { + let mut book = OfficeDocument::new(OfficeFormat::Xlsx, None).unwrap(); + let long_text = "long cell text ".repeat(40); + let rows: Vec = (0..600).map(|_| json!([long_text])).collect(); + book.apply( + &[json!({"op": "add_sheet", "name": "Data", "rows": rows})], + &ImageSources::new(), + ) + .unwrap(); + let request = ReadRequest { + sheet: Some("Data".to_string()), + range: Some("A1:A600".to_string()), + detail: Detail::Full, + limit: Some(2), + ..ReadRequest::default() + }; + let page = book.read(&request).unwrap(); + assert_eq!(page["rows"].as_array().unwrap().len(), 2); + assert_eq!(page["rows"][0]["cells"][0], json!(long_text)); + assert_eq!(page["next_offset"], json!(2)); + let last = book + .read(&ReadRequest { + offset: Some(599), + ..request + }) + .unwrap(); + assert_eq!(last["rows"].as_array().unwrap().len(), 1); + assert_eq!(last["rows"][0]["row"], json!(600)); + assert!(last.get("next_offset").is_none()); +} + +#[test] +fn xlsx_insert_rows_cannot_overwrite_existing_rows() { + let mut book = OfficeDocument::new(OfficeFormat::Xlsx, None).unwrap(); + book.apply( + &[json!({"op": "add_sheet", "name": "Data", "rows": [["keep"]]})], + &ImageSources::new(), + ) + .unwrap(); + let before = book.to_bytes().unwrap(); + assert!(book + .apply( + &[json!({"op": "insert_rows", "row": 1, "count": 1, "rows": [["new"], ["overwrite"]]})], + &ImageSources::new() + ) + .is_err()); + assert_eq!(book.to_bytes().unwrap(), before); +} + +#[test] +fn external_changes_are_detected() { + let mut doc = OfficeDocument::new(OfficeFormat::Docx, None).unwrap(); + doc.apply( + &ops(json!([{"op": "insert_blocks", "markdown": "hello"}])), + &ImageSources::new(), + ) + .unwrap(); + let bytes = doc.to_bytes().unwrap(); + let mut parts = entries(&bytes); + let document = text_of(&parts, "word/document.xml").replace("hello", "edited elsewhere"); + parts.insert("word/document.xml".to_string(), document.into_bytes()); + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + for (name, content) in &parts { + writer + .start_file(name.as_str(), zip::write::SimpleFileOptions::default()) + .unwrap(); + writer.write_all(content).unwrap(); + } + let modified = writer.finish().unwrap().into_inner(); + let error = OfficeDocument::open(&modified, &OpenOptions::default()).unwrap_err(); + assert_eq!(error.kind, OfficeErrorKind::ExternallyModified); + assert!(OfficeDocument::open( + &modified, + &OpenOptions { + discard_external_changes: true + } + ) + .is_ok()); + + let foreign = { + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + writer + .start_file( + "word/document.xml", + zip::write::SimpleFileOptions::default(), + ) + .unwrap(); + writer.write_all(b"").unwrap(); + writer.finish().unwrap().into_inner() + }; + assert_eq!( + OfficeDocument::open(&foreign, &OpenOptions::default()) + .unwrap_err() + .kind, + OfficeErrorKind::NotGenerated + ); +} + +#[test] +fn unknown_fields_in_stored_documents_survive_a_round_trip() { + let mut deck = OfficeDocument::new(OfficeFormat::Pptx, None).unwrap(); + deck.apply( + &ops(json!([{"op": "insert_slides", "slides": [{"elements": [{"type": "text", "x": 10, "y": 10, "w": 200, "h": 40, "text": "hi"}]}]}])), + &ImageSources::new(), + ) + .unwrap(); + let bytes = deck.to_bytes().unwrap(); + // Simulate a newer writer that stored a field this version does not know. + let mut parts = entries(&bytes); + let mut source: Value = serde_json::from_slice(&parts["openbitfun/genoffice.json"]).unwrap(); + source["document"]["slides"][0]["future_field"] = json!({"kept": true}); + parts.insert( + "openbitfun/genoffice.json".to_string(), + serde_json::to_vec(&source).unwrap(), + ); + let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new())); + for (name, content) in &parts { + writer + .start_file(name.as_str(), zip::write::SimpleFileOptions::default()) + .unwrap(); + writer.write_all(content).unwrap(); + } + let bytes = writer.finish().unwrap().into_inner(); + let reopened = OfficeDocument::open(&bytes, &OpenOptions::default()).unwrap(); + let parts = entries(&reopened.to_bytes().unwrap()); + let source: Value = serde_json::from_slice(&parts["openbitfun/genoffice.json"]).unwrap(); + assert_eq!( + source["document"]["slides"][0]["future_field"], + json!({"kept": true}) + ); +} + +#[test] +fn image_sources_include_markdown_and_element_patches() { + let operations = ops(json!([ + {"op": "insert_blocks", "markdown": "![a](/abs/a.png)", "blocks": null}, + {"op": "insert_slides", "slides": [{"elements": [ + {"type": "image", "src": "/abs/b.png", "x": 0, "y": 0, "w": 10, "h": 10}, + {"type": "image", "asset": "img-00.png", "src": "/abs/gone.png", "x": 0, "y": 0, "w": 10, "h": 10}, + {"type": "text", "x": 0, "y": 0, "w": 10, "h": 10, "paragraphs": [{"runs": [{"text": "x", "url": "https://example.com"}]}]} + ]}]}, + {"op": "update_slide", "index": 0, "update_elements": [{"index": 0, "src": "/abs/c.png"}]}, + {"op": "insert_slides", "slides": [{"elements": [{"type": "image", "src": "data:image/png;base64,AAAA", "x": 0, "y": 0, "w": 1, "h": 1}]}]} + ])); + assert_eq!( + collect_image_sources(&operations), + vec!["/abs/a.png", "/abs/b.png", "/abs/c.png"] + ); +} diff --git a/src/crates/execution/office-documents/tests/fixtures/chart.png b/src/crates/execution/office-documents/tests/fixtures/chart.png new file mode 100644 index 0000000000..67672d2b6c Binary files /dev/null and b/src/crates/execution/office-documents/tests/fixtures/chart.png differ diff --git a/src/crates/execution/tool-provider-groups/Cargo.toml b/src/crates/execution/tool-provider-groups/Cargo.toml index c0247c9902..73773ac88b 100644 --- a/src/crates/execution/tool-provider-groups/Cargo.toml +++ b/src/crates/execution/tool-provider-groups/Cargo.toml @@ -18,11 +18,12 @@ browser-web = [] computer-use = [] image-analysis = [] image-generation = [] +office-documents = [] miniapp = [] pages = [] creation = [] agent-control = [] -product-full = ["basic", "git", "mcp", "browser-web", "computer-use", "image-analysis", "image-generation", "miniapp", "pages", "creation", "agent-control"] +product-full = ["basic", "git", "mcp", "browser-web", "computer-use", "image-analysis", "image-generation", "office-documents", "miniapp", "pages", "creation", "agent-control"] [lints] workspace = true diff --git a/src/crates/execution/tool-provider-groups/src/lib.rs b/src/crates/execution/tool-provider-groups/src/lib.rs index 0ff7b64563..051d2e2f68 100644 --- a/src/crates/execution/tool-provider-groups/src/lib.rs +++ b/src/crates/execution/tool-provider-groups/src/lib.rs @@ -16,6 +16,7 @@ pub enum ToolPackFeatureGroup { ComputerUse, ImageAnalysis, ImageGeneration, + OfficeDocuments, MiniApp, Pages, Creation, @@ -32,6 +33,7 @@ impl ToolPackFeatureGroup { Self::ComputerUse => "computer-use", Self::ImageAnalysis => "image-analysis", Self::ImageGeneration => "image-generation", + Self::OfficeDocuments => "office-documents", Self::MiniApp => "miniapp", Self::Pages => "pages", Self::Creation => "creation", @@ -48,6 +50,7 @@ pub const ALL_FEATURE_GROUPS: &[ToolPackFeatureGroup] = &[ ToolPackFeatureGroup::ComputerUse, ToolPackFeatureGroup::ImageAnalysis, ToolPackFeatureGroup::ImageGeneration, + ToolPackFeatureGroup::OfficeDocuments, ToolPackFeatureGroup::MiniApp, ToolPackFeatureGroup::Pages, ToolPackFeatureGroup::Creation, @@ -79,6 +82,10 @@ pub fn enabled_feature_groups() -> Vec { cfg!(feature = "image-generation"), ToolPackFeatureGroup::ImageGeneration, ), + ( + cfg!(feature = "office-documents"), + ToolPackFeatureGroup::OfficeDocuments, + ), (cfg!(feature = "miniapp"), ToolPackFeatureGroup::MiniApp), (cfg!(feature = "pages"), ToolPackFeatureGroup::Pages), (cfg!(feature = "creation"), ToolPackFeatureGroup::Creation), @@ -106,6 +113,7 @@ pub fn tool_feature_group(tool_name: &str) -> Option { "ComputerUse" => Some(ToolPackFeatureGroup::ComputerUse), "view_image" | "analyze_image" => Some(ToolPackFeatureGroup::ImageAnalysis), "generate_image" => Some(ToolPackFeatureGroup::ImageGeneration), + "GenOfficeFile" => Some(ToolPackFeatureGroup::OfficeDocuments), "GenerativeUI" | "InitMiniApp" | "FinalizeMiniApp" | "PublishMiniApp" | "MiniAppBrowser" | "PublishAppearance" | "Playbook" => { Some(ToolPackFeatureGroup::MiniApp) @@ -159,6 +167,7 @@ const CORE_BASIC_FEATURE_GROUPS: &[ToolPackFeatureGroup] = &[ ToolPackFeatureGroup::Basic, ToolPackFeatureGroup::ImageAnalysis, ToolPackFeatureGroup::ImageGeneration, + ToolPackFeatureGroup::OfficeDocuments, ]; const CORE_AGENT_FEATURE_GROUPS: &[ToolPackFeatureGroup] = &[ToolPackFeatureGroup::AgentControl]; const CORE_REVIEW_FEATURE_GROUPS: &[ToolPackFeatureGroup] = &[ToolPackFeatureGroup::AgentControl]; @@ -186,6 +195,7 @@ const PRODUCT_TOOL_PROVIDER_GROUP_PLAN: &[ToolProviderGroupPlan] = &[ "Write", "Edit", "Delete", + "GenOfficeFile", "ExecCommand", "WriteStdin", "ExecControl", @@ -357,6 +367,7 @@ mod tests { "computer-use", "image-analysis", "image-generation", + "office-documents", "miniapp", "pages", "creation", @@ -397,6 +408,10 @@ mod tests { groups.contains(&ToolPackFeatureGroup::ImageGeneration), cfg!(feature = "image-generation") ); + assert_eq!( + groups.contains(&ToolPackFeatureGroup::OfficeDocuments), + cfg!(feature = "office-documents") + ); assert_eq!( groups.contains(&ToolPackFeatureGroup::MiniApp), cfg!(feature = "miniapp") @@ -496,6 +511,10 @@ mod tests { ToolPackFeatureGroup::ImageGeneration.id(), "image-generation" ); + assert_eq!( + ToolPackFeatureGroup::OfficeDocuments.id(), + "office-documents" + ); assert_eq!(ToolPackFeatureGroup::MiniApp.id(), "miniapp"); assert_eq!(ToolPackFeatureGroup::Creation.id(), "creation"); assert_eq!(ToolPackFeatureGroup::AgentControl.id(), "agent-control"); @@ -546,6 +565,7 @@ mod tests { "Write", "Edit", "Delete", + "GenOfficeFile", "ExecCommand", "WriteStdin", "ExecControl", @@ -622,7 +642,12 @@ mod tests { vec![ ( "core.basic", - vec!["basic", "image-analysis", "image-generation"] + vec![ + "basic", + "image-analysis", + "image-generation", + "office-documents" + ] ), ("core.agent", vec!["agent-control"]), ("core.session", vec!["agent-control"]), diff --git a/src/crates/interfaces/acp/Cargo.toml b/src/crates/interfaces/acp/Cargo.toml index 5449422ba9..4f74aabb6f 100644 --- a/src/crates/interfaces/acp/Cargo.toml +++ b/src/crates/interfaces/acp/Cargo.toml @@ -36,6 +36,7 @@ server = [ "openbitfun-core/tools-computer-use", "openbitfun-core/tools-image-analysis", "openbitfun-core/tools-image-generation", + "openbitfun-core/tools-office-documents", "openbitfun-core/tools-agent-control", ] diff --git a/src/shared/interactive-capabilities/catalog.json b/src/shared/interactive-capabilities/catalog.json index 842b3c13eb..164dce4d18 100644 --- a/src/shared/interactive-capabilities/catalog.json +++ b/src/shared/interactive-capabilities/catalog.json @@ -4,6 +4,18 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "searchAcceptance": [ + { + "id": "native-office-generation", + "query": "GenOfficeFile", + "expectedFirstCapabilityId": "feature.ai-assistant", + "expectedCapabilityIds": [ + "feature.ai-assistant" + ], + "expectedItem": { + "capabilityId": "feature.ai-assistant", + "itemId": "office-document-generation" + } + }, { "id": "native-image-generation", "query": "generate_image", @@ -485,6 +497,31 @@ "source:src/crates/assembly/core/builtin_skills/generate-image/SKILL.md#generate_image" ] }, + { + "id": "office-document-generation", + "titleZh": "用 GenOfficeFile 创建并编辑 Word、Excel 和 PowerPoint 文件", + "titleEn": "Create and edit Word, Excel, and PowerPoint files with GenOfficeFile", + "control": { + "kind": "delegate", + "tools": [ + "GenOfficeFile" + ], + "workflowZh": [ + "先用 GenOfficeFile guide 读取格式指南,再通过 create 和 edit 分批生成或修改 .docx、.xlsx、.pptx 文件,无需安装 Office", + "用 read 分页查看文档结构;文件和引用图片通过当前工作区文件系统读写,支持本地或远程工作区", + "仅能继续编辑由该工具生成的文件;其他程序改过的内容默认拒绝覆盖,需要用户明确同意丢弃外部修改" + ], + "workflowEn": [ + "Read the format guide with GenOfficeFile guide, then use create and edit to build or revise .docx, .xlsx, and .pptx files in batches without installing Office", + "Use read to page through document structure; documents and referenced images use the active local or remote workspace filesystem", + "Only files generated by this tool can be reopened for editing; external changes are rejected by default and may be discarded only with the user's explicit agreement" + ] + }, + "evidence": [ + "source:src/crates/assembly/core/src/agentic/tools/implementations/gen_office_file_tool.rs#GenOfficeFile", + "source:src/crates/execution/office-documents/src/lib.rs#OfficeDocument" + ] + }, { "id": "turn-control", "titleZh": "开始、引导、打断、取消或恢复一次智能体运行", diff --git a/src/web-ui/AGENTS-CN.md b/src/web-ui/AGENTS-CN.md index 63ef81b844..5e8d84b893 100644 --- a/src/web-ui/AGENTS-CN.md +++ b/src/web-ui/AGENTS-CN.md @@ -80,6 +80,19 @@ pnpm run check:web `check:web` 会执行类型检查,以及 CI 使用的 Appearance contract、主题颜色和主题视觉治理门禁,确保渲染 DOM 或样式回归能在本地发现。完整 lint、build 与大范围测试由 CI 兜底,除非本地改动确实需要复现。 +能力目录条目及其全局搜索多语言标签使用以下聚焦检查: + +```bash +pnpm run capabilities:generate && pnpm run capabilities:check && pnpm run capabilities:test +pnpm run website:test +pnpm --dir src/web-ui run test:run src/app/global-search/providers/interactiveCapabilitySearchProvider.test.ts +pnpm run i18n:audit +``` + +新增目录条目还需在各语言的 `scenes/capabilities.json` 中补齐 `search.capabilities` +标签;目录生成器不会写入这些资源。共享搜索验收用例同时覆盖说明书网站和 Web UI, +并检查是否匹配到正确的子能力。 + 导航分割线拖拽、弹性反馈、取消操作与键盘调宽使用以下聚焦检查: ```bash diff --git a/src/web-ui/AGENTS.md b/src/web-ui/AGENTS.md index a44bf23f4b..a50a2017c9 100644 --- a/src/web-ui/AGENTS.md +++ b/src/web-ui/AGENTS.md @@ -112,6 +112,20 @@ deliberate layout transitions or animate virtualized content. Rely on CI for full lint, build, and broad test coverage unless the local change specifically needs it. +For capability catalog entries and their localized global-search labels: + +```bash +pnpm run capabilities:generate && pnpm run capabilities:check && pnpm run capabilities:test +pnpm run website:test +pnpm --dir src/web-ui run test:run src/app/global-search/providers/interactiveCapabilitySearchProvider.test.ts +pnpm run i18n:audit +``` + +Every new catalog item also needs a label under `search.capabilities` in each +locale's `scenes/capabilities.json`; the catalog generator does not write these +resources. The shared search acceptance corpus exercises both the Playbook and +Web UI, including the matched sub-capability. + For Agent creation, hidden internal IDs, editing, and surface-switch draft fences: ```bash diff --git a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json index c28ab14b20..caa51d800d 100644 --- a/src/web-ui/src/app/global-search/generated/interactive-capabilities.json +++ b/src/web-ui/src/app/global-search/generated/interactive-capabilities.json @@ -4,9 +4,21 @@ "title": "OpenBitFun Playbook", "origin": "https://playbook.openbitfun.com", "source": "src/shared/interactive-capabilities/catalog.json", - "digest": "eac1f9fc6338c11451dfeb8ff17123dad2d8de1f1339de27eeaa17cb22e5ff66", + "digest": "8a02be2b328791ebb823e4b7a956bf0371c523caa7f881a6c778cbaa42d72575", "ownerDigest": "31d6371f7765bde7bee88e22a6a4f03c2c5370e138cf49975bdc88f3c5eeb052", "searchAcceptance": [ + { + "id": "native-office-generation", + "query": "GenOfficeFile", + "expectedFirstCapabilityId": "feature.ai-assistant", + "expectedCapabilityIds": [ + "feature.ai-assistant" + ], + "expectedItem": { + "capabilityId": "feature.ai-assistant", + "itemId": "office-document-generation" + } + }, { "id": "native-image-generation", "query": "generate_image", @@ -175,10 +187,10 @@ "features": 22, "settings": 22, "userFacing": 44, - "documentedItems": 333, + "documentedItems": 334, "controlCoverage": { "direct": 63, - "delegated": 70, + "delegated": 71, "interactive": 200, "unsupported": 0 } @@ -231,6 +243,7 @@ "model-mode-permissions", "creative-frontend-authoring", "image-generation", + "office-document-generation", "turn-control", "permission-mailbox", "history-search", @@ -517,6 +530,51 @@ "sceneId": "session" } }, + { + "id": "feature.ai-assistant:delegate:office-document-generation", + "capabilityId": "feature.ai-assistant", + "itemIds": [ + "office-document-generation" + ], + "kind": "delegate", + "risk": "execute", + "executionHost": "workspaceHost", + "availability": { + "desktop": { + "available": true + }, + "cli": { + "available": true + }, + "peer": { + "available": true, + "requiredCapabilities": [ + "product_control_v1" + ] + }, + "remoteControl": { + "available": true + }, + "detachedDispatch": { + "available": true + } + }, + "inputSchema": { + "type": "object", + "additionalProperties": true + }, + "outputSchema": { + "type": "object", + "additionalProperties": true + }, + "delegateTools": [ + "GenOfficeFile" + ], + "presentationTarget": { + "kind": "scene", + "sceneId": "session" + } + }, { "id": "feature.ai-assistant:open:turn-control", "capabilityId": "feature.ai-assistant", @@ -20593,6 +20651,27 @@ ] } }, + { + "id": "office-document-generation", + "titleZh": "用 GenOfficeFile 创建并编辑 Word、Excel 和 PowerPoint 文件", + "titleEn": "Create and edit Word, Excel, and PowerPoint files with GenOfficeFile", + "control": { + "kind": "delegate", + "tools": [ + "GenOfficeFile" + ], + "workflowZh": [ + "先用 GenOfficeFile guide 读取格式指南,再通过 create 和 edit 分批生成或修改 .docx、.xlsx、.pptx 文件,无需安装 Office", + "用 read 分页查看文档结构;文件和引用图片通过当前工作区文件系统读写,支持本地或远程工作区", + "仅能继续编辑由该工具生成的文件;其他程序改过的内容默认拒绝覆盖,需要用户明确同意丢弃外部修改" + ], + "workflowEn": [ + "Read the format guide with GenOfficeFile guide, then use create and edit to build or revise .docx, .xlsx, and .pptx files in batches without installing Office", + "Use read to page through document structure; documents and referenced images use the active local or remote workspace filesystem", + "Only files generated by this tool can be reopened for editing; external changes are rejected by default and may be discarded only with the user's explicit agreement" + ] + } + }, { "id": "turn-control", "titleZh": "开始、引导、打断、取消或恢复一次智能体运行", @@ -20857,6 +20936,8 @@ "Extend client UI and runtime capabilities in Creative mode", "通过已配置的默认图像模型生成图片", "Generate images with the configured default image model", + "用 GenOfficeFile 创建并编辑 Word、Excel 和 PowerPoint 文件", + "Create and edit Word, Excel, and PowerPoint files with GenOfficeFile", "开始、引导、打断、取消或恢复一次智能体运行", "Start, steer, interrupt, cancel, or recover an agent turn", "查看并逐个或批量回答等待中的权限请求", @@ -20904,6 +20985,13 @@ "Use generate_image to create images from the user's description; omit service_id to use the configured default image model", "Specify count and size when needed and deliver the returned file paths; access remote workspace files through the active workspace data plane", "Report missing configuration, authentication failures, or quota limits explicitly without automatically switching services", + "GenOfficeFile", + "先用 GenOfficeFile guide 读取格式指南,再通过 create 和 edit 分批生成或修改 .docx、.xlsx、.pptx 文件,无需安装 Office", + "用 read 分页查看文档结构;文件和引用图片通过当前工作区文件系统读写,支持本地或远程工作区", + "仅能继续编辑由该工具生成的文件;其他程序改过的内容默认拒绝覆盖,需要用户明确同意丢弃外部修改", + "Read the format guide with GenOfficeFile guide, then use create and edit to build or revise .docx, .xlsx, and .pptx files in batches without installing Office", + "Use read to page through document structure; documents and referenced images use the active local or remote workspace filesystem", + "Only files generated by this tool can be reopened for editing; external changes are rejected by default and may be discarded only with the user's explicit agreement", "ListWorkspaces", "SessionControl", "SessionHistory", diff --git a/src/web-ui/src/infrastructure/api/generated/productControl.ts b/src/web-ui/src/infrastructure/api/generated/productControl.ts index ed606b263f..b5fcabf42a 100644 --- a/src/web-ui/src/infrastructure/api/generated/productControl.ts +++ b/src/web-ui/src/infrastructure/api/generated/productControl.ts @@ -1,5 +1,5 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. -export const PRODUCT_CONTROL_GRAPH_DIGEST = "eac1f9fc6338c11451dfeb8ff17123dad2d8de1f1339de27eeaa17cb22e5ff66" as const; +export const PRODUCT_CONTROL_GRAPH_DIGEST = "8a02be2b328791ebb823e4b7a956bf0371c523caa7f881a6c778cbaa42d72575" as const; export type ProductControlCapabilityId = "feature.ai-assistant" | "feature.agents" | "feature.personal-assistants" | "feature.projects" | "feature.files-editor" | "feature.terminal" | "feature.git" | "feature.code-review" | "feature.browser" | "feature.computer-use" | "feature.skills" | "feature.miniapps" | "feature.tasks-automation" | "feature.insights" | "feature.ecosystem-compatibility" | "feature.remote-workspaces" | "feature.remote-connect" | "feature.detached-dispatch" | "feature.pages" | "feature.voice-input" | "feature.desktop-pet" | "feature.desktop-cards" | "setting.application.general" | "setting.application.appearance" | "setting.application.pet" | "setting.application.input" | "setting.application.shortcuts" | "setting.application.development" | "setting.ai.models" | "setting.ai.memory" | "setting.workspace.session" | "setting.workspace.worktrees" | "setting.tools.execution" | "setting.application.terminal" | "setting.tools.desktop-control" | "setting.tools.browser-control" | "setting.tools.automation" | "setting.tools.web-search" | "setting.tools.mcp" | "setting.tools.acp" | "setting.data.usage" | "setting.data.archived" | "setting.data.diagnostics" | "feature.generative-ui"; diff --git a/src/web-ui/src/locales/en-US/scenes/capabilities.json b/src/web-ui/src/locales/en-US/scenes/capabilities.json index 6479cac75a..9879d075dc 100644 --- a/src/web-ui/src/locales/en-US/scenes/capabilities.json +++ b/src/web-ui/src/locales/en-US/scenes/capabilities.json @@ -43,6 +43,7 @@ "model-mode-permissions": "Choose the model, work mode, memory mode, and permission mode per session", "creative-frontend-authoring": "Extend client UI and runtime capabilities in Creative mode", "image-generation": "Generate images with the configured default image model", + "office-document-generation": "Create and edit Word, Excel, and PowerPoint files with GenOfficeFile", "turn-control": "Start, steer, interrupt, cancel, or recover an agent turn", "permission-mailbox": "Review and answer pending permission requests individually or in a batch", "history-search": "Page through, search, and backfill historical turns and session content", diff --git a/src/web-ui/src/locales/zh-CN/scenes/capabilities.json b/src/web-ui/src/locales/zh-CN/scenes/capabilities.json index 5a088348fd..46d6669244 100644 --- a/src/web-ui/src/locales/zh-CN/scenes/capabilities.json +++ b/src/web-ui/src/locales/zh-CN/scenes/capabilities.json @@ -43,6 +43,7 @@ "model-mode-permissions": "为会话选择模型、工作模式、记忆模式与权限模式", "creative-frontend-authoring": "让创造模式扩展客户端界面与运行时能力", "image-generation": "通过已配置的默认图像模型生成图片", + "office-document-generation": "用 GenOfficeFile 创建并编辑 Word、Excel 和 PowerPoint 文件", "turn-control": "开始、引导、打断、取消或恢复一次智能体运行", "permission-mailbox": "查看并逐个或批量回答等待中的权限请求", "history-search": "分页加载、搜索和回填历史消息与会话内容", diff --git a/src/web-ui/src/locales/zh-TW/scenes/capabilities.json b/src/web-ui/src/locales/zh-TW/scenes/capabilities.json index 48ce008660..031f490c00 100644 --- a/src/web-ui/src/locales/zh-TW/scenes/capabilities.json +++ b/src/web-ui/src/locales/zh-TW/scenes/capabilities.json @@ -43,6 +43,7 @@ "model-mode-permissions": "為工作階段選擇模型、工作模式、記憶模式與權限模式", "creative-frontend-authoring": "讓創造模式擴展客戶端界面與運行時能力", "image-generation": "透過已設定的預設圖像模型生成圖片", + "office-document-generation": "使用 GenOfficeFile 建立並編輯 Word、Excel 和 PowerPoint 檔案", "turn-control": "開始、引導、打斷、取消或恢復一次智能體運行", "permission-mailbox": "查看並逐個或批量回答等待中的權限請求", "history-search": "分頁加載、搜索和回填歷史消息與工作階段內容",