From 331eb3a5cb1257ac7277401db9b66a0ccf5b0025 Mon Sep 17 00:00:00 2001 From: Bob Lee Date: Fri, 6 Nov 2026 14:00:24 +0800 Subject: [PATCH] fix(office): improve tool contracts and multilingual document output --- .../implementations/gen_office_file_tool.rs | 166 +++++++++-- .../execution/office-documents/src/common.rs | 24 ++ .../office-documents/src/docx/render.rs | 6 + .../office-documents/src/guides/docx.md | 8 +- .../office-documents/src/guides/pptx.md | 35 ++- .../office-documents/src/guides/xlsx.md | 4 + .../execution/office-documents/src/lib.rs | 5 + .../src/operation_contract.rs | 231 +++++++++++++++ .../office-documents/src/pptx/model.rs | 20 +- .../office-documents/src/pptx/ops.rs | 37 ++- .../office-documents/src/pptx/render.rs | 45 ++- .../office-documents/tests/end_to_end.rs | 280 ++++++++++++++++++ 12 files changed, 821 insertions(+), 40 deletions(-) create mode 100644 src/crates/execution/office-documents/src/operation_contract.rs 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 index 338507925e..2b33e05b58 100644 --- 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 @@ -15,7 +15,8 @@ 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, + collect_image_sources, guide, operation_recovery_hint, operation_schema, + validate_operation_headers, Detail, ImageSources, OfficeDocument, OfficeError, OfficeFormat, OpenOptions, ReadRequest, }; use serde_json::{json, Value}; @@ -142,6 +143,7 @@ impl GenOfficeFileTool { { return Err("`sheet` and `range` only apply to .xlsx files".to_string()); } + validate_operation_headers(format, &operations).map_err(Self::office_error_message)?; Ok((action, format)) } @@ -170,10 +172,18 @@ impl GenOfficeFileTool { } } + fn office_error_message(error: OfficeError) -> String { + match error.operation.as_deref() { + Some(op) => format!( + "{error}. Nothing was written: the entire batch was rolled back (operation numbers are 0-based). {} Correct the input before retrying; use a smaller batch if indexes are uncertain.", + operation_recovery_hint(op) + ), + None => format!("{error}. The file was not changed. Use action=guide for the format's contract."), + } + } + 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." - )) + OpenBitFunError::tool(Self::office_error_message(error)) } /// Loads image files referenced by the operations through the workspace @@ -255,6 +265,10 @@ impl GenOfficeFileTool { format.as_str(), document.revision() ); + text.push_str("\nFile written; visual rendering was not performed by this tool."); + if format == OfficeFormat::Pptx { + text.push_str(" Layout warnings are geometric/text-size estimates."); + } if !changes.is_empty() { text.push_str("\nChanges:"); for change in changes.iter().take(30) { @@ -273,24 +287,26 @@ impl GenOfficeFileTool { } 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. + r#"Create and incrementally edit Word (.docx), Excel (.xlsx), and PowerPoint (.pptx) files directly, without scripts or an installed Office application. The extension selects the format. -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. +Workflow: call guide once for the format, create a first batch, then edit in small sections/slides/row chunks. Send text as ordinary Unicode strings; the tool writes UTF-8 XML. Do not manually re-encode, HTML-escape, or replace non-Latin characters. 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. +- guide: pass format (docx | xlsx | pptx) for fields, defaults and examples. +- create: absolute file_path, optional settings and operations. Existing files require explicit overwrite:true. +- edit: file_path and non-empty operations. For content corrections, replace/update in place; do not insert/delete/move just to replace content. +- read: file_path, offset/limit, detail:"full" for exact content and current indexes. XLSX accepts sheet and range (A1:D20); use next_offset to continue. + +Each operation is {op, ...fields}. Operations run in array order against the result of earlier operations. Block/slide/element indexes are 0-based and shift after insert/delete; move `to` is the position after removing the source. A failed batch writes nothing. Use the error's field/index guidance, read the target if uncertain, and send corrected input; do not repeat an unchanged failed call or replay a successful batch. -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. +Common edits: +- DOCX: insert_blocks {markdown} to append; replace_blocks {index, count?, markdown} to replace. +- XLSX: add_sheet {name, rows}; append_rows {sheet, rows}; set_cells {sheet, start, rows}; format_range {sheet, range, style}. +- PPTX: insert_slides {slides} to append; replace_slide {index, slide} to replace one complete slide; update_slide {index, update_elements:[{index, ...changed fields}]} for element patches (no nested op); update_slide {index, elements} to replace all elements while keeping slide metadata. Use set_theme for deck defaults. Canvas: 1280×720 px, or 960×720 for 4:3. -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. +PPTX warnings estimate text overflow and off-canvas geometry; read/audit is not visual rendering. If visual verification is needed, use an available renderer and report what was actually checked. An unavailable preview renderer does not prevent file generation. For CJK text, choose an east_asia_font available on the target viewer; language is inferred unless lang is supplied in the guide's supported locations. -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)."# +Images accept absolute workspace paths or data URLs (PNG/JPEG/GIF/BMP); download web images first. Reuse embedded asset names from read. Only files created by this tool are editable. External modifications are preserved by refusing edits; discard_external_changes:true explicitly rebuilds from the last embedded model and drops those modifications."# .to_string() } } @@ -329,17 +345,12 @@ impl Tool for GenOfficeFileTool { }, "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 - } + "description": "create/edit: ordered atomic batch. Each item needs op AND that operation's fields. Indexes refer to the state after preceding operations. Prefer in-place replacement for content edits.", + "items": operation_schema() }, "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.", + "description": "create only: document defaults. docx: page, styles, header, footer, properties. pptx: slide_size (16:9 | 4:3), theme {font, east_asia_font, text_color, lang?}, properties. xlsx: properties. lang is an optional BCP 47 override; omitted PPTX language follows the text.", "additionalProperties": true }, "overwrite": { @@ -373,6 +384,7 @@ impl Tool for GenOfficeFileTool { "counts": { "type": "object" }, "changes": { "type": "array", "items": { "type": "string" } }, "warnings": { "type": "array", "items": { "type": "string" } }, + "visual_rendered": { "type": "boolean" }, "view": { "type": "object" }, "guide": { "type": "string" } }, @@ -661,6 +673,7 @@ impl Tool for GenOfficeFileTool { "counts": document.summary(), "changes": report.changes, "warnings": report.warnings, + "visual_rendered": false, }), Some(text), )]) @@ -905,4 +918,109 @@ mod tests { ); assert_eq!(GenOfficeFileTool::parent_directory("a.pptx", true), None); } + + #[tokio::test] + async fn malformed_edits_return_actionable_feedback_before_workspace_access() { + // No workspace services: these failures must come from input validation, + // with enough information to repair the call without touching any file. + let tool = GenOfficeFileTool::new(); + let mut no_workspace = context(Arc::new(MemoryFs::default()), false); + no_workspace.workspace = None; + no_workspace.runtime_handles = ToolRuntimeHandles::new(None, None); + for (operation, expected) in [ + (json!({"op":"replace_slide"}), "index, slide"), + ( + json!({"op":"replace_slide","index":0,"slide":3}), + "complete slide object", + ), + ( + json!({"op":"update_slide","index":0,"update_elements":[{"index":0,"op":"replace","text":"New"}]}), + "no op", + ), + ( + json!({"op":"move_slides","index":-1,"to":0}), + "integer >= 0", + ), + ] { + let input = + json!({"action":"edit","file_path":"/docs/deck.pptx","operations":[operation]}); + let validation = tool.validate_input(&input, None).await; + assert!(!validation.result); + let message = validation.message.unwrap(); + assert!(message.contains(expected), "{message}"); + assert!(message.contains("Nothing was written"), "{message}"); + assert!(message.contains("Correct the input"), "{message}"); + let error = tool.call_impl(&input, &no_workspace).await.unwrap_err(); + assert!(error.to_string().contains(expected), "{error}"); + } + } + + #[cfg(unix)] + #[tokio::test] + async fn failed_slide_replacement_can_be_repaired_through_the_tool_on_local_and_remote_workspaces( + ) { + for remote in [false, true] { + let fs = Arc::new(MemoryFs::default()); + let context = context(fs.clone(), remote); + let tool = GenOfficeFileTool::new(); + let path = "/remote/workspace/out/recovery.pptx"; + let guide = data( + tool.call_impl(&json!({"action":"guide","format":"pptx"}), &context) + .await + .unwrap(), + ); + assert!(guide["guide"].as_str().unwrap().contains("replace_slide")); + let slide = |title: &str| { + json!({"title":title,"notes":"Keep notes","elements":[ + {"type":"text","x":40,"y":40,"w":900,"h":90,"size_pt":30,"text":title} + ]}) + }; + let created = data(tool.call_impl(&json!({"action":"create","file_path":path,"operations":[ + {"op":"insert_slides","slides":(0..9).map(|i|slide(&format!("Page {i}"))).collect::>()} + ]}), &context).await.unwrap()); + assert_eq!(created["visual_rendered"], false); + let saved = fs.files.lock().unwrap()[path].clone(); + for index in [4, 6] { + let failed = tool + .call_impl( + &json!({"action":"edit","file_path":path,"operations":[ + {"op":"insert_slides","slides":[slide("Replacement")]}, + {"op":"delete_slides","index":index}, + {"op":"move_slides","index":9,"to":index} + ]}), + &context, + ) + .await + .unwrap_err(); + let message = failed.to_string(); + assert!(message.contains("move_slides"), "{message}"); + assert!(message.contains("indexes 0..=8"), "{message}"); + assert!(message.contains("recalculate selectors"), "{message}"); + assert!(message.contains("replace_slide"), "{message}"); + assert_eq!(fs.files.lock().unwrap()[path], saved); + } + let repaired = data(tool.call_impl(&json!({"action":"edit","file_path":path,"operations":[ + {"op":"replace_slide","index":4,"slide":slide("待更新")}, + {"op":"update_slide","index":4,"update_elements":[{"index":0,"text":"四种模式,按任务选择协作方式"}]} + ]}), &context).await.unwrap()); + assert_eq!(repaired["revision"], 2); + assert_eq!(repaired["counts"]["slides"], 9); + assert_eq!(repaired["visual_rendered"], false); + let read = data( + tool.call_impl( + &json!({"action":"read","file_path":path,"offset":4,"limit":1,"detail":"full"}), + &context, + ) + .await + .unwrap(), + ); + let element = &read["view"]["slides"][0]["elements"][0]; + assert_eq!( + element["paragraphs"][0]["runs"][0]["text"], + "四种模式,按任务选择协作方式" + ); + assert_eq!(element["size_pt"], 30.0); + assert_eq!(read["view"]["slides"][0]["notes"], "Keep notes"); + } + } } diff --git a/src/crates/execution/office-documents/src/common.rs b/src/crates/execution/office-documents/src/common.rs index 7a447e97a1..3fae1dd82c 100644 --- a/src/crates/execution/office-documents/src/common.rs +++ b/src/crates/execution/office-documents/src/common.rs @@ -182,6 +182,9 @@ pub struct Run { pub size_pt: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub font: Option, + /// BCP 47 text language; omitted legacy runs keep automatic language selection. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub lang: Option, /// External hyperlink target (http, https, or mailto). #[serde(default, skip_serializing_if = "Option::is_none", alias = "url")] pub link: Option, @@ -198,6 +201,9 @@ impl Run { } pub fn validate(&self, path: &str) -> OfficeResult<()> { + if let Some(lang) = &self.lang { + validate_language(lang).map_err(|err| prefix(err, path, "lang"))?; + } if let Some(color) = &self.color { parse_color(color).map_err(|err| prefix(err, path, "color"))?; } @@ -218,6 +224,24 @@ impl Run { } } +/// A syntax check, not a locale allowlist: Office language tags are independent +/// of the product UI's supported locales. +pub(crate) fn validate_language(lang: &str) -> OfficeResult<()> { + let mut parts = lang.split('-'); + let primary = parts.next().unwrap_or_default(); + if (!(2..=8).contains(&primary.len()) && !matches!(primary, "x" | "X" | "i" | "I")) + || !primary.bytes().all(|c| c.is_ascii_alphabetic()) + || parts.any(|part| { + part.is_empty() || part.len() > 8 || !part.bytes().all(|c| c.is_ascii_alphanumeric()) + }) + { + return Err(OfficeError::invalid( + "use a BCP 47 language tag, such as en-US, zh-CN, zh-TW, ja-JP, or ko-KR", + )); + } + Ok(()) +} + impl UnknownFields for Run { fn unknown_fields(&self, path: &str, out: &mut Vec) { report_extra(&self.extra, path, out); diff --git a/src/crates/execution/office-documents/src/docx/render.rs b/src/crates/execution/office-documents/src/docx/render.rs index f23b555f0c..81c3cad923 100644 --- a/src/crates/execution/office-documents/src/docx/render.rs +++ b/src/crates/execution/office-documents/src/docx/render.rs @@ -309,6 +309,12 @@ impl Writer<'_> { } else if run.subscript == Some(true) { rpr.push_str(""); } + if let Some(lang) = &run.lang { + let lang = esc(lang); + rpr.push_str(&format!( + "" + )); + } let mut out = String::from(""); if !rpr.is_empty() { out.push_str(&format!("{rpr}")); diff --git a/src/crates/execution/office-documents/src/guides/docx.md b/src/crates/execution/office-documents/src/guides/docx.md index ed670f7856..cd3c3ec5b5 100644 --- a/src/crates/execution/office-documents/src/guides/docx.md +++ b/src/crates/execution/office-documents/src/guides/docx.md @@ -2,6 +2,8 @@ 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. +Pass ordinary Unicode text; do not manually transcode or pre-escape XML. The tool writes UTF-8. Choose fonts installed in the intended viewer; fonts are not embedded. File generation does not require an Office installation, and `read` is a model inspection, not a rendered page preview. + ## 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. @@ -19,7 +21,7 @@ Every block is an object with `type`. Text fields take either `text` (plain stri | `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). +**Run** fields: `text`, `bold`, `italic`, `underline`, `strike`, `code`, `superscript`, `subscript`, `color` (`#RRGGBB`), `highlight` (`#RRGGBB`), `size_pt`, `font`, `lang` (optional BCP 47 language, e.g. `zh-CN`), `link` (http/https/mailto URL). ### Markdown @@ -41,9 +43,11 @@ Every block is an object with `type`. Text fields take either `text` (plain stri 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. +Prefer `replace_blocks` for content corrections instead of insert/delete/move sequences. After failure, correct the named field/index; read the current target if uncertain. Do not repeat unchanged failed input or replay successful batches. + ## 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`). +`settings` may carry `page`, `styles`, `header`, `footer`, `properties` (same fields as above). Use the style defaults unless document requirements call for specific fonts; `styles.east_asia_font` sets the East Asian font. Font availability and substitution depend on the viewing environment, which may differ from the generation environment. ## Example diff --git a/src/crates/execution/office-documents/src/guides/pptx.md b/src/crates/execution/office-documents/src/guides/pptx.md index a6548a83ba..5f5d16d8c4 100644 --- a/src/crates/execution/office-documents/src/guides/pptx.md +++ b/src/crates/execution/office-documents/src/guides/pptx.md @@ -2,13 +2,26 @@ 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. +## Editing workflow + +- Append new pages with `insert_slides`. To rewrite a page, use `replace_slide` with **both `index` and `slide`**; no insert/delete/move sequence is needed. +- For a small correction, `read` the target with `detail: "full"`, then `update_slide` with its slide index and element patches. Each patch is `{index, ...changed fields}`, with **no nested `op`**. `text` replaces the old paragraphs; use `paragraphs` instead to retain rich run formatting. Do not supply both. +- Indexes are live within a batch: inserting or deleting slides shifts subsequent indexes. Recalculate later selectors against the resulting order. `move_slides.to` is measured after removing the moved pages. +- Failure leaves the whole batch unapplied. Correct the named field/index; if uncertain, read the current document and retry a smaller edit. Do not resend unchanged failed input or replay successful calls. + +## Text and fonts + +Pass ordinary Unicode text; do not manually transcode or pre-escape XML. The tool writes UTF-8. Set deck defaults at create with `settings.theme`, or later with `set_theme`: `{font, east_asia_font, text_color, lang}`. Use the theme defaults unless document requirements call for specific fonts. Fonts are not embedded; availability and substitution depend on the viewing environment, which may differ from the generation environment. + +`lang` is an optional BCP 47 override on the theme, text/shape element, paragraph, or run (most specific wins). Omit it for automatic selection: kana → `ja-JP`, Hangul → `ko-KR`, Han → `zh-CN`, otherwise `en-US`. Set the intended language explicitly when script alone is ambiguous, such as Traditional Chinese or Han-only Japanese/Korean. `font` on an element/run overrides its font; `theme.east_asia_font` supplies the theme's East Asian font. + ## 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. +Colors are `#RRGGBB` or `#RRGGBBAA` (alpha). Text-bearing elements accept `text` (string, `\n` = new paragraph) or `paragraphs`, plus element-level defaults `size_pt`, `bold`, `italic`, `color`, `font`, `lang`, `align`. Defaults apply only where a run/paragraph does not set its own value; changing element size/color/font does not override explicit values inside runs. **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. @@ -18,9 +31,9 @@ Colors are `#RRGGBB` or `#RRGGBBAA` (alpha). Text-bearing elements accept `text` **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}`. +**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, lang}`. -**Run** — `{text, size_pt, bold, italic, underline, strike, superscript, subscript, color, highlight, font, link}`. +**Run** — `{text, size_pt, bold, italic, underline, strike, superscript, subscript, color, highlight, font, lang, link}`. GenOffice spec spellings are accepted as aliases: `sizePt`, `lineSpacingPct`, `spaceBeforePt`, `spaceAfterPt`, `widthPt`, `flipH`, `flipV`, `url`. @@ -34,10 +47,22 @@ GenOffice spec spellings are accepted as aliases: `sizePt`, `lineSpacingPct`, `s | `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_theme` | `font`, `east_asia_font`, `text_color`, `lang` (null clears an override) | 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`. +After a batch the tool audits the touched slides and reports elements outside the canvas and text that likely overflows its box; fix relevant findings with `update_slide`. These are estimates, not rendered images. Visual verification is a separate step using an available viewer/renderer; report the environment actually checked. File generation does not require an installed Office application or renderer. + +### In-place edit examples + +```json +{"action":"edit","file_path":"/abs/deck.pptx","operations":[ + {"op":"replace_slide","index":2,"slide":{"title":"Summary","elements":[ + {"type":"text","x":80,"y":80,"w":1000,"h":100,"size_pt":32,"text":"Updated result"} + ]}} +]} +``` + +Then change only that text with `{"op":"update_slide","index":2,"update_elements":[{"index":0,"text":"Final result"}]}`. Slide index 2 and element index 0 are different selectors; get both from `read`. ## Design rules (from GenOffice's deck pipeline) diff --git a/src/crates/execution/office-documents/src/guides/xlsx.md b/src/crates/execution/office-documents/src/guides/xlsx.md index 69df0cf144..3c14d9a133 100644 --- a/src/crates/execution/office-documents/src/guides/xlsx.md +++ b/src/crates/execution/office-documents/src/guides/xlsx.md @@ -4,6 +4,8 @@ A workbook is a list of **sheets**; each sheet holds sparse cells addressed A1-s 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. +Pass ordinary Unicode text; do not manually transcode or pre-escape XML. The tool writes UTF-8. Use `style.font_name` for a font available in the target viewer; fonts are not embedded. File generation does not require an Office installation, and `read` is not a rendered workbook preview. + ## Cell values Rows are arrays of cell values: @@ -46,6 +48,8 @@ Formula results are computed and cached for arithmetic, comparisons, `&`, cell a 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. +Prefer `set_cells`/`format_range` for corrections instead of deleting/recreating sheets or rows. After failure, correct the named field/range; read the current sheet if uncertain. Do not repeat unchanged failed input or replay successful batches. + ## Example ```json diff --git a/src/crates/execution/office-documents/src/lib.rs b/src/crates/execution/office-documents/src/lib.rs index 0caa37af87..ae0373a8a1 100644 --- a/src/crates/execution/office-documents/src/lib.rs +++ b/src/crates/execution/office-documents/src/lib.rs @@ -15,6 +15,7 @@ pub mod docx; mod error; mod guide; pub mod image; +mod operation_contract; mod package; pub mod pptx; pub mod xlsx; @@ -22,6 +23,9 @@ mod xml; pub use error::{OfficeError, OfficeErrorKind, OfficeResult}; pub use guide::guide; +pub use operation_contract::{ + operation_recovery_hint, operation_schema, validate_operation_headers, +}; use common::{merge_patch, operation_name, UnknownFields}; use docx::DocxDocument; @@ -349,6 +353,7 @@ impl OfficeDocument { "a batch is limited to {MAX_OPERATIONS_PER_BATCH} operations; split it across calls" ))); } + validate_operation_headers(self.format(), operations)?; let mut model = self.model.clone(); let mut assets = self.assets.clone(); let mut ctx = ApplyContext { diff --git a/src/crates/execution/office-documents/src/operation_contract.rs b/src/crates/execution/office-documents/src/operation_contract.rs new file mode 100644 index 0000000000..d967778311 --- /dev/null +++ b/src/crates/execution/office-documents/src/operation_contract.rs @@ -0,0 +1,231 @@ +//! Compact tool-facing fields and IO-free operation preflight. +//! +//! Keep a flat schema: provider adapters may flatten unions by retaining only +//! the first variant's enum/fields. Format-specific parsing remains with each +//! document owner; this preflight catches missing selectors/content before IO. + +use crate::common::{operation_name, unknown_operation}; +use crate::{OfficeError, OfficeFormat, OfficeResult}; +use serde_json::{json, Value}; + +/// Common operation fields, with the full field reference supplied by `guide`. +/// Additional properties preserve format-specific fields and accepted aliases. +pub fn operation_schema() -> Value { + let mut names = Vec::new(); + for format in [OfficeFormat::Docx, OfficeFormat::Xlsx, OfficeFormat::Pptx] { + for name in format.operations() { + if !names.contains(name) { + names.push(*name); + } + } + } + json!({ + "type": "object", + "properties": { + "op": {"type": "string", "enum": names}, + "index": {"type": "integer", "minimum": 0, "description": "Current 0-based block/slide index. Required to replace/update/delete/move blocks or slides, and for duplicate_slide. Optional insertion position for insert_blocks, insert_slides, or add_sheet. Earlier operations in this batch shift indexes."}, + "count": {"type": "integer", "minimum": 1, "description": "Number of items; omit for the operation's default."}, + "to": {"type": "integer", "minimum": 0, "description": "Move destination after removing the source items; required for move operations."}, + "slide": {"type": "object", "description": "replace_slide: complete replacement slide {title?, background?, notes?, elements:[...]}; both index and slide are required.", "properties": { + "elements": {"type": "array", "items": {"type": "object", "additionalProperties": true}} + }, "additionalProperties": true}, + "slides": {"type": "array", "minItems": 1, "description": "insert_slides: complete slide objects. Omit index to append.", "items": {"type": "object", "additionalProperties": true}}, + "elements": {"type": "array", "description": "update_slide: replace all elements while keeping slide metadata. Do not combine with update/remove/append_elements.", "items": {"type": "object", "additionalProperties": true}}, + "update_elements": {"type": "array", "description": "update_slide: patches {index, ...changed element fields}. No nested op, patch, or replace field.", "items": { + "type": "object", "properties": { + "index": {"type": "integer", "minimum": 0}, + "text": {"type": "string"}, + "x": {"type": "number"}, "y": {"type": "number"}, + "w": {"type": "number"}, "h": {"type": "number"}, + "size_pt": {"type": "number"}, "color": {"type": "string"} + }, "required": ["index"], "additionalProperties": true + }}, + "remove_elements": {"type": "array", "items": {"type": "integer", "minimum": 0}}, + "append_elements": {"type": "array", "items": {"type": "object", "additionalProperties": true}}, + "markdown": {"type": "string", "description": "Word insert_blocks/replace_blocks content; use this or blocks."}, + "blocks": {"type": "array", "items": {"type": "object", "additionalProperties": true}}, + "sheet": {"description": "Excel sheet name (preferred) or 0-based index; omit only for a one-sheet workbook."}, + "name": {"type": "string", "description": "add_sheet/rename_sheet: sheet name."}, + "start": {"type": "string", "description": "Excel starting cell, e.g. A1."}, + "rows": {"description": "Excel: 2-D array of cell values; for freeze_panes only, a non-negative row count."}, + "row": {"type": "integer", "minimum": 1}, + "column": {"type": "string", "description": "Excel column letters, e.g. A."}, + "range": {"description": "Excel A1 range; set_autofilter also accepts null to clear it."}, + "style": {"type": "object", "additionalProperties": true}, + "font": {"type": "string"}, + "east_asia_font": {"type": "string"}, + "lang": {"type": "string", "description": "PPTX set_theme: optional BCP 47 language, e.g. zh-CN or zh-TW. Omit for automatic text-based selection."} + }, + "required": ["op"], + "additionalProperties": true + }) +} + +/// Required top-level fields. A `|` denotes existing aliases/alternatives. +/// Null optional values still reach the format parser unchanged. +fn required_fields(op: &str) -> &'static [&'static str] { + match op { + "insert_blocks" => &["blocks|markdown"], + "replace_blocks" => &["index", "blocks|markdown"], + "delete_blocks" | "delete_slides" | "duplicate_slide" | "update_slide" => &["index"], + "move_blocks" | "move_slides" => &["index", "to"], + "replace_text" => &["find", "replace"], + "insert_slides" => &["slides"], + "replace_slide" => &["index", "slide"], + "add_sheet" | "rename_sheet" => &["name"], + "move_sheet" => &["to"], + "set_cells" | "append_rows" => &["rows|values"], + "insert_rows" | "delete_rows" => &["row"], + "insert_columns" | "delete_columns" => &["column"], + "clear_range" | "merge_cells" | "unmerge_cells" => &["range"], + "format_range" => &["range", "style"], + "set_column_widths" => &["widths"], + "set_row_heights" => &["heights"], + _ => &[], + } +} + +/// Checks selectors and required payloads without reading files, images or +/// document state. Bounds and full payload validation run on the working copy. +pub fn validate_operation_headers(format: OfficeFormat, operations: &[Value]) -> OfficeResult<()> { + for (index, operation) in operations.iter().enumerate() { + let name = operation_name(operation).map_err(|err| err.at_operation(index, "?"))?; + let check = || -> OfficeResult<()> { + if !format.operations().contains(&name) { + return Err(unknown_operation(name, format.operations())); + } + let missing: Vec<_> = required_fields(name) + .iter() + .filter(|field| { + !field + .split('|') + .any(|key| operation.get(key).is_some_and(|value| !value.is_null())) + }) + .copied() + .collect(); + if !missing.is_empty() { + return Err(OfficeError::invalid(format!( + "{name} requires field(s): {}", + missing.join(", ") + ))); + } + for field in ["index", "to", "count"] { + if let Some(value) = operation.get(field).filter(|value| !value.is_null()) { + // Workbook operations historically normalize count=0 to 1. + let minimum = u64::from(field == "count" && format != OfficeFormat::Xlsx); + if !value.as_u64().is_some_and(|number| number >= minimum) { + return Err(OfficeError::invalid(format!( + "`{field}` must be an integer >= {minimum}" + ))); + } + } + } + if name == "replace_slide" && !operation["slide"].is_object() { + return Err(OfficeError::invalid( + "`slide` must be a complete slide object, not an index or array", + )); + } + if name == "update_slide" { + if let Some(patches) = operation.get("update_elements") { + let patches = patches.as_array().ok_or_else(|| { + OfficeError::invalid( + "`update_elements` must be an array of {index, ...changed fields}", + ) + })?; + for (patch_index, patch) in patches.iter().enumerate() { + if !patch + .get("index") + .is_some_and(|value| value.as_u64().is_some()) + { + return Err(OfficeError::invalid(format!("update_elements[{patch_index}] requires a non-negative integer `index`"))); + } + if patch.get("op").is_some() { + return Err(OfficeError::invalid(format!("update_elements[{patch_index}].op is not supported; put changed fields beside index, e.g. {{\"index\":0,\"text\":\"Updated text\"}}"))); + } + } + } + } + Ok(()) + }; + check().map_err(|err| err.at_operation(index, name))?; + } + Ok(()) +} + +/// Recovery advice keyed to the actual failed operation, not a loop counter. +pub fn operation_recovery_hint(op: &str) -> &'static str { + match op { + "replace_slide" => "Use {op:\"replace_slide\",index:,slide:}. This replaces the slide in place; no insert/delete/move is needed.", + "update_slide" => "Read the target slide with detail=full. Use {op:\"update_slide\",index:,update_elements:[{index:,...changed fields}]}; patches have no op. Or pass elements to replace the whole element list.", + "move_slides" => "Indexes use the state after earlier operations in this batch. Inserting or deleting slides shifts subsequent indexes; recalculate selectors against that order. `to` is measured after removing the moved slides. To replace content, use replace_slide with index and slide instead.", + "move_blocks" => "Indexes use the state after earlier operations in this batch; `to` is measured after removing the moved blocks. To replace content, prefer replace_blocks with index and blocks or markdown.", + _ => "Use action=guide for the format's exact fields; use action=read when the current target or index is uncertain.", + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ImageSources, OfficeDocument}; + + #[test] + fn preflight_preserves_legacy_aliases_and_optional_nulls() { + for (format, operations) in [ + ( + OfficeFormat::Docx, + vec![ + json!({"op":"insert_blocks","index":null,"blocks":null,"markdown":"中文"}), + json!({"op":"replace_blocks","index":0,"count":null,"markdown":"Updated"}), + ], + ), + ( + OfficeFormat::Xlsx, + vec![ + json!({"op":"add_sheet","name":"Data","values":[["中文"]]}), + json!({"op":"set_cells","anchor":"B1","values":[[2]]}), + json!({"op":"insert_rows","row":2,"count":0}), + ], + ), + ( + OfficeFormat::Pptx, + vec![ + json!({"op":"insert_slides","index":null,"slides":[{"elements":[]}]}), + json!({"op":"duplicate_slide","index":0,"to":null}), + json!({"op":"set_theme","lang":null}), + ], + ), + ] { + validate_operation_headers(format, &operations).unwrap(); + let mut document = OfficeDocument::new(format, None).unwrap(); + document.apply(&operations, &ImageSources::new()).unwrap(); + } + } + + #[test] + fn preflight_reports_the_specific_operation_and_missing_fields() { + for (operation, expected) in [ + (json!({"op":"replace_slide"}), "index, slide"), + ( + json!({"op":"replace_slide","index":0,"slide":null}), + "slide", + ), + ( + json!({"op":"update_slide","index":0,"update_elements":[{"text":"x"}]}), + "update_elements[0]", + ), + (json!({"op":"move_slides","index":1.5,"to":0}), "integer"), + ( + json!({"op":"replace_blocks","index":0,"markdown":"x"}), + "unknown operation", + ), + ] { + let error = validate_operation_headers( + OfficeFormat::Pptx, + &[json!({"op":"set_theme","font":"Arial"}), operation], + ) + .unwrap_err(); + assert_eq!(error.operation_index, Some(1)); + assert!(error.to_string().contains(expected), "{error}"); + } + } +} diff --git a/src/crates/execution/office-documents/src/pptx/model.rs b/src/crates/execution/office-documents/src/pptx/model.rs index 080006315b..fb5f979063 100644 --- a/src/crates/execution/office-documents/src/pptx/model.rs +++ b/src/crates/execution/office-documents/src/pptx/model.rs @@ -3,8 +3,8 @@ //! 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, + canonical_runs, parse_color, prefix, report_extra, report_list, runs_text, validate_language, + validate_runs, Align, DocumentProperties, Extra, Run, TableCell, UnknownFields, VerticalAlign, }; use crate::error::{OfficeError, OfficeResult}; use serde::{Deserialize, Serialize}; @@ -66,6 +66,9 @@ pub struct DeckTheme { /// Font for CJK text. #[serde(default, skip_serializing_if = "Option::is_none")] pub east_asia_font: Option, + /// Default text language; runs/elements may override it. Omitted means auto. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub lang: Option, /// Default text color. #[serde(default, skip_serializing_if = "Option::is_none")] pub text_color: Option, @@ -131,6 +134,8 @@ pub struct TextDefaults { #[serde(default, skip_serializing_if = "Option::is_none")] pub font: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + pub lang: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] pub align: Option, } @@ -365,6 +370,8 @@ struct ParagraphFull { color: Option, #[serde(default)] font: Option, + #[serde(default)] + lang: Option, #[serde(flatten)] extra: Extra, } @@ -388,6 +395,9 @@ impl From for Paragraph { if run.font.is_none() { run.font = full.font.clone(); } + if run.lang.is_none() { + run.lang = full.lang.clone(); + } } Paragraph { runs: full.runs, @@ -441,6 +451,9 @@ impl UnknownFields for Paragraph { impl TextDefaults { fn validate(&self, path: &str) -> OfficeResult<()> { + if let Some(lang) = &self.lang { + validate_language(lang).map_err(|err| prefix(err, path, "lang"))?; + } if let Some(color) = &self.color { parse_color(color).map_err(|err| prefix(err, path, "color"))?; } @@ -748,6 +761,9 @@ impl UnknownFields for PptxDocument { impl PptxDocument { pub fn validate_settings(&self) -> OfficeResult<()> { + if let Some(lang) = &self.theme.lang { + validate_language(lang).map_err(|err| prefix(err, "theme", "lang"))?; + } if let Some(color) = &self.theme.text_color { parse_color(color).map_err(|err| prefix(err, "theme", "text_color"))?; } diff --git a/src/crates/execution/office-documents/src/pptx/ops.rs b/src/crates/execution/office-documents/src/pptx/ops.rs index b7e9486572..6bb297cbdd 100644 --- a/src/crates/execution/office-documents/src/pptx/ops.rs +++ b/src/crates/execution/office-documents/src/pptx/ops.rs @@ -140,8 +140,28 @@ pub(crate) fn apply( .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(); + move_span(&mut deck.slides, span.clone(), to, "slide")?; + // Keep auditing edited/inserted slides after their positions change. + // Moving a slide must not discard that batch's layout findings. + ctx.touched = std::mem::take(&mut ctx.touched) + .into_iter() + .map(|index| { + if span.contains(&index) { + to + index - span.start + } else { + let after_removal = if index >= span.end { + index - span.len() + } else { + index + }; + if after_removal >= to { + after_removal + span.len() + } else { + after_removal + } + } + }) + .collect(); ctx.note(format!("moved slide(s) from {} to {to}", input.index)); Ok(()) } @@ -339,6 +359,19 @@ fn update_slide( } let mut current = serde_json::to_value(&slide.elements[target]) .map_err(|err| OfficeError::invalid(err.to_string()))?; + // Stored text is canonical paragraphs. A new plain-text value must + // replace them, otherwise canonicalize() silently keeps the old text. + if patch.get("text").is_some_and(Value::is_string) { + if patch.contains_key("paragraphs") { + return Err(OfficeError::invalid(format!( + "{path}: pass text or paragraphs, not both" + ))); + } + current + .as_object_mut() + .expect("serialized element object") + .remove("paragraphs"); + } crate::common::merge_patch(&mut current, &Value::Object(patch)); let mut updated = parse_element(¤t, &path)?; // A changed picture source must be embedded again. diff --git a/src/crates/execution/office-documents/src/pptx/render.rs b/src/crates/execution/office-documents/src/pptx/render.rs index 9b346759da..df60d8098b 100644 --- a/src/crates/execution/office-documents/src/pptx/render.rs +++ b/src/crates/execution/office-documents/src/pptx/render.rs @@ -76,7 +76,10 @@ pub(crate) fn render( 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("")), + notes_xml( + slide.notes.as_deref().unwrap_or(""), + deck.theme.lang.as_deref(), + ), ); parts.add_xml( format!("ppt/notesSlides/_rels/notesSlide{number}.xml.rels"), @@ -451,6 +454,10 @@ impl SlideWriter<'_> { } } let end = Run { + // The insertion point must use the paragraph's language too; an + // empty English end run can reintroduce the wrong font fallback. + text: paragraph.runs.iter().map(|run| run.text.as_str()).collect(), + lang: paragraph.runs.last().and_then(|run| run.lang.clone()), size_pt: Some(size), ..Run::default() }; @@ -460,7 +467,14 @@ impl SlideWriter<'_> { } fn run_properties(&mut self, run: &Run, defaults: &TextDefaults, tag: &str) -> String { - let mut attributes = String::from(" lang=\"en-US\""); + let lang = text_language( + &run.text, + run.lang + .as_deref() + .or(defaults.lang.as_deref()) + .or(self.deck.theme.lang.as_deref()), + ); + let mut attributes = format!(" lang=\"{}\"", esc(lang)); if let Some(size) = run.size_pt.or(defaults.size_pt) { attributes.push_str(&format!(" sz=\"{}\"", (size * 100.0).round() as i64)); } @@ -618,6 +632,7 @@ impl SlideWriter<'_> { .or_else(|| is_header.then(|| table.header_color.clone())) .or_else(|| table.text_color.clone()), font: table.font.clone(), + lang: None, align: cell.align, }; let paragraph = Paragraph { @@ -726,15 +741,35 @@ fn notes_master_xml() -> String { ) } -fn notes_xml(notes: &str) -> String { +/// PowerPoint uses the run language when choosing the script/font mapping. +/// Forcing en-US onto CJK text can display unrelated Latin glyphs even though +/// the XML is valid UTF-8. Han-only text defaults to Chinese; explicit `lang` +/// handles Traditional Chinese and Japanese/Korean text containing only Han. +fn text_language<'a>(text: &str, explicit: Option<&'a str>) -> &'a str { + if let Some(lang) = explicit { + return lang; + } + if text.chars().any(|c| matches!(c as u32, 0x3040..=0x30FF | 0x31F0..=0x31FF | 0xFF66..=0xFF9D | 0x1B000..=0x1B16F)) { + "ja-JP" + } else if text.chars().any(|c| matches!(c as u32, 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF | 0xFFA0..=0xFFDC)) { + "ko-KR" + } else if text.chars().any(|c| matches!(c as u32, 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF | 0x20000..=0x2FA1F | 0x30000..=0x323AF)) { + "zh-CN" + } else { + "en-US" + } +} + +fn notes_xml(notes: &str, default_lang: Option<&str>) -> String { let paragraphs: String = notes .split('\n') .map(|line| { + let lang = esc(text_language(line, default_lang)); if line.is_empty() { - "".to_string() + format!("") } else { format!( - "{}", + "{}", esc(line) ) } diff --git a/src/crates/execution/office-documents/tests/end_to_end.rs b/src/crates/execution/office-documents/tests/end_to_end.rs index 8f0b0ab402..5939c6dc16 100644 --- a/src/crates/execution/office-documents/tests/end_to_end.rs +++ b/src/crates/execution/office-documents/tests/end_to_end.rs @@ -463,3 +463,283 @@ fn image_sources_include_markdown_and_element_patches() { vec!["/abs/a.png", "/abs/b.png", "/abs/c.png"] ); } + +#[test] +fn pptx_failed_replacement_recovers_in_place_without_losing_text_or_audit() { + let images = ImageSources::new(); + let mut deck = OfficeDocument::new(OfficeFormat::Pptx, None).unwrap(); + let slide = |title: &str| { + json!({"title": title, "notes": "Keep these notes", "elements": [ + {"type":"text","x":40,"y":40,"w":800,"h":90,"size_pt":30,"text":title}, + {"type":"shape","shape":"rect","x":40,"y":160,"w":800,"h":90,"fill":"#EFEFEF","text":"Original card"} + ]}) + }; + deck.apply(&[json!({"op":"insert_slides","slides":(0..9).map(|i|slide(&format!("Page {i}"))).collect::>()})], &images).unwrap(); + let saved = deck.to_bytes().unwrap(); + // Same operation order/source index as the reported model call. + let error = deck + .apply( + &ops(json!([ + {"op":"insert_slides","slides":[slide("Replacement")]}, + {"op":"delete_slides","index":4}, + {"op":"move_slides","index":9,"to":4} + ])), + &images, + ) + .unwrap_err(); + assert_eq!(error.operation_index, Some(2)); + assert_eq!(error.kind, OfficeErrorKind::OutOfRange); + assert_eq!(deck.to_bytes().unwrap(), saved); + + let mut deck = OfficeDocument::open(&saved, &OpenOptions::default()).unwrap(); + deck.apply( + &ops(json!([ + {"op":"replace_slide","index":4,"slide":slide("Replaced")}, + {"op":"update_slide","index":4,"update_elements":[ + {"index":0,"text":"四种模式,按任务选择协作方式"}, + {"index":1,"text":"已更新卡片\nSecond line"} + ]} + ])), + &images, + ) + .unwrap(); + let parts = assert_well_formed(&deck.to_bytes().unwrap()); + let xml = text_of(&parts, "ppt/slides/slide5.xml"); + assert!(xml.contains("四种模式,按任务选择协作方式")); + assert!(xml.contains("已更新卡片")); + assert!(xml.contains("Second line")); + assert!(!xml.contains("Original card")); + assert!(!xml.contains("Replaced")); + let view = deck + .read(&ReadRequest { + offset: Some(4), + limit: Some(1), + detail: Detail::Full, + ..Default::default() + }) + .unwrap(); + assert_eq!(view["total_slides"], 9); + assert_eq!(view["slides"][0]["notes"], "Keep these notes"); + assert_eq!(view["slides"][0]["elements"][0]["size_pt"], 30.0); + + // Geometry findings must follow a newly inserted slide through delete/move. + let report = deck.apply(&ops(json!([ + {"op":"insert_slides","slides":[{"elements":[{"type":"text","x":1400,"y":40,"w":100,"h":90,"text":"Outside"}]}]}, + {"op":"delete_slides","index":4}, + {"op":"move_slides","index":8,"to":4} + ])), &images).unwrap(); + assert!( + report + .warnings + .iter() + .any(|w| w.contains("slide 4 element 0") && w.contains("extends past")), + "{:?}", + report.warnings + ); + // And follow an edited existing slide when a preceding block moves past it. + let report = deck + .apply( + &ops(json!([ + {"op":"update_slide","index":4,"update_elements":[{"index":0,"x":1500}]}, + {"op":"move_slides","index":0,"count":2,"to":7} + ])), + &images, + ) + .unwrap(); + assert!( + report + .warnings + .iter() + .any(|w| w.contains("slide 2 element 0") && w.contains("extends past")), + "{:?}", + report.warnings + ); +} + +#[test] +fn pptx_cjk_language_and_fonts_survive_export_reopen_and_edits() { + let mut deck = OfficeDocument::new( + OfficeFormat::Pptx, + Some(&json!({"theme":{"font":"Arial","east_asia_font":"PingFang SC"}})), + ) + .unwrap(); + let cases = [ + ("四种模式 & 🙂", None, "zh-CN"), + ("日本語の説明", None, "ja-JP"), + ("한국어 설명", None, "ko-KR"), + ("Plain English", None, "en-US"), + ("繁體中文", Some("zh-TW"), "zh-TW"), + ("日本漢字", Some("ja-JP"), "ja-JP"), + ]; + let elements: Vec<_> = cases + .iter() + .enumerate() + .map(|(i, (text, lang, _))| { + let mut element = + json!({"type":"text","x":40,"y":40+i*90,"w":1100,"h":80,"size_pt":28,"text":text}); + if let Some(lang) = lang { + element["lang"] = json!(lang); + } + element + }) + .collect(); + deck.apply( + &[json!({"op":"insert_slides","slides":[{"notes":"中文演讲备注","elements":elements}]})], + &ImageSources::new(), + ) + .unwrap(); + let bytes = deck.to_bytes().unwrap(); + keep_sample("cjk-languages.pptx", &bytes); + let reopened = OfficeDocument::open(&bytes, &OpenOptions::default()).unwrap(); + let parts = assert_well_formed(&reopened.to_bytes().unwrap()); + let xml = text_of(&parts, "ppt/slides/slide1.xml"); + let dom = roxmltree::Document::parse(&xml).unwrap(); + for (text, _, lang) in cases { + let t = dom + .descendants() + .find(|node| { + node.has_tag_name(("http://schemas.openxmlformats.org/drawingml/2006/main", "t")) + && node.text() == Some(text) + }) + .unwrap(); + let properties = t + .parent() + .unwrap() + .children() + .find(|n| n.tag_name().name() == "rPr") + .unwrap(); + assert_eq!(properties.attribute("lang"), Some(lang)); + // Preserve theme/script fallback; do not force a platform UI font onto + // every run just because it was supplied as a generic theme font. + assert!(!properties.children().any(|n| n.tag_name().name() == "ea")); + let end = t + .parent() + .unwrap() + .parent() + .unwrap() + .children() + .find(|n| n.tag_name().name() == "endParaRPr") + .unwrap(); + assert_eq!(end.attribute("lang"), Some(lang)); + } + let theme_xml = text_of(&parts, "ppt/theme/theme1.xml"); + let theme = roxmltree::Document::parse(&theme_xml).unwrap(); + for (script, expected) in [ + ("Hans", "等线"), + ("Hant", "新細明體"), + ("Jpan", "游ゴシック"), + ("Hang", "맑은 고딕"), + ] { + let font = theme + .descendants() + .find(|n| n.attribute("script") == Some(script)) + .unwrap(); + assert_eq!(font.attribute("typeface"), Some(expected)); + } + assert!(text_of(&parts, "ppt/notesSlides/notesSlide1.xml").contains("lang=\"zh-CN\"")); + + // Theme, element, paragraph and run language overrides retain precedence. + let mut edited = reopened; + edited.apply(&ops(json!([ + {"op":"set_theme","lang":"zh-TW"}, + {"op":"replace_slide","index":0,"slide":{"elements":[ + {"type":"text","x":40,"y":40,"w":1000,"h":80,"text":"主題語言"}, + {"type":"text","x":40,"y":140,"w":1000,"h":80,"lang":"zh-CN","paragraphs":[{"lang":"ja-JP","runs":[{"text":"漢字"},{"text":"繁體","lang":"zh-HK"}]}]}, + {"type":"table","x":40,"y":240,"w":600,"h":200,"rows":[[{"runs":[{"text":"한국어","lang":"ko-KR"}]}]]} + ]}} + ])), &ImageSources::new()).unwrap(); + let bytes = edited.to_bytes().unwrap(); + let reopened = OfficeDocument::open(&bytes, &OpenOptions::default()).unwrap(); + let parts = entries(&reopened.to_bytes().unwrap()); + let xml = text_of(&parts, "ppt/slides/slide1.xml"); + let dom = roxmltree::Document::parse(&xml).unwrap(); + for (text, lang) in [ + ("主題語言", "zh-TW"), + ("漢字", "ja-JP"), + ("繁體", "zh-HK"), + ("한국어", "ko-KR"), + ] { + let t = dom + .descendants() + .find(|n| n.tag_name().name() == "t" && n.text() == Some(text)) + .unwrap(); + assert_eq!( + t.parent() + .unwrap() + .children() + .find(|n| n.tag_name().name() == "rPr") + .unwrap() + .attribute("lang"), + Some(lang) + ); + } +} + +#[test] +fn legacy_pptx_without_language_fields_round_trips_and_renders_cjk() { + // Hand-authored version-1 payload: no new language fields, no current writer. + let legacy = br#"{"schema":"openbitfun.genoffice","version":1,"format":"pptx","revision":7,"document":{"slide_size":"16:9","theme":{"font":"Arial"},"slides":[{"title":"Legacy","elements":[{"type":"text","x":40,"y":40,"w":900,"h":90,"paragraphs":[{"runs":[{"text":"\u4e2d\u6587 Agent"}]}]}]}]}}"#; + let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); + zip.start_file( + "openbitfun/genoffice.json", + zip::write::SimpleFileOptions::default(), + ) + .unwrap(); + zip.write_all(legacy).unwrap(); + let old_bytes = zip.finish().unwrap().into_inner(); + let old = OfficeDocument::open(&old_bytes, &OpenOptions::default()).unwrap(); + assert_eq!(old.revision(), 7); + let read = ReadRequest { + detail: Detail::Full, + ..Default::default() + }; + let old_view = old.read(&read).unwrap(); + let bytes = old.to_bytes().unwrap(); + let reopened = OfficeDocument::open(&bytes, &OpenOptions::default()).unwrap(); + assert_eq!(reopened.read(&read).unwrap(), old_view); + let parts = assert_well_formed(&bytes); + assert!(text_of(&parts, "ppt/slides/slide1.xml").contains("lang=\"zh-CN\"")); + let source: Value = serde_json::from_slice(&parts["openbitfun/genoffice.json"]).unwrap(); + assert_eq!(source["version"], 1); + assert!(source["document"]["theme"].get("lang").is_none()); + assert!( + source["document"]["slides"][0]["elements"][0]["paragraphs"][0]["runs"][0] + .get("lang") + .is_none() + ); +} + +#[test] +fn unicode_text_is_preserved_in_word_and_excel_xml() { + let text = "中文、繁體、日本語、한국어 & 🙂"; + for (format, operations, part) in [ + ( + OfficeFormat::Docx, + vec![ + json!({"op":"insert_blocks","blocks":[{"type":"paragraph","runs":[{"text":text,"lang":"zh-CN"}]}]}), + ], + "word/document.xml", + ), + ( + OfficeFormat::Xlsx, + vec![json!({"op":"add_sheet","name":"数据","rows":[[text]]})], + "xl/sharedStrings.xml", + ), + ] { + let mut doc = OfficeDocument::new(format, None).unwrap(); + doc.apply(&operations, &ImageSources::new()).unwrap(); + let bytes = doc.to_bytes().unwrap(); + let reopened = OfficeDocument::open(&bytes, &OpenOptions::default()).unwrap(); + let parts = assert_well_formed(&reopened.to_bytes().unwrap()); + let xml = text_of(&parts, part); + let dom = roxmltree::Document::parse(&xml).unwrap(); + assert!( + dom.descendants() + .any(|n| n.tag_name().name() == "t" && n.text() == Some(text)), + "{xml}" + ); + if format == OfficeFormat::Docx { + assert!(xml.contains("w:lang w:val=\"zh-CN\"")); + } + } +}