commit d2fe8ddaaec5595a280a0e0668f7e370488e393c Author: GenOffice Date: Sun Aug 2 19:52:16 2026 +0800 Initial public release diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..6222db1 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,44 @@ +name: Bug report +description: Something is broken or behaves unexpectedly +labels: [bug] +body: + - type: dropdown + id: app + attributes: + label: App + description: Which part of the suite is affected? + options: + - GenOffice Docs (docs) + - GenOffice Sheets (sheets) + - GenOffice Slides (slides) + - GenOffice PDF (pdf) + - Shell / home screen + - AI panel / providers + - Build / packaging + - Other + validations: + required: true + - type: input + id: version + attributes: + label: Version and OS + description: App version (or commit) and operating system + placeholder: '0.1.0 on macOS 15.3 / Windows 11' + validations: + required: true + - type: textarea + id: what-happened + attributes: + label: What happened? + description: > + What did you do, what did you expect, and what happened instead? + If a document triggers the bug, attach a minimal sample file if + possible (please remove anything confidential first). + placeholder: Steps to reproduce, expected behavior, actual behavior. + validations: + required: true + - type: textarea + id: logs + attributes: + label: Logs / screenshots + description: Console output, stack traces, or screenshots, if any. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..5ef5267 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: true +contact_links: + - name: Security vulnerability + url: https://github.com/genspark-ai/genoffice/security/advisories/new + about: Please report security issues privately, never as a public issue. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..9936575 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,30 @@ +name: Feature request +description: Suggest a new capability or an improvement +labels: [enhancement] +body: + - type: dropdown + id: app + attributes: + label: App + options: + - GenOffice Docs (docs) + - GenOffice Sheets (sheets) + - GenOffice Slides (slides) + - GenOffice PDF (pdf) + - Shell / home screen + - AI panel / providers + - Whole suite + validations: + required: true + - type: textarea + id: problem + attributes: + label: Problem + description: What are you trying to do that is currently hard or impossible? + validations: + required: true + - type: textarea + id: proposal + attributes: + label: Proposed solution + description: How would you like it to work? Alternatives you considered are welcome too. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..084e5f3 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,27 @@ +## Summary + +- What changed? +- Why is this change needed? + +## Related issue + +Closes # + +## Validation + +- [ ] `npm run format:check` +- [ ] `npm run lint` +- [ ] `npm run typecheck` +- [ ] `npm test` + +List any checks not run and explain why: + +## Screenshots or recordings + +Include before/after evidence for visible changes, or write "Not applicable." + +## Contributor checklist + +- [ ] The change is focused and does not include unrelated reformatting or refactoring. +- [ ] User-facing strings use the existing i18n resources. +- [ ] File open/save changes include an appropriate round-trip or fidelity test. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e21274f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,86 @@ +name: CI + +# Test gate for every PR and push: changed-file formatting, lint, typecheck across +# all workspaces, and the full unit-test suite (engine packages and app tests; the +# sheets suite also runs the Rust xlsx-sidecar tests). Packaging/signing is handled +# by separate release automation — this workflow never builds installers. + +on: + push: + branches: [main, 'dev_*', 'release_*'] + pull_request: + branches: [main] + workflow_dispatch: + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm + cache-dependency-path: package-lock.json + + - name: Setup Rust + # SHA-pinned (third-party action); the ref no longer selects the + # toolchain, so it is passed explicitly. + uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable branch, 2026-07 + with: + toolchain: stable + + - name: Cache cargo (xlsx-sidecar) + uses: Swatinem/rust-cache@c19371144df3bb44fab255c43d04cbc2ab54d1c4 # v2.9.1 + with: + workspaces: apps/sheets/native/xlsx-engine + + - name: Install dependencies + run: npm ci + + - name: Check dependency licenses + run: npm run licenses + + - name: Check Rust dependency licenses (xlsx-sidecar) + uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1 + with: + command: check licenses + manifest-path: apps/sheets/native/xlsx-engine/Cargo.toml + + - name: Check formatting + env: + FORMAT_BASE_REF: ${{ github.event.pull_request.base.sha || github.event.before }} + # For PRs the checkout is the PR merge commit, so its first parent is the + # exact main revision the merge was built against. The event's base.sha can + # lag behind a fast-moving main, which pulls unrelated main-side files into + # the changed-file set and fails the check on files the PR never touched. + run: | + if [ "${{ github.event_name }}" = "pull_request" ]; then + FORMAT_BASE_REF=$(git rev-parse HEAD^1) + fi + npm run format:check + + - name: Lint + run: npm run lint + + - name: Typecheck + run: npm run typecheck + + - name: Regenerate test fixtures + run: npm run fixtures + + - name: Test + run: npm test diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..76f080e --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ +node_modules +out/ +dist/ +release/ +*.log +.DS_Store +.refs/ +.env +.env.* +electron-builder.env +~$* + +# Local ad-hoc e2e driver scripts (not pushed); the folder and README are tracked, the scripts are not +/scripts/drivers/driver.*.mjs +/probe*.mjs +/apps/shell/build/THIRD-PARTY-NOTICES.txt +/example/ +/.task/ +/docs-archive/ +.idea/ +.claude/ + +# Local build artifacts dropped in the repo root +/*.dmg +/*.exe +/*.zip +/windows/ + +.cursor/rules/git-remote.mdc +__pycache__/ +/notes/ +/MEMORY.md diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..209e3ef --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +20 diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..321cab5 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,15 @@ +node_modules/ +dist/ +out/ +release/ +.build/ +target/ +coverage/ + +# Generated artifacts and dependency-managed metadata. +package-lock.json +apps/*/build/ +apps/shell/build/THIRD-PARTY-NOTICES.txt + +# Local-only acceptance drivers are intentionally outside CI. +scripts/drivers/driver.*.mjs diff --git a/.prettierrc.json b/.prettierrc.json new file mode 100644 index 0000000..87edd93 --- /dev/null +++ b/.prettierrc.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://json.schemastore.org/prettierrc", + "semi": false, + "singleQuote": true, + "trailingComma": "all", + "printWidth": 100, + "endOfLine": "lf" +} diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..b5fb22c --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,74 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +- Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery, and sexual attention or advances + of any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, + without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for +moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement through the +repository's security advisory channel or the contact listed in +[SECURITY.md](SECURITY.md). All complaints will be reviewed and investigated +promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..10c283c --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,145 @@ +# Contributing to GenOffice + +Thanks for your interest in contributing. This document covers the local +setup, the checks a change must pass, and the conventions used in this +repository. + +## Repository layout + +- `apps/*` — the five Electron apps (docs, sheets, slides, pdf, shell). + Each app is an npm workspace with its own `src/main` (Electron main + process), `src/renderer` (React UI), and `tests/`. +- `packages/*` — pure TypeScript engine and shared packages (no Electron + dependency, unit-tested): docx/pptx engines, AI agent core, providers, + i18n, UI kit. +- `apps/sheets/native/xlsx-engine` — Rust xlsx engine (runs as a sidecar process) for xlsx import/export. + +## Getting started + +Prerequisites: Node 20+, npm 10+, and a Rust toolchain (`cargo` on PATH, +needed only for the sheets xlsx sidecar). + +```bash +npm install +npm run fixtures # generate test .docx fixtures (one-time, and after docx-engine changes) +npm run dev # all editors + shell against Vite dev servers +npm run dev:docs # or run a single app +``` + +## Checks every change must pass + +CI runs these on every PR; please run them locally first: + +```bash +npm run format:check # Prettier check for uncommitted changed/new files +npm run lint # ESLint across the repo (0 errors required; warnings allowed) +npm run typecheck # tsc --noEmit across every workspace +npm test # engine + app unit tests (also runs the Rust sidecar tests) +npm run licenses # production dependency licenses within the permissive allowlist +``` + +Formatting is intentionally incremental: existing files are not reformatted +unless they are part of your change. Run these exact commands before committing: + +```bash +npm run format # format uncommitted changed/new files +npm run format:check # verify uncommitted changed/new files +npm run format:check -- --base origin/main # verify committed files on your branch +``` + +CI supplies the PR or push base automatically and checks only files changed from +that base. This keeps the formatter gate useful without creating a repository-wide +formatting diff. + +## Building installers + +```bash +npm run dist:mac -w @genoffice/shell # dmg + zip +npm run dist:win -w @genoffice/shell # nsis installer +``` + +Without Apple or Windows signing credentials in the environment these produce +unsigned artifacts: code signing and notarization are skipped with a warning +rather than failing. That is the expected result for a contributor build. + +`dist:win` additionally expects the xlsx sidecar at the MinGW cross-compilation +path. Building on Windows leaves it under the MSVC target instead, so stage it +first: + +```bash +cargo build --release --target x86_64-pc-windows-gnu # from apps/sheets/native/xlsx-engine +``` + +or copy an existing `target/release/xlsx-sidecar.exe` to +`target/x86_64-pc-windows-gnu/release/`. + +## Environment variables + +None are required — the apps run with all of these unset. They exist for +testing and local overrides: + +| Variable | Effect | +| -------------------------------------------------------- | ---------------------------------------------------------------------- | +| `GENOFFICE_USER_DATA` | Override the Electron userData directory (test isolation) | +| `GENOFFICE_LANG` | Force the UI language instead of following the OS locale | +| `GENOFFICE_FAKE_UPDATE` | Exercise the updater UI without a real release feed | +| `GENOFFICE_CLOUD_SLIDE`, `GENOFFICE_CLOUD_SLIDE_TIER` | Route slide generation through the cloud endpoint | +| `GSK_API_KEY`, `GSK_CLI_PATH` | Genspark credentials / CLI location for the built-in AI provider | +| `AI_SEARCH_DISABLE_GSK`, `SERPER_API_KEY` | Disable the gsk search backend / supply a Serper key instead | +| `XLSX_SIDECAR_PATH`, `XLSX_OPEN_PATH`, `XLSX_DEBUG_PORT` | Point at a locally built xlsx sidecar and its debug port | +| `*_DEV_PORT`, `*_RENDERER_URL` | Per-app Vite dev server ports and renderer URLs (set by `npm run dev`) | + +AI features degrade rather than break without credentials: requests surface an +inline sign-in prompt, and web search falls back to a keyless backend. + +## Coding conventions + +- **English only** in code, comments, commit messages, and docs. User-facing + strings go through the i18n resources (`src/renderer/i18n/`, plus the inline + main-process dictionaries in `src/main/`), which are the only places + non-English text belongs (plus test fixture text). +- TypeScript everywhere; avoid adding new `any` surfaces where a precise type + is cheap. +- Tests live in `apps/*/tests` and `packages/*/tests` (vitest). New engine + behavior needs a unit test; renderer-only UI tweaks generally don't. +- Local Playwright/Electron acceptance drivers belong in `scripts/drivers/` + (gitignored, excluded from CI) — see `scripts/drivers/README.md`. +- The Word-fidelity scripts (`scripts/docs-word-fidelity.mjs`, + `scripts/pagination-baseline-word.mjs`) need macOS with Microsoft Word + installed and AppleScript automation permission granted; they are optional + local tools and never run in CI. +- Keep files from growing without bound: if you are adding a substantial new + concern to an already-large file, prefer a new module. + +## Commit and PR guidelines + +- Small, focused commits with imperative English subject lines + (e.g. `fix docx table border round-trip`, `add slides chart legend parsing`). +- A PR should explain _why_ the change is needed, and mention which of the + checks above you ran. +- File format fidelity is the core product promise: for changes touching + open/save paths (docx/xlsx/pptx), include a round-trip test proving + untouched content survives byte-for-byte. + +## Reporting bugs and requesting features + +Use the issue templates. For suspected security issues, do **not** open a +public issue — follow [SECURITY.md](SECURITY.md). + +## Code of conduct + +All community spaces follow the +[Contributor Covenant](CODE_OF_CONDUCT.md); participation implies acceptance. + +## License and CLA + +There is no CLA (contributor license agreement), and we do not plan to add +one. By contributing, you agree that your contributions are licensed under +the [Apache License 2.0](LICENSE) that covers this project — inbound = +outbound, per Apache-2.0 §5. Because community contributions keep their +Apache-2.0 terms, the open-source core cannot be retroactively relicensed. + +The `ee/` directory is reserved for future enterprise modules under a +[separate license](ee/LICENSE) and does not accept external contributions — +pull requests from outside the maintainer team must not modify files under +`ee/` (enforced via [CODEOWNERS](.github/CODEOWNERS)). diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3017411 --- /dev/null +++ b/LICENSE @@ -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/NOTICE b/NOTICE new file mode 100644 index 0000000..dc4dcf7 --- /dev/null +++ b/NOTICE @@ -0,0 +1,14 @@ +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2c3bedd --- /dev/null +++ b/README.md @@ -0,0 +1,99 @@ +# GenOffice + +An AI-native office suite for macOS and Windows: word processor, spreadsheet, +presentations, and PDF — five Electron apps sharing one engine layer, built +around AI editing as a first-class workflow rather than a bolted-on chat box. + +## Apps + +| App | Product | What it is | +| ------------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `apps/docs` | **GenOffice Docs** | `.docx` word processor. Byte-preserving round trip: only dirty paragraphs are regenerated (paragraph patch), everything else in the original file is kept byte-for-byte, so opening and saving never breaks layout in Word. Paginated view whose line metrics reproduce the original document's layout, tracked changes, comments, styles, equations, ink. | +| `apps/sheets` | **GenOffice Sheets** | `.xlsx` spreadsheet. UI built on the open-source [Univer](https://github.com/dream-num/univer) core (Apache-2.0) with a large layer of in-house extensions; xlsx import/export runs through an in-house Rust sidecar (calamine + IronCalc), charts are rendered in-house (Konva), plus pivot tables, slicers, conditional formatting, and formula tracing. | +| `apps/slides` | **GenOffice Slides** | `.pptx` presentations. In-house pptx parse/render/edit engine with masters, charts, cropping, ink, and text shaping (HarfBuzz metrics). | +| `apps/pdf` | **GenOffice PDF** | PDF viewer/editor on pdf.js + pdf-lib: annotations, forms, outlines, stamps, signatures, page operations, print. | +| `apps/shell` | **GenOffice** | The suite shell: home screen, tabbed hosting of the four editors, auto-update. | + +Every app embeds the same AI panel: block-granular AI editing with version +snapshots and diffs in docs, a tool-calling agent over workbook/slide/PDF +state in the others. + +**AI providers.** The apps sign in to a Genspark account and route model +calls through the Genspark service side; no model API key is stored locally. + +## Engine packages + +All pure TypeScript, unit-tested, no Electron dependency: + +- `packages/docx-engine` — docx parsing → block tree (with `docxIndex` anchors + - passthrough), OOXML fragment generation, byte-level paragraph patching. +- `packages/pptx-engine` / `packages/pptx-render` — pptx model and rendering. +- `packages/file-parse` — text extraction for AI attachments (office formats, + text formats). +- `packages/agent-core` — the AI agent loop and skill composition shared by + every app. +- `packages/ai-provider` — provider abstraction and streaming for the model + backends. +- `packages/ai-search` — Genspark auth + web/image search tools. +- `packages/i18n`, `packages/ui`, `packages/project-store`, + `packages/electron-utils` — shared i18n core, React UI kit, recent-files + store, and Electron main-process helpers. + +## Development + +```bash +npm install +npm run fixtures # generate test .docx fixtures +npm test # engine + app unit tests (docs/sheets/slides need no display) +npm run typecheck # tsc --noEmit across every workspace +npm run dev # all four editors + shell against Vite dev servers +npm run dev:docs # a single app (same pattern works per workspace) +npm run dist:mac # package macOS dmg (regenerates third-party notices) +npm run dist:win # package Windows nsis installer +``` + +The sheets app additionally needs a Rust toolchain for its xlsx sidecar +(`cargo` on PATH); `npm run build -w @genoffice/sheets` compiles it +automatically. + +Local UI/e2e driver scripts (Playwright + Electron, for local acceptance, not +committed by default) live in [`scripts/drivers/`](scripts/drivers/README.md). + +## Architecture notes (docx round trip) + +``` +open docx ─► archive original by hash (never touched) + ─► docx-engine parses word/document.xml top-level elements (w:p / w:tbl / …) + ─► Block tree, each block anchored by docxIndex + original XML slice + ─► TipTap streaming editor (manual + AI editing, dirty tracking) +save ─► dirty blocks → OOXML fragments (referencing existing styles only) + ─► splice into original document.xml (untouched blocks keep original bytes) + ─► repack zip; all other entries copied byte-for-byte +``` + +The same philosophy holds in sheets and slides: the original file is the +source of truth, edits are applied as narrow patches, and everything the +editor didn't touch survives the round trip untouched. + +## Security + +See [SECURITY.md](SECURITY.md) for the process security posture (renderer +sandboxing, IPC validation, external-link gating) and the threat models for +AI-generated content. + +## Third-party notices + +`npm run notices` regenerates the bundled third-party license summary +(`tools/gen-third-party-notices.mjs`); all runtime dependencies are +MIT/Apache-2.0/OFL, and the bundled fonts (Liberation, Carlito, Caladea, Noto +CJK subsets) are OFL/Apache. + +## License + +GenOffice is licensed under the [Apache License 2.0](LICENSE), with one +exception: the `ee/` directory is reserved for future enterprise modules and +is covered by the [GenOffice Enterprise License](ee/LICENSE). + +The GenOffice and Genspark names and logos are trademarks of Mainfunc, Inc. +The Apache-2.0 license does not grant permission to use them (see section 6); +forks should use their own branding. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..3338fe5 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,85 @@ +# Security Policy + +## Reporting a Vulnerability + +Please report suspected vulnerabilities privately via GitHub's +[private vulnerability reporting](../../security/advisories/new) on this +repository. Do not open public issues for security reports. We aim to +acknowledge reports within 72 hours. + +## Process Security Posture + +All application windows run with the full Electron renderer lockdown: + +- `contextIsolation: true`, `nodeIntegration: false`, `sandbox: true` for every + document window and tab view (docs, sheets, slides, pdf, shell, updater). +- Renderers reach the main process only through typed, validated IPC channels + (payloads are schema-checked in the main process; sheets uses zod end to end). +- Every `shell.openExternal` call goes through a single shared gate + (`@genoffice/electron-utils` → `safeExternalUrl`) that parses the URL and + enforces a protocol allowlist (http/https; pdf link annotations additionally + allow mailto). `file:`, `javascript:`, and custom schemes are always rejected. +- No API keys are hardcoded. AI requests are proxied through the signed-in + account by default; user-supplied keys stay in the OS-level settings store. + +## Threat Model: AI-Generated Layout Scripts (slides) + +The slides AI can adjust slide layouts by emitting a small script that is +parsed with Acorn and evaluated by a constrained AST interpreter +(`apps/slides/src/renderer/ai/layout-script-interpreter.ts`). The source looks +like a small, synchronous subset of JavaScript for model compatibility, but it +is not passed to `eval`, `Function`, a VM context, a worker, or the JavaScript +engine as executable source. + +**What the script can do by design:** read prototype-free JSON copies of +`els`/`canvas`, perform bounded arithmetic/control flow, use explicitly +implemented string/array/regular-expression/Math helpers, and call +`setBox/moveBy/resizeBy/setText/setStyle/setFill/setStroke/log`. Every edit +primitive validates its arguments (element existence, read-only flags, finite +numbers, hex colors) and writes only into an op buffer that is applied through +the same command pipeline as manual edits. + +**Interpreter boundary:** + +1. Identifiers resolve only in interpreter-owned lexical scopes seeded with the + documented data and callables. There are no ambient globals, module loader, + DOM, network, IPC bridge, timers, process APIs, or dynamic code primitives. +2. Property reads are dispatched by value type. Data objects expose own JSON + fields only; arrays, strings, and regexes expose a small method allowlist. + Host prototypes and function properties are never traversed, including + through computed property names. +3. Calls accept only interpreter-created functions or explicit builtins. A host + function obtained through a constructor/prototype chain cannot be + represented. +4. Inputs and values crossing into edit primitives are recursively copied as + JSON-like, prototype-free data. Errors discard all buffered operations; + logs are capped. +5. Execution has statement/expression and call-depth limits to bound runaway + loops or recursion. + +The Electron renderer sandbox remains defense in depth, but it is not the +layout-script security boundary. The interpreter is designed so a layout +script cannot obtain renderer capabilities in the first place. + +If you find a way for a layout script to reach anything beyond the injected +primitives (network, storage, IPC channels not reachable by design, or the +main process), that is a vulnerability — please report it. + +## Threat Model: Rendering AI-Generated HTML (slides export) + +The HTML-to-pptx export pipeline renders AI-generated HTML in a hidden +`BrowserWindow`. That window is treated as hostile content: full renderer +lockdown (`sandbox: true`, `contextIsolation: true`, `nodeIntegration: false`), +no preload script, no IPC surface — the main process drives it exclusively +through `executeJavaScript` and destroys it under a watchdog timeout. + +## Out of Scope + +- The cloud AI services this client talks to are operated separately and are + not part of this repository; issues with them should be reported through the + service provider's channels. +- Vulnerabilities that require an already-compromised machine or a modified + binary. This includes the deliberate environment-variable override points + for local development (`GSK_CLI_PATH`, `XLSX_SIDECAR_PATH`): setting them + requires control of the process environment, which is equivalent to code + execution on the machine. diff --git a/apps/docs/build/icon.icns b/apps/docs/build/icon.icns new file mode 100644 index 0000000..7b20c76 Binary files /dev/null and b/apps/docs/build/icon.icns differ diff --git a/apps/docs/build/icon.ico b/apps/docs/build/icon.ico new file mode 100644 index 0000000..9389c4f Binary files /dev/null and b/apps/docs/build/icon.ico differ diff --git a/apps/docs/build/icon.png b/apps/docs/build/icon.png new file mode 100644 index 0000000..69e0a67 Binary files /dev/null and b/apps/docs/build/icon.png differ diff --git a/apps/docs/electron.vite.config.ts b/apps/docs/electron.vite.config.ts new file mode 100644 index 0000000..c18419c --- /dev/null +++ b/apps/docs/electron.vite.config.ts @@ -0,0 +1,22 @@ +import react from '@vitejs/plugin-react' +import { defineConfig, externalizeDepsPlugin } from 'electron-vite' + +export default defineConfig({ + // Main and preload use only electron + node builtins; bundle everything so + // the packaged app doesn't rely on node_modules at runtime. + // @genoffice/* deps ship as raw TS source with extensionless imports, so they + // must be bundled — externalizing them yields ERR_MODULE_NOT_FOUND under Node + // (same setup as apps/slides). + main: { + plugins: [externalizeDepsPlugin({ exclude: ['@genoffice/electron-utils'] })], + }, + preload: {}, + renderer: { + plugins: [react()], + server: { + // Overridable so multiple genoffice dev instances can coexist (default 5173). + port: Number(process.env.DOCS_DEV_PORT) || 5173, + strictPort: Boolean(process.env.DOCS_DEV_PORT), + }, + }, +}) diff --git a/apps/docs/package.json b/apps/docs/package.json new file mode 100644 index 0000000..f2117ed --- /dev/null +++ b/apps/docs/package.json @@ -0,0 +1,96 @@ +{ + "name": "@genoffice/docs", + "productName": "GenOffice Docs", + "version": "0.1.0", + "license": "Apache-2.0", + "private": true, + "description": "AI-native streaming docx editor with paragraph-patch save", + "main": "out/main/index.js", + "scripts": { + "dev": "electron-vite dev", + "dev:renderer": "vite --config vite.renderer.config.ts", + "build": "electron-vite build", + "typecheck": "tsc --noEmit", + "test": "vitest run", + "test:watch": "vitest", + "dist:mac": "electron-vite build && electron-builder --mac", + "dist:win": "electron-vite build && electron-builder --win", + "dist:dir": "electron-vite build && electron-builder --dir" + }, + "devDependencies": { + "@genoffice/agent-core": "*", + "@genoffice/i18n": "*", + "@genoffice/ai-provider": "*", + "@genoffice/ai-search": "*", + "@genoffice/docx-engine": "*", + "@genoffice/file-parse": "*", + "@genoffice/project-store": "*", + "@genoffice/ui": "*", + "@tiptap/core": "^3.28.0", + "@tiptap/extensions": "^3.28.0", + "@tiptap/pm": "^3.28.0", + "@tiptap/react": "^3.28.0", + "@types/opentype.js": "^1.3.8", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^5.0.4", + "electron": "^41.0.3", + "electron-builder": "^26.0.12", + "electron-vite": "^5.0.0", + "jsdom": "^28.0.0", + "opentype.js": "^2.0.0", + "react": "^19.2.4", + "react-dom": "^19.2.4", + "typescript": "^5.9.3", + "vite": "^7.3.1", + "vitest": "^4.1.0" + }, + "author": "GenOffice", + "build": { + "appId": "com.genoffice.docs", + "productName": "GenOffice Docs", + "electronVersion": "41.7.1", + "artifactName": "AIDocx-${version}-${arch}.${ext}", + "directories": { + "output": "release" + }, + "files": [ + "out/**" + ], + "fileAssociations": [ + { + "ext": "docx", + "name": "Word Document", + "role": "Editor" + } + ], + "npmRebuild": false, + "mac": { + "target": [ + "dmg", + "zip" + ], + "category": "public.app-category.productivity", + "identity": null + }, + "win": { + "target": [ + { + "target": "nsis", + "arch": [ + "x64" + ] + } + ] + }, + "nsis": { + "oneClick": false, + "allowToChangeInstallationDirectory": true + } + }, + "dependencies": { + "@genoffice/electron-utils": "*", + "electron-updater": "^6.8.9", + "pdf-lib": "^1.17.1" + } +} diff --git a/apps/docs/scripts/generate-corpus.ts b/apps/docs/scripts/generate-corpus.ts new file mode 100644 index 0000000..5ce6af7 --- /dev/null +++ b/apps/docs/scripts/generate-corpus.ts @@ -0,0 +1,791 @@ +/** + * Pagination corpus generation script + * Run: tsx apps/docs/scripts/generate-corpus.ts + * Output: apps/docs/tests/pagination-corpus/docx/*.docx + * apps/docs/tests/pagination-corpus/meta/*.json + */ + +import { mkdirSync, writeFileSync, copyFileSync, existsSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import JSZip from 'jszip' + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const REPO_ROOT = join(__dirname, '../../..') +const DOCX_OUT = join(__dirname, '../tests/pagination-corpus/docx') +const META_OUT = join(__dirname, '../tests/pagination-corpus/meta') + +mkdirSync(DOCX_OUT, { recursive: true }) +mkdirSync(META_OUT, { recursive: true }) + +const XML_DECL = '\r\n' +const DOC_NS = + '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 STYLES_XML = + XML_DECL + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + +// A4 page + standard margins + docGrid (Chinese document grid) +const A4_SECT_PR = + '' + + '' + + '' + + '' + +// A4 + docGrid (standard Chinese document grid: line=360, type=lines) +const A4_SECT_WITH_DOCGRID = + '' + + '' + + '' + + '' + + '' + +// US Letter landscape +const LETTER_LANDSCAPE_SECT_PR = + '' + + '' + + '' + + '' + +interface DocSpec { + name: string + bodyXml: string + sectPr?: string + extraStylesXml?: string + footnotesXml?: string + meta: { + title: string + tags: string[] + description: string + } +} + +async function buildDocx(spec: DocSpec): Promise { + const zip = new JSZip() + const sectPr = spec.sectPr ?? A4_SECT_PR + const extraStyles = spec.extraStylesXml ?? '' + const hasFootnotes = !!spec.footnotesXml + + const stylesXml = extraStyles + ? STYLES_XML.replace('', extraStyles + '') + : STYLES_XML + + const contentTypeOverrides = [ + '', + '', + hasFootnotes + ? '' + : '', + ].join('') + + zip.file( + '[Content_Types].xml', + `${XML_DECL}` + + '' + + '' + + contentTypeOverrides + + '', + ) + zip.file( + '_rels/.rels', + `${XML_DECL}` + + '' + + '', + ) + const docRels = [ + '', + hasFootnotes + ? '' + : '', + ].join('') + zip.file( + 'word/_rels/document.xml.rels', + `${XML_DECL}${docRels}`, + ) + zip.file('word/styles.xml', stylesXml) + if (hasFootnotes) zip.file('word/footnotes.xml', spec.footnotesXml!) + zip.file( + 'word/document.xml', + `${XML_DECL}${spec.bodyXml}${sectPr}`, + ) + return zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE' }) +} + +// ---- Paragraph helpers ---- + +const p = (text: string, style?: string, extra?: string): string => { + const pStyle = style ? `` : '' + const pPr = pStyle || extra ? `${pStyle}${extra ?? ''}` : '' + return `${pPr}${escXml(text)}` +} + +const pBreak = (): string => '' + +const escXml = (s: string) => s.replace(/&/g, '&').replace(//g, '>') + +// build a paragraph from repeated text +function loremParagraph(n: number, lang: 'en' | 'zh'): string { + if (lang === 'en') { + const words = + 'Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat'.split( + ' ', + ) + let text = '' + for (let i = 0; i < n; i++) text += words[i % words.length] + ' ' + return p(text.trim()) + } else { + const chars = + '在中国经济社会发展的重要历史时期,人工智能技术的广泛应用正在深刻改变各行各业的生产方式和商业模式。数字化转型已成为企业保持竞争力的关键战略,各类组织机构纷纷加快推进信息化建设步伐。' + let text = '' + for (let i = 0; i < n; i++) text += chars[i % chars.length] + return p(text) + } +} + +// generate table rows +function tableRows(rows: number, cols: number, withHeader = false): string { + let xml = '' + const colWidth = Math.floor(8000 / cols) + for (let r = 0; r < rows; r++) { + const isHeader = withHeader && r === 0 + xml += '' + for (let c = 0; c < cols; c++) { + const fill = isHeader ? '' : '' + const cellText = isHeader ? `列${c + 1}标题` : `第${r + 1}行第${c + 1}列` + xml += + `${fill}` + + `${isHeader ? '' : ''}${isHeader ? '' : ''}${escXml(cellText)}` + } + xml += '' + } + return xml +} + +function table(rows: number, cols: number, withHeader = false): string { + const colWidth = Math.floor(8000 / cols) + const border = (n: string) => `` + const borders = + '' + + ['top', 'left', 'bottom', 'right', 'insideH', 'insideV'].map(border).join('') + + '' + const gridCols = Array.from({ length: cols }, () => ``).join('') + return ( + `${borders}` + + `${gridCols}` + + tableRows(rows, cols, withHeader) + + '' + ) +} + +// ---- Corpus specs ---- + +const specs: DocSpec[] = [] + +// 01. Simple English document (2 pages) +{ + let body = p('Simple English Document', 'Heading1') + for (let i = 0; i < 40; i++) body += loremParagraph(30, 'en') + specs.push({ + name: '01-simple-english', + bodyXml: body, + meta: { + title: 'Simple English Document', + tags: ['english', 'multi-page', 'simple'], + description: 'Pure English long text, ~2 pages, no special formatting', + }, + }) +} + +// 02. Long pure-Chinese document (with docGrid) +{ + let body = p('中文长篇文档测试', 'Heading1') + for (let i = 0; i < 50; i++) body += loremParagraph(50, 'zh') + specs.push({ + name: '02-chinese-long-docgrid', + bodyXml: body, + sectPr: A4_SECT_WITH_DOCGRID, + meta: { + title: 'Long Chinese text (docGrid)', + tags: ['chinese', 'docGrid', 'multi-page'], + description: + 'Pure Chinese with a w:docGrid lines grid, typical Chinese official-document format', + }, + }) +} + +// 03. Mixed Chinese-English +{ + let body = p('中英文混排文档', 'Heading1') + for (let i = 0; i < 20; i++) { + body += loremParagraph(20, 'zh') + body += loremParagraph(20, 'en') + } + specs.push({ + name: '03-mixed-lang', + bodyXml: body, + meta: { + title: 'Mixed Chinese-English', + tags: ['mixed-language', 'multi-page'], + description: 'Alternating Chinese/English paragraphs, tests mixed-language pagination', + }, + }) +} + +// 04. Multilevel headings (keepNext styles) +{ + let body = '' + for (let h = 1; h <= 5; h++) { + body += p(`第${h}章 标题层级测试`, 'Heading1') + body += p(`第${h}.1节`, 'Heading2') + for (let i = 0; i < 8; i++) body += loremParagraph(30, 'zh') + body += p(`第${h}.2节`, 'Heading2') + body += p(`第${h}.2.1小节`, 'Heading3') + for (let i = 0; i < 6; i++) body += loremParagraph(30, 'zh') + } + specs.push({ + name: '04-headings-keepnext', + bodyXml: body, + sectPr: A4_SECT_WITH_DOCGRID, + meta: { + title: 'Multilevel headings document', + tags: ['headings', 'keepNext', 'multi-section', 'docGrid'], + description: + '5 chapters of multilevel headings (with keepNext styles), tests heading page-break behavior', + }, + }) +} + +// 05. Long table across pages +{ + let body = p('长表格跨页测试', 'Heading1') + body += p('以下表格含 30 行,跨多页:') + body += table(30, 4, true) + body += p('表格后续正文段落。') + specs.push({ + name: '05-long-table', + bodyXml: body, + meta: { + title: 'Long table across pages', + tags: ['table', 'cross-page', 'table-header'], + description: '30-row 4-column table, tests table splitting across pages', + }, + }) +} + +// 06. With footnotes (full footnotes.xml structure) +{ + // footnote documents need footnotes.xml + a Content-Type override + rels + // built directly with the customBuildDocxWithFootnotes function + const FOOTNOTE_COUNT = 20 + let body = p('含脚注文档测试', 'Heading1') + for (let i = 1; i <= FOOTNOTE_COUNT; i++) { + body += + `第${i}段正文,包含参考引用。` + + `` + } + for (let i = 0; i < 20; i++) body += loremParagraph(20, 'zh') + // generate footnotes.xml (with the separator + each footnote) + const FOOTNOTES_NS = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"' + let footnotesXml = `${XML_DECL}` + // two built-in system footnotes: separator and continuationSeparator + footnotesXml += + '' + footnotesXml += + '' + for (let i = 1; i <= FOOTNOTE_COUNT; i++) { + footnotesXml += + `` + + `${i}` + + ` 这是第${i}条脚注内容,详见参考文献。` + + `` + } + footnotesXml += '' + specs.push({ + name: '06-with-footnotes', + bodyXml: body, + footnotesXml, + meta: { + title: 'Document with footnotes', + tags: ['footnotes', 'multi-page'], + description: "20 footnote references, tests footnote placeholders' impact on pagination", + }, + }) +} + +// 07. With page breaks +{ + let body = p('分页符测试文档', 'Heading1') + body += p('第一页内容') + for (let i = 0; i < 5; i++) body += loremParagraph(20, 'zh') + body += pBreak() + body += p('第二页(强制分页符后)') + for (let i = 0; i < 5; i++) body += loremParagraph(20, 'zh') + body += pBreak() + body += p('第三页') + for (let i = 0; i < 8; i++) body += loremParagraph(20, 'zh') + specs.push({ + name: '07-page-breaks', + bodyXml: body, + meta: { + title: 'Manual page breaks', + tags: ['page-break', 'forced-break'], + description: 'Two manual page breaks, tests breakAfter logic', + }, + }) +} + +// 08. Multi-section mixed paper (A4 portrait + A4 landscape) +{ + const sect1 = + '' + + '' + + '' + + '' + let body = p('多节文档 - 第一节(A4 竖向)', 'Heading1') + for (let i = 0; i < 15; i++) body += loremParagraph(25, 'zh') + // insert a section break (sectPr embedded in the paragraph's pPr) + body += `${sect1}` + body += p('第二节(A4 横向)', 'Heading1') + for (let i = 0; i < 10; i++) body += loremParagraph(25, 'zh') + specs.push({ + name: '08-multi-section-paper', + bodyXml: body, + sectPr: LETTER_LANDSCAPE_SECT_PR, + meta: { + title: 'Multi-section mixed paper sizes', + tags: ['multi-section', 'landscape', 'portrait', 'section-break'], + description: 'Two sections: A4 portrait + landscape, tests pagination at section switches', + }, + }) +} + +// 09. Large paragraph (within one page) +{ + let body = p('大段落测试', 'Heading1') + // one large paragraph, close to but not exceeding a page + let bigPara = '' + for (let i = 0; i < 200; i++) bigPara += '这是一段很长的文字内容,用于测试大段落的分页处理行为。' + body += `${escXml(bigPara)}` + body += p('段落后继续内容') + for (let i = 0; i < 5; i++) body += loremParagraph(30, 'zh') + specs.push({ + name: '09-large-paragraph', + bodyXml: body, + meta: { + title: 'Large paragraph (cross-page)', + tags: ['large-paragraph', 'cross-page'], + description: 'One oversized paragraph spanning pages, tests intra-block splitting', + }, + }) +} + +// 10. Chinese official-document format (docGrid + standard page margins) +{ + let body = '' + body += + `` + + `关于深化体制改革的通知` + body += `各省、自治区、直辖市人民政府:` + for (let i = 0; i < 8; i++) { + body += + `` + + `${escXml('  ' + '为贯彻落实党中央、国务院关于深化体制改革的重要决策部署,切实推进政府职能转变,优化营商环境,提升治理效能,现就有关事项通知如下:'.repeat(3))}` + } + body += `国务院办公厅` + body += `二○二六年七月二十六日` + // attachments + for (let i = 1; i <= 3; i++) { + body += p(`附件${i}:相关事项说明`, 'Heading2') + for (let j = 0; j < 10; j++) body += loremParagraph(40, 'zh') + } + specs.push({ + name: '10-cn-official-doc', + bodyXml: body, + sectPr: A4_SECT_WITH_DOCGRID, + meta: { + title: 'Chinese official-document format', + tags: ['chinese', 'official-doc', 'docGrid', 'firstLine-indent', 'center-justify'], + description: + 'Standard government document format: centered large title + first-line-indented body + signature block, docGrid', + }, + }) +} + +// 11. Table-dense (multiple tables) +{ + let body = p('多表格文档', 'Heading1') + for (let t = 0; t < 5; t++) { + body += p(`表格 ${t + 1}`) + body += table(8, 3, true) + body += p('表格说明文字:以上数据来自系统统计。') + } + specs.push({ + name: '11-multi-tables', + bodyXml: body, + meta: { + title: 'Multi-table document', + tags: ['table', 'multi-table', 'table-header'], + description: '5 tables interleaved with text, tests pagination of text between tables', + }, + }) +} + +// 12. Orphan heading test (heading right at the page bottom) +{ + let body = p('标题孤悬测试', 'Heading1') + // fill until close to the page end + for (let i = 0; i < 30; i++) body += loremParagraph(15, 'en') + // the heading here should sit at the page bottom, with the following content on the next page + body += p('这是一个可能孤悬的二级标题', 'Heading2') + body += p('标题后面的正文段落,标题不应孤悬。') + for (let i = 0; i < 10; i++) body += loremParagraph(20, 'en') + specs.push({ + name: '12-orphan-heading', + bodyXml: body, + meta: { + title: 'Orphan heading test', + tags: ['headings', 'keepNext', 'orphan', 'widow'], + description: 'Heading lands right at the page bottom, tests keepNext orphan prevention', + }, + }) +} + +// 13. Long pure-English document (3+ pages) +{ + let body = p('Long English Report', 'Heading1') + body += p('Abstract', 'Heading2') + for (let i = 0; i < 15; i++) body += loremParagraph(40, 'en') + body += p('Introduction', 'Heading2') + for (let i = 0; i < 20; i++) body += loremParagraph(35, 'en') + body += p('Methodology', 'Heading2') + for (let i = 0; i < 20; i++) body += loremParagraph(35, 'en') + body += p('Results', 'Heading2') + for (let i = 0; i < 15; i++) body += loremParagraph(30, 'en') + body += p('Conclusion', 'Heading2') + for (let i = 0; i < 10; i++) body += loremParagraph(30, 'en') + specs.push({ + name: '13-english-report', + bodyXml: body, + meta: { + title: 'English Report (3+ pages)', + tags: ['english', 'headings', 'multi-page', 'long'], + description: 'English report format, 4-section heading structure, 3+ pages', + }, + }) +} + +// 14. Long Chinese document (no docGrid) +{ + let body = p('中文文档(无网格)', 'Heading1') + for (let i = 0; i < 60; i++) body += loremParagraph(40, 'zh') + specs.push({ + name: '14-chinese-no-docgrid', + bodyXml: body, + meta: { + title: 'Long Chinese text (no docGrid)', + tags: ['chinese', 'no-docGrid', 'multi-page'], + description: 'Pure Chinese without docGrid, contrast test against 02', + }, + }) +} + +// 15. Mixed elements (headings + tables + body) +{ + let body = p('混合内容文档', 'Heading1') + for (let section = 1; section <= 4; section++) { + body += p(`第${section}节 内容概述`, 'Heading2') + for (let i = 0; i < 5; i++) body += loremParagraph(25, 'zh') + body += p(`第${section}.1 数据汇总`, 'Heading3') + body += table(6, 3, true) + for (let i = 0; i < 3; i++) body += loremParagraph(20, 'zh') + body += p(`第${section}.2 分析结论`, 'Heading3') + for (let i = 0; i < 6; i++) body += loremParagraph(25, 'zh') + } + specs.push({ + name: '15-mixed-content', + bodyXml: body, + sectPr: A4_SECT_WITH_DOCGRID, + meta: { + title: 'Mixed content (headings + tables + body)', + tags: ['mixed', 'table', 'headings', 'docGrid'], + description: 'Headings, tables and body text mixed — the most common report structure', + }, + }) +} + +// 16. Numbered-list document +{ + const _NUMBERING_XML = + XML_DECL + + '' + + '' + + '' + + '' + + '' + // inline numbering into extra styles (no separate file; simplified approach) + let body = p('编号列表文档', 'Heading1') + for (let i = 1; i <= 50; i++) { + body += + `` + + `${i}. 列表项目:${escXml('这是第' + i + '条列表内容,用于测试编号列表的分页行为。')}` + } + specs.push({ + name: '16-numbered-list', + bodyXml: body, + meta: { + title: 'Numbered-list document', + tags: ['numbered-list', 'list-paragraph', 'multi-page'], + description: '50 numbered list items, tests list pagination across pages', + }, + }) +} + +// 17. Short single-page document +{ + let body = p('单页短文档', 'Heading1') + body += p('这是一份很短的文档,所有内容都在第一页内。') + body += p('第二段内容。') + body += p('第三段内容,文档到此结束。') + specs.push({ + name: '17-single-page', + bodyXml: body, + meta: { + title: 'Short single-page document', + tags: ['single-page', 'short'], + description: 'All content fits on one page, baseline case', + }, + }) +} + +// 18. Paragraphs with the pageBreakBefore property +{ + let body = p('pageBreakBefore 测试', 'Heading1') + for (let i = 0; i < 5; i++) body += loremParagraph(20, 'zh') + body += `此段落设置了 pageBreakBefore 属性` + for (let i = 0; i < 5; i++) body += loremParagraph(20, 'zh') + body += `第二个 pageBreakBefore 段落` + for (let i = 0; i < 5; i++) body += loremParagraph(20, 'zh') + specs.push({ + name: '18-page-break-before', + bodyXml: body, + meta: { + title: 'pageBreakBefore property', + tags: ['pageBreakBefore', 'forced-break'], + description: 'Two paragraphs with the pageBreakBefore property, tests breakBefore logic', + }, + }) +} + +// 19. Large table (over one page) +{ + let body = p('超大表格测试', 'Heading1') + body += p('以下表格超过一页:') + body += table(60, 3, true) + body += p('超大表格后续内容。') + specs.push({ + name: '19-oversized-table', + bodyXml: body, + meta: { + title: 'Oversized table (>1 page)', + tags: ['table', 'cross-page', 'large-table', 'pixel-cut'], + description: '60-row table exceeding one page, triggers the pixel hard-cut logic', + }, + }) +} + +// 20. Chinese official document (shorter, ~1.5 pages) +{ + let body = + `` + + `人工智能办公系统建设方案` + body += `信息化建设工作小组` + body += `2026年7月` + for (let i = 0; i < 12; i++) { + body += + `` + + `${escXml('  本方案旨在系统推进办公自动化智能升级,通过引入先进的人工智能技术,全面提升行政办公效率,降低运营成本,改善用户体验,为现代化治理体系建设提供有力支撑。'.repeat(2))}` + } + specs.push({ + name: '20-cn-short-report', + bodyXml: body, + sectPr: A4_SECT_WITH_DOCGRID, + meta: { + title: 'Short Chinese report (~1.5 pages)', + tags: ['chinese', 'docGrid', 'short-report', 'center-title'], + description: '~1.5-page Chinese report, centered title, first-line-indented body', + }, + }) +} + +// 21. Multi-section continuation (continuous section) +{ + const sect1Continuous = + '' + + '' + + '' + + '' + let body = p('连续节分隔符测试', 'Heading1') + for (let i = 0; i < 10; i++) body += loremParagraph(25, 'zh') + body += `${sect1Continuous}` + body += p('续页节(内容紧接上节)', 'Heading2') + for (let i = 0; i < 15; i++) body += loremParagraph(25, 'zh') + specs.push({ + name: '21-continuous-section', + bodyXml: body, + meta: { + title: 'Continuous section break', + tags: ['multi-section', 'continuous-section'], + description: + 'Contains a continuous section break, tests section switching without a forced page break', + }, + }) +} + +// 22. Multi-column document +{ + const twoColSect = + '' + + '' + + '' + + '' + + '' + let body = p('双栏布局文档', 'Heading1') + for (let i = 0; i < 30; i++) body += loremParagraph(20, 'zh') + specs.push({ + name: '22-two-columns', + bodyXml: body, + sectPr: twoColSect, + meta: { + title: 'Two-column layout', + tags: ['two-column', 'columns', 'layout'], + description: 'Two-column layout, tests pagination with columns', + }, + }) +} + +// 23. tblHeader repeated headers across pages +{ + const border = (n: string) => `` + const borders = + '' + + ['top', 'left', 'bottom', 'right', 'insideH', 'insideV'].map(border).join('') + + '' + let rows = + '' + + ['列A表头', '列B表头'] + .map( + (t) => + `` + + `${t}`, + ) + .join('') + + '' + for (let r = 1; r <= 45; r++) { + const cantSplit = r % 10 === 0 ? '' : '' + rows += + `${cantSplit}` + + [1, 2] + .map( + (c) => + `` + + `第${r}行${c === 1 ? 'A' : 'B'}`, + ) + .join('') + + '' + } + const body = + p('tblHeader 跨页表头重复测试', 'Heading1') + + `${borders}${rows}` + + p('表后段落。') + specs.push({ + name: '23-tblheader-repeat', + bodyXml: body, + meta: { + title: 'tblHeader repeated header', + tags: ['table', 'tblHeader', 'cantSplit'], + description: + 'Cross-page table with a tblHeader first row (repeated header placeholder on following pages) + some cantSplit rows', + }, + }) +} + +// write the files +async function writeAll() { + for (const spec of specs) { + const bytes = await buildDocx(spec) + const docxPath = join(DOCX_OUT, `${spec.name}.docx`) + writeFileSync(docxPath, bytes) + const metaPath = join(META_OUT, `${spec.name}.json`) + writeFileSync(metaPath, JSON.stringify({ ...spec.meta, file: `${spec.name}.docx` }, null, 2)) + console.log(`✓ ${spec.name}.docx (${(bytes.length / 1024).toFixed(1)} KB)`) + } + + // copy existing fixtures (simple files, already in the docx directory) + const existingFiles = [ + { src: join(REPO_ROOT, 'fixtures/generated/simple.docx'), name: 'fixture-simple.docx' }, + { + src: join(REPO_ROOT, 'fixtures/generated/kitchen-sink.docx'), + name: 'fixture-kitchen-sink.docx', + }, + ] + for (const f of existingFiles) { + if (existsSync(f.src)) { + const dst = join(DOCX_OUT, f.name) + copyFileSync(f.src, dst) + console.log(`✓ ${f.name} (copied from fixtures)`) + // meta + const title = f.name.replace(/^fixture-/, '').replace('.docx', '') + const metaPath = join(META_OUT, f.name.replace('.docx', '.json')) + writeFileSync( + metaPath, + JSON.stringify( + { + title, + file: f.name, + tags: ['fixture', 'real-world'], + description: `Real test file copied from repo fixtures`, + }, + null, + 2, + ), + ) + } + } + + console.log( + `\ntotal ${specs.length + existingFiles.length} corpus files (${specs.length} programmatically built, ${existingFiles.length} from fixtures)`, + ) +} + +writeAll().catch((err) => { + console.error(err) + process.exit(1) +}) diff --git a/apps/docs/src/main/docs-main.ts b/apps/docs/src/main/docs-main.ts new file mode 100644 index 0000000..c363577 --- /dev/null +++ b/apps/docs/src/main/docs-main.ts @@ -0,0 +1,3445 @@ +import { createHash } from 'node:crypto' +import { + copyFileSync, + existsSync, + mkdirSync, + readdirSync, + readFileSync, + statSync, + unlinkSync, + writeFileSync, +} from 'node:fs' +import { basename, join } from 'node:path' +import { BrowserWindow, Menu, WebContentsView, app, dialog, ipcMain, shell } from 'electron' +import { fetchWithSsrfGuard, safeExternalUrl } from '@genoffice/electron-utils' +import { createI18n, getUiLang, normalizeLang, setUiLang } from '@genoffice/i18n' +import { ProjectStore } from '@genoffice/project-store' +import type { + IpcMainInvokeEvent, + MenuItemConstructorOptions, + OpenDialogOptions, + SaveDialogOptions, + WebContents, +} from 'electron' +import { parseFileToText } from '@genoffice/file-parse' +import { + chatForProvider, + defaultAiSettings, + resolveAiSettings, + streamForProvider, + type AiChatRequest, + type AiSettings, + type AiStreamChunk, + type AiStreamRequest, + type GenSparkAccountStatus, + type LegacyAiSettings, +} from '@genoffice/ai-provider' +import { + gskApiKey, + gskLogin, + gskLoginInfo, + hasGskAuth, + webSearch, + imageSearch, +} from '@genoffice/ai-search' +import type { + AttachmentAddResult, + AttachmentImageResult, + AttachmentMeta, + AttachmentReadResult, + DocsTabInfo, + MenuCommand, + OpenFileResult, +} from '../shared/ipc' +import { ATTACHMENT_IMAGE_EXTS } from '../shared/ipc' +import { findDocxPath } from '../shared/open-file' +import { initDocsAutoUpdater } from './updater' + +/** + * Docs main-process logic as an embeddable module: no top-level side effects. + * Standalone mode (apps/docs entry) calls startDocsStandalone(); the unified + * shell (apps/shell) instead calls configureDocsRuntime() + registerDocsIpc() + * + createDocsWindow() and owns the app lifecycle itself. + */ + +const isDev = !!process.env.ELECTRON_RENDERER_URL + +const tMain = createI18n({ + zh: { + dlgOpenDoc: '打开文档', + filterWord: 'Word 文档', + dlgSaveAs: '另存为', + closeUnsavedMsg: '此文档有未保存的更改。', + closeUnsavedDetail: '关闭前是否保存?', + closeNoReplyMsg: '文档没有响应,可能有未保存的更改。', + closeNoReplyDetail: '仍要关闭吗?未保存的更改将丢失。', + btnCloseAnyway: '仍要关闭', + autosaveFoundTitle: '发现自动恢复版本', + autosaveFoundBody: '上次会话有未保存的更改。要恢复自动保存的版本吗?', + autosaveRestore: '恢复', + autosaveDiscard: '放弃', + btnDontSave: '不保存', + btnCancel: '取消', + dlgInsertImage: '插入图片', + filterImages: '图片', + dlgAddAttachment: '添加附件', + filterSupported: '支持的文件', + filterAll: '所有文件', + dlgExportPdf: '导出为 PDF', + errUnsupportedExt: '暂不支持 .{ext} 类型', + errNotFile: '不是文件', + errTooLarge: '超过 {mb}MB 上限', + errImageTooLarge: '图片超过 5MB 上限', + errUnreadable: '无法读取', + errFileTooLarge: '文件超过大小上限', + errParseFailed: '文件解析失败', + errImageNoText: '图片附件不提供文本,已作为图像随用户消息发送,直接看图即可', + errNotImage: '不是支持的图片类型', + errGskNotLoggedIn: '未登录 Genspark:请点击下方「登录 Genspark」完成登录后重试', + errNoApiKey: '未配置 {provider} 的 API Key', + errNoModel: '未配置模型名称', + menuFile: '文件', + menuNewDoc: '新建文档', + menuNewWindow: '新建窗口', + menuOpen: '打开…', + menuOpenRecent: '打开最近的文档', + menuNoRecent: '无最近文档', + menuClose: '关闭', + menuSave: '保存', + menuSaveAs: '另存为…', + menuPageSetup: '页面设置…', + menuExportPdf: '导出为 PDF…', + menuPrint: '打印…', + menuEdit: '编辑', + menuUndo: '撤销', + menuRedo: '重做', + menuCut: '剪切', + menuCopy: '复制', + menuPaste: '粘贴', + menuPasteMatch: '粘贴并匹配格式', + menuFindReplace: '查找和替换…', + menuSelectAll: '全选', + menuView: '视图', + menuZoomIn: '放大', + menuZoomOut: '缩小', + menuZoom100: '实际大小 (100%)', + menuPageWidth: '页宽', + menuWholePage: '整页', + menuAiSidebar: 'AI 侧栏', + menuDarkMode: '深色模式', + menuFullscreen: '进入全屏', + menuInsert: '插入', + menuInsertTable: '表格(3×3)', + menuInsertImage: '图片…', + menuInsertPageBreak: '分页符', + menuInsertLink: '超链接…', + menuInsertEquation: '公式…', + menuComment: '批注', + menuFormat: '格式', + menuBold: '加粗', + menuItalic: '斜体', + menuUnderline: '下划线', + menuAlign: '对齐', + menuAlignLeft: '左对齐', + menuAlignCenter: '居中', + menuAlignRight: '右对齐', + menuAlignJustify: '两端对齐', + menuFont: '字体…', + menuParagraph: '段落…', + menuTools: '工具', + menuWordCount: '字数统计…', + menuSpelling: '拼写和语法检查', + menuMacros: '宏', + menuWindow: '窗口', + menuHelp: '帮助', + menuDocsHelp: 'GenOffice Docs 帮助', + }, + en: { + dlgOpenDoc: 'Open Document', + filterWord: 'Word Documents', + dlgSaveAs: 'Save As', + closeUnsavedMsg: 'This document has unsaved changes.', + closeUnsavedDetail: 'Do you want to save them before closing?', + closeNoReplyMsg: 'The document is not responding and may have unsaved changes.', + closeNoReplyDetail: 'Close anyway? Unsaved changes will be lost.', + btnCloseAnyway: 'Close Anyway', + autosaveFoundTitle: 'Recovered version found', + autosaveFoundBody: + 'There are unsaved changes from your last session. Restore the autosaved version?', + autosaveRestore: 'Restore', + autosaveDiscard: 'Discard', + btnDontSave: "Don't Save", + btnCancel: 'Cancel', + dlgInsertImage: 'Insert Image', + filterImages: 'Images', + dlgAddAttachment: 'Add Attachments', + filterSupported: 'Supported Files', + filterAll: 'All Files', + dlgExportPdf: 'Export as PDF', + errUnsupportedExt: '.{ext} files are not supported', + errNotFile: 'not a file', + errTooLarge: 'exceeds the {mb}MB limit', + errImageTooLarge: 'image exceeds the 5MB limit', + errUnreadable: 'cannot be read', + errFileTooLarge: 'File exceeds the size limit', + errParseFailed: 'Failed to parse file', + errImageNoText: 'Image attachments have no text; the image is sent along with the user message', + errNotImage: 'not a supported image type', + errGskNotLoggedIn: + 'Not signed in to Genspark: click “Sign in to Genspark” below, sign in, then retry', + errNoApiKey: 'No API key configured for {provider}', + errNoModel: 'No model name configured', + menuFile: 'File', + menuNewDoc: 'New Document', + menuNewWindow: 'New Window', + menuOpen: 'Open…', + menuOpenRecent: 'Open Recent', + menuNoRecent: 'No Recent Documents', + menuClose: 'Close', + menuSave: 'Save', + menuSaveAs: 'Save As…', + menuPageSetup: 'Page Setup…', + menuExportPdf: 'Export as PDF…', + menuPrint: 'Print…', + menuEdit: 'Edit', + menuUndo: 'Undo', + menuRedo: 'Redo', + menuCut: 'Cut', + menuCopy: 'Copy', + menuPaste: 'Paste', + menuPasteMatch: 'Paste and Match Style', + menuFindReplace: 'Find and Replace…', + menuSelectAll: 'Select All', + menuView: 'View', + menuZoomIn: 'Zoom In', + menuZoomOut: 'Zoom Out', + menuZoom100: 'Actual Size (100%)', + menuPageWidth: 'Page Width', + menuWholePage: 'Whole Page', + menuAiSidebar: 'AI Sidebar', + menuDarkMode: 'Dark Mode', + menuFullscreen: 'Enter Full Screen', + menuInsert: 'Insert', + menuInsertTable: 'Table (3×3)', + menuInsertImage: 'Image…', + menuInsertPageBreak: 'Page Break', + menuInsertLink: 'Hyperlink…', + menuInsertEquation: 'Equation…', + menuComment: 'Comment', + menuFormat: 'Format', + menuBold: 'Bold', + menuItalic: 'Italic', + menuUnderline: 'Underline', + menuAlign: 'Align', + menuAlignLeft: 'Align Left', + menuAlignCenter: 'Center', + menuAlignRight: 'Align Right', + menuAlignJustify: 'Justify', + menuFont: 'Font…', + menuParagraph: 'Paragraph…', + menuTools: 'Tools', + menuWordCount: 'Word Count…', + menuSpelling: 'Spelling and Grammar', + menuMacros: 'Macros', + menuWindow: 'Window', + menuHelp: 'Help', + menuDocsHelp: 'GenOffice Docs Help', + }, + ja: { + dlgOpenDoc: '文書を開く', + filterWord: 'Word 文書', + dlgSaveAs: '名前を付けて保存', + closeUnsavedMsg: 'このドキュメントに未保存の変更があります。', + closeUnsavedDetail: '閉じる前に保存しますか?', + closeNoReplyMsg: 'ドキュメントが応答していません。未保存の変更がある可能性があります。', + closeNoReplyDetail: 'それでも閉じますか?未保存の変更は失われます。', + btnCloseAnyway: '閉じる', + autosaveFoundTitle: '自動回復バージョンがあります', + autosaveFoundBody: '前回のセッションに未保存の変更があります。自動保存版を復元しますか?', + autosaveRestore: '復元', + autosaveDiscard: '破棄', + btnDontSave: '保存しない', + btnCancel: 'キャンセル', + dlgInsertImage: '画像の挿入', + filterImages: '画像', + dlgAddAttachment: '添付ファイルの追加', + filterSupported: 'サポートされているファイル', + filterAll: 'すべてのファイル', + dlgExportPdf: 'PDF としてエクスポート', + errUnsupportedExt: '.{ext} 形式には対応していません', + errNotFile: 'ファイルではありません', + errTooLarge: '{mb}MB の上限を超えています', + errImageTooLarge: '画像が 5MB の上限を超えています', + errUnreadable: '読み取れません', + errFileTooLarge: 'ファイルがサイズ上限を超えています', + errParseFailed: 'ファイルの解析に失敗しました', + errImageNoText: + '画像の添付ファイルはテキストを提供しません。画像としてユーザーメッセージと一緒に送信されるため、そのまま画像をご確認ください', + errNotImage: 'サポートされていない画像形式です', + errGskNotLoggedIn: + 'Genspark にサインインしていません。下の「Genspark にサインイン」からサインインして再試行してください', + errNoApiKey: '{provider} の API キーが設定されていません', + errNoModel: 'モデル名が設定されていません', + menuFile: 'ファイル', + menuNewDoc: '新規文書', + menuNewWindow: '新規ウィンドウ', + menuOpen: '開く…', + menuOpenRecent: '最近使った文書を開く', + menuNoRecent: '最近使った文書はありません', + menuClose: '閉じる', + menuSave: '保存', + menuSaveAs: '名前を付けて保存…', + menuPageSetup: 'ページ設定…', + menuExportPdf: 'PDF としてエクスポート…', + menuPrint: '印刷…', + menuEdit: '編集', + menuUndo: '元に戻す', + menuRedo: 'やり直す', + menuCut: '切り取り', + menuCopy: 'コピー', + menuPaste: '貼り付け', + menuPasteMatch: '貼り付けて書式を合わせる', + menuFindReplace: '検索と置換…', + menuSelectAll: 'すべて選択', + menuView: '表示', + menuZoomIn: '拡大', + menuZoomOut: '縮小', + menuZoom100: '実際のサイズ (100%)', + menuPageWidth: 'ページ幅', + menuWholePage: 'ページ全体', + menuAiSidebar: 'AI サイドバー', + menuDarkMode: 'ダークモード', + menuFullscreen: 'フルスクリーンにする', + menuInsert: '挿入', + menuInsertTable: '表 (3×3)', + menuInsertImage: '画像…', + menuInsertPageBreak: '改ページ', + menuInsertLink: 'ハイパーリンク…', + menuInsertEquation: '数式…', + menuComment: 'コメント', + menuFormat: '書式', + menuBold: '太字', + menuItalic: '斜体', + menuUnderline: '下線', + menuAlign: '配置', + menuAlignLeft: '左揃え', + menuAlignCenter: '中央揃え', + menuAlignRight: '右揃え', + menuAlignJustify: '両端揃え', + menuFont: 'フォント…', + menuParagraph: '段落…', + menuTools: 'ツール', + menuWordCount: '文字カウント…', + menuSpelling: 'スペルチェックと文章校正', + menuMacros: 'マクロ', + menuWindow: 'ウィンドウ', + menuHelp: 'ヘルプ', + menuDocsHelp: 'GenOffice Docs ヘルプ', + }, + ko: { + dlgOpenDoc: '문서 열기', + filterWord: 'Word 문서', + dlgSaveAs: '다른 이름으로 저장', + closeUnsavedMsg: '이 문서에 저장하지 않은 변경 사항이 있습니다.', + closeUnsavedDetail: '닫기 전에 저장하시겠습니까?', + closeNoReplyMsg: '문서가 응답하지 않으며 저장하지 않은 변경 사항이 있을 수 있습니다.', + closeNoReplyDetail: '그래도 닫을까요? 저장하지 않은 변경 사항은 사라집니다.', + btnCloseAnyway: '닫기', + autosaveFoundTitle: '자동 복구 버전 발견', + autosaveFoundBody: + '마지막 세션에 저장되지 않은 변경 내용이 있습니다. 자동 저장 버전을 복원할까요?', + autosaveRestore: '복원', + autosaveDiscard: '취소', + btnDontSave: '저장 안 함', + btnCancel: '취소', + dlgInsertImage: '그림 삽입', + filterImages: '그림', + dlgAddAttachment: '첨부 파일 추가', + filterSupported: '지원되는 파일', + filterAll: '모든 파일', + dlgExportPdf: 'PDF로 내보내기', + errUnsupportedExt: '.{ext} 형식은 지원되지 않습니다', + errNotFile: '파일이 아닙니다', + errTooLarge: '{mb}MB 제한을 초과했습니다', + errImageTooLarge: '이미지가 5MB 제한을 초과했습니다', + errUnreadable: '읽을 수 없습니다', + errFileTooLarge: '파일이 크기 제한을 초과했습니다', + errParseFailed: '파일을 분석하지 못했습니다', + errImageNoText: + '이미지 첨부 파일은 텍스트를 제공하지 않으며, 이미지 형태로 사용자 메시지와 함께 전송되므로 이미지를 직접 확인하면 됩니다', + errNotImage: '지원되지 않는 이미지 형식입니다', + errGskNotLoggedIn: + 'Genspark에 로그인되어 있지 않습니다. 아래 "Genspark 로그인"을 눌러 로그인한 뒤 다시 시도하세요', + errNoApiKey: '{provider}의 API 키가 설정되지 않았습니다', + errNoModel: '모델 이름이 설정되지 않았습니다', + menuFile: '파일', + menuNewDoc: '새 문서', + menuNewWindow: '새 창', + menuOpen: '열기…', + menuOpenRecent: '최근 문서 열기', + menuNoRecent: '최근 문서 없음', + menuClose: '닫기', + menuSave: '저장', + menuSaveAs: '다른 이름으로 저장…', + menuPageSetup: '페이지 설정…', + menuExportPdf: 'PDF로 내보내기…', + menuPrint: '인쇄…', + menuEdit: '편집', + menuUndo: '실행 취소', + menuRedo: '다시 실행', + menuCut: '잘라내기', + menuCopy: '복사', + menuPaste: '붙여넣기', + menuPasteMatch: '서식 맞춰 붙여넣기', + menuFindReplace: '찾기 및 바꾸기…', + menuSelectAll: '모두 선택', + menuView: '보기', + menuZoomIn: '확대', + menuZoomOut: '축소', + menuZoom100: '실제 크기(100%)', + menuPageWidth: '페이지 너비', + menuWholePage: '전체 페이지', + menuAiSidebar: 'AI 사이드바', + menuDarkMode: '다크 모드', + menuFullscreen: '전체 화면 시작', + menuInsert: '삽입', + menuInsertTable: '표(3×3)', + menuInsertImage: '그림…', + menuInsertPageBreak: '페이지 나누기', + menuInsertLink: '하이퍼링크…', + menuInsertEquation: '수식…', + menuComment: '메모', + menuFormat: '서식', + menuBold: '굵게', + menuItalic: '기울임꼴', + menuUnderline: '밑줄', + menuAlign: '맞춤', + menuAlignLeft: '왼쪽 맞춤', + menuAlignCenter: '가운데 맞춤', + menuAlignRight: '오른쪽 맞춤', + menuAlignJustify: '양쪽 맞춤', + menuFont: '글꼴…', + menuParagraph: '단락…', + menuTools: '도구', + menuWordCount: '단어 개수…', + menuSpelling: '맞춤법 및 문법 검사', + menuMacros: '매크로', + menuWindow: '창', + menuHelp: '도움말', + menuDocsHelp: 'GenOffice Docs 도움말', + }, + fr: { + dlgOpenDoc: 'Ouvrir un document', + filterWord: 'Documents Word', + dlgSaveAs: 'Enregistrer sous', + closeUnsavedMsg: 'Ce document contient des modifications non enregistrées.', + closeUnsavedDetail: 'Voulez-vous les enregistrer avant de fermer ?', + closeNoReplyMsg: + 'Le document ne répond pas et peut contenir des modifications non enregistrées.', + closeNoReplyDetail: 'Fermer quand même ? Les modifications non enregistrées seront perdues.', + btnCloseAnyway: 'Fermer quand même', + autosaveFoundTitle: 'Version récupérée trouvée', + autosaveFoundBody: + 'Des modifications non enregistrées existent. Restaurer la version auto-enregistrée ?', + autosaveRestore: 'Restaurer', + autosaveDiscard: 'Ignorer', + btnDontSave: 'Ne pas enregistrer', + btnCancel: 'Annuler', + dlgInsertImage: 'Insérer une image', + filterImages: 'Images', + dlgAddAttachment: 'Ajouter des pièces jointes', + filterSupported: 'Fichiers pris en charge', + filterAll: 'Tous les fichiers', + dlgExportPdf: 'Exporter au format PDF', + errUnsupportedExt: 'les fichiers .{ext} ne sont pas pris en charge', + errNotFile: "n'est pas un fichier", + errTooLarge: 'dépasse la limite de {mb} Mo', + errImageTooLarge: "l'image dépasse la limite de 5 Mo", + errUnreadable: 'lecture impossible', + errFileTooLarge: 'Le fichier dépasse la taille maximale', + errParseFailed: "Échec de l'analyse du fichier", + errImageNoText: + "Les pièces jointes image ne fournissent pas de texte ; l'image est envoyée avec le message de l'utilisateur, consultez-la directement", + errNotImage: "type d'image non pris en charge", + errGskNotLoggedIn: + 'Non connecté à Genspark : cliquez sur « Se connecter à Genspark » ci-dessous, connectez-vous puis réessayez', + errNoApiKey: 'Aucune clé API configurée pour {provider}', + errNoModel: 'Aucun nom de modèle configuré', + menuFile: 'Fichier', + menuNewDoc: 'Nouveau document', + menuNewWindow: 'Nouvelle fenêtre', + menuOpen: 'Ouvrir…', + menuOpenRecent: 'Ouvrir un document récent', + menuNoRecent: 'Aucun document récent', + menuClose: 'Fermer', + menuSave: 'Enregistrer', + menuSaveAs: 'Enregistrer sous…', + menuPageSetup: 'Mise en page…', + menuExportPdf: 'Exporter au format PDF…', + menuPrint: 'Imprimer…', + menuEdit: 'Édition', + menuUndo: 'Annuler', + menuRedo: 'Rétablir', + menuCut: 'Couper', + menuCopy: 'Copier', + menuPaste: 'Coller', + menuPasteMatch: 'Coller et adapter le style', + menuFindReplace: 'Rechercher et remplacer…', + menuSelectAll: 'Tout sélectionner', + menuView: 'Affichage', + menuZoomIn: 'Zoom avant', + menuZoomOut: 'Zoom arrière', + menuZoom100: 'Taille réelle (100 %)', + menuPageWidth: 'Largeur de page', + menuWholePage: 'Page entière', + menuAiSidebar: 'Volet IA', + menuDarkMode: 'Mode sombre', + menuFullscreen: 'Activer le mode plein écran', + menuInsert: 'Insertion', + menuInsertTable: 'Tableau (3×3)', + menuInsertImage: 'Image…', + menuInsertPageBreak: 'Saut de page', + menuInsertLink: 'Lien hypertexte…', + menuInsertEquation: 'Équation…', + menuComment: 'Commentaire', + menuFormat: 'Format', + menuBold: 'Gras', + menuItalic: 'Italique', + menuUnderline: 'Souligné', + menuAlign: 'Alignement', + menuAlignLeft: 'Aligner à gauche', + menuAlignCenter: 'Centrer', + menuAlignRight: 'Aligner à droite', + menuAlignJustify: 'Justifier', + menuFont: 'Police…', + menuParagraph: 'Paragraphe…', + menuTools: 'Outils', + menuWordCount: 'Statistiques…', + menuSpelling: 'Grammaire et orthographe', + menuMacros: 'Macros', + menuWindow: 'Fenêtre', + menuHelp: 'Aide', + menuDocsHelp: 'Aide GenOffice Docs', + }, + de: { + dlgOpenDoc: 'Dokument öffnen', + filterWord: 'Word-Dokumente', + dlgSaveAs: 'Speichern unter', + closeUnsavedMsg: 'Dieses Dokument enthält ungespeicherte Änderungen.', + closeUnsavedDetail: 'Vor dem Schließen speichern?', + closeNoReplyMsg: + 'Das Dokument reagiert nicht und enthält möglicherweise ungespeicherte Änderungen.', + closeNoReplyDetail: 'Trotzdem schließen? Ungespeicherte Änderungen gehen verloren.', + btnCloseAnyway: 'Trotzdem schließen', + autosaveFoundTitle: 'Wiederhergestellte Version gefunden', + autosaveFoundBody: + 'Es gibt ungespeicherte Änderungen. Automatisch gespeicherte Version wiederherstellen?', + autosaveRestore: 'Wiederherstellen', + autosaveDiscard: 'Verwerfen', + btnDontSave: 'Nicht speichern', + btnCancel: 'Abbrechen', + dlgInsertImage: 'Bild einfügen', + filterImages: 'Bilder', + dlgAddAttachment: 'Anlagen hinzufügen', + filterSupported: 'Unterstützte Dateien', + filterAll: 'Alle Dateien', + dlgExportPdf: 'Als PDF exportieren', + errUnsupportedExt: '.{ext}-Dateien werden nicht unterstützt', + errNotFile: 'keine Datei', + errTooLarge: 'überschreitet das Limit von {mb} MB', + errImageTooLarge: 'Bild überschreitet das Limit von 5 MB', + errUnreadable: 'kann nicht gelesen werden', + errFileTooLarge: 'Datei überschreitet die maximale Größe', + errParseFailed: 'Datei konnte nicht analysiert werden', + errImageNoText: + 'Bildanlagen liefern keinen Text; das Bild wird mit der Benutzernachricht gesendet und kann direkt betrachtet werden', + errNotImage: 'kein unterstütztes Bildformat', + errGskNotLoggedIn: + 'Nicht bei Genspark angemeldet: Klicken Sie unten auf „Bei Genspark anmelden“, melden Sie sich an und versuchen Sie es erneut', + errNoApiKey: 'Kein API-Schlüssel für {provider} konfiguriert', + errNoModel: 'Kein Modellname konfiguriert', + menuFile: 'Datei', + menuNewDoc: 'Neues Dokument', + menuNewWindow: 'Neues Fenster', + menuOpen: 'Öffnen…', + menuOpenRecent: 'Zuletzt verwendete Dokumente', + menuNoRecent: 'Keine zuletzt verwendeten Dokumente', + menuClose: 'Schließen', + menuSave: 'Speichern', + menuSaveAs: 'Speichern unter…', + menuPageSetup: 'Seite einrichten…', + menuExportPdf: 'Als PDF exportieren…', + menuPrint: 'Drucken…', + menuEdit: 'Bearbeiten', + menuUndo: 'Rückgängig', + menuRedo: 'Wiederholen', + menuCut: 'Ausschneiden', + menuCopy: 'Kopieren', + menuPaste: 'Einfügen', + menuPasteMatch: 'Einfügen und Stil anpassen', + menuFindReplace: 'Suchen und Ersetzen…', + menuSelectAll: 'Alles auswählen', + menuView: 'Ansicht', + menuZoomIn: 'Vergrößern', + menuZoomOut: 'Verkleinern', + menuZoom100: 'Originalgröße (100 %)', + menuPageWidth: 'Seitenbreite', + menuWholePage: 'Ganze Seite', + menuAiSidebar: 'KI-Seitenleiste', + menuDarkMode: 'Dunkelmodus', + menuFullscreen: 'Vollbild ein', + menuInsert: 'Einfügen', + menuInsertTable: 'Tabelle (3×3)', + menuInsertImage: 'Bild…', + menuInsertPageBreak: 'Seitenumbruch', + menuInsertLink: 'Hyperlink…', + menuInsertEquation: 'Formel…', + menuComment: 'Kommentar', + menuFormat: 'Format', + menuBold: 'Fett', + menuItalic: 'Kursiv', + menuUnderline: 'Unterstrichen', + menuAlign: 'Ausrichten', + menuAlignLeft: 'Linksbündig', + menuAlignCenter: 'Zentriert', + menuAlignRight: 'Rechtsbündig', + menuAlignJustify: 'Blocksatz', + menuFont: 'Schriftart…', + menuParagraph: 'Absatz…', + menuTools: 'Extras', + menuWordCount: 'Wörter zählen…', + menuSpelling: 'Rechtschreibung und Grammatik', + menuMacros: 'Makros', + menuWindow: 'Fenster', + menuHelp: 'Hilfe', + menuDocsHelp: 'GenOffice Docs-Hilfe', + }, + es: { + dlgOpenDoc: 'Abrir documento', + filterWord: 'Documentos de Word', + dlgSaveAs: 'Guardar como', + closeUnsavedMsg: 'Este documento tiene cambios sin guardar.', + closeUnsavedDetail: '¿Desea guardarlos antes de cerrar?', + closeNoReplyMsg: 'El documento no responde y puede tener cambios sin guardar.', + closeNoReplyDetail: '¿Cerrar de todos modos? Los cambios sin guardar se perderán.', + btnCloseAnyway: 'Cerrar de todos modos', + autosaveFoundTitle: 'Se encontró una versión recuperada', + autosaveFoundBody: + 'Hay cambios sin guardar de la última sesión. ¿Restaurar la versión autoguardada?', + autosaveRestore: 'Restaurar', + autosaveDiscard: 'Descartar', + btnDontSave: 'No guardar', + btnCancel: 'Cancelar', + dlgInsertImage: 'Insertar imagen', + filterImages: 'Imágenes', + dlgAddAttachment: 'Agregar datos adjuntos', + filterSupported: 'Archivos compatibles', + filterAll: 'Todos los archivos', + dlgExportPdf: 'Exportar como PDF', + errUnsupportedExt: 'los archivos .{ext} no son compatibles', + errNotFile: 'no es un archivo', + errTooLarge: 'supera el límite de {mb} MB', + errImageTooLarge: 'la imagen supera el límite de 5 MB', + errUnreadable: 'no se puede leer', + errFileTooLarge: 'El archivo supera el tamaño máximo', + errParseFailed: 'No se pudo analizar el archivo', + errImageNoText: + 'Las imágenes adjuntas no proporcionan texto; la imagen se envía junto con el mensaje del usuario, puedes verla directamente', + errNotImage: 'no es un tipo de imagen compatible', + errGskNotLoggedIn: + 'No has iniciado sesión en Genspark: pulsa «Iniciar sesión en Genspark» abajo, inicia sesión y vuelve a intentarlo', + errNoApiKey: 'No hay clave de API configurada para {provider}', + errNoModel: 'No se ha configurado el nombre del modelo', + menuFile: 'Archivo', + menuNewDoc: 'Nuevo documento', + menuNewWindow: 'Nueva ventana', + menuOpen: 'Abrir…', + menuOpenRecent: 'Abrir recientes', + menuNoRecent: 'No hay documentos recientes', + menuClose: 'Cerrar', + menuSave: 'Guardar', + menuSaveAs: 'Guardar como…', + menuPageSetup: 'Configurar página…', + menuExportPdf: 'Exportar como PDF…', + menuPrint: 'Imprimir…', + menuEdit: 'Edición', + menuUndo: 'Deshacer', + menuRedo: 'Rehacer', + menuCut: 'Cortar', + menuCopy: 'Copiar', + menuPaste: 'Pegar', + menuPasteMatch: 'Pegar con el mismo estilo', + menuFindReplace: 'Buscar y reemplazar…', + menuSelectAll: 'Seleccionar todo', + menuView: 'Ver', + menuZoomIn: 'Acercar', + menuZoomOut: 'Alejar', + menuZoom100: 'Tamaño real (100 %)', + menuPageWidth: 'Ancho de página', + menuWholePage: 'Página completa', + menuAiSidebar: 'Barra lateral de IA', + menuDarkMode: 'Modo oscuro', + menuFullscreen: 'Usar pantalla completa', + menuInsert: 'Insertar', + menuInsertTable: 'Tabla (3×3)', + menuInsertImage: 'Imagen…', + menuInsertPageBreak: 'Salto de página', + menuInsertLink: 'Hipervínculo…', + menuInsertEquation: 'Ecuación…', + menuComment: 'Comentario', + menuFormat: 'Formato', + menuBold: 'Negrita', + menuItalic: 'Cursiva', + menuUnderline: 'Subrayado', + menuAlign: 'Alinear', + menuAlignLeft: 'Alinear a la izquierda', + menuAlignCenter: 'Centrar', + menuAlignRight: 'Alinear a la derecha', + menuAlignJustify: 'Justificar', + menuFont: 'Fuente…', + menuParagraph: 'Párrafo…', + menuTools: 'Herramientas', + menuWordCount: 'Contar palabras…', + menuSpelling: 'Ortografía y gramática', + menuMacros: 'Macros', + menuWindow: 'Ventana', + menuHelp: 'Ayuda', + menuDocsHelp: 'Ayuda de GenOffice Docs', + }, + th: { + dlgOpenDoc: 'เปิดเอกสาร', + filterWord: 'เอกสาร Word', + dlgSaveAs: 'บันทึกเป็น', + closeUnsavedMsg: 'เอกสารนี้มีการเปลี่ยนแปลงที่ยังไม่ได้บันทึก', + closeUnsavedDetail: 'ต้องการบันทึกก่อนปิดหรือไม่?', + closeNoReplyMsg: 'เอกสารไม่ตอบสนองและอาจมีการเปลี่ยนแปลงที่ยังไม่ได้บันทึก', + closeNoReplyDetail: 'ปิดต่อไปหรือไม่ การเปลี่ยนแปลงที่ยังไม่ได้บันทึกจะหายไป', + btnCloseAnyway: 'ปิดต่อไป', + autosaveFoundTitle: 'พบเวอร์ชันกู้คืนอัตโนมัติ', + autosaveFoundBody: 'มีการเปลี่ยนแปลงที่ยังไม่ได้บันทึกจากครั้งก่อน ต้องการกู้คืนหรือไม่?', + autosaveRestore: 'กู้คืน', + autosaveDiscard: 'ละทิ้ง', + btnDontSave: 'ไม่บันทึก', + btnCancel: 'ยกเลิก', + dlgInsertImage: 'แทรกรูปภาพ', + filterImages: 'รูปภาพ', + dlgAddAttachment: 'เพิ่มสิ่งที่แนบ', + filterSupported: 'ไฟล์ที่รองรับ', + filterAll: 'ไฟล์ทั้งหมด', + dlgExportPdf: 'ส่งออกเป็น PDF', + errUnsupportedExt: 'ไม่รองรับไฟล์ .{ext}', + errNotFile: 'ไม่ใช่ไฟล์', + errTooLarge: 'เกินขีดจำกัด {mb}MB', + errImageTooLarge: 'รูปภาพเกินขีดจำกัด 5MB', + errUnreadable: 'ไม่สามารถอ่านได้', + errFileTooLarge: 'ไฟล์เกินขนาดสูงสุด', + errParseFailed: 'แยกวิเคราะห์ไฟล์ไม่สำเร็จ', + errImageNoText: + 'สิ่งที่แนบเป็นรูปภาพไม่มีข้อความ รูปจะถูกส่งไปพร้อมข้อความของผู้ใช้ ดูรูปได้โดยตรง', + errNotImage: 'ไม่ใช่ชนิดรูปภาพที่รองรับ', + errGskNotLoggedIn: + 'ยังไม่ได้ลงชื่อเข้าใช้ Genspark: แตะ “ลงชื่อเข้าใช้ Genspark” ด้านล่าง แล้วลองอีกครั้ง', + errNoApiKey: 'ยังไม่ได้ตั้งค่า API Key ของ {provider}', + errNoModel: 'ยังไม่ได้ตั้งค่าชื่อโมเดล', + menuFile: 'ไฟล์', + menuNewDoc: 'เอกสารใหม่', + menuNewWindow: 'หน้าต่างใหม่', + menuOpen: 'เปิด…', + menuOpenRecent: 'เปิดเอกสารล่าสุด', + menuNoRecent: 'ไม่มีเอกสารล่าสุด', + menuClose: 'ปิด', + menuSave: 'บันทึก', + menuSaveAs: 'บันทึกเป็น…', + menuPageSetup: 'ตั้งค่าหน้ากระดาษ…', + menuExportPdf: 'ส่งออกเป็น PDF…', + menuPrint: 'พิมพ์…', + menuEdit: 'แก้ไข', + menuUndo: 'เลิกทำ', + menuRedo: 'ทำซ้ำ', + menuCut: 'ตัด', + menuCopy: 'คัดลอก', + menuPaste: 'วาง', + menuPasteMatch: 'วางแบบจับคู่ลักษณะ', + menuFindReplace: 'ค้นหาและแทนที่…', + menuSelectAll: 'เลือกทั้งหมด', + menuView: 'มุมมอง', + menuZoomIn: 'ขยาย', + menuZoomOut: 'ย่อ', + menuZoom100: 'ขนาดจริง (100%)', + menuPageWidth: 'ความกว้างของหน้า', + menuWholePage: 'ทั้งหน้า', + menuAiSidebar: 'แถบข้าง AI', + menuDarkMode: 'โหมดมืด', + menuFullscreen: 'เข้าสู่โหมดเต็มหน้าจอ', + menuInsert: 'แทรก', + menuInsertTable: 'ตาราง (3×3)', + menuInsertImage: 'รูปภาพ…', + menuInsertPageBreak: 'ตัวแบ่งหน้า', + menuInsertLink: 'ไฮเปอร์ลิงก์…', + menuInsertEquation: 'สมการ…', + menuComment: 'ข้อคิดเห็น', + menuFormat: 'รูปแบบ', + menuBold: 'ตัวหนา', + menuItalic: 'ตัวเอียง', + menuUnderline: 'ขีดเส้นใต้', + menuAlign: 'จัดแนว', + menuAlignLeft: 'จัดชิดซ้าย', + menuAlignCenter: 'จัดกึ่งกลาง', + menuAlignRight: 'จัดชิดขวา', + menuAlignJustify: 'จัดชิดขอบ', + menuFont: 'ฟอนต์…', + menuParagraph: 'ย่อหน้า…', + menuTools: 'เครื่องมือ', + menuWordCount: 'นับจำนวนคำ…', + menuSpelling: 'การสะกดและไวยากรณ์', + menuMacros: 'แมโคร', + menuWindow: 'หน้าต่าง', + menuHelp: 'วิธีใช้', + menuDocsHelp: 'วิธีใช้ GenOffice Docs', + }, + id: { + dlgOpenDoc: 'Buka Dokumen', + filterWord: 'Dokumen Word', + dlgSaveAs: 'Simpan Sebagai', + closeUnsavedMsg: 'Dokumen ini memiliki perubahan yang belum disimpan.', + closeUnsavedDetail: 'Simpan sebelum menutup?', + closeNoReplyMsg: 'Dokumen tidak merespons dan mungkin memiliki perubahan yang belum disimpan.', + closeNoReplyDetail: 'Tetap tutup? Perubahan yang belum disimpan akan hilang.', + btnCloseAnyway: 'Tetap Tutup', + autosaveFoundTitle: 'Versi pemulihan ditemukan', + autosaveFoundBody: + 'Ada perubahan yang belum disimpan dari sesi terakhir. Pulihkan versi tersimpan otomatis?', + autosaveRestore: 'Pulihkan', + autosaveDiscard: 'Buang', + btnDontSave: 'Jangan Simpan', + btnCancel: 'Batal', + dlgInsertImage: 'Sisipkan Gambar', + filterImages: 'Gambar', + dlgAddAttachment: 'Tambahkan Lampiran', + filterSupported: 'File yang Didukung', + filterAll: 'Semua File', + dlgExportPdf: 'Ekspor sebagai PDF', + errUnsupportedExt: 'file .{ext} tidak didukung', + errNotFile: 'bukan file', + errTooLarge: 'melebihi batas {mb}MB', + errImageTooLarge: 'gambar melebihi batas 5MB', + errUnreadable: 'tidak dapat dibaca', + errFileTooLarge: 'File melebihi batas ukuran', + errParseFailed: 'Gagal mengurai file', + errImageNoText: + 'Lampiran gambar tidak menyediakan teks; gambar dikirim bersama pesan pengguna dan dapat dilihat langsung', + errNotImage: 'bukan jenis gambar yang didukung', + errGskNotLoggedIn: 'Belum masuk ke Genspark: klik “Masuk ke Genspark” di bawah, lalu coba lagi', + errNoApiKey: 'API Key untuk {provider} belum dikonfigurasi', + errNoModel: 'Nama model belum dikonfigurasi', + menuFile: 'File', + menuNewDoc: 'Dokumen Baru', + menuNewWindow: 'Jendela Baru', + menuOpen: 'Buka…', + menuOpenRecent: 'Buka Terbaru', + menuNoRecent: 'Tidak Ada Dokumen Terbaru', + menuClose: 'Tutup', + menuSave: 'Simpan', + menuSaveAs: 'Simpan Sebagai…', + menuPageSetup: 'Penyetelan Halaman…', + menuExportPdf: 'Ekspor sebagai PDF…', + menuPrint: 'Cetak…', + menuEdit: 'Edit', + menuUndo: 'Urungkan', + menuRedo: 'Ulangi', + menuCut: 'Potong', + menuCopy: 'Salin', + menuPaste: 'Tempel', + menuPasteMatch: 'Tempel dan Samakan Gaya', + menuFindReplace: 'Temukan dan Ganti…', + menuSelectAll: 'Pilih Semua', + menuView: 'Tampilan', + menuZoomIn: 'Perbesar', + menuZoomOut: 'Perkecil', + menuZoom100: 'Ukuran Sebenarnya (100%)', + menuPageWidth: 'Lebar Halaman', + menuWholePage: 'Seluruh Halaman', + menuAiSidebar: 'Bilah Samping AI', + menuDarkMode: 'Mode Gelap', + menuFullscreen: 'Masuk Layar Penuh', + menuInsert: 'Sisipkan', + menuInsertTable: 'Tabel (3×3)', + menuInsertImage: 'Gambar…', + menuInsertPageBreak: 'Pemisah Halaman', + menuInsertLink: 'Hyperlink…', + menuInsertEquation: 'Persamaan…', + menuComment: 'Komentar', + menuFormat: 'Format', + menuBold: 'Tebal', + menuItalic: 'Miring', + menuUnderline: 'Garis Bawah', + menuAlign: 'Perataan', + menuAlignLeft: 'Rata Kiri', + menuAlignCenter: 'Rata Tengah', + menuAlignRight: 'Rata Kanan', + menuAlignJustify: 'Rata Kiri Kanan', + menuFont: 'Font…', + menuParagraph: 'Paragraf…', + menuTools: 'Alat', + menuWordCount: 'Hitungan Kata…', + menuSpelling: 'Ejaan dan Tata Bahasa', + menuMacros: 'Makro', + menuWindow: 'Jendela', + menuHelp: 'Bantuan', + menuDocsHelp: 'Bantuan GenOffice Docs', + }, + ru: { + dlgOpenDoc: 'Открыть документ', + filterWord: 'Документы Word', + dlgSaveAs: 'Сохранить как', + closeUnsavedMsg: 'В этом документе есть несохранённые изменения.', + closeUnsavedDetail: 'Сохранить их перед закрытием?', + closeNoReplyMsg: 'Документ не отвечает; возможно, есть несохранённые изменения.', + closeNoReplyDetail: 'Всё равно закрыть? Несохранённые изменения будут потеряны.', + btnCloseAnyway: 'Закрыть всё равно', + autosaveFoundTitle: 'Найдена восстановленная версия', + autosaveFoundBody: + 'Есть несохранённые изменения из прошлого сеанса. Восстановить автосохранённую версию?', + autosaveRestore: 'Восстановить', + autosaveDiscard: 'Отклонить', + btnDontSave: 'Не сохранять', + btnCancel: 'Отмена', + dlgInsertImage: 'Вставить рисунок', + filterImages: 'Изображения', + dlgAddAttachment: 'Добавить вложения', + filterSupported: 'Поддерживаемые файлы', + filterAll: 'Все файлы', + dlgExportPdf: 'Экспорт в PDF', + errUnsupportedExt: 'файлы .{ext} не поддерживаются', + errNotFile: 'не является файлом', + errTooLarge: 'превышает лимит {mb} МБ', + errImageTooLarge: 'изображение превышает лимит 5 МБ', + errUnreadable: 'не удается прочитать', + errFileTooLarge: 'Файл превышает максимальный размер', + errParseFailed: 'Не удалось разобрать файл', + errImageNoText: + 'Вложенные изображения не содержат текста; изображение отправляется вместе с сообщением пользователя, смотрите его напрямую', + errNotImage: 'неподдерживаемый тип изображения', + errGskNotLoggedIn: + 'Вы не вошли в Genspark: нажмите «Войти в Genspark» ниже, войдите и повторите попытку', + errNoApiKey: 'API-ключ для {provider} не настроен', + errNoModel: 'Не указано имя модели', + menuFile: 'Файл', + menuNewDoc: 'Создать документ', + menuNewWindow: 'Новое окно', + menuOpen: 'Открыть…', + menuOpenRecent: 'Открыть последние', + menuNoRecent: 'Нет последних документов', + menuClose: 'Закрыть', + menuSave: 'Сохранить', + menuSaveAs: 'Сохранить как…', + menuPageSetup: 'Параметры страницы…', + menuExportPdf: 'Экспорт в PDF…', + menuPrint: 'Печать…', + menuEdit: 'Правка', + menuUndo: 'Отменить', + menuRedo: 'Повторить', + menuCut: 'Вырезать', + menuCopy: 'Копировать', + menuPaste: 'Вставить', + menuPasteMatch: 'Вставить и согласовать стиль', + menuFindReplace: 'Найти и заменить…', + menuSelectAll: 'Выделить все', + menuView: 'Вид', + menuZoomIn: 'Увеличить', + menuZoomOut: 'Уменьшить', + menuZoom100: 'Фактический размер (100%)', + menuPageWidth: 'По ширине страницы', + menuWholePage: 'Страница целиком', + menuAiSidebar: 'Боковая панель ИИ', + menuDarkMode: 'Темный режим', + menuFullscreen: 'Перейти в полноэкранный режим', + menuInsert: 'Вставка', + menuInsertTable: 'Таблица (3×3)', + menuInsertImage: 'Рисунок…', + menuInsertPageBreak: 'Разрыв страницы', + menuInsertLink: 'Гиперссылка…', + menuInsertEquation: 'Уравнение…', + menuComment: 'Примечание', + menuFormat: 'Формат', + menuBold: 'Полужирный', + menuItalic: 'Курсив', + menuUnderline: 'Подчеркнутый', + menuAlign: 'Выравнивание', + menuAlignLeft: 'По левому краю', + menuAlignCenter: 'По центру', + menuAlignRight: 'По правому краю', + menuAlignJustify: 'По ширине', + menuFont: 'Шрифт…', + menuParagraph: 'Абзац…', + menuTools: 'Сервис', + menuWordCount: 'Статистика…', + menuSpelling: 'Правописание', + menuMacros: 'Макросы', + menuWindow: 'Окно', + menuHelp: 'Справка', + menuDocsHelp: 'Справка GenOffice Docs', + }, + ar: { + dlgOpenDoc: 'فتح مستند', + filterWord: 'مستندات Word', + dlgSaveAs: 'حفظ باسم', + closeUnsavedMsg: 'يحتوي هذا المستند على تغييرات غير محفوظة.', + closeUnsavedDetail: 'هل تريد حفظها قبل الإغلاق؟', + closeNoReplyMsg: 'المستند لا يستجيب وقد يحتوي على تغييرات غير محفوظة.', + closeNoReplyDetail: 'هل تريد الإغلاق رغم ذلك؟ ستفقد التغييرات غير المحفوظة.', + btnCloseAnyway: 'إغلاق على أي حال', + autosaveFoundTitle: 'تم العثور على نسخة مستردة', + autosaveFoundBody: + 'توجد تغييرات غير محفوظة من الجلسة الأخيرة. هل تريد استعادة النسخة المحفوظة تلقائيًا؟', + autosaveRestore: 'استعادة', + autosaveDiscard: 'تجاهل', + btnDontSave: 'عدم الحفظ', + btnCancel: 'إلغاء', + dlgInsertImage: 'إدراج صورة', + filterImages: 'الصور', + dlgAddAttachment: 'إضافة مرفقات', + filterSupported: 'الملفات المدعومة', + filterAll: 'كل الملفات', + dlgExportPdf: 'تصدير بتنسيق PDF', + errUnsupportedExt: 'ملفات .{ext} غير مدعومة', + errNotFile: 'ليس ملفًا', + errTooLarge: 'يتجاوز الحد {mb}MB', + errImageTooLarge: 'الصورة تتجاوز حد 5MB', + errUnreadable: 'تعذرت القراءة', + errFileTooLarge: 'الملف يتجاوز الحد الأقصى للحجم', + errParseFailed: 'فشل تحليل الملف', + errImageNoText: + 'مرفقات الصور لا توفر نصًا؛ تُرسل الصورة مع رسالة المستخدم ويمكن الاطلاع عليها مباشرة', + errNotImage: 'ليس نوع صورة مدعومًا', + errGskNotLoggedIn: + 'لم تسجّل الدخول إلى Genspark: انقر على «تسجيل الدخول إلى Genspark» أدناه ثم أعد المحاولة', + errNoApiKey: 'لم يتم تكوين مفتاح API لـ {provider}', + errNoModel: 'لم يتم تكوين اسم النموذج', + menuFile: 'ملف', + menuNewDoc: 'مستند جديد', + menuNewWindow: 'نافذة جديدة', + menuOpen: 'فتح…', + menuOpenRecent: 'فتح الأخيرة', + menuNoRecent: 'لا توجد مستندات أخيرة', + menuClose: 'إغلاق', + menuSave: 'حفظ', + menuSaveAs: 'حفظ باسم…', + menuPageSetup: 'إعداد الصفحة…', + menuExportPdf: 'تصدير بتنسيق PDF…', + menuPrint: 'طباعة…', + menuEdit: 'تحرير', + menuUndo: 'تراجع', + menuRedo: 'إعادة', + menuCut: 'قص', + menuCopy: 'نسخ', + menuPaste: 'لصق', + menuPasteMatch: 'لصق مع مطابقة النمط', + menuFindReplace: 'بحث واستبدال…', + menuSelectAll: 'تحديد الكل', + menuView: 'عرض', + menuZoomIn: 'تكبير', + menuZoomOut: 'تصغير', + menuZoom100: 'الحجم الفعلي (100%)', + menuPageWidth: 'عرض الصفحة', + menuWholePage: 'صفحة كاملة', + menuAiSidebar: 'الشريط الجانبي للذكاء الاصطناعي', + menuDarkMode: 'الوضع الداكن', + menuFullscreen: 'الدخول إلى ملء الشاشة', + menuInsert: 'إدراج', + menuInsertTable: 'جدول (3×3)', + menuInsertImage: 'صورة…', + menuInsertPageBreak: 'فاصل صفحات', + menuInsertLink: 'ارتباط تشعبي…', + menuInsertEquation: 'معادلة…', + menuComment: 'تعليق', + menuFormat: 'تنسيق', + menuBold: 'غامق', + menuItalic: 'مائل', + menuUnderline: 'تسطير', + menuAlign: 'محاذاة', + menuAlignLeft: 'محاذاة إلى اليسار', + menuAlignCenter: 'توسيط', + menuAlignRight: 'محاذاة إلى اليمين', + menuAlignJustify: 'ضبط', + menuFont: 'الخط…', + menuParagraph: 'فقرة…', + menuTools: 'أدوات', + menuWordCount: 'عدد الكلمات…', + menuSpelling: 'تدقيق إملائي ونحوي', + menuMacros: 'وحدات الماكرو', + menuWindow: 'نافذة', + menuHelp: 'تعليمات', + menuDocsHelp: 'تعليمات GenOffice Docs', + }, + pt: { + dlgOpenDoc: 'Abrir Documento', + filterWord: 'Documentos do Word', + dlgSaveAs: 'Salvar Como', + closeUnsavedMsg: 'Este documento tem alterações não salvas.', + closeUnsavedDetail: 'Deseja salvá-las antes de fechar?', + closeNoReplyMsg: 'O documento não está respondendo e pode ter alterações não salvas.', + closeNoReplyDetail: 'Fechar mesmo assim? As alterações não salvas serão perdidas.', + btnCloseAnyway: 'Fechar mesmo assim', + autosaveFoundTitle: 'Versão recuperada encontrada', + autosaveFoundBody: + 'Há alterações não salvas da sua última sessão. Restaurar a versão salva automaticamente?', + autosaveRestore: 'Restaurar', + autosaveDiscard: 'Descartar', + btnDontSave: 'Não Salvar', + btnCancel: 'Cancelar', + dlgInsertImage: 'Inserir Imagem', + filterImages: 'Imagens', + dlgAddAttachment: 'Adicionar Anexos', + filterSupported: 'Arquivos Compatíveis', + filterAll: 'Todos os Arquivos', + dlgExportPdf: 'Exportar como PDF', + errUnsupportedExt: 'arquivos .{ext} não são suportados', + errNotFile: 'não é um arquivo', + errTooLarge: 'excede o limite de {mb}MB', + errImageTooLarge: 'a imagem excede o limite de 5MB', + errUnreadable: 'não é possível ler', + errFileTooLarge: 'O arquivo excede o limite de tamanho', + errParseFailed: 'Falha ao analisar o arquivo', + errImageNoText: + 'Anexos de imagem não fornecem texto; a imagem é enviada junto com a mensagem do usuário, basta vê-la diretamente', + errNotImage: 'não é um tipo de imagem suportado', + errGskNotLoggedIn: + 'Não conectado ao Genspark: clique em “Entrar no Genspark” abaixo, entre e tente novamente', + errNoApiKey: 'Nenhuma chave de API configurada para {provider}', + errNoModel: 'Nenhum nome de modelo configurado', + menuFile: 'Arquivo', + menuNewDoc: 'Novo Documento', + menuNewWindow: 'Nova Janela', + menuOpen: 'Abrir…', + menuOpenRecent: 'Abrir Recente', + menuNoRecent: 'Nenhum Documento Recente', + menuClose: 'Fechar', + menuSave: 'Salvar', + menuSaveAs: 'Salvar Como…', + menuPageSetup: 'Configurar Página…', + menuExportPdf: 'Exportar como PDF…', + menuPrint: 'Imprimir…', + menuEdit: 'Editar', + menuUndo: 'Desfazer', + menuRedo: 'Refazer', + menuCut: 'Recortar', + menuCopy: 'Copiar', + menuPaste: 'Colar', + menuPasteMatch: 'Colar com a Mesma Formatação', + menuFindReplace: 'Localizar e Substituir…', + menuSelectAll: 'Selecionar Tudo', + menuView: 'Exibir', + menuZoomIn: 'Ampliar', + menuZoomOut: 'Reduzir', + menuZoom100: 'Tamanho Real (100%)', + menuPageWidth: 'Largura da Página', + menuWholePage: 'Página Inteira', + menuAiSidebar: 'Barra Lateral de IA', + menuDarkMode: 'Modo Escuro', + menuFullscreen: 'Entrar em Tela Cheia', + menuInsert: 'Inserir', + menuInsertTable: 'Tabela (3×3)', + menuInsertImage: 'Imagem…', + menuInsertPageBreak: 'Quebra de Página', + menuInsertLink: 'Hiperlink…', + menuInsertEquation: 'Equação…', + menuComment: 'Comentário', + menuFormat: 'Formatar', + menuBold: 'Negrito', + menuItalic: 'Itálico', + menuUnderline: 'Sublinhado', + menuAlign: 'Alinhar', + menuAlignLeft: 'Alinhar à Esquerda', + menuAlignCenter: 'Centralizar', + menuAlignRight: 'Alinhar à Direita', + menuAlignJustify: 'Justificar', + menuFont: 'Fonte…', + menuParagraph: 'Parágrafo…', + menuTools: 'Ferramentas', + menuWordCount: 'Contagem de Palavras…', + menuSpelling: 'Ortografia e Gramática', + menuMacros: 'Macros', + menuWindow: 'Janela', + menuHelp: 'Ajuda', + menuDocsHelp: 'Ajuda do GenOffice Docs', + }, + it: { + dlgOpenDoc: 'Apri documento', + filterWord: 'Documenti Word', + dlgSaveAs: 'Salva con nome', + closeUnsavedMsg: 'Questo documento contiene modifiche non salvate.', + closeUnsavedDetail: 'Salvarle prima di chiudere?', + closeNoReplyMsg: 'Il documento non risponde e potrebbe avere modifiche non salvate.', + closeNoReplyDetail: 'Chiudere comunque? Le modifiche non salvate andranno perse.', + btnCloseAnyway: 'Chiudi comunque', + autosaveFoundTitle: 'Trovata versione recuperata', + autosaveFoundBody: + "Ci sono modifiche non salvate dall'ultima sessione. Ripristinare la versione salvata automaticamente?", + autosaveRestore: 'Ripristina', + autosaveDiscard: 'Ignora', + btnDontSave: 'Non salvare', + btnCancel: 'Annulla', + dlgInsertImage: 'Inserisci immagine', + filterImages: 'Immagini', + dlgAddAttachment: 'Aggiungi allegati', + filterSupported: 'File supportati', + filterAll: 'Tutti i file', + dlgExportPdf: 'Esporta come PDF', + errUnsupportedExt: 'i file .{ext} non sono supportati', + errNotFile: 'non è un file', + errTooLarge: 'supera il limite di {mb} MB', + errImageTooLarge: "l'immagine supera il limite di 5 MB", + errUnreadable: 'impossibile leggere', + errFileTooLarge: 'Il file supera il limite di dimensione', + errParseFailed: 'Impossibile analizzare il file', + errImageNoText: + "Gli allegati immagine non forniscono testo; l'immagine viene inviata insieme al messaggio dell'utente, basta guardarla direttamente", + errNotImage: 'tipo di immagine non supportato', + errGskNotLoggedIn: + 'Accesso a Genspark non effettuato: fai clic su “Accedi a Genspark” qui sotto, accedi e riprova', + errNoApiKey: 'Nessuna chiave API configurata per {provider}', + errNoModel: 'Nessun nome di modello configurato', + menuFile: 'File', + menuNewDoc: 'Nuovo documento', + menuNewWindow: 'Nuova finestra', + menuOpen: 'Apri…', + menuOpenRecent: 'Apri recenti', + menuNoRecent: 'Nessun documento recente', + menuClose: 'Chiudi', + menuSave: 'Salva', + menuSaveAs: 'Salva con nome…', + menuPageSetup: 'Imposta pagina…', + menuExportPdf: 'Esporta come PDF…', + menuPrint: 'Stampa…', + menuEdit: 'Modifica', + menuUndo: 'Annulla', + menuRedo: 'Ripeti', + menuCut: 'Taglia', + menuCopy: 'Copia', + menuPaste: 'Incolla', + menuPasteMatch: 'Incolla e adatta lo stile', + menuFindReplace: 'Trova e sostituisci…', + menuSelectAll: 'Seleziona tutto', + menuView: 'Visualizza', + menuZoomIn: 'Ingrandisci', + menuZoomOut: 'Riduci', + menuZoom100: 'Dimensioni effettive (100%)', + menuPageWidth: 'Larghezza pagina', + menuWholePage: 'Pagina intera', + menuAiSidebar: 'Barra laterale IA', + menuDarkMode: 'Modalità scura', + menuFullscreen: 'Attiva schermo intero', + menuInsert: 'Inserisci', + menuInsertTable: 'Tabella (3×3)', + menuInsertImage: 'Immagine…', + menuInsertPageBreak: 'Interruzione di pagina', + menuInsertLink: 'Collegamento ipertestuale…', + menuInsertEquation: 'Equazione…', + menuComment: 'Commento', + menuFormat: 'Formato', + menuBold: 'Grassetto', + menuItalic: 'Corsivo', + menuUnderline: 'Sottolineato', + menuAlign: 'Allinea', + menuAlignLeft: 'Allinea a sinistra', + menuAlignCenter: 'Centra', + menuAlignRight: 'Allinea a destra', + menuAlignJustify: 'Giustifica', + menuFont: 'Carattere…', + menuParagraph: 'Paragrafo…', + menuTools: 'Strumenti', + menuWordCount: 'Conteggio parole…', + menuSpelling: 'Ortografia e grammatica', + menuMacros: 'Macro', + menuWindow: 'Finestra', + menuHelp: 'Aiuto', + menuDocsHelp: 'Guida di GenOffice Docs', + }, + pl: { + dlgOpenDoc: 'Otwórz dokument', + filterWord: 'Dokumenty programu Word', + dlgSaveAs: 'Zapisz jako', + closeUnsavedMsg: 'Ten dokument zawiera niezapisane zmiany.', + closeUnsavedDetail: 'Czy zapisać je przed zamknięciem?', + closeNoReplyMsg: 'Dokument nie odpowiada i może zawierać niezapisane zmiany.', + closeNoReplyDetail: 'Zamknąć mimo to? Niezapisane zmiany zostaną utracone.', + btnCloseAnyway: 'Zamknij mimo to', + autosaveFoundTitle: 'Znaleziono odzyskaną wersję', + autosaveFoundBody: + 'Istnieją niezapisane zmiany z ostatniej sesji. Przywrócić wersję zapisaną automatycznie?', + autosaveRestore: 'Przywróć', + autosaveDiscard: 'Odrzuć', + btnDontSave: 'Nie zapisuj', + btnCancel: 'Anuluj', + dlgInsertImage: 'Wstaw obraz', + filterImages: 'Obrazy', + dlgAddAttachment: 'Dodaj załączniki', + filterSupported: 'Obsługiwane pliki', + filterAll: 'Wszystkie pliki', + dlgExportPdf: 'Eksportuj jako PDF', + errUnsupportedExt: 'pliki .{ext} nie są obsługiwane', + errNotFile: 'to nie jest plik', + errTooLarge: 'przekracza limit {mb} MB', + errImageTooLarge: 'obraz przekracza limit 5 MB', + errUnreadable: 'nie można odczytać', + errFileTooLarge: 'Plik przekracza limit rozmiaru', + errParseFailed: 'Nie udało się przeanalizować pliku', + errImageNoText: + 'Załączniki graficzne nie zawierają tekstu; obraz jest wysyłany razem z wiadomością użytkownika, wystarczy na niego spojrzeć', + errNotImage: 'nieobsługiwany typ obrazu', + errGskNotLoggedIn: + 'Nie zalogowano do Genspark: kliknij „Zaloguj się do Genspark” poniżej, zaloguj się i spróbuj ponownie', + errNoApiKey: 'Nie skonfigurowano klucza API dla {provider}', + errNoModel: 'Nie skonfigurowano nazwy modelu', + menuFile: 'Plik', + menuNewDoc: 'Nowy dokument', + menuNewWindow: 'Nowe okno', + menuOpen: 'Otwórz…', + menuOpenRecent: 'Otwórz ostatnie', + menuNoRecent: 'Brak ostatnich dokumentów', + menuClose: 'Zamknij', + menuSave: 'Zapisz', + menuSaveAs: 'Zapisz jako…', + menuPageSetup: 'Ustawienia strony…', + menuExportPdf: 'Eksportuj jako PDF…', + menuPrint: 'Drukuj…', + menuEdit: 'Edycja', + menuUndo: 'Cofnij', + menuRedo: 'Ponów', + menuCut: 'Wytnij', + menuCopy: 'Kopiuj', + menuPaste: 'Wklej', + menuPasteMatch: 'Wklej i dopasuj styl', + menuFindReplace: 'Znajdź i zamień…', + menuSelectAll: 'Zaznacz wszystko', + menuView: 'Widok', + menuZoomIn: 'Powiększ', + menuZoomOut: 'Pomniejsz', + menuZoom100: 'Rzeczywisty rozmiar (100%)', + menuPageWidth: 'Szerokość strony', + menuWholePage: 'Cała strona', + menuAiSidebar: 'Pasek boczny AI', + menuDarkMode: 'Tryb ciemny', + menuFullscreen: 'Przejdź do pełnego ekranu', + menuInsert: 'Wstaw', + menuInsertTable: 'Tabela (3×3)', + menuInsertImage: 'Obraz…', + menuInsertPageBreak: 'Podział strony', + menuInsertLink: 'Hiperłącze…', + menuInsertEquation: 'Równanie…', + menuComment: 'Komentarz', + menuFormat: 'Formatowanie', + menuBold: 'Pogrubienie', + menuItalic: 'Kursywa', + menuUnderline: 'Podkreślenie', + menuAlign: 'Wyrównaj', + menuAlignLeft: 'Wyrównaj do lewej', + menuAlignCenter: 'Wyśrodkuj', + menuAlignRight: 'Wyrównaj do prawej', + menuAlignJustify: 'Wyjustuj', + menuFont: 'Czcionka…', + menuParagraph: 'Akapit…', + menuTools: 'Narzędzia', + menuWordCount: 'Statystyka wyrazów…', + menuSpelling: 'Pisownia i gramatyka', + menuMacros: 'Makra', + menuWindow: 'Okno', + menuHelp: 'Pomoc', + menuDocsHelp: 'Pomoc GenOffice Docs', + }, + nl: { + dlgOpenDoc: 'Document openen', + filterWord: 'Word-documenten', + dlgSaveAs: 'Opslaan als', + closeUnsavedMsg: 'Dit document bevat niet-opgeslagen wijzigingen.', + closeUnsavedDetail: 'Wilt u ze opslaan voordat u sluit?', + closeNoReplyMsg: 'Het document reageert niet en heeft mogelijk niet-opgeslagen wijzigingen.', + closeNoReplyDetail: 'Toch sluiten? Niet-opgeslagen wijzigingen gaan verloren.', + btnCloseAnyway: 'Toch sluiten', + autosaveFoundTitle: 'Herstelde versie gevonden', + autosaveFoundBody: + 'Er zijn niet-opgeslagen wijzigingen van uw laatste sessie. De automatisch opgeslagen versie herstellen?', + autosaveRestore: 'Herstellen', + autosaveDiscard: 'Negeren', + btnDontSave: 'Niet opslaan', + btnCancel: 'Annuleren', + dlgInsertImage: 'Afbeelding invoegen', + filterImages: 'Afbeeldingen', + dlgAddAttachment: 'Bijlagen toevoegen', + filterSupported: 'Ondersteunde bestanden', + filterAll: 'Alle bestanden', + dlgExportPdf: 'Exporteren als PDF', + errUnsupportedExt: '.{ext}-bestanden worden niet ondersteund', + errNotFile: 'geen bestand', + errTooLarge: 'overschrijdt de limiet van {mb} MB', + errImageTooLarge: 'afbeelding overschrijdt de limiet van 5 MB', + errUnreadable: 'kan niet worden gelezen', + errFileTooLarge: 'Bestand overschrijdt de maximale grootte', + errParseFailed: 'Kan bestand niet parseren', + errImageNoText: + 'Afbeeldingsbijlagen bevatten geen tekst; de afbeelding wordt samen met het gebruikersbericht verzonden en kan direct worden bekeken', + errNotImage: 'geen ondersteund afbeeldingstype', + errGskNotLoggedIn: + 'Niet aangemeld bij Genspark: klik hieronder op “Aanmelden bij Genspark”, meld u aan en probeer het opnieuw', + errNoApiKey: 'Geen API-sleutel geconfigureerd voor {provider}', + errNoModel: 'Geen modelnaam geconfigureerd', + menuFile: 'Bestand', + menuNewDoc: 'Nieuw document', + menuNewWindow: 'Nieuw venster', + menuOpen: 'Openen…', + menuOpenRecent: 'Recent geopend', + menuNoRecent: 'Geen recente documenten', + menuClose: 'Sluiten', + menuSave: 'Opslaan', + menuSaveAs: 'Opslaan als…', + menuPageSetup: 'Pagina-instelling…', + menuExportPdf: 'Exporteren als PDF…', + menuPrint: 'Afdrukken…', + menuEdit: 'Bewerken', + menuUndo: 'Ongedaan maken', + menuRedo: 'Opnieuw', + menuCut: 'Knippen', + menuCopy: 'Kopiëren', + menuPaste: 'Plakken', + menuPasteMatch: 'Plakken met dezelfde stijl', + menuFindReplace: 'Zoeken en vervangen…', + menuSelectAll: 'Alles selecteren', + menuView: 'Beeld', + menuZoomIn: 'Inzoomen', + menuZoomOut: 'Uitzoomen', + menuZoom100: 'Ware grootte (100%)', + menuPageWidth: 'Paginabreedte', + menuWholePage: 'Hele pagina', + menuAiSidebar: 'AI-zijbalk', + menuDarkMode: 'Donkere modus', + menuFullscreen: 'Schermvullende weergave', + menuInsert: 'Invoegen', + menuInsertTable: 'Tabel (3×3)', + menuInsertImage: 'Afbeelding…', + menuInsertPageBreak: 'Pagina-einde', + menuInsertLink: 'Hyperlink…', + menuInsertEquation: 'Vergelijking…', + menuComment: 'Opmerking', + menuFormat: 'Opmaak', + menuBold: 'Vet', + menuItalic: 'Cursief', + menuUnderline: 'Onderstrepen', + menuAlign: 'Uitlijnen', + menuAlignLeft: 'Links uitlijnen', + menuAlignCenter: 'Centreren', + menuAlignRight: 'Rechts uitlijnen', + menuAlignJustify: 'Uitvullen', + menuFont: 'Lettertype…', + menuParagraph: 'Alinea…', + menuTools: 'Extra', + menuWordCount: 'Woorden tellen…', + menuSpelling: 'Spelling en grammatica', + menuMacros: "Macro's", + menuWindow: 'Venster', + menuHelp: 'Help', + menuDocsHelp: 'GenOffice Docs Help', + }, + ms: { + dlgOpenDoc: 'Buka Dokumen', + filterWord: 'Dokumen Word', + dlgSaveAs: 'Simpan Sebagai', + closeUnsavedMsg: 'Dokumen ini mempunyai perubahan yang belum disimpan.', + closeUnsavedDetail: 'Adakah anda mahu menyimpannya sebelum menutup?', + closeNoReplyMsg: 'Dokumen tidak bertindak balas dan mungkin ada perubahan yang belum disimpan.', + closeNoReplyDetail: 'Tutup juga? Perubahan yang belum disimpan akan hilang.', + btnCloseAnyway: 'Tutup Juga', + autosaveFoundTitle: 'Versi pulihan ditemui', + autosaveFoundBody: + 'Terdapat perubahan yang belum disimpan daripada sesi terakhir anda. Pulihkan versi yang disimpan secara automatik?', + autosaveRestore: 'Pulihkan', + autosaveDiscard: 'Buang', + btnDontSave: 'Jangan Simpan', + btnCancel: 'Batal', + dlgInsertImage: 'Sisipkan Imej', + filterImages: 'Imej', + dlgAddAttachment: 'Tambah Lampiran', + filterSupported: 'Fail yang Disokong', + filterAll: 'Semua Fail', + dlgExportPdf: 'Eksport sebagai PDF', + errUnsupportedExt: 'fail .{ext} tidak disokong', + errNotFile: 'bukan fail', + errTooLarge: 'melebihi had {mb}MB', + errImageTooLarge: 'imej melebihi had 5MB', + errUnreadable: 'tidak dapat dibaca', + errFileTooLarge: 'Fail melebihi had saiz', + errParseFailed: 'Gagal menghurai fail', + errImageNoText: + 'Lampiran imej tidak menyediakan teks; imej dihantar bersama mesej pengguna dan boleh dilihat terus', + errNotImage: 'bukan jenis imej yang disokong', + errGskNotLoggedIn: + 'Belum log masuk ke Genspark: klik “Log masuk ke Genspark” di bawah, kemudian cuba lagi', + errNoApiKey: 'Kunci API untuk {provider} belum dikonfigurasikan', + errNoModel: 'Nama model belum dikonfigurasikan', + menuFile: 'Fail', + menuNewDoc: 'Dokumen Baharu', + menuNewWindow: 'Tetingkap Baharu', + menuOpen: 'Buka…', + menuOpenRecent: 'Buka Terkini', + menuNoRecent: 'Tiada Dokumen Terkini', + menuClose: 'Tutup', + menuSave: 'Simpan', + menuSaveAs: 'Simpan Sebagai…', + menuPageSetup: 'Persediaan Halaman…', + menuExportPdf: 'Eksport sebagai PDF…', + menuPrint: 'Cetak…', + menuEdit: 'Edit', + menuUndo: 'Buat Asal', + menuRedo: 'Buat Semula', + menuCut: 'Potong', + menuCopy: 'Salin', + menuPaste: 'Tampal', + menuPasteMatch: 'Tampal dan Padankan Gaya', + menuFindReplace: 'Cari dan Ganti…', + menuSelectAll: 'Pilih Semua', + menuView: 'Lihat', + menuZoomIn: 'Zum Masuk', + menuZoomOut: 'Zum Keluar', + menuZoom100: 'Saiz Sebenar (100%)', + menuPageWidth: 'Lebar Halaman', + menuWholePage: 'Seluruh Halaman', + menuAiSidebar: 'Bar Sisi AI', + menuDarkMode: 'Mod Gelap', + menuFullscreen: 'Masuk Skrin Penuh', + menuInsert: 'Sisip', + menuInsertTable: 'Jadual (3×3)', + menuInsertImage: 'Imej…', + menuInsertPageBreak: 'Pemisah Halaman', + menuInsertLink: 'Hiperpautan…', + menuInsertEquation: 'Persamaan…', + menuComment: 'Komen', + menuFormat: 'Format', + menuBold: 'Tebal', + menuItalic: 'Condong', + menuUnderline: 'Garis Bawah', + menuAlign: 'Jajarkan', + menuAlignLeft: 'Jajar Kiri', + menuAlignCenter: 'Tengah', + menuAlignRight: 'Jajar Kanan', + menuAlignJustify: 'Justifikasi', + menuFont: 'Fon…', + menuParagraph: 'Perenggan…', + menuTools: 'Alat', + menuWordCount: 'Kiraan Perkataan…', + menuSpelling: 'Ejaan dan Tatabahasa', + menuMacros: 'Makro', + menuWindow: 'Tetingkap', + menuHelp: 'Bantuan', + menuDocsHelp: 'Bantuan GenOffice Docs', + }, + he: { + dlgOpenDoc: 'פתיחת מסמך', + filterWord: 'מסמכי Word', + dlgSaveAs: 'שמירה בשם', + closeUnsavedMsg: 'במסמך זה יש שינויים שלא נשמרו.', + closeUnsavedDetail: 'האם לשמור אותם לפני הסגירה?', + closeNoReplyMsg: 'המסמך אינו מגיב וייתכן שיש בו שינויים שלא נשמרו.', + closeNoReplyDetail: 'לסגור בכל זאת? שינויים שלא נשמרו יאבדו.', + btnCloseAnyway: 'סגור בכל זאת', + autosaveFoundTitle: 'נמצאה גרסה משוחזרת', + autosaveFoundBody: 'קיימים שינויים שלא נשמרו מהפעלה הקודמת. לשחזר את הגרסה שנשמרה אוטומטית?', + autosaveRestore: 'שחזר', + autosaveDiscard: 'התעלם', + btnDontSave: 'אל תשמור', + btnCancel: 'ביטול', + dlgInsertImage: 'הוספת תמונה', + filterImages: 'תמונות', + dlgAddAttachment: 'הוספת קבצים מצורפים', + filterSupported: 'קבצים נתמכים', + filterAll: 'כל הקבצים', + dlgExportPdf: 'ייצוא כ-PDF', + errUnsupportedExt: 'קובצי .{ext} אינם נתמכים', + errNotFile: 'אינו קובץ', + errTooLarge: 'חורג מהמגבלה של {mb}MB', + errImageTooLarge: 'התמונה חורגת מהמגבלה של 5MB', + errUnreadable: 'לא ניתן לקרוא', + errFileTooLarge: 'הקובץ חורג ממגבלת הגודל', + errParseFailed: 'ניתוח הקובץ נכשל', + errImageNoText: + 'קבצים מצורפים מסוג תמונה אינם מספקים טקסט; התמונה נשלחת יחד עם הודעת המשתמש וניתן לצפות בה ישירות', + errNotImage: 'סוג תמונה שאינו נתמך', + errGskNotLoggedIn: 'לא מחובר ל-Genspark: לחץ על "התחבר ל-Genspark" למטה, התחבר ונסה שוב', + errNoApiKey: 'לא הוגדר מפתח API עבור {provider}', + errNoModel: 'לא הוגדר שם מודל', + menuFile: 'קובץ', + menuNewDoc: 'מסמך חדש', + menuNewWindow: 'חלון חדש', + menuOpen: 'פתיחה…', + menuOpenRecent: 'פתיחת מסמכים אחרונים', + menuNoRecent: 'אין מסמכים אחרונים', + menuClose: 'סגירה', + menuSave: 'שמירה', + menuSaveAs: 'שמירה בשם…', + menuPageSetup: 'הגדרת עמוד…', + menuExportPdf: 'ייצוא כ-PDF…', + menuPrint: 'הדפסה…', + menuEdit: 'עריכה', + menuUndo: 'בטל', + menuRedo: 'בצע שוב', + menuCut: 'גזור', + menuCopy: 'העתק', + menuPaste: 'הדבק', + menuPasteMatch: 'הדבק והתאם סגנון', + menuFindReplace: 'חיפוש והחלפה…', + menuSelectAll: 'בחר הכול', + menuView: 'תצוגה', + menuZoomIn: 'התקרבות', + menuZoomOut: 'התרחקות', + menuZoom100: 'גודל אמיתי (100%)', + menuPageWidth: 'רוחב עמוד', + menuWholePage: 'עמוד שלם', + menuAiSidebar: 'סרגל צד AI', + menuDarkMode: 'מצב כהה', + menuFullscreen: 'מעבר למסך מלא', + menuInsert: 'הוספה', + menuInsertTable: 'טבלה (3×3)', + menuInsertImage: 'תמונה…', + menuInsertPageBreak: 'מעבר עמוד', + menuInsertLink: 'היפר-קישור…', + menuInsertEquation: 'משוואה…', + menuComment: 'הערה', + menuFormat: 'עיצוב', + menuBold: 'מודגש', + menuItalic: 'נטוי', + menuUnderline: 'קו תחתון', + menuAlign: 'יישור', + menuAlignLeft: 'יישור לשמאל', + menuAlignCenter: 'מרכוז', + menuAlignRight: 'יישור לימין', + menuAlignJustify: 'יישור לשני הצדדים', + menuFont: 'גופן…', + menuParagraph: 'פסקה…', + menuTools: 'כלים', + menuWordCount: 'ספירת מילים…', + menuSpelling: 'איות ודקדוק', + menuMacros: 'פקודות מאקרו', + menuWindow: 'חלון', + menuHelp: 'עזרה', + menuDocsHelp: 'עזרה של GenOffice Docs', + }, + hi: { + dlgOpenDoc: 'दस्तावेज़ खोलें', + filterWord: 'Word दस्तावेज़', + dlgSaveAs: 'इस रूप में सहेजें', + closeUnsavedMsg: 'इस दस्तावेज़ में सहेजे नहीं गए परिवर्तन हैं।', + closeUnsavedDetail: 'क्या आप बंद करने से पहले उन्हें सहेजना चाहते हैं?', + closeNoReplyMsg: 'दस्तावेज़ प्रतिक्रिया नहीं दे रहा है और उसमें सहेजे न गए बदलाव हो सकते हैं।', + closeNoReplyDetail: 'फिर भी बंद करें? सहेजे न गए बदलाव खो जाएँगे।', + btnCloseAnyway: 'फिर भी बंद करें', + autosaveFoundTitle: 'पुनर्प्राप्त संस्करण मिला', + autosaveFoundBody: + 'आपके पिछले सत्र से सहेजे नहीं गए परिवर्तन हैं। स्वतः सहेजा गया संस्करण पुनर्स्थापित करें?', + autosaveRestore: 'पुनर्स्थापित करें', + autosaveDiscard: 'छोड़ें', + btnDontSave: 'न सहेजें', + btnCancel: 'रद्द करें', + dlgInsertImage: 'छवि सम्मिलित करें', + filterImages: 'छवियाँ', + dlgAddAttachment: 'अनुलग्नक जोड़ें', + filterSupported: 'समर्थित फ़ाइलें', + filterAll: 'सभी फ़ाइलें', + dlgExportPdf: 'PDF के रूप में निर्यात करें', + errUnsupportedExt: '.{ext} फ़ाइलें समर्थित नहीं हैं', + errNotFile: 'फ़ाइल नहीं है', + errTooLarge: '{mb}MB की सीमा से अधिक है', + errImageTooLarge: 'छवि 5MB की सीमा से अधिक है', + errUnreadable: 'पढ़ा नहीं जा सकता', + errFileTooLarge: 'फ़ाइल आकार सीमा से अधिक है', + errParseFailed: 'फ़ाइल पार्स करने में विफल', + errImageNoText: + 'छवि अनुलग्नक टेक्स्ट प्रदान नहीं करते; छवि उपयोगकर्ता संदेश के साथ भेजी जाती है, उसे सीधे देखें', + errNotImage: 'समर्थित छवि प्रकार नहीं है', + errGskNotLoggedIn: + 'Genspark में साइन इन नहीं है: नीचे “Genspark में साइन इन करें” पर क्लिक करें, साइन इन करें और फिर से कोशिश करें', + errNoApiKey: '{provider} के लिए कोई API कुंजी कॉन्फ़िगर नहीं है', + errNoModel: 'कोई मॉडल नाम कॉन्फ़िगर नहीं है', + menuFile: 'फ़ाइल', + menuNewDoc: 'नया दस्तावेज़', + menuNewWindow: 'नई विंडो', + menuOpen: 'खोलें…', + menuOpenRecent: 'हाल के दस्तावेज़ खोलें', + menuNoRecent: 'कोई हालिया दस्तावेज़ नहीं', + menuClose: 'बंद करें', + menuSave: 'सहेजें', + menuSaveAs: 'इस रूप में सहेजें…', + menuPageSetup: 'पृष्ठ सेटअप…', + menuExportPdf: 'PDF के रूप में निर्यात करें…', + menuPrint: 'प्रिंट करें…', + menuEdit: 'संपादन', + menuUndo: 'पूर्ववत करें', + menuRedo: 'फिर से करें', + menuCut: 'काटें', + menuCopy: 'कॉपी करें', + menuPaste: 'चिपकाएँ', + menuPasteMatch: 'चिपकाएँ और शैली मिलाएँ', + menuFindReplace: 'ढूँढें और बदलें…', + menuSelectAll: 'सभी चुनें', + menuView: 'दृश्य', + menuZoomIn: 'ज़ूम इन', + menuZoomOut: 'ज़ूम आउट', + menuZoom100: 'वास्तविक आकार (100%)', + menuPageWidth: 'पृष्ठ चौड़ाई', + menuWholePage: 'पूरा पृष्ठ', + menuAiSidebar: 'AI साइडबार', + menuDarkMode: 'डार्क मोड', + menuFullscreen: 'पूर्ण स्क्रीन में जाएँ', + menuInsert: 'सम्मिलित करें', + menuInsertTable: 'तालिका (3×3)', + menuInsertImage: 'छवि…', + menuInsertPageBreak: 'पृष्ठ विराम', + menuInsertLink: 'हाइपरलिंक…', + menuInsertEquation: 'समीकरण…', + menuComment: 'टिप्पणी', + menuFormat: 'स्वरूप', + menuBold: 'बोल्ड', + menuItalic: 'इटैलिक', + menuUnderline: 'रेखांकित', + menuAlign: 'संरेखित करें', + menuAlignLeft: 'बाएँ संरेखित करें', + menuAlignCenter: 'केंद्र में रखें', + menuAlignRight: 'दाएँ संरेखित करें', + menuAlignJustify: 'जस्टिफ़ाई करें', + menuFont: 'फ़ॉन्ट…', + menuParagraph: 'अनुच्छेद…', + menuTools: 'उपकरण', + menuWordCount: 'शब्द गणना…', + menuSpelling: 'वर्तनी और व्याकरण', + menuMacros: 'मैक्रो', + menuWindow: 'विंडो', + menuHelp: 'सहायता', + menuDocsHelp: 'GenOffice Docs सहायता', + }, + 'zh-TW': { + dlgOpenDoc: '開啟文件', + filterWord: 'Word 文件', + dlgSaveAs: '另存新檔', + closeUnsavedMsg: '此文件有未儲存的變更。', + closeUnsavedDetail: '關閉前是否要儲存?', + closeNoReplyMsg: '文件沒有回應,可能有未儲存的變更。', + closeNoReplyDetail: '仍要關閉嗎?未儲存的變更將遺失。', + btnCloseAnyway: '仍要關閉', + autosaveFoundTitle: '發現自動復原版本', + autosaveFoundBody: '上次工作階段有未儲存的變更。要復原自動儲存的版本嗎?', + autosaveRestore: '復原', + autosaveDiscard: '放棄', + btnDontSave: '不儲存', + btnCancel: '取消', + dlgInsertImage: '插入圖片', + filterImages: '圖片', + dlgAddAttachment: '新增附件', + filterSupported: '支援的檔案', + filterAll: '所有檔案', + dlgExportPdf: '匯出為 PDF', + errUnsupportedExt: '暫不支援 .{ext} 類型', + errNotFile: '不是檔案', + errTooLarge: '超過 {mb}MB 上限', + errImageTooLarge: '圖片超過 5MB 上限', + errUnreadable: '無法讀取', + errFileTooLarge: '檔案超過大小上限', + errParseFailed: '檔案解析失敗', + errImageNoText: '圖片附件不提供文字,已作為影像隨使用者訊息傳送,直接看圖即可', + errNotImage: '不是支援的圖片類型', + errGskNotLoggedIn: '未登入 Genspark:請點擊下方「登入 Genspark」完成登入後重試', + errNoApiKey: '未設定 {provider} 的 API Key', + errNoModel: '未設定模型名稱', + menuFile: '檔案', + menuNewDoc: '新增文件', + menuNewWindow: '新增視窗', + menuOpen: '開啟…', + menuOpenRecent: '開啟最近的文件', + menuNoRecent: '沒有最近的文件', + menuClose: '關閉', + menuSave: '儲存', + menuSaveAs: '另存新檔…', + menuPageSetup: '版面設定…', + menuExportPdf: '匯出為 PDF…', + menuPrint: '列印…', + menuEdit: '編輯', + menuUndo: '復原', + menuRedo: '重做', + menuCut: '剪下', + menuCopy: '複製', + menuPaste: '貼上', + menuPasteMatch: '貼上並符合格式', + menuFindReplace: '尋找與取代…', + menuSelectAll: '全選', + menuView: '檢視', + menuZoomIn: '放大', + menuZoomOut: '縮小', + menuZoom100: '實際大小 (100%)', + menuPageWidth: '頁面寬度', + menuWholePage: '整頁', + menuAiSidebar: 'AI 側邊欄', + menuDarkMode: '深色模式', + menuFullscreen: '進入全螢幕', + menuInsert: '插入', + menuInsertTable: '表格(3×3)', + menuInsertImage: '圖片…', + menuInsertPageBreak: '分頁符號', + menuInsertLink: '超連結…', + menuInsertEquation: '方程式…', + menuComment: '註解', + menuFormat: '格式', + menuBold: '粗體', + menuItalic: '斜體', + menuUnderline: '底線', + menuAlign: '對齊', + menuAlignLeft: '靠左對齊', + menuAlignCenter: '置中', + menuAlignRight: '靠右對齊', + menuAlignJustify: '左右對齊', + menuFont: '字型…', + menuParagraph: '段落…', + menuTools: '工具', + menuWordCount: '字數統計…', + menuSpelling: '拼字及文法檢查', + menuMacros: '巨集', + menuWindow: '視窗', + menuHelp: '說明', + menuDocsHelp: 'GenOffice Docs 說明', + }, +}) +const tm = (key: Parameters[1], params?: Parameters[2]) => + tMain(getUiLang(), key, params) + +// ---- runtime configuration (paths differ when bundled into the shell) ---- + +interface DocsRuntimeConfig { + /** absolute path to the docs preload bundle */ + preloadPath: string + /** dev-server URL for the docs renderer (wins over rendererFile) */ + rendererUrl?: string | undefined + /** absolute path to the built docs renderer index.html */ + rendererFile: string +} + +let runtime: DocsRuntimeConfig = { + preloadPath: join(__dirname, '../preload/index.js'), + rendererUrl: process.env.ELECTRON_RENDERER_URL, + rendererFile: join(__dirname, '../renderer/index.html'), +} + +export function configureDocsRuntime(config: DocsRuntimeConfig): void { + runtime = config +} + +let mainWindow: BrowserWindow | null = null +let rendererReady = false +let pendingOpenPath = findDocxPath(process.argv) +/** documents queued for windows/tabs spawned via New Tab, keyed by webContents id */ +const pendingWindowOpens = new Map() +/** webContents ids that should open as a new blank doc instead of the start screen */ +const pendingNewBlankIds = new Set() + +/** mark a docs webContents as "open blank on first consume" (called by the shell for home:new-doc) */ +export function markDocsNewBlank(wcId: number): void { + pendingNewBlankIds.add(wcId) +} + +/** the single real BrowserWindow hosting the tab strip, used as dialog parent in tab mode */ +let docsShellWindow: BrowserWindow | null = null +export function setDocsShellWindow(win: BrowserWindow | null): void { + docsShellWindow = win +} + +/** injected by the shell in tab mode: resolves the webContents of the currently active docs tab, + * used for menu-command forwarding where there is no IpcMainInvokeEvent to key off of. */ +let activeDocsResolver: (() => WebContents | null) | null = null +export function setActiveDocsResolver(fn: (() => WebContents | null) | null): void { + activeDocsResolver = fn +} + +function activeDocsWebContents(): WebContents | null { + if (activeDocsResolver) return activeDocsResolver() + return BrowserWindow.getFocusedWindow()?.webContents ?? mainWindow?.webContents ?? null +} + +/** dialog parent for the calling tab (standalone mode falls back to its own BrowserWindow) */ +function dialogParent(event: IpcMainInvokeEvent): BrowserWindow | undefined { + return docsShellWindow ?? BrowserWindow.fromWebContents(event.sender) ?? undefined +} + +async function openDialog(event: IpcMainInvokeEvent, options: OpenDialogOptions) { + const parent = dialogParent(event) + return parent ? dialog.showOpenDialog(parent, options) : dialog.showOpenDialog(options) +} + +async function saveDialog(event: IpcMainInvokeEvent, options: SaveDialogOptions) { + const parent = dialogParent(event) + return parent ? dialog.showSaveDialog(parent, options) : dialog.showSaveDialog(options) +} + +/** default folder where new files land on their first (silent) save; shared with the other editors via shell */ +export function defaultSaveDir(): string { + const dir = join(app.getPath('documents'), 'GenOffice') + mkdirSync(dir, { recursive: true }) + return dir +} + +/** first free path for fileName inside dir: name.ext, name-2.ext, name-3.ext… */ +export function uniquePathIn(dir: string, fileName: string): string { + const dot = fileName.lastIndexOf('.') + const base = dot > 0 ? fileName.slice(0, dot) : fileName + const ext = dot > 0 ? fileName.slice(dot) : '' + let candidate = join(dir, fileName) + for (let i = 2; existsSync(candidate); i++) candidate = join(dir, `${base}-${i}${ext}`) + return candidate +} + +export function openExternalDocx(filePath: string | null): void { + if (!filePath || !/\.docx$/i.test(filePath)) return + const win = BrowserWindow.getFocusedWindow() ?? mainWindow + if (!rendererReady || !win) { + pendingOpenPath = filePath + return + } + void loadDocx(filePath).then((result) => { + if (!result || win.isDestroyed()) return + if (win.isMinimized()) win.restore() + win.show() + win.focus() + win.webContents.send('docs:opened', result) + }) +} + +function userDataPath(...parts: string[]): string { + return join(app.getPath('userData'), ...parts) +} + +function readJson(path: string, fallback: T): T { + try { + if (existsSync(path)) return JSON.parse(readFileSync(path, 'utf-8')) as T + } catch { + /* corrupted state file: fall back to defaults */ + } + return fallback +} + +function writeJson(path: string, value: unknown): void { + mkdirSync(join(path, '..'), { recursive: true }) + writeFileSync(path, JSON.stringify(value, null, 2)) +} + +// ---- recent files ---- + +const RECENT_PATH = () => userDataPath('recent.json') + +// the home screen lists all of these; the File menu shows only the first few +const RECENT_LIMIT = 100 + +function pushRecent(filePath: string): void { + const recent = readJson(RECENT_PATH(), []) + // Every save lands here (autosave = every 30s): skip the write and the menu + // rebuild when the file is already at the head of the list + if (recent[0] === filePath) return + const next = [filePath, ...recent.filter((p) => p !== filePath)].slice(0, RECENT_LIMIT) + writeJson(RECENT_PATH(), next) + buildDocsMenu() // keep File > Open Recent in sync +} + +/** unified recents for the shell home screen (paths only; type = extension) */ +export function readRecentFiles(): string[] { + return readJson(RECENT_PATH(), []).filter((p) => existsSync(p)) +} + +export function recordRecentFile(filePath: string): void { + pushRecent(filePath) +} + +export function removeRecentFiles(filePaths: string[]): void { + const drop = new Set(filePaths) + const recent = readJson(RECENT_PATH(), []) + writeJson( + RECENT_PATH(), + recent.filter((p) => !drop.has(p)), + ) + buildDocsMenu() +} + +/** shell notification: the file of an open view was renamed on disk (renamed in + * the Home list) — push to the matching renderer so it syncs its save path and + * title bar (docs keeps path state on the renderer side). */ +export function docsFileRenamed(wc: WebContents, oldPath: string, newPath: string): void { + // keep the save allowlist in sync so docs:save accepts the renamed path + docWritablePaths.delete(oldPath) + docWritablePaths.add(newPath) + wc.send('docs:renamed', { oldPath, newPath }) +} + +/** keep a renamed file at its old position in the recent/starred lists */ +export function replaceRecentFile(oldPath: string, newPath: string): void { + const recent = readJson(RECENT_PATH(), []) + writeJson( + RECENT_PATH(), + recent.map((p) => (p === oldPath ? newPath : p)), + ) + const starred = readJson(STARRED_PATH(), []) + if (starred.includes(oldPath)) { + writeJson( + STARRED_PATH(), + starred.map((p) => (p === oldPath ? newPath : p)), + ) + } + buildDocsMenu() +} + +// ---- starred files (home screen favorites) ---- + +const STARRED_PATH = () => userDataPath('starred.json') + +export function readStarredFiles(): string[] { + return readJson(STARRED_PATH(), []).filter((p) => existsSync(p)) +} + +export function toggleStarredFile(filePath: string): void { + const starred = readJson(STARRED_PATH(), []) + const next = starred.includes(filePath) + ? starred.filter((p) => p !== filePath) + : [...starred, filePath] + writeJson(STARRED_PATH(), next) +} + +// ---- original archive (pass-through base: original file archived by content hash) ---- + +function archiveOriginal(filePath: string, bytes: Buffer): string { + const hash = createHash('sha256').update(bytes).digest('hex') + const dir = userDataPath('originals') + mkdirSync(dir, { recursive: true }) + const target = join(dir, `${hash}.docx`) + if (!existsSync(target)) copyFileSync(filePath, target) + return hash +} + +/** paths the renderer may overwrite via docs:save — populated by open/save-as flows */ +const docWritablePaths = new Set() + +// ── Crash recovery: dirty renderers push a copy every 30s +// (docs:write-recovery); a normal save cleans it up; open offers Restore/Discard ── +const recoveryDir = () => userDataPath('docs-autosave') +const recoveryPathFor = (filePath: string) => + join(recoveryDir(), `${createHash('sha1').update(filePath).digest('hex').slice(0, 16)}.docx`) + +function clearRecoveryCopy(filePath: string): void { + try { + unlinkSync(recoveryPathFor(filePath)) + } catch { + /* nothing to clean */ + } +} + +/** On open, if a recovery copy newer than the original exists, ask whether to restore + * (still points at the original path; only save persists it). */ +async function maybeRecoverDocBytes(filePath: string, original: Buffer): Promise { + const asPath = recoveryPathFor(filePath) + try { + if (!existsSync(asPath)) return original + if (statSync(asPath).mtimeMs <= statSync(filePath).mtimeMs) { + unlinkSync(asPath) + return original + } + } catch { + return original + } + const options = { + type: 'question' as const, + buttons: [tm('autosaveRestore'), tm('autosaveDiscard')], + defaultId: 0, + cancelId: 1, + message: tm('autosaveFoundTitle'), + detail: tm('autosaveFoundBody'), + } + const parent = BrowserWindow.getFocusedWindow() ?? mainWindow + const r = + parent && !parent.isDestroyed() + ? await dialog.showMessageBox(parent, options) + : await dialog.showMessageBox(options) + if (r.response === 0) { + try { + return readFileSync(asPath) + } catch { + return original + } + } + clearRecoveryCopy(filePath) + return original +} + +async function loadDocx(filePath: string): Promise { + if (typeof filePath !== 'string' || !/\.docx$/i.test(filePath)) return null + if (!existsSync(filePath)) return null + const original = readFileSync(filePath) + const hash = archiveOriginal(filePath, original) + const bytes = await maybeRecoverDocBytes(filePath, original) + pushRecent(filePath) + docWritablePaths.add(filePath) + return { + path: filePath, + name: basename(filePath), + data: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer, + hash, + } +} + +// ---- IPC ---- + +const IMAGE_MIME: Record = { + png: 'image/png', + jpg: 'image/jpeg', + jpeg: 'image/jpeg', + gif: 'image/gif', +} + +// ---- chat attachments: local files parsed for the agent ---- + +const ATTACHMENT_MAX_BYTES = 50 * 1024 * 1024 +/** plain-text extensions read as UTF-8 */ +const TEXT_EXTS = new Set([ + 'txt', + 'md', + 'markdown', + 'csv', + 'tsv', + 'json', + 'yaml', + 'yml', + 'xml', + 'html', + 'htm', + 'log', + 'js', + 'ts', + 'tsx', + 'jsx', + 'py', + 'java', + 'c', + 'h', + 'cpp', + 'go', + 'rs', + 'rb', + 'sh', + 'sql', + 'css', +]) +/** office/pdf formats get text extracted via @genoffice/file-parse; images skip extraction and go multimodal (files:read-image) */ +const ATTACHMENT_EXTS = new Set([ + ...TEXT_EXTS, + 'docx', + 'pdf', + 'pptx', + 'ppt', + 'xlsx', + 'xls', + ...ATTACHMENT_IMAGE_EXTS, +]) + +const ATTACHMENT_IMAGE_MIME: Record = { + png: 'image/png', + jpg: 'image/jpeg', + jpeg: 'image/jpeg', + gif: 'image/gif', + webp: 'image/webp', +} +/** multimodal size cap per image attachment (keeps the context from blowing up) */ +const ATTACHMENT_IMAGE_MAX_BYTES = 5 * 1024 * 1024 + +/** extracted text cache keyed by path; invalidated by mtime+size */ +const attachmentTextCache = new Map() + +function statAttachment(filePath: string): { meta?: AttachmentMeta; error?: string } { + const name = basename(filePath) + const ext = name.split('.').pop()?.toLowerCase() ?? '' + if (!ATTACHMENT_EXTS.has(ext)) return { error: `${name}: ${tm('errUnsupportedExt', { ext })}` } + try { + const stat = statSync(filePath) + if (!stat.isFile()) return { error: `${name}: ${tm('errNotFile')}` } + if (stat.size > ATTACHMENT_MAX_BYTES) { + return { + error: `${name}: ${tm('errTooLarge', { mb: Math.round(ATTACHMENT_MAX_BYTES / 1024 / 1024) })}`, + } + } + if (ATTACHMENT_IMAGE_EXTS.has(ext) && stat.size > ATTACHMENT_IMAGE_MAX_BYTES) { + return { error: `${name}: ${tm('errImageTooLarge')}` } + } + return { meta: { path: filePath, name, ext, sizeBytes: stat.size } } + } catch { + return { error: `${name}: ${tm('errUnreadable')}` } + } +} + +function collectAttachments(paths: string[]): AttachmentAddResult { + const accepted: AttachmentMeta[] = [] + const rejected: string[] = [] + for (const p of paths) { + const { meta, error } = statAttachment(p) + if (meta) accepted.push(meta) + else if (error) rejected.push(error) + } + return { accepted, rejected } +} + +/** save clipboard-pasted image bytes to a temp file (screenshots/bitmaps with no local path); returns null for non-images or empty data */ +let pastedImageSeq = 0 +let pastedDirPruned = false + +/** drop pasted-image temp files older than 7 days (once per app run) */ +function prunePastedImages(dir: string): void { + if (pastedDirPruned) return + pastedDirPruned = true + const cutoff = Date.now() - 7 * 24 * 60 * 60 * 1000 + try { + for (const name of readdirSync(dir)) { + const p = join(dir, name) + try { + if (statSync(p).mtimeMs < cutoff) unlinkSync(p) + } catch { + // ignore: another tab may have removed it already + } + } + } catch { + // ignore: directory may not exist yet + } +} +function savePastedImage(data: unknown, ext: unknown): string | null { + const cleanExt = typeof ext === 'string' ? ext.toLowerCase() : '' + if (!ATTACHMENT_IMAGE_EXTS.has(cleanExt)) return null + const bytes = + data instanceof ArrayBuffer + ? Buffer.from(data) + : ArrayBuffer.isView(data) + ? Buffer.from(data.buffer, data.byteOffset, data.byteLength) + : null + if (!bytes || bytes.byteLength === 0) return null + const dir = join(app.getPath('temp'), 'genoffice-pasted') + mkdirSync(dir, { recursive: true }) + prunePastedImages(dir) + const stamp = new Date().toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '-') + const filePath = join(dir, `pasted-${stamp}-${++pastedImageSeq}.${cleanExt}`) + writeFileSync(filePath, bytes) + return filePath +} + +/** parse an attachment to text via @genoffice/file-parse (docx/pdf/pptx/xlsx/plain text) */ +async function extractAttachmentText(filePath: string): Promise { + const stat = statSync(filePath) + const stamp = `${stat.mtimeMs}:${stat.size}` + const cached = attachmentTextCache.get(filePath) + if (cached && cached.stamp === stamp) return cached.text + if (stat.size > ATTACHMENT_MAX_BYTES) throw new Error(tm('errFileTooLarge')) + const parsed = await parseFileToText(filePath) + if (!parsed.ok || parsed.kind !== 'text' || parsed.text == null) { + throw new Error(parsed.error ?? tm('errParseFailed')) + } + attachmentTextCache.set(filePath, { stamp, text: parsed.text }) + // keep the cache bounded (a handful of recent files is plenty) + if (attachmentTextCache.size > 8) { + const oldest = attachmentTextCache.keys().next().value + if (oldest) attachmentTextCache.delete(oldest) + } + return parsed.text +} + +// ---- print / export PDF ---- + +const TWIPS_PER_INCH = 1440 + +// ---- AI settings + chat proxy (main process avoids renderer CORS) ---- +// provider metadata, settings defaults/migration, and per-provider streaming/chat +// implementations live in @genoffice/ai-provider, shared with apps/sheets. + +const SETTINGS_PATH = () => userDataPath('ai-settings.json') + +const activeAiStreams = new Map() + +/** + * AI settings + chat/stream proxy handlers. Split out so the shell can + * register them exactly once for all window types (docs, sheets, home) — + * sheets' standalone AI handlers use the same channel names. + */ +export function registerAiIpc(): void { + ipcMain.handle('ai:get-settings', (): AiSettings => { + const stored = readJson & LegacyAiSettings>(SETTINGS_PATH(), {}) + const settings = resolveAiSettings(stored, defaultAiSettings()) + // AI features all go through Genspark (gsk login); legacy settings with another provider are reset + settings.provider = 'genspark' + return settings + }) + + // Genspark account (gsk login state): auth source for AI features; the frontend uses it to prompt login when logged out + ipcMain.handle( + 'ai:gsk-status', + async (_event, withEmail?: boolean): Promise => { + if (!hasGskAuth()) return { loggedIn: false } + if (!withEmail) return { loggedIn: true } + const info = await gskLoginInfo() + return info?.email ? { loggedIn: true, email: info.email } : { loggedIn: true } + }, + ) + + ipcMain.handle('ai:gsk-login', () => { + gskLogin() + }) + + ipcMain.handle('ai:set-settings', (_event, settings: AiSettings) => { + writeJson(SETTINGS_PATH(), settings) + }) + + ipcMain.handle('ai:stream', async (event, request: AiStreamRequest) => { + const { requestId, settings, system, messages } = request + const tools = request.tools ?? [] + const maxTokens = request.maxTokens ?? 8192 + const provider = settings.provider + let config = settings.providers?.[provider] + // the genspark key never enters the settings file; requests take it from the gsk login state + if (provider === 'genspark' && config && !config.apiKey) { + config = { ...config, apiKey: gskApiKey() } + } + const send = (chunk: AiStreamChunk) => { + if (!event.sender.isDestroyed()) event.sender.send('ai:stream-chunk', chunk) + } + if (!config?.apiKey) { + send({ + requestId, + type: 'error', + error: provider === 'genspark' ? tm('errGskNotLoggedIn') : tm('errNoApiKey', { provider }), + }) + return + } + if (!config.model) { + send({ requestId, type: 'error', error: tm('errNoModel') }) + return + } + const controller = new AbortController() + activeAiStreams.set(requestId, controller) + try { + await streamForProvider(provider, config, system, messages, tools, maxTokens, { + signal: controller.signal, + onDelta: (text) => send({ requestId, type: 'delta', text }), + onToolCall: (toolCall) => send({ requestId, type: 'tool-call', toolCall }), + }) + send({ requestId, type: 'done' }) + } catch (err) { + if (controller.signal.aborted) { + send({ requestId, type: 'done' }) + } else { + send({ requestId, type: 'error', error: err instanceof Error ? err.message : String(err) }) + } + } finally { + activeAiStreams.delete(requestId) + } + }) + + ipcMain.handle('ai:stream-cancel', (_event, requestId: string) => { + activeAiStreams.get(requestId)?.abort() + }) + + // shared search tools (content + images): Serper with DuckDuckGo fallback (same source as slides/sheets) + ipcMain.handle('ai:web-search', async (_event, query: string, maxResults?: number) => { + try { + return await webSearch(String(query), typeof maxResults === 'number' ? maxResults : 6) + } catch (err) { + return { results: [], method: 'error', error: String(err) } + } + }) + ipcMain.handle('ai:image-search', async (_event, query: string, maxResults?: number) => { + try { + return await imageSearch(String(query), typeof maxResults === 'number' ? maxResults : 8) + } catch (err) { + return { images: [], method: 'error', error: String(err) } + } + }) + + // download image from URL → base64+mime (download in the main process avoids CORS; the renderer builds the image node and measures size itself) + ipcMain.handle( + 'ai:fetch-image', + async (_event, url: string): Promise<{ base64: string; mime: string } | null> => { + try { + // the URL originates from AI tool calls (prompt-injectable via web search + // results), so refuse non-http schemes and private/link-local targets; + // redirects are followed manually so every hop is validated too + const resp = await fetchWithSsrfGuard(String(url), { + headers: { 'User-Agent': 'Mozilla/5.0' }, + }) + if (!resp || !resp.ok) return null + const buf = Buffer.from(await resp.arrayBuffer()) + const ct = resp.headers.get('content-type') ?? '' + const mime = ct.includes('png') + ? 'image/png' + : ct.includes('gif') + ? 'image/gif' + : 'image/jpeg' + return { base64: buf.toString('base64'), mime } + } catch { + return null + } + }, + ) + + ipcMain.handle('ai:chat', async (_event, request: AiChatRequest) => { + const { settings, system, user } = request + const provider = settings.provider + let config = settings.providers?.[provider] + if (provider === 'genspark' && config && !config.apiKey) { + config = { ...config, apiKey: gskApiKey() } + } + if (!config?.apiKey) { + return { + ok: false, + error: provider === 'genspark' ? tm('errGskNotLoggedIn') : tm('errNoApiKey', { provider }), + } + } + if (!config.model) return { ok: false, error: tm('errNoModel') } + try { + return await chatForProvider(provider, config, system, user) + } catch (err) { + return { ok: false, error: String(err) } + } + }) +} + +// ── project-store IPC (shared across docs / slides / sheets) ────────────── + +let projectStore: ProjectStore | null = null +let projectIpcRegistered = false + +function getProjectStore(): ProjectStore { + if (!projectStore) projectStore = new ProjectStore(app.getPath('userData')) + return projectStore +} + +/** + * Fired when a save lands on a new path (save-as / first silent save). The shell + * uses it to sync the tab title/path, record recents and apply a pending project — + * same contract as the sheets/slides opened hooks. Never called standalone. + */ +let fileSavedHook: ((wc: WebContents, filePath: string) => void) | null = null + +export function setDocsFileSavedHook(hook: (wc: WebContents, filePath: string) => void): void { + fileSavedHook = hook +} + +function notifyFileSaved(wc: WebContents, filePath: string): void { + if (fileSavedHook) fileSavedHook(wc, filePath) +} + +/** + * Reverse lookup from a sheets sessionId to its file path. In shell mode the + * project:* handlers are registered by this file, but only sheets-main knows the + * sessionId mapping; the shell injects it at startup (standalone docs doesn't need it). + */ +let sessionPathResolver: ((senderId: number, sessionId: string) => string | null) | null = null + +export function setSessionPathResolver( + fn: (senderId: number, sessionId: string) => string | null, +): void { + sessionPathResolver = fn +} + +/** After a file is renamed/moved on disk, sync project-store (fileMap/chatIdByPath re-key accordingly; history follows the file). */ +export function projectFileRenamed(oldPath: string, newPath: string): void { + try { + getProjectStore().fileRenamed(oldPath, newPath) + } catch (err) { + console.warn('[project-store] fileRenamed failed:', err) + } +} + +/** + * Register the project:* IPC handlers (all three apps share the same channel names). + * Idempotency guard: registered only once in shell mode. + */ +export function registerProjectIpc(): void { + if (projectIpcRegistered) return + projectIpcRegistered = true + + /** Resolve projectId + chatId from a file path (sheets without a path resolves via sessionId) */ + ipcMain.handle( + 'project:resolveChat', + (event, args: { filePath: string | null; tempChatId?: string; sessionId?: string }) => { + const store = getProjectStore() + store.ensureDefaultProject() + let resolvedPath = args.filePath + if (!resolvedPath && args.sessionId && sessionPathResolver) { + resolvedPath = sessionPathResolver(event.sender.id, args.sessionId) + } + if (!resolvedPath) { + return { + projectId: 'default', + chatId: args.tempChatId ?? `unsaved-${Date.now()}`, + } + } + return store.resolveChatForFile(resolvedPath) + }, + ) + + /** Append a message */ + ipcMain.handle( + 'project:appendChat', + ( + _event, + args: { + projectId: string + chatId: string + role: 'user' | 'assistant' + text: string + tools?: Array<{ + name: string + summary: string + isError?: boolean + input?: string + output?: string + }> + attachments?: Array<{ name: string; path?: string; ext?: string; sizeBytes?: number }> + }, + ) => { + const store = getProjectStore() + const msg: Parameters[2] = { + role: args.role, + text: args.text, + } + if (args.tools) msg.tools = args.tools + if (args.attachments) msg.attachments = args.attachments + store.appendChatMessage(args.projectId, args.chatId, msg) + }, + ) + + /** Read history */ + ipcMain.handle( + 'project:loadChat', + ( + _event, + args: { + projectId: string + chatId: string + limit?: number + }, + ) => { + const store = getProjectStore() + return store.loadChat(args.projectId, args.chatId, args.limit ?? 200) + }, + ) + + /** rebind chat (called after a file first hits disk): newFilePath/sessionId take priority; the main process computes chatId and records fileMap */ + ipcMain.handle( + 'project:rebindChat', + ( + event, + args: { + projectId: string + tempChatId: string + newChatId?: string + newFilePath?: string + sessionId?: string + }, + ) => { + const store = getProjectStore() + let path = args.newFilePath ?? null + if (!path && args.sessionId && sessionPathResolver) { + path = sessionPathResolver(event.sender.id, args.sessionId) + } + if (path) { + return store.rebindChatToFile(args.projectId, args.tempChatId, path) + } + if (args.newChatId) store.rebindChat(args.projectId, args.tempChatId, args.newChatId) + return { projectId: args.projectId, chatId: args.newChatId ?? args.tempChatId } + }, + ) + + // ── P1 extension IPC ───────────────────────────────────── + + /** List all projects (with file count + last-active time) */ + ipcMain.handle('project:list', () => { + return getProjectStore().listProjectsSummary() + }) + + /** List existing files belonging to one project */ + ipcMain.handle('project:files', (_event, args: { projectId: string }) => { + return getProjectStore().listProjectFiles(args.projectId) + }) + + /** Create a project */ + ipcMain.handle('project:create', (_event, args: { name: string }) => { + const store = getProjectStore() + const data = store.createProject(args.name) + // returns ProjectSummary shape + return store.listProjectsSummary().find((s) => s.id === data.id) ?? data + }) + + /** Rename a project */ + ipcMain.handle('project:rename', (_event, args: { id: string; name: string }) => { + getProjectStore().renameProject(args.id, args.name) + }) + + /** Soft-delete a project */ + ipcMain.handle('project:delete', (_event, args: { id: string }) => { + getProjectStore().deleteProject(args.id) + }) + + /** Move a file into the given project */ + ipcMain.handle('project:moveFile', (_event, args: { filePath: string; projectId: string }) => { + getProjectStore().moveFileToProject(args.filePath, args.projectId) + }) + + /** Get the project timeline */ + ipcMain.handle('project:timeline', (_event, args: { projectId: string; limit?: number }) => { + return getProjectStore().getProjectTimeline(args.projectId, args.limit ?? 20) + }) +} + +/** document/attachment/window IPC (everything except the AI proxy above) */ +export function registerDocsIpc(): void { + // shared with the other editor modules — last (identical) registration wins + ipcMain.removeHandler('app:get-language') + ipcMain.handle('app:get-language', () => getUiLang()) + + ipcMain.handle('docs:open', async (event) => { + const result = await openDialog(event, { + title: tm('dlgOpenDoc'), + filters: [{ name: tm('filterWord'), extensions: ['docx'] }], + properties: ['openFile'], + }) + if (result.canceled || result.filePaths.length === 0) return null + return loadDocx(result.filePaths[0]) + }) + + ipcMain.handle('docs:open-path', (_event, filePath: string) => loadDocx(filePath)) + + ipcMain.handle('docs:consume-pending-open', (event) => { + rendererReady = true + // a tab spawned via New Tab loads the document queued for it specifically + const queued = pendingWindowOpens.get(event.sender.id) + if (queued) { + pendingWindowOpens.delete(event.sender.id) + return loadDocx(queued) + } + const filePath = pendingOpenPath + pendingOpenPath = null + return filePath ? loadDocx(filePath) : null + }) + + /** returns true when this tab was opened via "New Document" and should start blank */ + ipcMain.handle('docs:consume-new-blank', (event) => { + rendererReady = true + if (pendingNewBlankIds.has(event.sender.id)) { + pendingNewBlankIds.delete(event.sender.id) + return true + } + return false + }) + + ipcMain.handle('docs:save', (_event, filePath: string, data: ArrayBuffer) => { + try { + // only paths the user opened or chose via save-as may be overwritten + if (typeof filePath !== 'string' || !docWritablePaths.has(filePath)) { + return { ok: false, error: 'save target is not an opened document' } + } + writeFileSync(filePath, Buffer.from(data)) + clearRecoveryCopy(filePath) + pushRecent(filePath) + return { ok: true } + } catch (err) { + return { ok: false, error: String(err) } + } + }) + + // crash-recovery copy from a dirty renderer; best-effort, never surfaces + ipcMain.handle('docs:write-recovery', (_event, filePath: string, data: ArrayBuffer) => { + try { + if (typeof filePath !== 'string' || !docWritablePaths.has(filePath)) return { ok: false } + mkdirSync(recoveryDir(), { recursive: true }) + writeFileSync(recoveryPathFor(filePath), Buffer.from(data)) + return { ok: true } + } catch { + return { ok: false } + } + }) + + ipcMain.handle('docs:save-as', async (event, defaultName: string, data: ArrayBuffer) => { + const result = await saveDialog(event, { + title: tm('dlgSaveAs'), + defaultPath: defaultName, + filters: [{ name: tm('filterWord'), extensions: ['docx'] }], + }) + if (result.canceled || !result.filePath) return { ok: false } + try { + writeFileSync(result.filePath, Buffer.from(data)) + docWritablePaths.add(result.filePath) + pushRecent(result.filePath) + notifyFileSaved(event.sender, result.filePath) + return { ok: true, path: result.filePath } + } catch (err) { + return { ok: false, error: String(err) } + } + }) + + ipcMain.handle('docs:save-new', (event, defaultName: string, data: ArrayBuffer) => { + try { + const filePath = uniquePathIn(defaultSaveDir(), defaultName) + writeFileSync(filePath, Buffer.from(data)) + docWritablePaths.add(filePath) + pushRecent(filePath) + notifyFileSaved(event.sender, filePath) + return { ok: true, path: filePath } + } catch (err) { + return { ok: false, error: String(err) } + } + }) + + ipcMain.handle('docs:recent', () => + readJson(RECENT_PATH(), []).filter((p) => existsSync(p)), + ) + + ipcMain.handle('docs:pick-image', async (event) => { + const result = await openDialog(event, { + title: tm('dlgInsertImage'), + filters: [{ name: tm('filterImages'), extensions: ['png', 'jpg', 'jpeg', 'gif'] }], + properties: ['openFile'], + }) + if (result.canceled || result.filePaths.length === 0) return null + const filePath = result.filePaths[0] + const ext = filePath.split('.').pop()?.toLowerCase() ?? '' + const mime = IMAGE_MIME[ext] + if (!mime) return null + return { + base64: readFileSync(filePath).toString('base64'), + mime, + name: basename(filePath), + } + }) + + ipcMain.handle('files:pick', async (event): Promise => { + const result = await openDialog(event, { + title: tm('dlgAddAttachment'), + filters: [ + { name: tm('filterSupported'), extensions: [...ATTACHMENT_EXTS] }, + { name: tm('filterAll'), extensions: ['*'] }, + ], + properties: ['openFile', 'multiSelections'], + }) + if (result.canceled || result.filePaths.length === 0) return null + return collectAttachments(result.filePaths) + }) + + ipcMain.handle('files:add', (_event, paths: string[]) => collectAttachments(paths)) + + ipcMain.handle( + 'files:read', + async ( + _event, + filePath: string, + offset: number, + maxChars: number, + ): Promise => { + const name = basename(filePath) + const ext = name.split('.').pop()?.toLowerCase() ?? '' + if (!ATTACHMENT_EXTS.has(ext)) return { ok: false, error: tm('errUnsupportedExt', { ext }) } + if (ATTACHMENT_IMAGE_EXTS.has(ext)) { + return { ok: false, error: tm('errImageNoText') } + } + try { + const text = await extractAttachmentText(filePath) + const start = Math.max(0, Math.floor(offset) || 0) + const size = Math.min(Math.max(1, Math.floor(maxChars) || 1), 48_000) + return { + ok: true, + name, + totalChars: text.length, + offset: start, + text: text.slice(start, start + size), + } + } catch (e) { + return { ok: false, error: e instanceof Error ? e.message : String(e) } + } + }, + ) + + // image attachments read raw bytes → base64; AiPanel puts them into the user message's images for multimodal + ipcMain.handle('files:read-image', (_event, filePath: string): AttachmentImageResult => { + const name = basename(filePath) + const ext = name.split('.').pop()?.toLowerCase() ?? '' + const mime = ATTACHMENT_IMAGE_MIME[ext] + if (!mime) return { ok: false, error: `${name}: ${tm('errNotImage')}` } + try { + const stat = statSync(filePath) + if (stat.size > ATTACHMENT_IMAGE_MAX_BYTES) { + return { ok: false, error: `${name}: ${tm('errImageTooLarge')}` } + } + return { ok: true, base64: readFileSync(filePath).toString('base64'), mime } + } catch { + return { ok: false, error: `${name}: ${tm('errUnreadable')}` } + } + }) + + // clipboard-pasted images (screenshots and other bitmaps with no local path): saved to a temp file then use the regular attachment path + ipcMain.handle( + 'files:add-pasted-image', + (_event, data: unknown, ext: unknown): AttachmentAddResult => { + const filePath = savePastedImage(data, ext) + return filePath + ? collectAttachments([filePath]) + : { accepted: [], rejected: [tm('errNotImage')] } + }, + ) + + ipcMain.handle('docs:print', (event) => { + // print the calling tab's own content; zero margins — the docx page padding provides them + event.sender.print({ margins: { marginType: 'none' } }) + }) + + ipcMain.handle( + 'docs:export-pdf', + async ( + event, + defaultName: string, + pageWidthTwips: number, + pageHeightTwips: number, + outPath?: string, + ) => { + let filePath = outPath ?? null + if (!filePath) { + const result = await saveDialog(event, { + title: tm('dlgExportPdf'), + defaultPath: defaultName.replace(/\.docx$/i, '') + '.pdf', + filters: [{ name: 'PDF', extensions: ['pdf'] }], + }) + if (result.canceled || !result.filePath) return { ok: false } + filePath = result.filePath + } + try { + const data = await event.sender.printToPDF({ + printBackground: true, + // custom pageSize is in inches; the docx page padding provides the margins + pageSize: { + width: pageWidthTwips / TWIPS_PER_INCH, + height: pageHeightTwips / TWIPS_PER_INCH, + }, + margins: { top: 0, bottom: 0, left: 0, right: 0 }, + }) + writeFileSync(filePath, data) + return { ok: true, path: filePath } + } catch (err) { + return { ok: false, error: String(err) } + } + }, + ) + + // mixed paper-size export: the renderer prints group by group per size (other pages hidden via CSS); this produces one group's bytes + ipcMain.handle( + 'docs:print-pdf-buffer', + async (event, pageWidthTwips: number, pageHeightTwips: number) => { + try { + const data = await event.sender.printToPDF({ + printBackground: true, + pageSize: { + width: pageWidthTwips / TWIPS_PER_INCH, + height: pageHeightTwips / TWIPS_PER_INCH, + }, + margins: { top: 0, bottom: 0, left: 0, right: 0 }, + }) + return { ok: true, base64: data.toString('base64') } + } catch (err) { + return { ok: false, error: String(err) } + } + }, + ) + + // merge grouped PDF fragments into one file in page order (pdf-lib) + ipcMain.handle( + 'docs:save-merged-pdf', + async (event, defaultName: string, base64Parts: string[], outPath?: string) => { + let filePath = outPath ?? null + if (!filePath) { + const result = await saveDialog(event, { + title: tm('dlgExportPdf'), + defaultPath: defaultName.replace(/\.docx$/i, '') + '.pdf', + filters: [{ name: 'PDF', extensions: ['pdf'] }], + }) + if (result.canceled || !result.filePath) return { ok: false } + filePath = result.filePath + } + try { + const { PDFDocument } = await import('pdf-lib') + const merged = await PDFDocument.create() + for (const b64 of base64Parts) { + const part = await PDFDocument.load(Buffer.from(b64, 'base64')) + const pages = await merged.copyPages(part, part.getPageIndices()) + for (const page of pages) merged.addPage(page) + } + writeFileSync(filePath, Buffer.from(await merged.save())) + return { ok: true, path: filePath } + } catch (err) { + return { ok: false, error: String(err) } + } + }, + ) + + ipcMain.handle('win:new', (_event, openPath: string | null) => { + // A pathless new tab/window starts as a blank document, not the start screen + const path = openPath ?? undefined + if (shellHooks) shellHooks.openTab(path, path ? undefined : { newBlank: true }) + else { + const win = createDocsWindow(path) + if (!path) markDocsNewBlank(win.webContents.id) + } + }) + + ipcMain.handle('win:list', (): DocsTabInfo[] => { + if (shellHooks) return shellHooks.listTabs() + return BrowserWindow.getAllWindows().map((w) => ({ + id: String(w.id), + title: w.getTitle(), + focused: w.isFocused(), + })) + }) + + ipcMain.handle('win:focus', (_event, id: string) => { + if (shellHooks) { + shellHooks.focusTab(id) + return + } + const win = BrowserWindow.fromId(Number(id)) + if (!win) return + if (win.isMinimized()) win.restore() + win.show() + win.focus() + }) +} + +/** hooks injected by the shell in tab mode; standalone mode leaves these unset + * and falls back to real multi-BrowserWindow behavior. */ +interface DocsShellHooks { + openTab(openPath?: string, options?: { newBlank?: boolean }): void + listTabs(): DocsTabInfo[] + focusTab(id: string): void + /** closes the calling tab instead of the whole shell window (Cmd+W / role:'close') */ + closeActiveTab(): void +} +let shellHooks: DocsShellHooks | null = null +export function setDocsShellHooks(hooks: DocsShellHooks | null): void { + shellHooks = hooks +} + +// ---- application menu ---- + +function sendCommand(command: MenuCommand, payload?: string): void { + activeDocsWebContents()?.send('menu:command', command, payload) +} + +/** shell-injected items appended to the File menu (e.g. Back to Home); persists + * across the internal rebuilds pushRecent() triggers */ +let extraFileMenuItems: MenuItemConstructorOptions[] = [] + +export function setDocsExtraFileMenuItems(items: MenuItemConstructorOptions[]): void { + extraFileMenuItems = items +} + +/** Shell-installed gate: inside the shell the docs menu may only take over the + * application menu while a docs tab is active — internal rebuilds (pushRecent + * after opening/saving any file) must not clobber another tab's menu. + * The standalone docs app registers no gate and always installs. */ +let docsMenuGate: (() => boolean) | null = null + +export function setDocsMenuGate(gate: () => boolean): void { + docsMenuGate = gate +} + +export function buildDocsMenu(): void { + if (docsMenuGate && !docsMenuGate()) return + const isMac = process.platform === 'darwin' + const recent = readJson(RECENT_PATH(), []) + .filter((p) => existsSync(p)) + .slice(0, 10) + + const recentSubmenu: MenuItemConstructorOptions[] = + recent.length > 0 + ? recent.map((p) => ({ + label: basename(p), + sublabel: isMac ? undefined : p, + toolTip: p, + click: () => sendCommand('open-path', p), + })) + : [{ label: tm('menuNoRecent'), enabled: false }] + + const template: MenuItemConstructorOptions[] = [ + ...(isMac + ? [ + { + label: app.name, + submenu: [ + { role: 'about' as const }, + { type: 'separator' as const }, + { role: 'services' as const }, + { type: 'separator' as const }, + { role: 'hide' as const }, + { role: 'hideOthers' as const }, + { role: 'unhide' as const }, + { type: 'separator' as const }, + { role: 'quit' as const }, + ], + }, + ] + : []), + { + label: tm('menuFile'), + submenu: [ + { label: tm('menuNewDoc'), accelerator: 'CmdOrCtrl+N', click: () => sendCommand('new') }, + { + label: tm('menuNewWindow'), + accelerator: 'Shift+CmdOrCtrl+N', + click: () => { + if (shellHooks) shellHooks.openTab(undefined, { newBlank: true }) + else markDocsNewBlank(createDocsWindow().webContents.id) + }, + }, + { label: tm('menuOpen'), accelerator: 'CmdOrCtrl+O', click: () => sendCommand('open') }, + { label: tm('menuOpenRecent'), submenu: recentSubmenu }, + ...(extraFileMenuItems.length > 0 + ? [{ type: 'separator' as const }, ...extraFileMenuItems] + : []), + { type: 'separator' }, + shellHooks + ? { + label: tm('menuClose'), + accelerator: 'CmdOrCtrl+W', + click: () => shellHooks?.closeActiveTab(), + } + : { role: 'close' as const, label: tm('menuClose') }, + { label: tm('menuSave'), accelerator: 'CmdOrCtrl+S', click: () => sendCommand('save') }, + { + label: tm('menuSaveAs'), + accelerator: 'Shift+CmdOrCtrl+S', + click: () => sendCommand('save-as'), + }, + { type: 'separator' }, + { label: tm('menuPageSetup'), click: () => sendCommand('page-setup') }, + { label: tm('menuExportPdf'), click: () => sendCommand('export-pdf') }, + { + label: tm('menuPrint'), + accelerator: 'CmdOrCtrl+P', + click: () => activeDocsWebContents()?.print({}), + }, + ], + }, + { + label: tm('menuEdit'), + submenu: [ + { label: tm('menuUndo'), accelerator: 'CmdOrCtrl+Z', click: () => sendCommand('undo') }, + { + label: tm('menuRedo'), + accelerator: 'Shift+CmdOrCtrl+Z', + click: () => sendCommand('redo'), + }, + { type: 'separator' }, + { role: 'cut', label: tm('menuCut') }, + { role: 'copy', label: tm('menuCopy') }, + { role: 'paste', label: tm('menuPaste') }, + { role: 'pasteAndMatchStyle', label: tm('menuPasteMatch') }, + { type: 'separator' }, + { + label: tm('menuFindReplace'), + accelerator: 'CmdOrCtrl+F', + click: () => sendCommand('find'), + }, + { type: 'separator' }, + { role: 'selectAll', label: tm('menuSelectAll') }, + ], + }, + { + label: tm('menuView'), + submenu: [ + { + label: tm('menuZoomIn'), + accelerator: 'CmdOrCtrl+=', + click: () => sendCommand('zoom-in'), + }, + { + label: tm('menuZoomOut'), + accelerator: 'CmdOrCtrl+-', + click: () => sendCommand('zoom-out'), + }, + { + label: tm('menuZoom100'), + accelerator: 'CmdOrCtrl+0', + click: () => sendCommand('zoom-100'), + }, + { label: tm('menuPageWidth'), click: () => sendCommand('zoom-page-width') }, + { label: tm('menuWholePage'), click: () => sendCommand('zoom-whole-page') }, + { type: 'separator' }, + { label: tm('menuAiSidebar'), click: () => sendCommand('toggle-ai') }, + { label: tm('menuDarkMode'), click: () => sendCommand('toggle-dark') }, + { type: 'separator' }, + { role: 'togglefullscreen', label: tm('menuFullscreen') }, + ...(isDev ? [{ role: 'toggleDevTools' as const }] : []), + ], + }, + { + label: tm('menuInsert'), + submenu: [ + { label: tm('menuInsertTable'), click: () => sendCommand('insert-table') }, + { label: tm('menuInsertImage'), click: () => sendCommand('insert-image') }, + { label: tm('menuInsertPageBreak'), click: () => sendCommand('insert-page-break') }, + { + label: tm('menuInsertLink'), + accelerator: 'CmdOrCtrl+K', + click: () => sendCommand('insert-link'), + }, + { label: tm('menuInsertEquation'), click: () => sendCommand('insert-equation') }, + { type: 'separator' }, + { label: tm('menuComment'), click: () => sendCommand('insert-comment') }, + ], + }, + { + label: tm('menuFormat'), + submenu: [ + { label: tm('menuBold'), accelerator: 'CmdOrCtrl+B', click: () => sendCommand('bold') }, + { label: tm('menuItalic'), accelerator: 'CmdOrCtrl+I', click: () => sendCommand('italic') }, + { + label: tm('menuUnderline'), + accelerator: 'CmdOrCtrl+U', + click: () => sendCommand('underline'), + }, + { type: 'separator' }, + { + label: tm('menuAlign'), + submenu: [ + { label: tm('menuAlignLeft'), click: () => sendCommand('align-left') }, + { label: tm('menuAlignCenter'), click: () => sendCommand('align-center') }, + { label: tm('menuAlignRight'), click: () => sendCommand('align-right') }, + { label: tm('menuAlignJustify'), click: () => sendCommand('align-justify') }, + ], + }, + { type: 'separator' }, + { + label: tm('menuFont'), + accelerator: 'CmdOrCtrl+D', + click: () => sendCommand('font-dialog'), + }, + { + label: tm('menuParagraph'), + accelerator: 'Alt+CmdOrCtrl+M', + click: () => sendCommand('paragraph-dialog'), + }, + ], + }, + { + // Word for Mac keeps Word Count in the Tools menu, not on the ribbon + label: tm('menuTools'), + submenu: [ + { label: tm('menuWordCount'), click: () => sendCommand('word-count') }, + { type: 'separator' }, + { label: tm('menuSpelling'), enabled: false }, + { label: tm('menuMacros'), enabled: false }, + ], + }, + { label: tm('menuWindow'), role: 'windowMenu' }, + { + label: tm('menuHelp'), + role: 'help', + submenu: [{ label: tm('menuDocsHelp'), enabled: false }], + }, + ] + + Menu.setApplicationMenu(Menu.buildFromTemplate(template)) +} + +// ---- window ---- + +export function createDocsWindow(openPath?: string): BrowserWindow { + const win = new BrowserWindow({ + width: 1360, + height: 900, + minWidth: 980, + minHeight: 600, + title: 'GenOffice Docs', + // Word-like custom title bar (document name centered, quick-access buttons) + ...(process.platform === 'darwin' + ? { titleBarStyle: 'hiddenInset' as const } + : { + titleBarStyle: 'hidden' as const, + titleBarOverlay: { color: '#ffffff', symbolColor: '#444444', height: 40 }, + }), + // packaged builds embed the icon (build/icon.icns|ico); dev needs the file path + ...(isDev && process.platform !== 'darwin' + ? { icon: join(app.getAppPath(), 'build/icon.png') } + : {}), + webPreferences: { + preload: runtime.preloadPath, + contextIsolation: true, + nodeIntegration: false, + sandbox: true, + backgroundThrottling: false, + }, + }) + + if (!mainWindow) { + mainWindow = win + rendererReady = false + } + // captured up front: webContents is already destroyed inside the 'closed' handler + const webContentsId = win.webContents.id + if (openPath) pendingWindowOpens.set(webContentsId, openPath) + + win.webContents.setWindowOpenHandler(({ url }) => { + const target = safeExternalUrl(url) + if (target) void shell.openExternal(target) + return { action: 'deny' } + }) + + if (runtime.rendererUrl) { + void win.loadURL(runtime.rendererUrl) + } else { + void win.loadFile(runtime.rendererFile) + } + // close guard for standalone-window mode (tab mode goes through the same flow via the shell's tab-manager/window-close path) + let closeConfirmed = false + win.on('close', (event) => { + if (closeConfirmed) return + event.preventDefault() + void requestDocsClose(win.webContents, win).then((proceed) => { + if (proceed && !win.isDestroyed()) { + closeConfirmed = true + win.close() + } + }) + }) + win.on('closed', () => { + pendingWindowOpens.delete(webContentsId) + // release any close-guard waiter still keyed on the gone webContents + closeCheckWaiters.get(webContentsId)?.({ dirty: false, autoSave: false }) + closeCheckWaiters.delete(webContentsId) + closeSaveWaiters.get(webContentsId)?.(false) + closeSaveWaiters.delete(webContentsId) + if (mainWindow === win) { + mainWindow = BrowserWindow.getAllWindows().find((w) => w !== win) ?? null + if (!mainWindow) rendererReady = false + } + }) + return win +} + +/** tab-mode equivalent of createDocsWindow: same runtime/IPC wiring, no BrowserWindow of its own. */ +// ── Close guard (aligned with sheets/pdf/slides): dirty documents prompt Save/Don't Save/Cancel before closing a tab/window ── +// docs' dirty state is a composite flag in the renderer; the main process doesn't mirror it and queries once at close time. +interface DocsCloseState { + dirty: boolean + autoSave: boolean + /** Open file path (for recovery-copy cleanup on "Don't Save") */ + filePath?: string | null + /** The renderer never replied to the close check (busy or wedged) */ + unresponsive?: boolean +} +const closeCheckWaiters = new Map void>() +const closeSaveWaiters = new Map void>() + +ipcMain.on('docs:close-check-result', (event, state: unknown) => { + const waiter = closeCheckWaiters.get(event.sender.id) + if (!waiter) return + closeCheckWaiters.delete(event.sender.id) + const s = state as { dirty?: unknown; autoSave?: unknown; filePath?: unknown } | boolean + waiter( + typeof s === 'boolean' + ? { dirty: s, autoSave: false } + : { + dirty: s?.dirty === true, + autoSave: s?.autoSave === true, + filePath: typeof s?.filePath === 'string' ? s.filePath : null, + }, + ) +}) + +ipcMain.on('docs:close-save-result', (event, ok: unknown) => { + const waiter = closeSaveWaiters.get(event.sender.id) + if (!waiter) return + closeSaveWaiters.delete(event.sender.id) + waiter(ok === true) +}) + +/** Ask the renderer for pre-close state (dirty flag + autosave switch); no reply within 2s + * fails CLOSED — a busy or wedged renderer may well hold unsaved changes, so the caller + * prompts instead of closing silently. */ +function queryCloseState(contents: WebContents): Promise { + if (contents.isDestroyed()) return Promise.resolve({ dirty: false, autoSave: false }) + return new Promise((resolve) => { + const timer = setTimeout(() => { + closeCheckWaiters.delete(contents.id) + resolve({ dirty: true, autoSave: false, unresponsive: true }) + }, 2000) + closeCheckWaiters.set(contents.id, (state) => { + clearTimeout(timer) + resolve(state) + }) + contents.send('docs:close-check') + }) +} + +export async function docsQueryDirty(contents: WebContents): Promise { + return (await queryCloseState(contents)).dirty +} + +/** Ask the renderer to run the full save flow and await the result (failure/timeout = false). */ +function requestRendererSave(contents: WebContents): Promise { + return new Promise((resolve) => { + const timer = setTimeout(() => { + closeSaveWaiters.delete(contents.id) + resolve(false) + }, 120_000) + closeSaveWaiters.set(contents.id, (ok) => { + clearTimeout(timer) + resolve(ok) + }) + contents.send('docs:close-save-request') + }) +} + +/** + * Close guard for the docs renderer: true means proceed with closing. + * Clean → true; with changes → Save/Don't Save/Cancel. On Save, ask the renderer + * to run the full save flow (new documents open Save As) and await the result; + * failure/cancel/timeout keeps the document open. + */ +export async function requestDocsClose( + contents: WebContents, + parent?: BrowserWindow | null, +): Promise { + const state = await queryCloseState(contents) + if (!state.dirty || contents.isDestroyed()) return true + if (state.unresponsive) { + // No reply: saving through the renderer won't work either — offer Close Anyway / Cancel + const options = { + type: 'warning' as const, + message: tm('closeNoReplyMsg'), + detail: tm('closeNoReplyDetail'), + buttons: [tm('btnCloseAnyway'), tm('btnCancel')], + defaultId: 1, + cancelId: 1, + noLink: true, + } + const { response } = + parent && !parent.isDestroyed() + ? await dialog.showMessageBox(parent, options) + : await dialog.showMessageBox(options) + return response === 0 + } + // autosave on (and has a path, already checked when the renderer reported): save silently and proceed; only prompt on failure + if (state.autoSave && (await requestRendererSave(contents))) return true + const options = { + type: 'warning' as const, + message: tm('closeUnsavedMsg'), + detail: tm('closeUnsavedDetail'), + buttons: [tm('menuSave'), tm('btnDontSave'), tm('btnCancel')], + defaultId: 0, + cancelId: 2, + noLink: true, + } + const { response } = + parent && !parent.isDestroyed() + ? await dialog.showMessageBox(parent, options) + : await dialog.showMessageBox(options) + if (response === 2) return false + if (response === 1) { + // Explicitly discarded: also drop the recovery copy so the next open doesn't offer it + if (state.filePath) clearRecoveryCopy(state.filePath) + return true + } + return requestRendererSave(contents) +} + +export function createDocsView(openPath?: string): WebContentsView { + const view = new WebContentsView({ + webPreferences: { + preload: runtime.preloadPath, + contextIsolation: true, + nodeIntegration: false, + sandbox: true, + backgroundThrottling: false, + }, + }) + + if (openPath) pendingWindowOpens.set(view.webContents.id, openPath) + + view.webContents.setWindowOpenHandler(({ url }) => { + const target = safeExternalUrl(url) + if (target) void shell.openExternal(target) + return { action: 'deny' } + }) + + // mode=tab: the shell's tab strip owns the traffic lights / caption buttons, + // so the ribbon must not reserve space for them + if (runtime.rendererUrl) { + // append via URL so a dev URL that already carries query params stays valid + const devUrl = new URL(runtime.rendererUrl) + devUrl.searchParams.set('mode', 'tab') + void view.webContents.loadURL(devUrl.toString()) + } else { + void view.webContents.loadFile(runtime.rendererFile, { query: { mode: 'tab' } }) + } + // view.webContents becomes undefined after destroy, so grab the id beforehand + const wcId = view.webContents.id + view.webContents.once('destroyed', () => { + pendingWindowOpens.delete(wcId) + closeCheckWaiters.get(wcId)?.({ dirty: false, autoSave: false }) + closeCheckWaiters.delete(wcId) + closeSaveWaiters.get(wcId)?.(false) + closeSaveWaiters.delete(wcId) + }) + return view +} + +/** true when at least one docs window is open (shell menu switching) */ +export function hasDocsWindow(): boolean { + return mainWindow !== null +} + +// ---- standalone lifecycle (apps/docs running on its own) ---- + +export function startDocsStandalone(): void { + // dev runs must not share the packaged app's userData (recent files, AI settings) + // or its single-instance lock — otherwise `npm run dev` silently quits whenever + // the installed GenOffice Docs is open and forwards its argv there instead. + if (isDev) app.setPath('userData', join(app.getPath('appData'), 'GenOffice Docs Dev')) + + const hasSingleInstanceLock = app.requestSingleInstanceLock() + if (!hasSingleInstanceLock) { + app.quit() + return + } + + app.on('open-file', (event, filePath) => { + event.preventDefault() + openExternalDocx(filePath) + }) + + app.on('second-instance', (_event, argv) => { + openExternalDocx(findDocxPath(argv)) + mainWindow?.show() + mainWindow?.focus() + }) + + registerAiIpc() + registerProjectIpc() + registerDocsIpc() + + app.whenReady().then(() => { + setUiLang(normalizeLang(process.env.GENOFFICE_LANG ?? app.getLocale())) + // packaged builds get the Dock icon from icon.icns; dev shows Electron's default + if (isDev && process.platform === 'darwin') { + app.dock?.setIcon(join(app.getAppPath(), 'build/icon.png')) + } + buildDocsMenu() + createDocsWindow() + initDocsAutoUpdater(() => mainWindow) + app.on('activate', () => { + if (BrowserWindow.getAllWindows().length === 0) createDocsWindow() + }) + }) + + app.on('window-all-closed', () => { + if (process.platform !== 'darwin') app.quit() + }) +} diff --git a/apps/docs/src/main/index.ts b/apps/docs/src/main/index.ts new file mode 100644 index 0000000..2cd3aad --- /dev/null +++ b/apps/docs/src/main/index.ts @@ -0,0 +1,3 @@ +import { startDocsStandalone } from './docs-main' + +startDocsStandalone() diff --git a/apps/docs/src/main/updater.ts b/apps/docs/src/main/updater.ts new file mode 100644 index 0000000..568af71 --- /dev/null +++ b/apps/docs/src/main/updater.ts @@ -0,0 +1,244 @@ +import { app, dialog } from 'electron' +import type { BrowserWindow } from 'electron' +import { autoUpdater } from 'electron-updater' +import type { UpdateInfo } from 'electron-updater' +import { createI18n, getUiLang } from '@genoffice/i18n' + +/** + * Full-package auto-update for the standalone GenOffice Docs app over the generic + * provider (Azure CDN). + * + * electron-builder bakes the publish URL into resources/app-update.yml at + * package time and emits the update feed (latest.yml on Windows, + * latest-mac.yml on macOS) next to the installers; the release pipeline + * uploads both to the CDN. Standalone docs builds currently ship without a + * publish config, so packaged runs simply log the missing-feed error. + * + * Unlike the shell's modal update window, docs keeps the flow minimal: + * updates download silently in the background and a single native dialog + * offers "Restart & Install" once the payload is ready. Declining defers the + * install to normal app quit (autoInstallOnAppQuit). + */ + +const tUpd = createI18n({ + zh: { + updTitle: '软件更新', + updHeadline: '发现新版本', + updDesc: '新版本包含性能改进与问题修复,建议立即更新。', + updInstall: '立即重启安装', + updLater: '稍后再说', + }, + en: { + updTitle: 'Software Update', + updHeadline: 'A new version is available', + updDesc: + 'This update includes performance improvements and bug fixes. We recommend updating now.', + updInstall: 'Restart & Install', + updLater: 'Remind me later', + }, + ja: { + updTitle: 'ソフトウェアアップデート', + updHeadline: '新しいバージョンがあります', + updDesc: + 'このアップデートにはパフォーマンス改善とバグ修正が含まれます。今すぐの更新をおすすめします。', + updInstall: '再起動してインストール', + updLater: '後で通知', + }, + ko: { + updTitle: '소프트웨어 업데이트', + updHeadline: '새 버전이 있습니다', + updDesc: + '이 업데이트에는 성능 개선과 버그 수정이 포함되어 있습니다. 지금 업데이트하는 것을 권장합니다.', + updInstall: '다시 시작 및 설치', + updLater: '나중에 알림', + }, + fr: { + updTitle: 'Mise à jour logicielle', + updHeadline: 'Une nouvelle version est disponible', + updDesc: + 'Cette mise à jour apporte des améliorations de performances et des corrections de bogues. Nous vous recommandons de mettre à jour maintenant.', + updInstall: 'Redémarrer et installer', + updLater: 'Plus tard', + }, + de: { + updTitle: 'Softwareaktualisierung', + updHeadline: 'Eine neue Version ist verfügbar', + updDesc: + 'Dieses Update enthält Leistungsverbesserungen und Fehlerbehebungen. Wir empfehlen, jetzt zu aktualisieren.', + updInstall: 'Neu starten und installieren', + updLater: 'Später erinnern', + }, + es: { + updTitle: 'Actualización de software', + updHeadline: 'Hay una nueva versión disponible', + updDesc: + 'Esta actualización incluye mejoras de rendimiento y correcciones de errores. Recomendamos actualizar ahora.', + updInstall: 'Reiniciar e instalar', + updLater: 'Recordar más tarde', + }, + th: { + updTitle: 'อัปเดตซอฟต์แวร์', + updHeadline: 'มีเวอร์ชันใหม่พร้อมใช้งาน', + updDesc: 'การอัปเดตนี้มีการปรับปรุงประสิทธิภาพและแก้ไขข้อบกพร่อง แนะนำให้อัปเดตทันที', + updInstall: 'รีสตาร์ทและติดตั้ง', + updLater: 'เตือนภายหลัง', + }, + id: { + updTitle: 'Pembaruan Perangkat Lunak', + updHeadline: 'Versi baru tersedia', + updDesc: + 'Pembaruan ini mencakup peningkatan kinerja dan perbaikan bug. Kami menyarankan untuk memperbarui sekarang.', + updInstall: 'Mulai Ulang & Pasang', + updLater: 'Ingatkan nanti', + }, + ru: { + updTitle: 'Обновление программы', + updHeadline: 'Доступна новая версия', + updDesc: + 'Это обновление содержит улучшения производительности и исправления ошибок. Рекомендуем обновиться сейчас.', + updInstall: 'Перезапустить и установить', + updLater: 'Напомнить позже', + }, + ar: { + updTitle: 'تحديث البرنامج', + updHeadline: 'يتوفر إصدار جديد', + updDesc: 'يتضمن هذا التحديث تحسينات في الأداء وإصلاحات للأخطاء. نوصي بالتحديث الآن.', + updInstall: 'إعادة التشغيل والتثبيت', + updLater: 'ذكّرني لاحقًا', + }, + pt: { + updTitle: 'Atualização de Software', + updHeadline: 'Uma nova versão está disponível', + updDesc: + 'Esta atualização inclui melhorias de desempenho e correções de erros. Recomendamos atualizar agora.', + updInstall: 'Reiniciar e instalar', + updLater: 'Lembrar mais tarde', + }, + it: { + updTitle: 'Aggiornamento software', + updHeadline: 'È disponibile una nuova versione', + updDesc: + 'Questo aggiornamento include miglioramenti delle prestazioni e correzioni di bug. Consigliamo di aggiornare subito.', + updInstall: 'Riavvia e installa', + updLater: 'Ricordamelo più tardi', + }, + pl: { + updTitle: 'Aktualizacja oprogramowania', + updHeadline: 'Dostępna jest nowa wersja', + updDesc: + 'Ta aktualizacja zawiera ulepszenia wydajności i poprawki błędów. Zalecamy aktualizację teraz.', + updInstall: 'Uruchom ponownie i zainstaluj', + updLater: 'Przypomnij później', + }, + nl: { + updTitle: 'Software-update', + updHeadline: 'Er is een nieuwe versie beschikbaar', + updDesc: + 'Deze update bevat prestatieverbeteringen en foutoplossingen. We raden aan nu bij te werken.', + updInstall: 'Opnieuw starten en installeren', + updLater: 'Later herinneren', + }, + ms: { + updTitle: 'Kemas Kini Perisian', + updHeadline: 'Versi baharu tersedia', + updDesc: + 'Kemas kini ini merangkumi penambahbaikan prestasi dan pembetulan pepijat. Kami syorkan kemas kini sekarang.', + updInstall: 'Mula Semula & Pasang', + updLater: 'Ingatkan kemudian', + }, + he: { + updTitle: 'עדכון תוכנה', + updHeadline: 'גרסה חדשה זמינה', + updDesc: 'עדכון זה כולל שיפורי ביצועים ותיקוני באגים. מומלץ לעדכן עכשיו.', + updInstall: 'הפעל מחדש והתקן', + updLater: 'הזכר לי מאוחר יותר', + }, + hi: { + updTitle: 'सॉफ़्टवेयर अपडेट', + updHeadline: 'नया संस्करण उपलब्ध है', + updDesc: + 'इस अपडेट में प्रदर्शन सुधार और बग फ़िक्स शामिल हैं। हम अभी अपडेट करने की सलाह देते हैं।', + updInstall: 'पुनरारंभ करें और इंस्टॉल करें', + updLater: 'बाद में याद दिलाएँ', + }, + 'zh-TW': { + updTitle: '軟體更新', + updHeadline: '發現新版本', + updDesc: '新版本包含效能改進與問題修復,建議立即更新。', + updInstall: '立即重新啟動安裝', + updLater: '稍後再說', + }, +}) + +const FIRST_CHECK_DELAY_MS = 15_000 +const RECHECK_INTERVAL_MS = 4 * 60 * 60 * 1000 + +let started = false +// version the user declined this session — don't nag again until next launch +let dismissedVersion: string | null = null + +function log(...args: unknown[]): void { + console.log('[docs-updater]', ...args) +} + +async function promptInstall(win: BrowserWindow | null, info: UpdateInfo): Promise { + const lang = getUiLang() + const options = { + type: 'info' as const, + title: tUpd(lang, 'updTitle'), + message: `${tUpd(lang, 'updHeadline')} (${info.version})`, + detail: tUpd(lang, 'updDesc'), + buttons: [tUpd(lang, 'updInstall'), tUpd(lang, 'updLater')], + defaultId: 0, + cancelId: 1, + } + const { response } = + win && !win.isDestroyed() + ? await dialog.showMessageBox(win, options) + : await dialog.showMessageBox(options) + if (response === 0) { + autoUpdater.quitAndInstall(true, true) + } else { + // autoInstallOnAppQuit still applies the update on normal quit + dismissedVersion = info.version + } +} + +export function initDocsAutoUpdater(getWindow: () => BrowserWindow | null): void { + if (started) return + started = true + + // Unpacked runs have no app-update.yml and must not hit the CDN with a dev + // version. Windows updates via NSIS (latest.yml); macOS via the zip target + // (latest-mac.yml) — Squirrel.Mac additionally requires a signed app, so + // unsigned local builds check but never install. + if (!app.isPackaged) return + if (process.platform !== 'win32' && process.platform !== 'darwin') return + + autoUpdater.autoDownload = true + autoUpdater.autoInstallOnAppQuit = true + // full-package policy: never attempt blockmap differential downloads + // (the publish pipeline does not upload .blockmap files) + autoUpdater.disableDifferentialDownload = true + + autoUpdater.on('error', (err) => { + // background check/download failures are expected offline; log only + log('error:', err instanceof Error ? err.message : err) + }) + + autoUpdater.on('update-downloaded', (info: UpdateInfo) => { + if (info.version === dismissedVersion) return + log('downloaded:', info.version) + promptInstall(getWindow(), info).catch((err) => { + log('install prompt failed:', err instanceof Error ? err.message : err) + }) + }) + + const check = (): void => { + autoUpdater + .checkForUpdates() + .catch((err) => log('check failed:', err instanceof Error ? err.message : err)) + } + setTimeout(check, FIRST_CHECK_DELAY_MS) + setInterval(check, RECHECK_INTERVAL_MS) +} diff --git a/apps/docs/src/preload/index.ts b/apps/docs/src/preload/index.ts new file mode 100644 index 0000000..6aa396e --- /dev/null +++ b/apps/docs/src/preload/index.ts @@ -0,0 +1,127 @@ +import { contextBridge, ipcRenderer, webUtils } from 'electron' +import type { IpcRendererEvent } from 'electron' +import type { + AiChatRequest, + AiSettings, + AiStreamChunk, + AiStreamRequest, + DesktopApi, + MenuCommand, +} from '../shared/ipc' +import type { ProjectApi } from '@genoffice/project-store' + +const api: DesktopApi = { + getLanguage: () => ipcRenderer.invoke('app:get-language'), + onLanguageChanged: (handler) => { + const listener = ( + _event: IpcRendererEvent, + lang: 'zh' | 'en' | 'ja' | 'ko' | 'fr' | 'de' | 'es' | 'th' | 'id' | 'ru' | 'ar', + ) => handler(lang) + ipcRenderer.on('app:language-changed', listener) + return () => ipcRenderer.removeListener('app:language-changed', listener) + }, + openDocx: () => ipcRenderer.invoke('docs:open'), + openDocxPath: (path: string) => ipcRenderer.invoke('docs:open-path', path), + consumePendingOpenDocx: () => ipcRenderer.invoke('docs:consume-pending-open'), + consumeNewBlankDoc: () => ipcRenderer.invoke('docs:consume-new-blank'), + onOpenDocx: (handler) => { + const listener = (_event: IpcRendererEvent, result: Parameters[0]) => + handler(result) + ipcRenderer.on('docs:opened', listener) + return () => ipcRenderer.removeListener('docs:opened', listener) + }, + onRenamedDocx: (handler) => { + const listener = (_event: IpcRendererEvent, paths: Parameters[0]) => + handler(paths) + ipcRenderer.on('docs:renamed', listener) + return () => ipcRenderer.removeListener('docs:renamed', listener) + }, + saveDocx: (path: string, data: ArrayBuffer) => ipcRenderer.invoke('docs:save', path, data), + writeRecoveryCopy: (path: string, data: ArrayBuffer) => + ipcRenderer.invoke('docs:write-recovery', path, data), + saveDocxAs: (defaultName: string, data: ArrayBuffer) => + ipcRenderer.invoke('docs:save-as', defaultName, data), + saveDocxNew: (defaultName: string, data: ArrayBuffer) => + ipcRenderer.invoke('docs:save-new', defaultName, data), + getRecentFiles: () => ipcRenderer.invoke('docs:recent'), + pickImage: () => ipcRenderer.invoke('docs:pick-image'), + print: () => ipcRenderer.invoke('docs:print'), + exportPdf: ( + defaultName: string, + pageWidthTwips: number, + pageHeightTwips: number, + outPath?: string, + ) => ipcRenderer.invoke('docs:export-pdf', defaultName, pageWidthTwips, pageHeightTwips, outPath), + printPdfBuffer: (pageWidthTwips: number, pageHeightTwips: number) => + ipcRenderer.invoke('docs:print-pdf-buffer', pageWidthTwips, pageHeightTwips), + saveMergedPdf: (defaultName: string, base64Parts: string[], outPath?: string) => + ipcRenderer.invoke('docs:save-merged-pdf', defaultName, base64Parts, outPath), + getAiSettings: () => ipcRenderer.invoke('ai:get-settings'), + setAiSettings: (settings: AiSettings) => ipcRenderer.invoke('ai:set-settings', settings), + aiChat: (request: AiChatRequest) => ipcRenderer.invoke('ai:chat', request), + aiStream: (request: AiStreamRequest) => ipcRenderer.invoke('ai:stream', request), + aiStreamCancel: (requestId: string) => ipcRenderer.invoke('ai:stream-cancel', requestId), + aiGskStatus: (withEmail?: boolean) => ipcRenderer.invoke('ai:gsk-status', withEmail), + aiGskLogin: () => ipcRenderer.invoke('ai:gsk-login'), + webSearch: (query: string, maxResults?: number) => + ipcRenderer.invoke('ai:web-search', query, maxResults), + imageSearch: (query: string, maxResults?: number) => + ipcRenderer.invoke('ai:image-search', query, maxResults), + fetchImage: (url: string) => ipcRenderer.invoke('ai:fetch-image', url), + pickAttachments: () => ipcRenderer.invoke('files:pick'), + addAttachmentPaths: (paths: string[]) => ipcRenderer.invoke('files:add', paths), + addPastedImage: (data: ArrayBuffer, ext: string) => + ipcRenderer.invoke('files:add-pasted-image', data, ext), + readAttachment: (path: string, offset: number, maxChars: number) => + ipcRenderer.invoke('files:read', path, offset, maxChars), + readAttachmentImage: (path: string) => ipcRenderer.invoke('files:read-image', path), + getPathForFile: (file: File) => webUtils.getPathForFile(file), + openNewTab: (openPath?: string | null) => ipcRenderer.invoke('win:new', openPath ?? null), + listDocsTabs: () => ipcRenderer.invoke('win:list'), + focusDocsTab: (id: string) => ipcRenderer.invoke('win:focus', id), + onAiStream: (handler: (chunk: AiStreamChunk) => void) => { + const listener = (_event: IpcRendererEvent, chunk: AiStreamChunk) => handler(chunk) + ipcRenderer.on('ai:stream-chunk', listener) + return () => ipcRenderer.removeListener('ai:stream-chunk', listener) + }, + onMenuCommand: (handler: (command: MenuCommand, payload?: string) => void) => { + const listener = (_event: IpcRendererEvent, command: MenuCommand, payload?: string) => + handler(command, payload) + ipcRenderer.on('menu:command', listener) + return () => ipcRenderer.removeListener('menu:command', listener) + }, + onCloseCheck: (handler: () => void) => { + const listener = () => handler() + ipcRenderer.on('docs:close-check', listener) + return () => ipcRenderer.removeListener('docs:close-check', listener) + }, + reportCloseCheck: (state: { dirty: boolean; autoSave: boolean; filePath?: string | null }) => + ipcRenderer.send('docs:close-check-result', { + dirty: state?.dirty === true, + autoSave: state?.autoSave === true, + filePath: typeof state?.filePath === 'string' ? state.filePath : null, + }), + onCloseSaveRequest: (handler: () => void) => { + const listener = () => handler() + ipcRenderer.on('docs:close-save-request', listener) + return () => ipcRenderer.removeListener('docs:close-save-request', listener) + }, + reportCloseSaveResult: (ok: boolean) => ipcRenderer.send('docs:close-save-result', ok === true), +} + +const projectApi: ProjectApi = { + resolveChat: (args) => ipcRenderer.invoke('project:resolveChat', args), + appendChat: (args) => ipcRenderer.invoke('project:appendChat', args), + loadChat: (args) => ipcRenderer.invoke('project:loadChat', args), + rebindChat: (args) => ipcRenderer.invoke('project:rebindChat', args), + // P1 extensions + listProjects: () => ipcRenderer.invoke('project:list'), + createProject: (args) => ipcRenderer.invoke('project:create', args), + renameProject: (args) => ipcRenderer.invoke('project:rename', args), + deleteProject: (args) => ipcRenderer.invoke('project:delete', args), + moveFile: (args) => ipcRenderer.invoke('project:moveFile', args), + getTimeline: (args) => ipcRenderer.invoke('project:timeline', args), +} + +contextBridge.exposeInMainWorld('desktop', api) +contextBridge.exposeInMainWorld('projectApi', projectApi) diff --git a/apps/docs/src/renderer/App.tsx b/apps/docs/src/renderer/App.tsx new file mode 100644 index 0000000..39798f0 --- /dev/null +++ b/apps/docs/src/renderer/App.tsx @@ -0,0 +1,3041 @@ +import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react' +import type { CSSProperties, MouseEvent as ReactMouseEvent } from 'react' +import { EditorContent, useEditor } from '@tiptap/react' +import type { Editor } from '@tiptap/core' +import { DOMParser as PmDOMParser, type Mark as PmMark } from '@tiptap/pm/model' +import { + BLANK_BULLET_NUM_ID, + BLANK_ORDERED_NUM_ID, + DEFAULT_SECTION, + applySectionSettings, + type Block, + type CommentInfo, + type CustomNumberingLevel, + type DocProtection, + type HeaderFooter, + type NoteInfo, + type SectionInfo, + type SectionSettings, + type SourceInfo, + type StyleUpsert, + type ThemeColors, + type ThemeFonts, +} from '@genoffice/docx-engine' +import type { AiSettings, OpenFileResult } from '../shared/ipc' +import { AI_PROVIDERS } from '../shared/ipc' +import { AiPanel } from './ai/AiPanel' +import { asianCharCount, countWords, nonAsianWordCount } from './word-count' +import { toRoman } from './note-format' +import { CommentsPanel } from './components/CommentsPanel' +import { StylesPanel } from './components/StylesPanel' +import { EquationModal } from './components/EquationModal' +import { HeaderFooterArea } from './components/HeaderFooterArea' +import { PaginationPreview } from './components/PaginationPreview' +import { + appendEndnotesBlock, + assignSections, + effectiveHfRefs, + lineStartCoords, + liveSections, + nextLineCoords, + measureBlocks, + pageNumbers, + sliceWithLineSplit, + tableRowFlags, + type BlockBox, + type BlockMeta, + type PageNoteItem, + pageAt, + sectionColGeom, + sectionColumns, + sectionGeoms, + sectionPageBox, + effectiveTopPx, + effectiveBottomPx, + type SectionGeom, + type SectionHfHeights, + type PageSlice, +} from './pagination' +import { setPageGaps, type PageGapSpec } from './editor/pagination-gaps' +import { + estimateFootnoteHeight, + estimateHfHeight, + FOOTNOTE_SEPARATOR_H, + textHasCjk, +} from './line-metrics' +import { saveUntilPersisted } from './save-until-persisted' +import { FindPanel } from './components/FindPanel' +import { Ribbon } from './components/Ribbon' +import { GensparkMark, IconRedo, IconSave, IconUndo } from './components/icons' +import { + LinkInsertModal, + insertImageFromDataUrl, + insertImageViaDialog, + insertPageBreakAt, + insertTableAt, + setParaAttrs, + type InkPenSettings, + type RevisionDisplayMode, + type ViewMode, +} from './components/ribbon-tabs' +import { ComparePanel } from './components/ComparePanel' +import { + EditorContextMenu, + FontDialog, + ParagraphDialog, + type ContextMenuState, +} from './components/ContextMenu' +import { PromptModal } from './components/PromptModal' +import { t, useI18n } from './i18n/locale' +import { setActiveSubEditor, subscribeSubEditorState } from './editor/active-editor' +import type { CompareEntry } from './editor/compare' + +import { + editorExtensions, + resolvedCommentsPluginKey, + revisionDisplayState, +} from './editor/extensions' +import { type InkAnnotation, type InkTool } from './editor/ink' +import { InkOverlay } from './components/InkOverlay' +import { collectRevisions, gotoRevision, type TrackChangesStorage } from './editor/revisions' +import { NavPane } from './components/NavPane' +import { Ruler } from './components/Ruler' +import { docLineFactor, docStyleCss, docThemeCss } from './doc-style-css' +import { + EMPTY_HF_VARIANTS, + hfFromPart, + type DocState, + type HfVariantKey, + type HfVariantsState, + type HfView, + type PendingNumbering, +} from './doc-state' +import { + exportPdf as exportPdfImpl, + loadFile as loadFileImpl, + newFile as newFileImpl, + save as saveImpl, + writeRecoveryCopy as writeRecoveryCopyImpl, + type FileActionContext, +} from './file-actions' +import { + allocateListNumId as allocateListNumIdImpl, + continueNumbering as continueNumberingImpl, + createCustomListDef as createCustomListDefImpl, + restartNumbering as restartNumberingImpl, + type NumberingContext, +} from './numbering-actions' +import { + addInk as addInkImpl, + cancelNewComment as cancelNewCommentImpl, + clearInks as clearInksImpl, + compareWithFile as compareWithFileImpl, + deleteComment as deleteCommentImpl, + deleteNote as deleteNoteImpl, + handleRevision as handleRevisionImpl, + removeInks as removeInksImpl, + replyToComment as replyToCommentImpl, + resolveComment as resolveCommentImpl, + startNewComment as startNewCommentImpl, + submitNewComment as submitNewCommentImpl, + submitNote as submitNoteImpl, + submitProtectModal as submitProtectModalImpl, + toggleProtection as toggleProtectionImpl, + type NotePrompt, + type ProtectModalState, + type ReviewContext, +} from './review-actions' + +const _IS_MAC = navigator.platform.toLowerCase().includes('mac') + +const twipsToPx = (twips: number) => (twips / 1440) * 96 + +/** Clean pasted Word/web HTML: mso conditional comments, , and unwrapping
  • x

  • */ +function cleanPastedHtml(html: string): string { + return html + .replace(//g, '') + .replace(/[\s\S]*?<\/o:p>/g, '') + .replace(/]*)>\s*]*>([\s\S]*?)<\/p>\s*<\/li>/g, '$2') +} + +/** Footnote area at the top of a page gap (previous page's bottom): absolutely positioned in the content area, double-click an entry to edit */ +function makeGapNotesEl( + items: PageNoteItem[], + leftPx: number, + widthPx: number, + heightPx: number, + onEdit: (id: string) => void, +): HTMLElement { + const wrap = document.createElement('div') + wrap.className = 'page-gap-notes' + wrap.style.left = `${leftPx}px` + wrap.style.width = `${widthPx}px` + wrap.style.height = `${heightPx}px` + for (const it of items) { + const row = document.createElement('div') + row.className = 'page-gap-note' + row.title = t('appDblclickEditFootnote') + // entries get fixed heights from the estimates: rendering matches the engine's reservation bookkeeping exactly, no more overflow + row.style.height = `${it.height}px` + const sup = document.createElement('sup') + sup.textContent = String(it.no) + row.append(sup) + if (it.richParas) { + it.richParas.forEach((para, pi) => { + if (pi > 0) row.append(document.createElement('br')) + for (const run of para) { + const span = document.createElement('span') + span.textContent = run.text + if (run.bold) span.style.fontWeight = '600' + if (run.italic) span.style.fontStyle = 'italic' + const deco = [run.underline && 'underline', run.strike && 'line-through'].filter(Boolean) + if (deco.length > 0) span.style.textDecoration = deco.join(' ') + if (run.color) span.style.color = `#${run.color}` + if (run.sizeHalfPoints) span.style.fontSize = `${run.sizeHalfPoints / 2}pt` + row.append(span) + } + }) + } else { + const span = document.createElement('span') + span.textContent = it.text + row.append(span) + } + row.addEventListener('dblclick', () => onEdit(it.id)) + wrap.appendChild(row) + } + return wrap +} + +/** fields of Word's Word Count dialog */ +interface DocStats { + pages: number + words: number + asianChars: number + nonAsianWords: number + charsNoSpace: number + charsWithSpace: number + paragraphs: number + lines: number +} + +const DEFAULT_SETTINGS: AiSettings = { + provider: 'anthropic', + providers: Object.fromEntries( + AI_PROVIDERS.map((p) => [ + p.id, + { apiKey: '', model: p.defaultModel, baseUrl: p.needsBaseUrl ? '' : undefined }, + ]), + ) as AiSettings['providers'], +} + +export function App() { + // subscribe to language switches for re-render; strings all go through module-level t, so memoized callbacks never capture stale closures + useI18n() + const [doc, setDoc] = useState(null) + /** true until the pending-open / new-blank boot checks settle; the start screen stays hidden meanwhile */ + const bootPendingRef = useRef | null>(null) + const bootHandledRef = useRef(false) + const [_recent, setRecent] = useState([]) + const [settings, setSettings] = useState(DEFAULT_SETTINGS) + const [showAi, setShowAi] = useState(() => localStorage.getItem('aidocs.showAi') !== '0') + /** Increments on every open/new document: AiPanel remounts by key to reset the conversation and history (save path changes don't bump it, so the session continues) */ + const [aiPanelKey, setAiPanelKey] = useState(0) + const [ribbonTabRequest, setRibbonTabRequest] = useState<{ tab: string; nonce: number } | null>( + null, + ) + const [status, setStatus] = useState('') + const [zoom, setZoom] = useState(100) + const [darkCanvas, setDarkCanvas] = useState(false) + const [section, setSection] = useState(null) + /** All sections (readSections): pagination/preview use per-section geometry; layout edits apply to the cursor's section */ + const [sections, setSections] = useState([]) + const [sectionDirty, setSectionDirty] = useState(false) + /** Index of the cursor's section (maintained by selectionUpdate) */ + const [activeSection, setActiveSection] = useState(0) + /** Indexes of edited non-final sections (their section-break paragraphs' sectPr is rewritten on save) */ + const [sectionsDirty, setSectionsDirty] = useState([]) + /** Start type pending write to the trailing sectPr after inserting a continuous section break */ + const [trailingStartType, setTrailingStartType] = useState(null) + const [pageColor, setPageColor] = useState(null) + const [pageColorDirty, setPageColorDirty] = useState(false) + const [header, setHeader] = useState(null) + const [headerDirty, setHeaderDirty] = useState(false) + const [footer, setFooter] = useState(null) + const [footerDirty, setFooterDirty] = useState(false) + const [hfVariants, setHfVariants] = useState(EMPTY_HF_VARIANTS) + const [hfVariantsDirty, setHfVariantsDirty] = useState([]) + const [titlePg, setTitlePg] = useState(false) + const [titlePgDirty, setTitlePgDirty] = useState(false) + const [evenOddHf, setEvenOddHf] = useState(false) + const [evenOddHfDirty, setEvenOddHfDirty] = useState(false) + const [hfView, setHfView] = useState('default') + /** Page-number-format dialog + pending final-section pgNumType write (non-final sections rewrite sectPr via pgNumDirtySections) */ + const [pgNumModal, setPgNumModal] = useState<{ fmt: string; start: string } | null>(null) + const [pgNumEdit, setPgNumEdit] = useState<{ fmt?: string; start?: number } | null>(null) + const [pgNumDirtySections, setPgNumDirtySections] = useState([]) + /** Pending numbering definitions to append (saved via SaveOptions.numbering; restart numbering / new list definitions) */ + const [pendingNumbering, setPendingNumbering] = useState({ + newDefs: [], + restartNums: [], + }) + const numberingDirty = + pendingNumbering.newDefs.length > 0 || pendingNumbering.restartNums.length > 0 + /** Header/footer edits for non-final sections (key = `${lastBlockIndex}:${kind}`), saved via SaveOptions.sectionHf */ + const [sectionHfEdits, setSectionHfEdits] = useState>({}) + /** The canvas header/footer area always views/edits the first section (multi-section docs: later sections inherit its refs) */ + const hfSectionClamped = 0 + const multiHf = sections.length > 1 + const effRefsAll = useMemo(() => effectiveHfRefs(sections), [sections]) + const effHfView: HfView = + (hfView === 'first' && !titlePg) || (hfView === 'even' && !evenOddHf) ? 'default' : hfView + /** Multi-section: the selected section's effective header/footer (local edits > referenced part > final section falls back to global edit state) */ + const sectionHfValue = (kind: 'header' | 'footer'): HeaderFooter | null => { + const idx = hfSectionClamped + const sec = sections[idx] + const globalState = kind === 'header' ? header : footer + if (!sec) return globalState + const refVariants = effRefsAll[idx]?.[kind] + const fromPart = () => { + const rId = refVariants?.default + return rId ? hfFromPart(doc?.parsed.hfParts?.[rId]) : null + } + if (idx === sections.length - 1) { + // final section: reuse the global edit state (save writes the final section's sectPr reference) + const dirty = kind === 'header' ? headerDirty : footerDirty + return dirty ? globalState : (fromPart() ?? globalState) + } + return sectionHfEdits[`${sec.lastBlockIndex}:${kind}`] ?? fromPart() + } + const shownHeader = + effHfView === 'first' + ? hfVariants.headerFirst + : effHfView === 'even' + ? hfVariants.headerEven + : multiHf + ? sectionHfValue('header') + : header + const shownFooter = + effHfView === 'first' + ? hfVariants.footerFirst + : effHfView === 'even' + ? hfVariants.footerEven + : multiHf + ? sectionHfValue('footer') + : footer + /** images of the part in the current view (logos etc., display-only; the save path keeps their bytes untouched) */ + const hfImagesOf = (kind: 'header' | 'footer') => { + const parsed = doc?.parsed + if (!parsed) return undefined + if (effHfView === 'first') { + return (kind === 'header' ? parsed.headerFirst : parsed.footerFirst)?.images + } + if (effHfView === 'even') { + return (kind === 'header' ? parsed.headerEven : parsed.footerEven)?.images + } + if (multiHf) { + const rId = effRefsAll[hfSectionClamped]?.[kind]?.default + const fromPart = rId ? parsed.hfParts?.[rId]?.images : undefined + if (fromPart?.length) return fromPart + } + return (kind === 'header' ? parsed.headerImages : parsed.footerImages) ?? undefined + } + + const commitHf = (kind: 'header' | 'footer', next: HeaderFooter) => { + // multi-section and not the final one: use the per-section edit channel (that section becomes its own part; earlier sections are unaffected) + if (effHfView === 'default' && multiHf && hfSectionClamped < sections.length - 1) { + const sec = sections[hfSectionClamped] + setSectionHfEdits((m) => ({ ...m, [`${sec.lastBlockIndex}:${kind}`]: next })) + return + } + if (effHfView === 'default') { + if (kind === 'header') { + setHeader(next) + setHeaderDirty(true) + } else { + setFooter(next) + setFooterDirty(true) + } + return + } + const key: HfVariantKey = + effHfView === 'first' + ? kind === 'header' + ? 'headerFirst' + : 'footerFirst' + : kind === 'header' + ? 'headerEven' + : 'footerEven' + setHfVariants((v) => ({ ...v, [key]: next })) + setHfVariantsDirty((d) => (d.includes(key) ? d : [...d, key])) + } + /** "Different first page" toggle, shared by the ribbon checkbox and the on-page chip */ + const toggleTitlePg = (on: boolean) => { + setTitlePg(on) + setTitlePgDirty(true) + setHfView(on ? 'first' : 'default') + setStatus(on ? t('appTitlePgOn') : t('appTitlePgOff')) + } + /** Unsaved section header/footer overrides for the pagination preview (default variant): local edits > document parts */ + const sectionHfOverride = useCallback( + (si: number, kind: 'header' | 'footer'): HeaderFooter | null => { + const sec = sections[si] + if (!sec) return null + if (si === sections.length - 1) { + const dirty = kind === 'header' ? headerDirty : footerDirty + return dirty ? (kind === 'header' ? header : footer) : null + } + return sectionHfEdits[`${sec.lastBlockIndex}:${kind}`] ?? null + }, + [sections, sectionHfEdits, header, footer, headerDirty, footerDirty], + ) + const [showMarks, setShowMarks] = useState(false) + const [showRuler, setShowRuler] = useState(false) + const [showNav, setShowNav] = useState(false) + const [viewMode, setViewMode] = useState('print') + const [readMode, setReadMode] = useState(false) + const [showGrid, setShowGrid] = useState(false) + const [splitView, setSplitView] = useState(false) + const [showPagePreview, setShowPagePreview] = useState(false) + const [splitHtml, setSplitHtml] = useState('') + const [showFind, setShowFind] = useState(false) + const [showComments, setShowComments] = useState(false) + const [showStylesPanel, setShowStylesPanel] = useState(false) + /** Style definitions pending write-back (key = styleId), saved via SaveOptions.styleUpserts */ + const [styleUpserts, setStyleUpserts] = useState>({}) + const [comments, setComments] = useState([]) + const [commentsDirty, setCommentsDirty] = useState(false) + const [watermark, setWatermark] = useState(null) + const [watermarkDirty, setWatermarkDirty] = useState(false) + const [inkAnnotations, setInkAnnotations] = useState([]) + const [inksDirty, setInksDirty] = useState(false) + const [inkTool, setInkTool] = useState('select') + const [inkPen, setInkPen] = useState({ color: 'C00000', width: 2 }) + const [inkHighlighter, setInkHighlighter] = useState({ + color: 'FFFF00', + width: 10, + }) + const [footnotes, setFootnotes] = useState([]) + /** Footnote ids already shown in canvas page gaps (the end-of-document list skips them to avoid duplication) */ + const [gapNoteIds, setGapNoteIds] = useState>(new Set()) + const [endnotes, setEndnotes] = useState([]) + const [notesDirty, setNotesDirty] = useState(false) + const [sources, setSources] = useState([]) + const [sourcesDirty, setSourcesDirty] = useState(false) + const [themeFonts, setThemeFonts] = useState(null) + const [themeFontsDirty, setThemeFontsDirty] = useState(false) + const [themeColors, setThemeColors] = useState(null) + const [themeColorsDirty, setThemeColorsDirty] = useState(false) + const [commentComposing, setCommentComposing] = useState(false) + const [trackChanges, setTrackChanges] = useState(false) + const [revisionDisplay, setRevisionDisplay] = useState('all') + // the original view restores old formatting via decorations: sync the mode and trigger one repaint + useEffect(() => { + revisionDisplayState.mode = revisionDisplay + if (editor) editor.view.dispatch(editor.state.tr.setMeta('addToHistory', false)) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [revisionDisplay]) + const [protection, setProtection] = useState(null) + const [protectionDirty, setProtectionDirty] = useState(false) + const [compareResult, setCompareResult] = useState<{ + otherName: string + entries: CompareEntry[] + } | null>(null) + const [autoSave, setAutoSave] = useState(() => localStorage.getItem('aidocs.autoSave') === '1') + const [aiPreset, setAiPreset] = useState<{ + text: string + nonce: number + autoRun?: boolean + } | null>(null) + const [docCss, setDocCss] = useState('') + // Live CJK-ness of the body while editing; overrides docCss's --doc-line-factor + const [liveDocCjk, setLiveDocCjk] = useState(null) + const [stats, setStats] = useState(null) + const [showLinkModal, setShowLinkModal] = useState(false) + const [showEquationModal, setShowEquationModal] = useState(false) + const [eqEditTarget, setEqEditTarget] = useState<{ + pos: number + latex: string + kind: 'inline' | 'block' + } | null>(null) + const [ctxMenu, setCtxMenu] = useState(null) + const [showFontDialog, setShowFontDialog] = useState(false) + const [showParaDialog, setShowParaDialog] = useState(false) + const [pageInfo, setPageInfo] = useState({ current: 1, total: 1 }) + const [, forceRender] = useReducer((x: number) => x + 1, 0) + const dirtyRef = useRef(false) + // serializes save(): overlapping saves (Cmd+S vs autosave timer vs blur) would + // otherwise race on the write + reparse + setContent sequence + const saveInFlightRef = useRef(false) + // set when a save wrote successfully but the editor changed while it was in + // flight, so the file on disk is already one step behind. save() still counts + // as succeeded; callers that must not lose data (the close guard) save again. + const saveIncompleteRef = useRef(false) + + const editorRef = useRef(null) + const editor = useEditor({ + extensions: editorExtensions, + content: { type: 'doc', content: [{ type: 'docParagraph' }] }, + editorProps: { + // Word checks spelling as you type by default + attributes: { class: 'doc-page', spellcheck: 'true' }, + // Word/web HTML cleanup: strip mso comments and , unwrap
  • x

  • + // (docListItem is an inline container; block-level p would shatter the list) + transformPastedHTML: cleanPastedHtml, + // clipboard images (screenshots/copied images): become inline images; mixed content + // with HTML still uses default parsing (text in the HTML takes priority) + handlePaste: (view, event) => { + const data = event.clipboardData + if (!data) return false + const html = data.getData('text/html') + // pasting block HTML onto an empty paragraph: replace wholesale (ProseMirror's default + // first-block merge would demote headings to body text; Word keeps the source block format on empty paragraphs) + const { $from, empty: selEmpty } = view.state.selection + if ( + html && + selEmpty && + $from.parent.isTextblock && + $from.parent.content.size === 0 && + $from.depth === 1 + ) { + try { + const dom = new window.DOMParser().parseFromString(cleanPastedHtml(html), 'text/html') + const parsed = PmDOMParser.fromSchema(view.state.schema).parse(dom.body) + if (parsed.content.childCount > 0) { + view.dispatch( + view.state.tr.replaceWith($from.before(1), $from.after(1), parsed.content), + ) + return true + } + } catch { + /* fall back to default paste on parse failure */ + } + } + const imageFile = [...data.items] + .find((item) => item.type.startsWith('image/')) + ?.getAsFile() + const text = data.getData('text/plain') + if (imageFile && !text.trim()) { + const reader = new FileReader() + reader.onload = () => { + const ed = editorRef.current + if (ed && typeof reader.result === 'string') { + void insertImageFromDataUrl(ed, reader.result, 'Image (pasted)') + } + } + reader.readAsDataURL(imageFile) + return true + } + return false + }, + }, + onSelectionUpdate: () => forceRender(), + // typing in the main document takes ribbon routing back from any textbox + onFocus: () => setActiveSubEditor(null), + onUpdate: () => { + dirtyRef.current = true + forceRender() + }, + }) + + // textbox sub-editors: re-render the ribbon on focus/selection changes and + // mark the document dirty when their content changes + useEffect( + () => + subscribeSubEditorState((docChanged) => { + if (docChanged) dirtyRef.current = true + forceRender() + }), + [], + ) + + useEffect(() => { + void window.desktop.getRecentFiles().then(setRecent) + void window.desktop.getAiSettings().then(setSettings) + }, []) + + useEffect(() => { + localStorage.setItem('aidocs.showAi', showAi ? '1' : '0') + }, [showAi]) + + useEffect(() => { + localStorage.setItem('aidocs.autoSave', autoSave ? '1' : '0') + }, [autoSave]) + + // Pinch-to-zoom: Chromium delivers trackpad pinch as a wheel event + // with ctrlKey set. Also support ⌘+scroll. Must be non-passive to preventDefault. + useEffect(() => { + const onWheel = (e: WheelEvent) => { + if (!e.ctrlKey && !e.metaKey) return + if (!(e.target as HTMLElement | null)?.closest?.('.editor-scroll')) return + e.preventDefault() + setZoom((z) => Math.min(200, Math.max(50, z - e.deltaY * 0.6))) + } + window.addEventListener('wheel', onWheel, { passive: false }) + return () => window.removeEventListener('wheel', onWheel) + }, []) + + const isProtected = !!protection?.enforced && protection.edit === 'readOnly' + + // Read Mode / Restrict Editing: the document becomes read-only; Esc leaves Read Mode + useEffect(() => { + if (!editor) return + editor.setEditable(!readMode && !isProtected) + if (!readMode) return + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape') setReadMode(false) + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [editor, readMode, isProtected]) + + // Track Changes: the recorder plugin reads its toggle from extension storage + useEffect(() => { + if (!editor) return + const storage = editor.storage.trackChanges as TrackChangesStorage + storage.enabled = trackChanges + }, [editor, trackChanges]) + + // window title follows the document, so the OS window list and Switch Window show file names + useEffect(() => { + document.title = doc ? doc.fileName : 'GenOffice Docs' + }, [doc]) + + // Crash-recovery copy: while the document is dirty, push a serialized + // copy to the main process every 30s; a normal save (or discarding on close) removes + // it, and reopening the file offers Restore/Discard when a newer copy exists. + useEffect(() => { + const timer = window.setInterval(() => { + void writeRecoveryCopyImpl(fileCtxRef.current) + }, 30_000) + return () => window.clearInterval(timer) + }, []) + + // Recompute the document-level line-height factor while editing: + // docStyleCss decides it once at parse time, so typing CJK into a blank document + // kept the Western factor until save/reopen (whole page ~8% shorter than the file). + useEffect(() => { + setLiveDocCjk(null) + }, [doc]) + useEffect(() => { + if (!editor) return + const recompute = () => { + let has = false + editor.state.doc.descendants((node) => { + if (has) return false + if (node.isText && node.text && textHasCjk(node.text)) has = true + return !has + }) + setLiveDocCjk(has) + } + let timer = 0 + const onUpdate = () => { + window.clearTimeout(timer) + timer = window.setTimeout(recompute, 300) + } + editor.on('update', onUpdate) + return () => { + window.clearTimeout(timer) + editor.off('update', onUpdate) + } + }, [editor]) + + // Split pane: keep the read-only bottom copy in sync with the editor (debounced) + useEffect(() => { + if (!splitView || !editor) return + const sync = () => setSplitHtml(editor.getHTML()) + sync() + let timer = 0 + const onUpdate = () => { + window.clearTimeout(timer) + timer = window.setTimeout(sync, 300) + } + editor.on('update', onUpdate) + return () => { + window.clearTimeout(timer) + editor.off('update', onUpdate) + } + }, [splitView, editor]) + + // Mixed-paper menu export: after the preview mounts and renders, the merge export resumes automatically + const pendingMixedExportRef = useRef(false) + + /** App state bundle for the extracted file actions (file-actions.ts); refreshed every render. */ + const fileCtxRef = useRef(null as unknown as FileActionContext) + fileCtxRef.current = { + editor, + doc, + dirtyRef, + saveInFlightRef, + saveIncompleteRef, + pendingMixedExportRef, + setStatus, + setRecent, + setShowAi, + setDoc, + setAiPanelKey, + setDocCss, + setShowPagePreview, + section, + sectionDirty, + sections, + sectionsDirty, + trailingStartType, + setSection, + setSections, + setSectionDirty, + setSectionsDirty, + setTrailingStartType, + pageColor, + pageColorDirty, + setPageColor, + setPageColorDirty, + header, + headerDirty, + footer, + footerDirty, + setHeader, + setHeaderDirty, + setFooter, + setFooterDirty, + hfVariants, + hfVariantsDirty, + setHfVariants, + setHfVariantsDirty, + sectionHfEdits, + setSectionHfEdits, + titlePg, + titlePgDirty, + evenOddHf, + evenOddHfDirty, + setTitlePg, + setTitlePgDirty, + setEvenOddHf, + setEvenOddHfDirty, + setHfView, + pgNumEdit, + pgNumDirtySections, + setPgNumEdit, + setPgNumDirtySections, + pendingNumbering, + numberingDirty, + setPendingNumbering, + styleUpserts, + setStyleUpserts, + comments, + commentsDirty, + setComments, + setCommentsDirty, + setShowComments, + setCommentComposing, + watermark, + watermarkDirty, + setWatermark, + setWatermarkDirty, + inkAnnotations, + inksDirty, + setInkAnnotations, + setInksDirty, + setInkTool, + footnotes, + endnotes, + notesDirty, + setFootnotes, + setEndnotes, + setNotesDirty, + sources, + sourcesDirty, + setSources, + setSourcesDirty, + themeFonts, + themeFontsDirty, + themeColors, + themeColorsDirty, + setThemeFonts, + setThemeFontsDirty, + setThemeColors, + setThemeColorsDirty, + setTrackChanges, + protection, + protectionDirty, + setProtection, + setProtectionDirty, + setCompareResult, + } + + const loadFile = useCallback( + (result: OpenFileResult | null) => loadFileImpl(fileCtxRef.current, result), + [], + ) + + // file renamed externally (renamed in the shell Home list) → sync the save path and title-bar file name (content unchanged) + useEffect( + () => + window.desktop.onRenamedDocx(({ oldPath, newPath }) => { + setDoc((prev) => + prev && prev.filePath === oldPath + ? { + ...prev, + filePath: newPath, + fileName: newPath.split(/[\\/]/).pop() ?? prev.fileName, + } + : prev, + ) + }), + [], + ) + + useEffect(() => { + if (!editor) return + const unsubscribe = window.desktop.onOpenDocx((result) => { + void loadFile(result) + }) + // With no pending file the window lands directly in the editor on a blank document + // (the AI panel carries the generate-from-prompt flow). StrictMode runs the mount + // effect twice but the pending queues can only be consumed once, so the consume + // Promise lives in a ref and its result is processed only once. + bootPendingRef.current ??= Promise.all([ + window.desktop.consumePendingOpenDocx(), + // Still consume the one-shot new-blank flag so it doesn't leak into the next open + window.desktop.consumeNewBlankDoc(), + ]) + void bootPendingRef.current + .then(async ([pending]) => { + if (bootHandledRef.current) return + bootHandledRef.current = true + if (pending) await loadFile(pending) + else await newFile() + }) + // Open failures also land on a blank document, or the tab stays at "Opening…" forever + .catch(() => { + if (bootHandledRef.current) return + bootHandledRef.current = true + void newFile().catch(() => {}) + }) + return unsubscribe + // newFile depends on editor (already in deps); we capture it by closure + // rather than listing it to avoid a forward-reference TypeScript error + // (newFile is declared after this effect in source order). + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [editor, loadFile]) + + const openFile = useCallback(async () => { + await loadFile(await window.desktop.openDocx()) + }, [loadFile]) + + /** new document from the built-in blank template (AI can then generate into it) */ + const newFile = useCallback(() => newFileImpl(fileCtxRef.current), []) + + const openRecent = useCallback( + async (path: string) => { + await loadFile(await window.desktop.openDocxPath(path)) + }, + [loadFile], + ) + + const save = useCallback( + (saveAs: boolean, auto = false) => saveImpl(fileCtxRef.current, saveAs, auto), + [], + ) + + // inserting a section break needs one save for the new section to take effect; the + // flag is consumed in the render after state commit, guaranteeing the save closure + // sees the latest sectionsDirty/trailingStartType + const pendingSectionSaveRef = useRef(false) + useEffect(() => { + if (pendingSectionSaveRef.current && doc?.filePath) { + pendingSectionSaveRef.current = false + void save(false, true) + } + }) + + /** + * Insert a section break: the new break paragraph takes a copy of the current + * section's sectPr (content before the break keeps the original + * section's settings); "continuous" is written to the following section's (the + * original current section sectPr's) w:type. + */ + const insertSectionBreak = useCallback( + (type: SectionInfo['startType']) => { + if (!editor || !doc) return + const cur = sections[activeSection] + const sectPrCopy = + cur?.sectPrXml || + applySectionSettings( + '', + section ?? sections[0]?.settings ?? DEFAULT_SECTION, + ) + const genXml = `${sectPrCopy}` + const { $head } = editor.state.selection + const pos = $head.depth > 0 ? $head.after(1) : $head.pos + editor + .chain() + .focus() + .insertContentAt(pos, { + type: 'docProtected', + attrs: { + blockType: 'passthrough', + label: 'Section break paragraph', + previewText: '', + genXml, + }, + }) + .run() + // the section after the break is terminated by the "original current section sectPr", + // whose w:type decides how the new section starts: always write the chosen type back + // (including a nextPage reset, so a leftover continuous from the original section doesn't linger) + if (sections.length === 0 || activeSection === sections.length - 1) { + setTrailingStartType(type) + } else { + setSections((prev) => + prev.map((s, i) => (i === activeSection ? { ...s, startType: type } : s)), + ) + setSectionsDirty((d) => (d.includes(activeSection) ? d : [...d, activeSection])) + } + const labels: Record = { + nextPage: t('appBreakNextPage'), + continuous: t('appBreakContinuous'), + evenPage: t('appBreakEvenPage'), + oddPage: t('appBreakOddPage'), + } + if (doc.filePath) { + pendingSectionSaveRef.current = true + setStatus(t('appSectionBreakInserted', { type: labels[type] })) + } else { + setStatus(t('appSectionBreakPending')) + } + }, + [editor, doc, sections, activeSection, section], + ) + + // ---- List numbering: restart numbering / new lists reuse document definitions (numbering.xml write-back) ---- + + /** Floor of numIds allocated within the same render cycle (prevents double allocation before setState commits) */ + const numIdFloorRef = useRef(0) + + /** Allocate an unused numId (above parsed definitions + pending appends + this cycle's allocations) */ + /** App state bundle for the extracted numbering actions (numbering-actions.ts); refreshed every render. */ + const numberingCtxRef = useRef(null as unknown as NumberingContext) + numberingCtxRef.current = { + editor, + doc, + pendingNumbering, + setPendingNumbering, + numIdFloorRef, + setStatus, + } + + const createCustomListDef = useCallback( + (levels: CustomNumberingLevel[]) => createCustomListDefImpl(numberingCtxRef.current, levels), + [], + ) + const allocateListNumId = useCallback( + (kind: 'bullet' | 'ordered') => allocateListNumIdImpl(numberingCtxRef.current, kind), + [], + ) + const restartNumbering = useCallback(() => restartNumberingImpl(numberingCtxRef.current), []) + const continueNumbering = useCallback(() => continueNumberingImpl(numberingCtxRef.current), []) + + // ---- Inline fields: insertion and F9 update (cached results recomputed locally) ---- + + const fieldValue = useCallback( + (instr: string): string => { + const kw = instr.trim().split(/\s+/)[0]?.toUpperCase() + const now = new Date() + switch (kw) { + case 'DATE': + case 'CREATEDATE': + case 'SAVEDATE': + return now.toLocaleDateString('zh-CN') + case 'TIME': + return now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }) + case 'NUMPAGES': + return String(pageInfo.total) + case 'PAGE': + return String(pageInfo.current) + case 'FILENAME': + return doc?.fileName ?? '' + default: + return '' + } + }, + [pageInfo, doc], + ) + + const insertField = useCallback( + (instr: string) => { + if (!editor) return + const value = fieldValue(instr) || ' ' + editor + .chain() + .focus() + .insertContent({ + type: 'text', + text: value, + marks: [{ type: 'instrField', attrs: { instr } }], + }) + .unsetMark('instrField') + .run() + setStatus(t('appFieldInserted', { instr })) + }, + [editor, fieldValue], + ) + + /** F9: recompute all inline field caches (PAGE/NUMPAGES/date-time/file name); REF/TOC are recomputed when Word opens the file */ + const updateFields = useCallback(() => { + if (!editor) return + const { state, view } = editor + const jobs: Array<{ from: number; to: number; text: string; marks: readonly PmMark[] }> = [] + state.doc.descendants((node, pos) => { + if (!node.isText) return + const mark = node.marks.find((m) => m.type.name === 'instrField') + if (!mark) return + const next = fieldValue(String(mark.attrs.instr)) + if (next && next !== node.text) { + jobs.push({ from: pos, to: pos + node.nodeSize, text: next, marks: node.marks }) + } + }) + if (jobs.length === 0) { + setStatus(t('appNoFieldsToUpdate')) + return + } + let tr = state.tr + for (const j of jobs.sort((a, b) => b.from - a.from)) { + tr = tr.replaceWith(j.from, j.to, state.schema.text(j.text, [...j.marks])) + } + view.dispatch(tr) + setStatus(t('appFieldsUpdated', { n: jobs.length })) + }, [editor, fieldValue]) + + // ---- Styles pane: apply/update/create styles (styles.xml write-back) ---- + + /** Capture formatting from the current selection → StyleUpsert's rPr/pPr */ + const captureSelectionFormat = useCallback((): Pick => { + if (!editor) return {} + const text = editor.getAttributes('docTextStyle') + const para = editor.isActive('docHeading') + ? editor.getAttributes('docHeading') + : editor.isActive('docListItem') + ? editor.getAttributes('docListItem') + : editor.getAttributes('docParagraph') + const rPr: NonNullable = {} + if (editor.isActive('bold') || text.bold) rPr.bold = true + if (editor.isActive('italic') || text.italic) rPr.italic = true + if (editor.isActive('underline')) rPr.underline = true + if (editor.isActive('strike')) rPr.strike = true + if (text.color) rPr.color = String(text.color).replace('#', '') + if (text.sizeHalfPoints) rPr.sizeHalfPoints = Number(text.sizeHalfPoints) + if (text.font) rPr.font = String(text.font) + const pPr: NonNullable = {} + if (para.align) pPr.align = para.align as NonNullable['align'] + if (para.lineSpacing) pPr.lineSpacing = Number(para.lineSpacing) + return { + ...(Object.keys(rPr).length > 0 ? { rPr } : {}), + ...(Object.keys(pPr).length > 0 ? { pPr } : {}), + } + }, [editor]) + + /** Upsert into the pending-save set + local style table / canvas CSS take effect immediately */ + const registerStyleUpsert = useCallback( + (up: StyleUpsert) => { + setStyleUpserts((m) => ({ ...m, [up.styleId]: up })) + if (doc) { + doc.parsed.styles.set(up.styleId, { + styleId: up.styleId, + name: up.name, + type: up.type, + display: { + ...(up.rPr?.bold ? { bold: true } : {}), + ...(up.rPr?.italic ? { italic: true } : {}), + ...(up.rPr?.underline ? { underline: true } : {}), + ...(up.rPr?.strike ? { strike: true } : {}), + ...(up.rPr?.color ? { color: up.rPr.color } : {}), + ...(up.rPr?.sizeHalfPoints ? { sizeHalfPoints: up.rPr.sizeHalfPoints } : {}), + ...(up.rPr?.font ? { font: up.rPr.font } : {}), + ...(up.pPr?.lineSpacing ? { lineSpacing: up.pPr.lineSpacing } : {}), + }, + }) + setDocCss(docStyleCss(doc.parsed)) + } + }, + [doc], + ) + + const applyStyleFromPanel = useCallback( + (styleId: string, type: 'paragraph' | 'character') => { + if (!editor) return + if (type === 'character') { + editor.chain().focus().setMark('docTextStyle', { styleId }).run() + return + } + const heading = doc?.parsed.styles.get(styleId)?.headingLevel + if (heading) { + editor.chain().focus().setNode('docHeading', { level: heading }).run() + } else if (styleId === 'Normal') { + editor.chain().focus().setNode('docParagraph', { styleId: null }).run() + } else { + editor + .chain() + .focus() + .setNode('docParagraph', {}) + .updateAttributes('docParagraph', { styleId }) + .run() + } + }, + [editor, doc], + ) + + const updateStyleFromSelection = useCallback( + (styleId: string, type: 'paragraph' | 'character', name: string) => { + const existing = doc?.parsed.styles.get(styleId) + registerStyleUpsert({ + styleId, + type, + name, + ...(type === 'paragraph' && styleId !== 'Normal' ? { basedOn: 'Normal' } : {}), + ...(existing?.headingLevel ? {} : {}), + ...captureSelectionFormat(), + }) + setStatus(t('appStyleUpdated', { name })) + }, + [doc, registerStyleUpsert, captureSelectionFormat], + ) + + const createStyleFromSelection = useCallback( + (name: string, type: 'paragraph' | 'character') => { + if (!doc) return + let base = name.replace(/[^A-Za-z0-9]/g, '') + if (!base) base = type === 'paragraph' ? 'CustomPara' : 'CustomChar' + let styleId = base + let n = 1 + while (doc.parsed.styles.has(styleId) || styleUpserts[styleId]) styleId = `${base}${++n}` + registerStyleUpsert({ + styleId, + type, + name, + ...(type === 'paragraph' ? { basedOn: 'Normal' } : {}), + ...captureSelectionFormat(), + }) + applyStyleFromPanel(styleId, type) + setStatus(t('appStyleCreated', { name })) + }, + [doc, styleUpserts, registerStyleUpsert, captureSelectionFormat, applyStyleFromPanel], + ) + + // editorRef: lets the handlePaste closure (the useEditor config exists before the instance) reach the instance + useEffect(() => { + editorRef.current = editor + }, [editor]) + + /** Pasted list items lacking a numId (schema default null; saving would lose list semantics): + * reuse the numId of an existing same-kind instance, otherwise fall back to creating a definition */ + useEffect(() => { + if (!editor) return + const fill = () => { + const missing: Array<{ pos: number; attrs: Record }> = [] + const reuse: Partial> = {} + editor.state.doc.descendants((node, pos) => { + if (node.type.name !== 'docListItem') return + const kind = (node.attrs.kind as 'bullet' | 'ordered') ?? 'bullet' + if (node.attrs.numId !== null) { + if (!reuse[kind]) reuse[kind] = String(node.attrs.numId) + return + } + missing.push({ pos, attrs: node.attrs }) + }) + if (missing.length === 0) return + const idOf: Partial> = {} + let tr = editor.state.tr + for (const item of missing) { + const kind = (item.attrs.kind as 'bullet' | 'ordered') ?? 'bullet' + if (!(kind in idOf)) idOf[kind] = reuse[kind] ?? allocateListNumId(kind) + const numId = idOf[kind] + if (numId) tr = tr.setNodeMarkup(item.pos, undefined, { ...item.attrs, numId }) + } + if (tr.docChanged) editor.view.dispatch(tr) + } + editor.on('update', fill) + return () => { + editor.off('update', fill) + } + }, [editor, allocateListNumId]) + + /** Open the page-number-format dialog (initial value = the cursor section's pgNumType) */ + const openPgNumModal = useCallback(() => { + const sec = sections[Math.min(activeSection, sections.length - 1)] + setPgNumModal({ + fmt: sec?.pageNumberFmt ?? 'decimal', + start: sec?.pageNumberStart !== undefined ? String(sec.pageNumberStart) : '', + }) + }, [sections, activeSection]) + + /** Apply the page-number format to the cursor's section: final section via SaveOptions.pgNumType, others rewrite their sectPr */ + const applyPgNumFormat = useCallback(() => { + if (!pgNumModal) return + const fmt = pgNumModal.fmt === 'decimal' ? undefined : pgNumModal.fmt + const start = + pgNumModal.start.trim() === '' ? undefined : Math.max(0, parseInt(pgNumModal.start, 10) || 0) + const idx = sections.length > 0 ? Math.min(activeSection, sections.length - 1) : -1 + if (idx >= 0) { + setSections((prev) => + prev.map((s, i) => (i === idx ? { ...s, pageNumberFmt: fmt, pageNumberStart: start } : s)), + ) + } + if (idx < 0 || idx === sections.length - 1) { + setPgNumEdit({ + ...(fmt !== undefined ? { fmt } : {}), + ...(start !== undefined ? { start } : {}), + }) + } else { + setPgNumDirtySections((d) => (d.includes(idx) ? d : [...d, idx])) + } + setPgNumModal(null) + setStatus(t('appPgNumFormatSet')) + }, [pgNumModal, sections, activeSection]) + + const exportPdf = useCallback( + (outPath?: string) => exportPdfImpl(fileCtxRef.current, outPath), + [], + ) + + // for real-device verification: trigger export directly via CDP (same as __pageDebug) + useEffect(() => { + ;(window as unknown as Record).__exportPdf = exportPdf + }, [exportPdf]) + + useEffect(() => { + if (!showPagePreview || pendingMixedExportRef.current === false) return + const pending = pendingMixedExportRef.current + pendingMixedExportRef.current = false + const timer = window.setTimeout(() => { + void exportPdf(typeof pending === 'string' ? pending : undefined) + }, 1200) + return () => window.clearTimeout(timer) + }, [showPagePreview, exportPdf]) + + // ---- References: footnotes / endnotes ---- + + const [notePrompt, setNotePrompt] = useState(null) + const [protectModal, setProtectModal] = useState(null) + + /** App state bundle for the extracted review actions (review-actions.ts); refreshed every render. */ + const reviewCtxRef = useRef(null as unknown as ReviewContext) + reviewCtxRef.current = { + editor, + doc, + dirtyRef, + setStatus, + notePrompt, + setNotePrompt, + footnotes, + endnotes, + setFootnotes, + setEndnotes, + setNotesDirty, + comments, + setComments, + setCommentsDirty, + setCommentComposing, + setShowComments, + setInkAnnotations, + setInksDirty, + protection, + setProtection, + setProtectionDirty, + protectModal, + setProtectModal, + setCompareResult, + } + + const insertNote = useCallback((kind: 'footnote' | 'endnote') => { + setNotePrompt({ kind }) + }, []) + + const editNote = useCallback((kind: 'footnote' | 'endnote', id: string) => { + setNotePrompt({ kind, id }) + }, []) + + const submitNote = useCallback((text: string) => submitNoteImpl(reviewCtxRef.current, text), []) + + const deleteNote = useCallback( + (kind: 'footnote' | 'endnote', id: string) => deleteNoteImpl(reviewCtxRef.current, kind, id), + [], + ) + + // Word: body shading of resolved threads is hidden + useEffect(() => { + if (!editor) return + const done = new Set(comments.filter((c) => c.done).map((c) => c.id)) + editor.view.dispatch(editor.state.tr.setMeta(resolvedCommentsPluginKey, done)) + }, [editor, comments]) + + const cancelNewComment = useCallback(() => cancelNewCommentImpl(reviewCtxRef.current), []) + const startNewComment = useCallback(() => startNewCommentImpl(reviewCtxRef.current), []) + const submitNewComment = useCallback( + (text: string) => submitNewCommentImpl(reviewCtxRef.current, text), + [], + ) + const replyToComment = useCallback( + (parentId: string, text: string) => replyToCommentImpl(reviewCtxRef.current, parentId, text), + [], + ) + const resolveComment = useCallback( + (id: string, done: boolean) => resolveCommentImpl(reviewCtxRef.current, id, done), + [], + ) + const deleteComment = useCallback((id: string) => deleteCommentImpl(reviewCtxRef.current, id), []) + const handleRevision = useCallback( + (action: 'accept' | 'reject', all: boolean) => + handleRevisionImpl(reviewCtxRef.current, action, all), + [], + ) + const addInk = useCallback( + (annotation: InkAnnotation) => addInkImpl(reviewCtxRef.current, annotation), + [], + ) + const removeInks = useCallback((ids: string[]) => removeInksImpl(reviewCtxRef.current, ids), []) + const clearInks = useCallback(() => clearInksImpl(reviewCtxRef.current), []) + const toggleProtection = useCallback(() => toggleProtectionImpl(reviewCtxRef.current), []) + const submitProtectModal = useCallback(() => submitProtectModalImpl(reviewCtxRef.current), []) + const compareWithFile = useCallback(() => compareWithFileImpl(reviewCtxRef.current), []) + + const revisionCount = editor && doc ? collectRevisions(editor.state.doc).length : 0 + + /** Word's page-width / whole-page zoom: compute the actual zoom ratio from the current window size */ + const zoomFit = useCallback( + (mode: 'width' | 'page') => { + if (!section) return + const scroller = document.querySelector('.editor-scroll') + if (!scroller) return + const pad = 48 + const next = + mode === 'width' + ? ((scroller.clientWidth - pad) / twipsToPx(section.pageWidth)) * 100 + : ((scroller.clientHeight - pad) / twipsToPx(section.pageHeight)) * 100 + setZoom(Math.min(200, Math.max(50, Math.round(next)))) + }, + [section], + ) + + // page-bottom height (px) reserved for footnote references inside a block: same estimation model as the parity runner + const footnoteExtraOf = useCallback( + (b: Block): number => { + if (!b.runs || footnotes.length === 0) return 0 + let extra = 0 + for (const run of b.runs) { + if (run.noteRef?.kind !== 'footnote') continue + const sec = + sections.find((s) => (b.docxIndex ?? 0) <= s.lastBlockIndex)?.settings ?? section + if (!sec) continue + const contentW = twipsToPx(sec.pageWidth - sec.marginLeft - sec.marginRight) + const fnText = footnotes.find((f) => f.id === run.noteRef!.id)?.text ?? '' + extra += estimateFootnoteHeight(fnText, contentW, sec.docGrid) + } + return extra > 0 ? extra + FOOTNOTE_SEPARATOR_H : 0 + }, + [footnotes, sections, section], + ) + + // single-section header/footer push-down: body top = max(marginTop, headerDist + header height) + const singleHfPx = useMemo(() => { + if (!section) return { headerPx: 0, footerPx: 0 } + const contentW = twipsToPx(section.pageWidth - section.marginLeft - section.marginRight) + return { + headerPx: estimateHfHeight(header, contentW, doc?.parsed.headerImages), + footerPx: estimateHfHeight(footer, contentW, doc?.parsed.footerImages), + } + }, [section, header, footer, doc]) + const effTopSingle = section ? effectiveTopPx(section, singleHfPx.headerPx) : 0 + const effBottomSingle = section ? effectiveBottomPx(section, singleHfPx.footerPx) : 0 + + // multi-section: estimated heights of each section's default-variant header/footer (capacity per section, variant differences ignored) + const hfHeightsOf = useCallback( + (secs: SectionInfo[]): SectionHfHeights[] => { + const refs = effectiveHfRefs(secs) + return secs.map((s, i) => { + const set = s.settings + const contentW = twipsToPx(set.pageWidth - set.marginLeft - set.marginRight) + const pick = (kind: 'header' | 'footer'): HeaderFooter | null => { + if (i === secs.length - 1) return kind === 'header' ? header : footer + const edited = sectionHfEdits[`${s.lastBlockIndex}:${kind}`] + if (edited) return edited + const rId = refs[i]?.[kind]?.default + return rId ? hfFromPart(doc?.parsed.hfParts?.[rId]) : null + } + const imagesOf = (kind: 'header' | 'footer') => { + const rId = refs[i]?.[kind]?.default + const fromPart = rId ? doc?.parsed.hfParts?.[rId]?.images : undefined + if (fromPart?.length) return fromPart + if (i === secs.length - 1) { + return ( + (kind === 'header' ? doc?.parsed.headerImages : doc?.parsed.footerImages) ?? undefined + ) + } + return undefined + } + return { + headerPx: estimateHfHeight(pick('header'), contentW, imagesOf('header')), + footerPx: estimateHfHeight(pick('footer'), contentW, imagesOf('footer')), + } + }) + }, + [doc, header, footer, sectionHfEdits], + ) + + // pagination-constraint injection: docxIndex → parse-layer semantics (keepNext/keepLines/widow/table-row flags). + // DOM measurement only has geometry; these constraints decide page cut points (no orphan headings / unbreakable lines / repeated table headers). + const blockMetaOf = useCallback( + (docxIndex: number): BlockMeta | undefined => { + const b = doc?.parsed.blocks.find((bl) => bl.docxIndex === docxIndex) + if (!b) return undefined + if (b.type === 'table') { + if (!b.originalXml || !/tblHeader|cantSplit/.test(b.originalXml)) return undefined + return { tableRowFlags: tableRowFlags(b.originalXml) } + } + const styleDisplay = b.styleId ? doc?.parsed.styles.get(b.styleId)?.display : undefined + const keepNext = b.format?.keepNext ?? styleDisplay?.keepNext + const keepLines = b.format?.keepLines ?? styleDisplay?.keepLines + const widowOff = b.format?.widowControl === false + const fnExtra = footnoteExtraOf(b) + if (!keepNext && !keepLines && !widowOff && fnExtra === 0) return undefined + return { + ...(keepNext ? { keepNext: true } : {}), + ...(keepLines ? { keepLines: true } : {}), + ...(widowOff ? { widowControl: false as const } : {}), + ...(fnExtra > 0 ? { footnoteExtraPx: fnExtra } : {}), + } + }, + [doc, footnoteExtraOf], + ) + + // per-page footnote collection: the page of the referencing block → that page's footnote entries (number/text/estimated height) + const pageFootnotesOf = useCallback( + (blocks: BlockBox[], slices: PageSlice[]): PageNoteItem[][] => { + const out: PageNoteItem[][] = slices.map(() => []) + if (!doc || footnotes.length === 0 || !section) return out + const noOf = new Map(footnotes.map((f, i) => [f.id, i + 1])) + for (const b of blocks) { + if (b.docxIndex === undefined) continue + const pb = doc.parsed.blocks.find((bl) => bl.docxIndex === b.docxIndex) + if (!pb?.runs) continue + const ids = pb.runs.filter((r) => r.noteRef?.kind === 'footnote').map((r) => r.noteRef!.id) + if (ids.length === 0) continue + const page = pageAt(slices, b.top + 0.5) - 1 + const sec = sections.find((s) => b.docxIndex! <= s.lastBlockIndex)?.settings ?? section + const contentW = twipsToPx(sec.pageWidth - sec.marginLeft - sec.marginRight) + for (const id of ids) { + const fn = footnotes.find((f) => f.id === id) + if (!fn) continue + out[page]?.push({ + no: noOf.get(id) ?? 0, + id, + text: fn.text, + ...(fn.richParas ? { richParas: fn.richParas } : {}), + height: estimateFootnoteHeight(fn.text, contentW, sec.docGrid), + }) + } + } + return out + }, + [doc, footnotes, sections, section], + ) + + // endnote-area entries (placed together at the document end, shared by pagination preview and page slicing): height estimated with the final section's content width + const endnoteItems = useMemo(() => { + if (!section || endnotes.length === 0) return [] + const sec = sections[sections.length - 1]?.settings ?? section + const contentW = twipsToPx(sec.pageWidth - sec.marginLeft - sec.marginRight) + return endnotes.map((n, i) => ({ + no: i + 1, + id: n.id, + text: n.text, + ...(n.richParas ? { richParas: n.richParas } : {}), + height: estimateFootnoteHeight(n.text, contentW, sec.docGrid), + })) + }, [endnotes, sections, section]) + + // canvas column-flow geometry (non-null when the cursor's section has equal-width columns — + // same follow-the-cursor rule as the canvas page box): shared by canvas CSS / measuring state / preview. + // equalWidth="0" (unequal local layout columns) is not modeled, matching the engine's scope + const colFlow = useMemo(() => { + const cur = sections[Math.min(activeSection, sections.length - 1)] + if (!cur || sectionColumns(cur) <= 1) return null + return sectionColGeom(cur) + }, [sections, activeSection]) + + // single-flow measuring state for the columned canvas: temporarily drop CSS columns and + // set the width to the column width so DOM measurement yields 1-D coordinates matching + // the engine's column flow (synchronous layout round-trip, no visible flicker) + const measureSingleFlow = useCallback( + function run(pm: HTMLElement, fn: () => T): T { + if (!colFlow || viewMode !== 'print') return fn() + pm.classList.add('measuring-columns') + try { + return fn() + } finally { + pm.classList.remove('measuring-columns') + } + }, + [colFlow, viewMode], + ) + + // column-flow geometry gate: when the canvas column CSS is inactive, measure as full-width single flow; the geometry must drop cols to match + const colGeomsFor = useCallback( + (geoms: SectionGeom[]): SectionGeom[] => { + if (colFlow && viewMode === 'print') return geoms + for (const g of geoms) if (g.cols) g.cols = undefined + return geoms + }, + [colFlow, viewMode], + ) + + // real TOC page-number backfill: compute each heading's (docHeading) page from the current real page slicing. + // Returns page numbers matching docHeadings in document order 1:1; returns null when not computable (page numbers left blank). + const headingPages = useCallback((): number[] | null => { + if (!editor || !section) return null + const pm = document.querySelector('.editor-scroll .ProseMirror') as HTMLElement | null + if (!pm) return null + const factor = zoom / 100 + const { mBlocks, slices, secs } = measureSingleFlow(pm, () => { + const origin = pm.getBoundingClientRect().top + effTopSingle * factor + const { blocks, totalHeight } = measureBlocks(pm, origin, factor) + const live = liveSections(sections, blocks) + let s: PageSlice[] + if (live.length > 0) { + assignSections(blocks, live) + s = sliceWithLineSplit( + blocks, + colGeomsFor(sectionGeoms(live, hfHeightsOf(live))), + totalHeight, + factor, + blockMetaOf, + ) + } else { + const contentH = twipsToPx(section.pageHeight) - effTopSingle - effBottomSingle + s = sliceWithLineSplit( + blocks, + [{ contentHeight: contentH, forceBreak: false }], + totalHeight, + factor, + blockMetaOf, + ) + } + return { mBlocks: blocks, slices: s, secs: live } + }) + const nums = secs.length > 1 ? pageNumbers(slices, secs) : slices.map((_, i) => i + 1) + const byEl = new Map(mBlocks.filter((b) => b.el).map((b) => [b.el as HTMLElement, b.top])) + const pages: number[] = [] + editor.state.doc.forEach((node, offset) => { + if (node.type.name !== 'docHeading' || !node.textContent.trim()) return + const dom = editor.view.nodeDOM(offset) as HTMLElement | null + const top = dom ? byEl.get(dom) : undefined + const idx = top === undefined ? 1 : pageAt(slices, top + 1) + pages.push(nums[Math.min(Math.max(idx, 1), nums.length) - 1] ?? idx) + }) + return pages + }, [ + editor, + section, + sections, + zoom, + blockMetaOf, + effTopSingle, + effBottomSingle, + hfHeightsOf, + measureSingleFlow, + colGeomsFor, + ]) + + // status-bar page number: real page slicing (same algorithm as the pagination preview). Edits remeasure with debounce; scrolling only relocates + useEffect(() => { + if (!doc || !section) { + setPageInfo({ current: 1, total: 1 }) + return + } + const scroller = document.querySelector('.editor-scroll') + if (!scroller) return + const factor = zoom / 100 + const mTopPx = effTopSingle + const contentH = twipsToPx(section.pageHeight) - effTopSingle - effBottomSingle + let slices: PageSlice[] = [] + let timer: number | null = null + const pmEl = () => document.querySelector('.editor-scroll .ProseMirror') as HTMLElement | null + const locate = () => { + const pm = pmEl() + if (!pm || slices.length === 0) return + const pmRect = pm.getBoundingClientRect() + const scrollRect = scroller.getBoundingClientRect() + const origin = pmRect.top + mTopPx * factor + const midScreen = Math.min(scrollRect.top + scrollRect.height / 2, pmRect.bottom) + // slices use gapless virtual coordinates; subtract the page-gap height above the midpoint (including mid-paragraph inline gaps) + let gapAbove = 0 + for (const gap of pm.querySelectorAll('.page-gap')) { + const r = gap.getBoundingClientRect() + if (r.top < midScreen) gapAbove += Math.min(r.height, midScreen - r.top) + } + const midY = (midScreen - origin - gapAbove) / factor + const current = pageAt(slices, midY) + const total = slices.length + setPageInfo((prev) => + prev.current === current && prev.total === total ? prev : { current, total }, + ) + } + const remeasure = () => { + const pm = pmEl() + if (!pm) return + // a columned canvas measures + slices in the single-flow measuring state (fillLineBoxes + // also reads the DOM for line sampling, so it must share the state); display-state DOM + // reads like gap positioning happen outside the measuring state + const measured = measureSingleFlow(pm, () => { + const origin = pm.getBoundingClientRect().top + mTopPx * factor + const { blocks, totalHeight } = measureBlocks(pm, origin, factor) + // multi-section: assign blocks to sections by docxIndex; each section has its own content height / forced breaks. + // liveSections: when a section-break block is deleted, that section merges into the next in real time (effective before saving) + const secList = sections.length > 0 ? liveSections(sections, blocks) : null + if (secList) assignSections(blocks, secList) + // the endnote area takes part in page slicing (placed together at the document end; overflows continue on later pages) + const withEndnotes = appendEndnotesBlock( + blocks, + totalHeight, + endnoteItems, + FOOTNOTE_SEPARATOR_H, + ) + const flowH = withEndnotes?.totalHeight ?? totalHeight + const hfHs = secList ? hfHeightsOf(secList) : null + const s = secList + ? sliceWithLineSplit( + blocks, + colGeomsFor(sectionGeoms(secList, hfHs!)), + flowH, + factor, + blockMetaOf, + ) + : sliceWithLineSplit( + blocks, + [{ contentHeight: contentH, forceBreak: false }], + flowH, + factor, + blockMetaOf, + ) + return { blocks, secList, hfHs, s } + }) + const { blocks, secList, hfHs } = measured + slices = measured.s + // M4 always-on pagination in the canvas: render page gaps before page-leading blocks + // (print view only; gaps don't count as content — measureBlocks subtracts them, so + // slice results are gap-independent and refresh is idempotent) + if (editor) { + const gaps: PageGapSpec[] = [] + const gapIds = new Set() + if (viewMode === 'print' && !readMode) { + const pmRect = pm.getBoundingClientRect() + const pageNotes = pageFootnotesOf(blocks, slices) + slices.slice(1).forEach((slice, k) => { + // an even/odd section's zero-height blank page shares its start with the following page: draw only one gap band on the canvas + if (slice.start === slices[k].start) return + // gap = previous page's (its section's) bottom margin + inter-page band + this page's (its section's) top margin + const prevSec = secList?.[slices[k].section]?.settings ?? section + const nextSec = secList?.[slice.section]?.settings ?? section + // effective margins after header/footer push-down (an over-tall header pushes the body down) + const nextHf = hfHs?.[slice.section] ?? singleHfPx + const prevHf = hfHs?.[slices[k].section] ?? singleHfPx + const metrics = { + marginTop: effectiveTopPx(nextSec, nextHf.headerPx), + marginBottom: effectiveBottomPx(prevSec, prevHf.footerPx), + marginLeft: twipsToPx(nextSec.marginLeft), + marginRight: twipsToPx(nextSec.marginRight), + } + // previous page's footnotes: rendered into the top of the gap (page-bottom area), with the gap enlarged by the reserved height. + // in-table gaps carry no footnote area (absolute positioning inside a table-row is unreliable); footnotes stay in the end-of-document list + const items = pageNotes[k] ?? [] + let notes: HTMLElement | undefined + let notesKey: string | undefined + let notesMetrics = metrics + if (items.length > 0) { + const fnH = items.reduce((s, n) => s + n.height, 0) + FOOTNOTE_SEPARATOR_H + const contentW = twipsToPx( + prevSec.pageWidth - prevSec.marginLeft - prevSec.marginRight, + ) + notes = makeGapNotesEl(items, twipsToPx(prevSec.marginLeft), contentW, fnH, (id) => + editNote('footnote', id), + ) + notesKey = `${Math.round(fnH)}:${items.map((n) => `${n.no}${n.text}`).join('|')}` + notesMetrics = { ...metrics, marginBottom: metrics.marginBottom + fnH } + } + const markShown = () => items.forEach((n) => gapIds.add(n.id)) + const i = blocks.findIndex((b) => Math.abs(b.top - slice.start) < 0.5) + if (i >= 0 && blocks[i].el) { + gaps.push({ + el: blocks[i].el!, + metrics: notesMetrics, + ...(notes ? { notes, notesKey } : {}), + }) + markShown() + return + } + // mid-paragraph page break (line-level cut point): insert an inline gap at the broken line. In-table cut points are not decorated yet + const b = blocks.find( + (bb) => bb.el && bb.top < slice.start && slice.start < bb.top + bb.height - 0.5, + ) + if (!b?.el) return + if (b.el.querySelector('tr')) { + // in-table cut point: insert an in-table gap row (display:table-row widget) + // before the broken row (next page's first row). Positioning must subtract the + // gap's own height: a tr's DOM offset includes in-table gaps above it, so + // subtract them before comparing with the slice's gapless virtual coordinates + const gapRects = Array.from(b.el.querySelectorAll('.page-gap-inline')).map((g) => + g.getBoundingClientRect(), + ) + const elTop = b.el.getBoundingClientRect().top + let matched = false + for (const tr of Array.from(b.el.querySelectorAll('tr')).filter( + (r) => !r.closest('.doc-nested-table'), + )) { + const trTop = tr.getBoundingClientRect().top + const gapsAbove = gapRects.reduce((s, g) => (g.top <= trTop ? s + g.height : s), 0) + const off = (trTop - elTop - gapsAbove) / factor + if (Math.abs(off - (slice.start - b.top)) < 1.5) { + matched = true + try { + const $pos = editor.view.state.doc.resolve(editor.view.posAtDOM(tr, 0)) + for (let d = $pos.depth; d > 0; d--) { + if ($pos.node(d).type.name === 'docTableRow') { + gaps.push({ pos: $pos.before(d), kind: 'table', metrics }) + break + } + } + } catch { + /* if posAtDOM fails, skip decorating this round */ + } + break + } + } + if (!matched) { + // inline cut point (page break mid-line): the cut falls in a line's band gap; locate the first line after it and insert a zero-height dashed marker + const coords = nextLineCoords(b.el, slice.start - b.top, factor) + const pos = coords ? editor.view.posAtCoords(coords)?.pos : undefined + if (pos != null) gaps.push({ pos, kind: 'cut', metrics }) + } + return + } + const coords = lineStartCoords(b.el, slice.start - b.top, factor) + const pos = coords ? editor.view.posAtCoords(coords)?.pos : undefined + if (pos == null) return + // fold the block's horizontal indent relative to the content area into negative margins so the gap spans the full paper width + const elRect = b.el.getBoundingClientRect() + gaps.push({ + pos, + metrics: { + ...notesMetrics, + marginLeft: metrics.marginLeft + (elRect.left - pmRect.left) / factor, + marginRight: metrics.marginRight + (pmRect.right - elRect.right) / factor, + }, + ...(notes ? { notes, notesKey } : {}), + }) + markShown() + }) + } + setPageGaps(editor.view, gaps) + // the last page paints as a full sheet like the ones above it: + // extend the canvas to that page's paper bottom, measured from the last gap + const gapEls = pm.querySelectorAll('.page-gap') + const lastGapEl = gapEls[gapEls.length - 1] + if (lastGapEl && slices.length > 1) { + const last = slices[slices.length - 1] + const lastSec = secList?.[last.section]?.settings ?? section + const lastHf = hfHs?.[last.section] ?? singleHfPx + const paperTop = + (lastGapEl.getBoundingClientRect().bottom - pm.getBoundingClientRect().top) / factor - + effectiveTopPx(lastSec, lastHf.headerPx) + pm.style.minHeight = `${Math.round(paperTop + twipsToPx(lastSec.pageHeight))}px` + } else { + pm.style.removeProperty('min-height') + } + // for real-device verification/troubleshooting: current slices and block geometry (read-only snapshot, no functional dependency) + ;(window as unknown as Record).__pageDebug = { + slices, + blocks: blocks.map((b) => ({ top: b.top, height: b.height, docxIndex: b.docxIndex })), + } + setGapNoteIds((prev) => { + if (prev.size === gapIds.size && [...gapIds].every((id) => prev.has(id))) return prev + return gapIds + }) + } + locate() + } + const onUpdate = () => { + if (timer) window.clearTimeout(timer) + timer = window.setTimeout(remeasure, 300) + } + remeasure() + // async @font-face loading triggers a full reflow (line-break points change); pagination must be remeasured + document.fonts.ready.then(onUpdate).catch(() => {}) + document.fonts.addEventListener('loadingdone', onUpdate) + scroller.addEventListener('scroll', locate, { passive: true }) + editor?.on('update', onUpdate) + return () => { + if (timer) window.clearTimeout(timer) + document.fonts.removeEventListener('loadingdone', onUpdate) + scroller.removeEventListener('scroll', locate) + editor?.off('update', onUpdate) + } + }, [ + doc, + section, + sections, + zoom, + editor, + viewMode, + readMode, + blockMetaOf, + pageFootnotesOf, + endnoteItems, + editNote, + effTopSingle, + effBottomSingle, + singleHfPx, + hfHeightsOf, + measureSingleFlow, + colGeomsFor, + ]) + + // section at the cursor: the target the Layout tab acts on + useEffect(() => { + if (!editor || sections.length === 0) { + setActiveSection(0) + return + } + const locateSection = () => { + const { $head } = editor.state.selection + const pmDoc = editor.state.doc + const topIndex = $head.depth > 0 ? $head.index(0) : 0 + let docxIndex: number | null = null + for (let i = Math.min(topIndex, pmDoc.childCount - 1); i >= 0; i--) { + const di = pmDoc.child(i).attrs?.docxIndex as number | null | undefined + if (di !== null && di !== undefined) { + docxIndex = di + break + } + } + const s = + docxIndex === null ? 0 : sections.findIndex((sec) => docxIndex! <= sec.lastBlockIndex) + setActiveSection(s >= 0 ? s : sections.length - 1) + } + locateSection() + editor.on('selectionUpdate', locateSection) + return () => { + editor.off('selectionUpdate', locateSection) + } + }, [editor, sections]) + + /** Word word-count dialog: pages/lines estimated from the current layout */ + const openStats = useCallback(() => { + if (!editor) return + const text = editor.state.doc.textContent + const pm = document.querySelector('.ProseMirror') + const zoomFactor = zoom / 100 + let lines = 0 + if (pm) { + for (const el of Array.from(pm.children) as HTMLElement[]) { + const cs = getComputedStyle(el) + let lh = parseFloat(cs.lineHeight) + if (!Number.isFinite(lh) || lh <= 0) lh = (parseFloat(cs.fontSize) || 15) * 1.2 + lines += Math.max(1, Math.round(el.getBoundingClientRect().height / zoomFactor / lh)) + } + } + // Word's paragraph figure counts non-empty paragraphs, including those + // inside table cells (descendants, not just top-level children) + let paragraphs = 0 + editor.state.doc.descendants((node) => { + if (node.isTextblock && node.textContent.trim() !== '') paragraphs++ + return true + }) + setStats({ + pages: pageInfo.total, + words: countWords(text), + asianChars: asianCharCount(text), + nonAsianWords: nonAsianWordCount(text), + charsNoSpace: text.replace(/\s/g, '').length, + charsWithSpace: text.replace(/\n/g, '').length, + paragraphs, + lines, + }) + }, [editor, zoom, pageInfo.total]) + + // "has unsaved changes" check shared by the close guard and autosave; refreshed on every + // render (all edit paths forceRender), so the guard's query reads the latest value + const anyDirtyRef = useRef(false) + const hasUnsavedChanges = + dirtyRef.current || + sectionDirty || + sectionsDirty.length > 0 || + trailingStartType !== null || + pageColorDirty || + headerDirty || + footerDirty || + hfVariantsDirty.length > 0 || + Object.keys(sectionHfEdits).length > 0 || + pgNumEdit !== null || + pgNumDirtySections.length > 0 || + numberingDirty || + Object.keys(styleUpserts).length > 0 || + titlePgDirty || + evenOddHfDirty || + watermarkDirty || + inksDirty || + notesDirty || + sourcesDirty || + themeFontsDirty || + themeColorsDirty || + commentsDirty || + protectionDirty + anyDirtyRef.current = hasUnsavedChanges + + // close guard: the main process queries dirty state before closing a tab/window; choosing "Save" runs a full save and reports back + useEffect(() => { + const offCheck = window.desktop.onCloseCheck?.(() => { + window.desktop.reportCloseCheck({ + dirty: !!doc && (anyDirtyRef.current || dirtyRef.current), + autoSave: autoSave && !!doc?.filePath, + filePath: doc?.filePath ?? null, + }) + }) + const offSave = window.desktop.onCloseSaveRequest?.(() => { + // Closing must not report success while edits are still unpersisted, so a + // save that raced with typing is retried until the file catches up. + void saveUntilPersisted({ + save: () => save(false), + wasIncomplete: () => saveIncompleteRef.current, + hasPath: () => !!doc?.filePath, + }).then( + (ok) => window.desktop.reportCloseSaveResult(ok === true), + () => window.desktop.reportCloseSaveResult(false), + ) + }) + return () => { + offCheck?.() + offSave?.() + } + }, [doc, save, autoSave]) + + // autosave: every 30s and on window blur, silently persist pending changes + useEffect(() => { + if (!autoSave || !doc || !doc.filePath) return + const tick = () => { + const anyDirty = + dirtyRef.current || + sectionDirty || + sectionsDirty.length > 0 || + trailingStartType !== null || + pageColorDirty || + headerDirty || + footerDirty || + hfVariantsDirty.length > 0 || + Object.keys(sectionHfEdits).length > 0 || + pgNumEdit !== null || + pgNumDirtySections.length > 0 || + numberingDirty || + Object.keys(styleUpserts).length > 0 || + titlePgDirty || + evenOddHfDirty || + watermarkDirty || + inksDirty || + notesDirty || + sourcesDirty || + themeFontsDirty || + themeColorsDirty + if (!anyDirty) return + if (editor?.view.composing) return // don't interrupt IME input + const active = document.activeElement as HTMLElement | null + if (active?.closest('td[contenteditable], .doc-textbox')) return // mid in-place edit + void save(false, true) + } + const id = window.setInterval(tick, 30_000) + window.addEventListener('blur', tick) + return () => { + window.clearInterval(id) + window.removeEventListener('blur', tick) + } + }, [ + autoSave, + doc, + editor, + save, + sectionDirty, + pageColorDirty, + headerDirty, + footerDirty, + hfVariantsDirty, + sectionHfEdits, + pgNumEdit, + pgNumDirtySections, + numberingDirty, + styleUpserts, + titlePgDirty, + evenOddHfDirty, + watermarkDirty, + inksDirty, + notesDirty, + sourcesDirty, + themeFontsDirty, + themeColorsDirty, + ]) + + // After an AI run finishes on a never-saved document, silently save it once: the + // first save derives the file name from the first heading (see deriveAutoFileName + // in file-actions), which also renames the shell tab — mirrors slides, where AI + // generation names and persists the draft deck. + useEffect(() => { + const handler = () => { + const cur = fileCtxRef.current + if (!cur.doc || cur.doc.filePath || !anyDirtyRef.current) return + if (editor?.view.composing) return + void save(false, true) + } + window.addEventListener('ai-docs-run-done', handler) + return () => window.removeEventListener('ai-docs-run-done', handler) + }, [editor, save]) + + useEffect(() => { + const handler = (e: KeyboardEvent) => { + if ((e.metaKey || e.ctrlKey) && e.key === 's') { + e.preventDefault() + void save(e.shiftKey) + } + if ((e.metaKey || e.ctrlKey) && e.key === 'o') { + e.preventDefault() + void openFile() + } + if ((e.metaKey || e.ctrlKey) && e.key === 'f') { + e.preventDefault() + if (doc) setShowFind(true) + } + // Word dialog shortcuts: Font ⌘D / Paragraph ⌥⌘M / Hyperlink ⌘K + if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && e.key === 'd' && doc) { + e.preventDefault() + setShowFontDialog(true) + } + if ((e.metaKey || e.ctrlKey) && e.altKey && e.code === 'KeyM' && doc) { + e.preventDefault() + setShowParaDialog(true) + } + if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && e.key === 'k' && doc) { + e.preventDefault() + setShowLinkModal(true) + } + if (e.key === 'F9' && doc) { + e.preventDefault() + updateFields() + } + // Word alignment shortcuts + const ALIGN_KEYS: Record = { + l: null, + e: 'center', + r: 'right', + j: 'justify', + } + if ((e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && e.key in ALIGN_KEYS && editor) { + e.preventDefault() + const align = ALIGN_KEYS[e.key] + editor + .chain() + .focus() + .updateAttributes('docParagraph', { align }) + .updateAttributes('docHeading', { align }) + .updateAttributes('docListItem', { align }) + .run() + } + } + window.addEventListener('keydown', handler) + return () => window.removeEventListener('keydown', handler) + }, [save, openFile, editor, doc, updateFields]) + + // double-click an inline equation / click an equation block's edit button (ones with LaTeX source) → reopen the equation dialog for editing + useEffect(() => { + const handler = (e: Event) => { + const detail = (e as CustomEvent<{ pos: number; latex: string; kind?: 'inline' | 'block' }>) + .detail + if (editor && doc && detail) setEqEditTarget({ kind: 'inline', ...detail }) + } + window.addEventListener('ai-docs-edit-inline-math', handler) + return () => window.removeEventListener('ai-docs-edit-inline-math', handler) + }, [editor, doc]) + + // native application menu → renderer commands + useEffect(() => { + return window.desktop.onMenuCommand((command, payload) => { + const align = (value: string | null) => editor && setParaAttrs(editor, { align: value }) + switch (command) { + case 'new': + void newFile() + break + case 'open': + void openFile() + break + case 'open-path': + if (payload) void openRecent(payload) + break + case 'save': + void save(false) + break + case 'save-as': + void save(true) + break + case 'undo': + editor?.chain().focus().undo().run() + break + case 'redo': + editor?.chain().focus().redo().run() + break + case 'zoom-in': + setZoom((z) => Math.min(200, Math.round(z) + 10)) + break + case 'zoom-out': + setZoom((z) => Math.max(50, Math.round(z) - 10)) + break + case 'zoom-100': + setZoom(100) + break + case 'zoom-page-width': + zoomFit('width') + break + case 'zoom-whole-page': + zoomFit('page') + break + case 'toggle-ai': + setShowAi((v) => !v) + break + case 'toggle-dark': + setDarkCanvas((v) => !v) + break + case 'insert-table': + if (editor && doc) insertTableAt(editor, 3, 3) + break + case 'insert-image': + if (editor && doc) void insertImageViaDialog(editor) + break + case 'insert-page-break': + if (editor && doc) insertPageBreakAt(editor) + break + case 'insert-link': + if (editor && doc) setShowLinkModal(true) + break + case 'insert-equation': + if (editor && doc) setShowEquationModal(true) + break + // Menu parity with the shortcuts and the right-click menu + case 'insert-comment': + if (editor && doc) { + setShowComments(true) + startNewComment() + } + break + case 'font-dialog': + if (doc) setShowFontDialog(true) + break + case 'paragraph-dialog': + if (doc) setShowParaDialog(true) + break + case 'word-count': + if (doc) openStats() + break + case 'bold': + editor?.chain().focus().toggleMark('bold').run() + break + case 'italic': + editor?.chain().focus().toggleMark('italic').run() + break + case 'underline': + editor?.chain().focus().toggleMark('underline').run() + break + case 'align-left': + align(null) + break + case 'align-center': + align('center') + break + case 'align-right': + align('right') + break + case 'align-justify': + align('justify') + break + case 'page-setup': + setRibbonTabRequest({ tab: 'layout', nonce: Date.now() }) + break + case 'find': + if (doc) setShowFind(true) + break + case 'export-pdf': + void exportPdf() + break + } + }) + }, [ + editor, + doc, + newFile, + openFile, + openRecent, + save, + exportPdf, + zoomFit, + openStats, + startNewComment, + ]) + + // Word: TOC entries jump on ⌘/Ctrl+click only; a plain click just places the + // caret. Resolve the bookmark anchor against the original block XML, fall + // back to matching the heading text. + const onDocClick = useCallback( + (e: ReactMouseEvent) => { + const commentSpan = (e.target as HTMLElement).closest('.doc-comment') as HTMLElement | null + if (commentSpan) { + const ids = (commentSpan.dataset.commentIds ?? '').split(' ') + if (comments.some((c) => !c.done && ids.includes(c.id))) setShowComments(true) + } + if (!e.metaKey && !e.ctrlKey) return + const line = (e.target as HTMLElement).closest('.doc-toc-line') as HTMLElement | null + if (!line) return + let target: Element | null = null + const anchor = line.dataset.tocAnchor + if (anchor && doc) { + const block = doc.parsed.blocks.find((b) => b.originalXml?.includes(`w:name="${anchor}"`)) + if (block && block.docxIndex !== null) { + target = document.querySelector(`.ProseMirror [data-idx="${block.docxIndex}"]`) + } + } + if (!target) { + const title = (line.dataset.tocTitle ?? '').replace(/\s+/g, '') + if (title) { + target = + [ + ...document.querySelectorAll( + '.ProseMirror h1, .ProseMirror h2, .ProseMirror h3, .ProseMirror h4, .ProseMirror h5, .ProseMirror h6', + ), + ].find((h) => (h.textContent ?? '').replace(/\s+/g, '') === title) ?? null + } + } + target?.scrollIntoView({ behavior: 'smooth', block: 'start' }) + }, + [doc, comments], + ) + + /** Editor right-click menu, only inside the document body */ + const onDocContextMenu = useCallback( + (e: ReactMouseEvent) => { + if (readMode || isProtected) return + if (!(e.target as HTMLElement).closest('.doc-page')) return + e.preventDefault() + // Word behavior: right-clicking outside the selection moves the cursor there first (menu items act on the clicked block) + if (editor) { + const hit = editor.view.posAtCoords({ left: e.clientX, top: e.clientY }) + if (hit) { + const { from, to } = editor.state.selection + if (hit.pos < from || hit.pos > to) { + editor.commands.setTextSelection(hit.pos) + } + } + } + setCtxMenu({ x: e.clientX, y: e.clientY }) + }, + [readMode, isProtected, editor], + ) + + // e2e/automation hook: lets tests drive open/edit/save without native dialogs + useEffect(() => { + ;(window as unknown as Record).__aidocs = { + editor, + openPath: (path: string) => openRecent(path), + save: () => save(false), + getStatus: () => status, + exportPdfTo: (path: string) => exportPdf(path), + } + }, [editor, openRecent, save, status, exportPdf]) + + if (!editor) return null + + const wordCount = countWords(editor.state.doc.textContent) + + const canvasSection = sections[activeSection]?.settings ?? section + const canvasBox = canvasSection ? sectionPageBox(canvasSection) : null + const canvasTop = canvasSection ? effectiveTopPx(canvasSection, singleHfPx.headerPx) : 0 + const canvasBottom = canvasSection ? effectiveBottomPx(canvasSection, singleHfPx.footerPx) : 0 + const docZoomStyle = { + zoom: zoom / 100, + '--page-w': canvasBox ? `${canvasBox.width}px` : undefined, + '--page-h': canvasBox ? `${canvasBox.height}px` : undefined, + '--section-content-w': canvasBox ? `${canvasBox.contentWidth}px` : undefined, + '--page-pad': canvasSection + ? `${canvasTop}px ${twipsToPx(canvasSection.marginRight)}px ${canvasBottom}px ${twipsToPx(canvasSection.marginLeft)}px` + : undefined, + '--header-dist': canvasBox ? `${canvasBox.headerDist}px` : undefined, + '--footer-dist': canvasBox ? `${canvasBox.footerDist}px` : undefined, + '--page-bg': pageColor ? `#${pageColor}` : undefined, + '--page-cols': colFlow && viewMode === 'print' ? colFlow.cols : undefined, + } as CSSProperties + + const docZoomClass = [ + 'doc-zoom', + showMarks ? 'show-marks' : '', + `view-${viewMode}`, + showGrid ? 'show-grid' : '', + ].join(' ') + + return ( +
    + {docCss && } + {doc && liveDocCjk != null && ( + + )} + {/* Theme CSS comes from live state, so a Design ▸ Themes/Fonts/Colors pick shows + on the page immediately instead of only in the saved file */} + {doc && } + {colFlow && viewMode === 'print' && ( + // columns (sectPr w:cols): column gap follows the document's w:space; measuring-columns + // is the single-flow measuring state (columns removed, content-box width = column width, + // toggled instantaneously for measurement, invisible). + // .doc-page is border-box, so the measured width must add back the left/right margin padding + + )} + + + + + +