Author SHA1 Message Date
ZacharyZhang-NY fa273aff13 Merge remote-tracking branch 'origin/main' 2026-10-09 16:04:54 -04:00
ZacharyZhang-NY 096b7f8fd4 Site: the release comment names no host 2026-10-09 16:04:45 -04:00
ZacharyZhang-NY 9b1b64884b docs: add AGit pull request instructions 2026-10-09 20:03:10 +00:00
ZacharyZhang-NY 623bc085f6 Hosting moves to git.zacharyzhang.com: component dependency, site links, references; GitHub workflows removed 2026-10-09 15:58:26 -04:00
ZacharyZhang-NY 383a1ea467 One copy per app: a second is refused and names the running process (X-03) 2026-10-09 14:57:30 -04:00
ZacharyZhang-NY 6bf5d6c7e6 ElyMark: keys typed before an outside write survive; same text adopts the file; autosave resumes (M-01) 2026-10-09 14:39:58 -04:00
ZacharyZhang-NY c9bfccc91c ElyPDF: the edit tool checks a page's text blocks in one pass (P-04) 2026-10-09 13:16:01 -04:00
ZacharyZhang-NY 4d8d5a6ef5 ElyPDF: text under a covering picture is aimed; a shaky click no longer moves it (P-03) 2026-10-09 13:05:48 -04:00
ZacharyZhang-NY 04040a2a03 ElyPDF: page pictures stay through an edit until they repaint (P-02) 2026-10-09 12:50:11 -04:00
ZacharyZhang-NY 139e8f6250 ElyDoc: mail merge keeps the template chosen with the data; previews are never templates (D-02) 2026-10-09 12:27:13 -04:00
ZacharyZhang-NY 1f4807c81c ElyDoc: closing a tab takes its export or print dialog, no crash (D-01) 2026-10-09 12:06:47 -04:00
ZacharyZhang-NY ec87e28a46 Doc, Table, Show start past unreadable settings; the newest author name signs, restarts too (X-02) 2026-10-09 11:59:26 -04:00
ZacharyZhang-NY 8a915ea354 Quit from any window, Settings too, asks about unsaved tabs in front (X-01) 2026-10-09 11:37:56 -04:00
ZacharyZhang-NY 943411fb1a ElyPDF: an OS permission error shows as an error, never a missing text key (P-01); component library f834f55 2026-10-09 10:58:47 -04:00
ZacharyZhang-NY ab85673eea ElyShow: a deck fits the slide once; a zoom then stays (S-03); per-deck state moves to extra.rs (S-02) 2026-10-09 10:39:45 -04:00
ZacharyZhang-NY f9bf82e3f8 Bug list: fatal and high first, then auto-update and 0.1.2 2026-10-09 10:26:35 -04:00
ZacharyZhang-NY a6d8a1de43 ElyTable: a sheet starts at the left, even before its geometry arrives (T-03) 2026-10-09 10:16:11 -04:00
ZacharyZhang-NY ecf977364b ElyTable: a cell scrolls in by the least amount; a drag never scrolls under the pointer (T-02) 2026-10-09 09:47:10 -04:00
ZacharyZhang-NY c52e1a3b16 Bug list progress file; reviews find bug items 2026-10-09 09:32:01 -04:00
ZacharyZhang-NY 63bf0cc828 Bug list from the static audit (branch claude/gracious-franklin-l5vhbv) 2026-10-09 09:29:06 -04:00
ZacharyZhang-NY 380e6783d6 Tasks: 0.1.1 published 2026-10-09 09:28:58 -04:00
ZacharyZhang-NY e4ca134655 Source archives leave out the internal rules, requirements and task records 2026-10-09 09:26:35 -04:00
ZacharyZhang-NY 4efe14bce7 ElyMark: the probe requires each task box laid out and visible (R2.14) 2026-10-09 09:19:15 -04:00
ZacharyZhang-NY eee3b9e288 ElyTable: the chart search uses its own sheet, scans the sheet as a last resort, and fails cleanly with no room (R2.10) 2026-10-09 09:10:28 -04:00
ZacharyZhang-NY b3fc6c9c82 ElyMark: the probe also requires each task box drawn (R2.14) 2026-10-09 09:01:13 -04:00
ZacharyZhang-NY 8a7e45d901 Version 0.1.1 2026-10-09 08:51:42 -04:00
ZacharyZhang-NY 47b05b52fa Shorten a comment in patch 0041 (R2.10) 2026-10-09 08:51:14 -04:00
ZacharyZhang-NY 81487fb32d ElyTable: the chart search skips merged cells, looks four ways, and never throws (R2.10) 2026-10-09 08:49:39 -04:00
ZacharyZhang-NY 326fe24cba Video: the check compares both renderers at the cut and every exit frame's recordings (R2.3) 2026-10-09 08:23:16 -04:00
ZacharyZhang-NY 35165139a8 ElyShow: the fullscreen check also requires the menu bar and Dock hidden (R2.5) 2026-10-09 08:22:31 -04:00
ZacharyZhang-NY 9a126611a2 ElyMark: the probe checks every task box, ticked or not (R2.14) 2026-10-09 08:09:54 -04:00
ZacharyZhang-NY 511fb8d4eb Tasks: R2.20 and R2.7 done; R2.6, R2.8, R2.12 at the round limit 2026-10-09 07:31:31 -04:00
ZacharyZhang-NY b243515190 ElyTree: per-language presets for diffs; component library b0dbfd4 (R2.12) 2026-10-09 07:31:13 -04:00
ZacharyZhang-NY ff790e31cf ElyTable: figures split at field names; a format's own semicolons stay (R2.8) 2026-10-09 07:27:19 -04:00
ZacharyZhang-NY cc589a07b3 ElyPDF: the old-tile test checks painted area covers the shown page (R2.6); shorter comments in patch 0041 2026-10-09 07:25:55 -04:00
ZacharyZhang-NY 3c6faf9a6e ElyTree: diffs color per language; component library c771248 (R2.12) 2026-10-09 06:53:36 -04:00
ZacharyZhang-NY f4dad1d269 ElyTable: a new chart goes in empty cells beside its data, off the view if need be, and scrolls into view (R2.10) 2026-10-09 06:47:31 -04:00
ZacharyZhang-NY 409805e863 Shorten a comment (R2.5) 2026-10-09 06:43:14 -04:00
ZacharyZhang-NY ecd849601b ElyShow: a real-window check that the show covers the whole screen (R2.5) 2026-10-09 06:43:11 -04:00
ZacharyZhang-NY 65d79295ec ElyMark: short table rows compare padded, as GFM reads them (R2.13) 2026-10-09 06:38:35 -04:00
ZacharyZhang-NY 301890485f Video: one slab list for montage and exit; a render check for the recordings at the cut (R2.3) 2026-10-09 06:36:27 -04:00
ZacharyZhang-NY 5b81c5acf2 Tasks: R2.11 done 2026-10-09 05:56:16 -04:00
ZacharyZhang-NY 6445f3144d Zoom reads the current centring offset, so bunched zooms hold the anchor (R2.7); figures pass kernel values through, tested (R2.8) 2026-10-09 05:56:15 -04:00
ZacharyZhang-NY 2c3f3894dd ElyShow: the large-layer test checks the shape lands past the first piece (R2.20) 2026-10-09 05:55:06 -04:00
ZacharyZhang-NY 03bcbab5ce ElyPDF: only content edits keep old tiles and known sizes; old tiles paint and free with their tab (R2.6) 2026-10-09 05:51:44 -04:00
ZacharyZhang-NY 1bf693f7ab Video: leaving screens share the montage's geometry; renderer tests for names and recordings (R2.3) 2026-10-09 05:19:34 -04:00
ZacharyZhang-NY 44a61443fa ElyMark: tables compare by alignment and cell source, in quotes and lists too; rewritten cells stay raw (R2.13) 2026-10-09 05:15:42 -04:00
ZacharyZhang-NY 844d98559b ElyTree: diff lines color by their file's syntax; component library 5caf5aa (R2.12) 2026-10-09 05:11:22 -04:00
ZacharyZhang-NY db1e889f15 Counts: tests read the real catalogs; the ElyTree summary is tested at 0, 1 and 2 (R2.11) 2026-10-09 05:06:24 -04:00
ZacharyZhang-NY 2537472bd3 Documents: zoom anchors past the centring offset; key zoom keeps the page's left edge (R2.7) 2026-10-09 04:40:12 -04:00
ZacharyZhang-NY 3f567bf4a0 ElyTable: selection figures show as the kernel formats them for the cell (R2.8) 2026-10-09 04:36:18 -04:00
ZacharyZhang-NY b870ba9d41 ElyPDF: old tiles stay under their page through edits and rescales until new ones land (R2.6) 2026-10-09 04:34:51 -04:00
ZacharyZhang-NY 50e18d835e ElyShow: a layer comes in 16 MiB pieces; closing a deck drops its waiting layers (R2.20) 2026-10-09 04:28:04 -04:00
ZacharyZhang-NY b591aa8625 ElyTable: a new chart lands beside its data (R2.10) 2026-10-09 04:02:32 -04:00
ZacharyZhang-NY efe5d4fc5d ElyShow: the show is native fullscreen off macOS, simple fullscreen on it (R2.5) 2026-10-09 04:02:29 -04:00
ZacharyZhang-NY c77bd2a281 ElyMark: task boxes are drawn at text size on the first line (R2.14) 2026-10-09 03:57:56 -04:00
ZacharyZhang-NY f28768634f ElyMark: a table stays a table whatever its spacing; edits keep the document's table style (R2.13) 2026-10-09 03:50:52 -04:00
ZacharyZhang-NY 7049a6a4aa Tasks: R2.9 done 2026-10-09 03:49:29 -04:00
ZacharyZhang-NY be33bb28aa Patch 0040: blank line before the diff 2026-10-09 03:44:29 -04:00
ZacharyZhang-NY cc67055ccc ElyTable: a filtered range keeps its rows only for a cell inside it (R2.9) 2026-10-09 03:43:29 -04:00
ZacharyZhang-NY e85884212b Tasks: R2.17 done 2026-10-09 03:39:03 -04:00
ZacharyZhang-NY c5e19eb0b5 ElyTree: prose diffs read plain; component library 7f2ac3e (R2.12) 2026-10-09 03:28:39 -04:00
ZacharyZhang-NY 5a6c17757e ElyPDF: the document's font reads codes as text extraction does, partial ToUnicode included (R2.17) 2026-10-09 03:22:39 -04:00
ZacharyZhang-NY 0ce468a3ad ElyTable: under LOK an AutoFilter range keeps its rows through list, apply, toggle, undo and reopen (R2.9) 2026-10-09 03:20:07 -04:00
ZacharyZhang-NY f4c1a1665b ElyPDF: the document's font writes through its own object and codes; shared glyphs keep their letters (R2.17) 2026-10-09 03:17:08 -04:00
ZacharyZhang-NY fbcf654812 Review: R2.17 round 1 2026-10-09 03:07:20 -04:00
ZacharyZhang-NY 6f90a7dc53 Counts read in the singular for one thing; parts build two-count messages (R2.11) 2026-10-09 03:07:13 -04:00
ZacharyZhang-NY d4c5f90c87 ElyTable: an AutoFilter on marked rows keeps the total below out (R2.9) 2026-10-09 02:53:55 -04:00
ZacharyZhang-NY 69b299f2db Tasks: R2.16 done 2026-10-09 02:50:06 -04:00
ZacharyZhang-NY bb3120ebe4 Shorten a comment (R2.8) 2026-10-09 02:40:34 -04:00
ZacharyZhang-NY e1950f9121 ElyTable: plain figures show ten significant digits (R2.8) 2026-10-09 02:40:31 -04:00
ZacharyZhang-NY 1cf81dcb44 Sheet scroll checks run on a real sheet with its geometry (R2.16) 2026-10-09 02:39:47 -04:00
ZacharyZhang-NY 05c3eab2f8 Shorten a comment (R2.7) 2026-10-09 02:38:50 -04:00
ZacharyZhang-NY 1b1148a410 ElyDoc: a page stays centred and zoom stays on the page; only a sheet grows past its size (R2.7) 2026-10-09 02:38:46 -04:00
ZacharyZhang-NY 9fe28f072b ElyPDF: an edit keeps the page drawn until its repaint lands (R2.6) 2026-10-09 02:34:32 -04:00
ZacharyZhang-NY 5e2cf83da8 Video: app names clear before the flatten; montage screens play while they lift (R2.3) 2026-10-09 02:31:47 -04:00
ZacharyZhang-NY 48e83a9b45 ElyShow: show layers come one per reply, so large slides play (R2.20) 2026-10-09 02:31:47 -04:00
ZacharyZhang-NY 56855acfb4 ElyTable: zoom and DPI keep the scroll in print twips; drag and zoom tests far down a sheet (R2.16) 2026-10-09 02:29:46 -04:00
ZacharyZhang-NY eb844cc72c ElyShow: the show hides the menu bar and Dock (R2.5) 2026-10-09 02:23:57 -04:00
ZacharyZhang-NY a3d29bec81 Shorten a comment (R2.17) 2026-10-09 02:20:41 -04:00
ZacharyZhang-NY 371b1e81c8 ElyPDF: write in a document's subset font through the page's own glyph codes (R2.17) 2026-10-09 02:20:36 -04:00
ZacharyZhang-NY 286631daf9 Tasks: R2.4 done 2026-10-09 02:16:34 -04:00
ZacharyZhang-NY ee98f6d7c0 ElyShow: test paints slide two's pixels after a switch (R2.4) 2026-10-09 02:11:58 -04:00
ZacharyZhang-NY be31260753 ElyShow: switching slides repaints the canvas (R2.4) 2026-10-09 02:05:45 -04:00
ZacharyZhang-NY 0d529e1b0d ElyTable: clicks and drags land on the cell under them far down a sheet (R2.16) 2026-10-09 02:04:13 -04:00
ZacharyZhang-NY 148885248b Tasks: R2.2 done 2026-10-09 01:47:15 -04:00
ZacharyZhang-NY 78a0158956 Site: names use the SVG's screen transform; resize tests use CSS size (R2.2) 2026-10-09 01:45:00 -04:00
ZacharyZhang-NY 4f4bf5c35c Tasks: R2.18 done 2026-10-09 01:43:53 -04:00
ZacharyZhang-NY c078d3d0a7 Site: drop dead screenshot text, screen() and images (R2.18) 2026-10-09 01:41:23 -04:00
ZacharyZhang-NY 92702273df Site: downloads go to the GitHub release page (R2.18) 2026-10-09 01:37:38 -04:00
ZacharyZhang-NY cf04a100ff Tasks: R2.15 done 2026-10-09 01:36:29 -04:00
ZacharyZhang-NY 034cbfce02 Tasks: user-reported R2.16–R2.19 2026-10-09 01:36:20 -04:00
ZacharyZhang-NY f6f4b95108 Inert step refuses an unreadable plist; guard runs it on a fake bundle (R2.15) 2026-10-09 01:34:07 -04:00
ZacharyZhang-NY b5d490c49a Inert step tolerates only 'not registered'; guard fails on query or plist errors; test asserts the tile rejection (R2.15) 2026-10-09 01:31:08 -04:00
ZacharyZhang-NY 1745ee237d Shorten a comment (R2.15) 2026-10-09 01:23:13 -04:00
ZacharyZhang-NY 466afe20a0 No LibreOffice in Open With: built bundle claims nothing, no image is mounted (R2.15) 2026-10-09 01:23:06 -04:00
ZacharyZhang-NY 5a36ffc272 Site: names placed from the rest pose, follow model resizes; two-axis tests with motion (R2.2) 2026-10-09 01:15:27 -04:00
ZacharyZhang-NY 41fe64c74d Site: shown names follow the camera; touch tests fail on console and request errors (R2.2) 2026-10-09 01:11:59 -04:00
ZacharyZhang-NY a9f093ca26 Tasks: R2.1 done 2026-10-09 01:10:19 -04:00
ZacharyZhang-NY f5455ecd36 Site: contrast check counts element and ancestor opacity (R2.1) 2026-10-09 01:08:06 -04:00
ZacharyZhang-NY 9df123ff94 Site: alpha-aware contrast check; test the open steps (R2.1) 2026-10-09 01:05:26 -04:00
ZacharyZhang-NY 5162692902 Site: source archives, macOS 15 open steps, contrast test in both themes (R2.1) 2026-10-09 01:02:15 -04:00
ZacharyZhang-NY aeeccb4696 Tasks: R2 fixes found after release 2026-10-09 01:01:33 -04:00
251 changed files with 5239 additions and 963 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
# Internal records stay out of source archives.
agents.md export-ignore
CLAUDE.md export-ignore
PRD.md export-ignore
tasks export-ignore
-77
View File
@@ -1,77 +0,0 @@
# Builds the patched engines once; release.yml downloads them.
name: engines
on:
workflow_dispatch:
permissions:
contents: write
jobs:
macos:
strategy:
fail-fast: false
matrix:
include:
- runner: macos-15
arch: arm64
- runner: macos-15-intel
arch: x86_64
runs-on: ${{ matrix.runner }}
timeout-minutes: 355
env:
GH_TOKEN: ${{ github.token }}
CCACHE_DIR: ${{ github.workspace }}/.ccache
CCACHE_MAXSIZE: 6G
steps:
- uses: actions/checkout@v4
- name: Key
id: key
run: echo "key=$(scripts/engines-key.sh)" >> "$GITHUB_OUTPUT"
- name: Already built?
id: done
run: |
if gh release view "engines-${{ steps.key.outputs.key }}" --json assets \
--jq '.assets[].name' 2>/dev/null | grep -qx "engines-macos-${{ matrix.arch }}.tar.zst"; then
echo "built=true" >> "$GITHUB_OUTPUT"
fi
- name: Tools
if: steps.done.outputs.built != 'true'
run: brew install make gnu-sed bison flex gettext autoconf automake libtool ccache nasm zstd
- name: Compiler cache
if: steps.done.outputs.built != 'true'
uses: actions/cache/restore@v4
with:
path: .ccache
key: ccache-macos-${{ matrix.arch }}-${{ steps.key.outputs.key }}-${{ github.run_id }}
restore-keys: ccache-macos-${{ matrix.arch }}-
- name: Upstream sources
if: steps.done.outputs.built != 'true'
run: scripts/fetch-references.sh
- name: LibreOffice (patched)
if: steps.done.outputs.built != 'true'
run: scripts/build-libreoffice.sh
- name: MuPDF (patched), Git, git-lfs, OCR data, CEF
if: steps.done.outputs.built != 'true'
run: |
scripts/build-mupdf.sh
scripts/build-git.sh
scripts/fetch-git-lfs.sh
scripts/fetch-tessdata.sh
scripts/fetch-cef.sh
- name: Keep the compiler cache, even after a timeout
if: always() && steps.done.outputs.built != 'true'
uses: actions/cache/save@v4
with:
path: .ccache
key: ccache-macos-${{ matrix.arch }}-${{ steps.key.outputs.key }}-${{ github.run_id }}
- name: Publish
if: steps.done.outputs.built != 'true'
run: |
archive=engines-macos-${{ matrix.arch }}.tar.zst
tar -C engines -cf - lo-src/instdir mupdf-build mupdf-src git git-src/COPYING git-src/LGPL-2.1 cef tessdata |
zstd -19 -T0 -o "$archive"
tag=engines-${{ steps.key.outputs.key }}
gh release view "$tag" >/dev/null 2>&1 ||
gh release create "$tag" --prerelease --title "$tag" --notes "Pinned, patched engines; built by engines.yml."
gh release upload "$tag" "$archive" --clobber
-58
View File
@@ -1,58 +0,0 @@
# Builds macOS apps for a release tag and attaches them.
name: release
on:
workflow_dispatch:
inputs:
tag:
description: Release tag to attach the packages to, such as v0.1.0
required: true
permissions:
contents: write
jobs:
macos:
strategy:
fail-fast: false
matrix:
include:
- runner: macos-15
arch: arm64
- runner: macos-15-intel
arch: x86_64
runs-on: ${{ matrix.runner }}
timeout-minutes: 120
env:
GH_TOKEN: ${{ github.token }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.tag }}
- name: Engines
run: |
brew install zstd
tag=engines-$(scripts/engines-key.sh)
gh release download "$tag" --pattern "engines-macos-${{ matrix.arch }}.tar.zst" ||
{ echo "::error::no $tag for ${{ matrix.arch }}; run the engines workflow first"; exit 1; }
mkdir -p engines
zstd -dc "engines-macos-${{ matrix.arch }}.tar.zst" | tar -C engines -xf -
- name: Upstream sources and ElyMark's page
run: |
scripts/fetch-references.sh
scripts/build-mark-content.sh
- name: Tests that need no window
run: |
tests/scripts/types.sh
tests/scripts/icons.sh
python3 tests/scripts/comments.py
- name: Packages
run: packaging/macos/release.sh 1
- name: Attach to the release
run: |
version=${{ inputs.tag }}
gh release view "$version" >/dev/null 2>&1 || gh release create "$version" --title "Ely Office $version" --notes "Built by release.yml."
gh release upload "$version" dist/*.dmg --clobber
if [ "${{ matrix.arch }}" = arm64 ]; then
gh release upload "$version" dist/ElyOffice-*-source.tar.gz dist/ElyOffice-*-upstream-source.tar.gz --clobber
fi
+15
View File
@@ -0,0 +1,15 @@
# Contributing
## Opening a pull request on git.zacharyzhang.com
Forking is disabled on this server. Open pull requests with AGit instead:
1. Register an account at https://git.zacharyzhang.com
2. Clone, commit your changes, then push to a `refs/for/<target-branch>` ref:
```bash
git clone https://git.zacharyzhang.com/ZacharyZhang-NY/ElyOffice.git
git push origin HEAD:refs/for/main -o topic=<short-name> -o title="<PR title>" -o description="<PR body>"
```
3. To update the pull request, push again with the same `topic`.
Generated
+18 -17
View File
@@ -1919,7 +1919,7 @@ checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
[[package]]
name = "ely-agent"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"ely-platform",
"ely-ui",
@@ -1927,7 +1927,7 @@ dependencies = [
[[package]]
name = "ely-doc"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"anyhow",
"csv",
@@ -1948,7 +1948,7 @@ dependencies = [
[[package]]
name = "ely-files"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"aes-gcm",
"ely-platform",
@@ -1964,7 +1964,7 @@ dependencies = [
[[package]]
name = "ely-gpui-component"
version = "0.1.1"
source = "git+https://github.com/ZacharyZhang-NY/Ely-GPUI-Components?rev=69265b4fd4da888e2d8e1268021af4d358e67afb#69265b4fd4da888e2d8e1268021af4d358e67afb"
source = "git+https://git.zacharyzhang.com/ZacharyZhang-NY/Ely-GPUI-Components?rev=5d6efd46ec0c93b381ec7578561a1273c366025b#5d6efd46ec0c93b381ec7578561a1273c366025b"
dependencies = [
"alacritty_terminal",
"anyhow",
@@ -2001,14 +2001,14 @@ dependencies = [
[[package]]
name = "ely-ipc"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"log",
]
[[package]]
name = "ely-lok"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"base64 0.23.1",
"ely-gpui-component",
@@ -2028,7 +2028,7 @@ dependencies = [
[[package]]
name = "ely-mail"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"ely-platform",
"ely-ui",
@@ -2036,7 +2036,7 @@ dependencies = [
[[package]]
name = "ely-mark"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"anyhow",
"base64 0.23.1",
@@ -2058,7 +2058,7 @@ dependencies = [
[[package]]
name = "ely-office"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"anyhow",
"directories",
@@ -2078,7 +2078,7 @@ dependencies = [
[[package]]
name = "ely-pdf"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"ely-files",
"ely-gpui-component",
@@ -2094,7 +2094,7 @@ dependencies = [
[[package]]
name = "ely-pdf-engine"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"cc",
"ely-ipc",
@@ -2110,7 +2110,7 @@ dependencies = [
[[package]]
name = "ely-platform"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"anyhow",
"arboard",
@@ -2143,7 +2143,7 @@ dependencies = [
[[package]]
name = "ely-show"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"ely-files",
"ely-gpui-component",
@@ -2162,7 +2162,7 @@ dependencies = [
[[package]]
name = "ely-table"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"ely-gpui-component",
"ely-lok",
@@ -2178,7 +2178,7 @@ dependencies = [
[[package]]
name = "ely-tree"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"ely-files",
"ely-gpui-component",
@@ -2196,7 +2196,7 @@ dependencies = [
[[package]]
name = "ely-ui"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"anyhow",
"directories",
@@ -2207,13 +2207,14 @@ dependencies = [
"gpui-pre-platform",
"log",
"notify",
"semver",
"serde_json",
"tempfile",
]
[[package]]
name = "ely-web-content"
version = "0.1.0"
version = "0.1.1"
dependencies = [
"anyhow",
"cef",
+2 -2
View File
@@ -5,7 +5,7 @@ members = ["apps/*", "crates/*"]
exclude = ["engines", "reference"]
[workspace.package]
version = "0.1.0"
version = "0.1.1"
edition = "2024"
rust-version = "1.95"
license = "AGPL-3.0-or-later"
@@ -17,7 +17,7 @@ encoding_rs = "0.8"
jiff = "0.2"
anyhow = "1"
directories = "6"
ely-gpui-component = { git = "https://github.com/ZacharyZhang-NY/Ely-GPUI-Components", rev = "69265b4fd4da888e2d8e1268021af4d358e67afb" }
ely-gpui-component = { git = "https://git.zacharyzhang.com/ZacharyZhang-NY/Ely-GPUI-Components", rev = "5d6efd46ec0c93b381ec7578561a1273c366025b" }
env_logger = "0.11"
gpui = { package = "gpui-pre", version = "=0.3.8", default-features = false, features = ["stacker"] }
gpui_platform = { package = "gpui-pre-platform", version = "=0.3.8", features = ["font-kit"] }
+3 -3
View File
@@ -529,7 +529,7 @@ AI 或脚本修改文件与其他外部修改使用同一套处理规则。ElyMa
### 15.2 接入基线
后端以 Kigi CLI(https://github.com/ZacharyZhang-NY/Kigi-CLI,Rust)为基础,以 Rust 依赖直接嵌入,不用 ACP(用户 2026-10-05 定)。提供商登录(订阅账号或 API 密钥)、模型与端点配置沿用 Kigi 的实现,不另写一套。不解析终端装饰文本来伪造结构化事件。
后端以 Kigi CLI(https://git.zacharyzhang.com/ZacharyZhang-NY/Kigi-CLI,Rust)为基础,以 Rust 依赖直接嵌入,不用 ACP(用户 2026-10-05 定)。提供商登录(订阅账号或 API 密钥)、模型与端点配置沿用 Kigi 的实现,不另写一套。不解析终端装饰文本来伪造结构化事件。
会话恢复只在 Kigi 的会话存储支持并通过验证时启用。不能把本地历史回放当成后端会话已经恢复。
@@ -870,10 +870,10 @@ UI 自动测试、内核测试和手工交互测试互相补充。三端的输
核对日期:2026-10-01。来源用于确认接口、项目结构和许可条件,不证明 Ely 已完成接入。产品功能、默认设置与性能目标由本文定义。正式实现应记录所采用版本的固定提交和许可证,而不是只引用默认分支。
[S1] Ely GPUI Components,README,组件库使用方式、主题及许可证。
`https://github.com/ZacharyZhang-NY/Ely-GPUI-Components/blob/main/README.md`
`https://git.zacharyzhang.com/ZacharyZhang-NY/Ely-GPUI-Components/blob/main/README.md`
[S2] Ely GPUI Components,TASKS,组件分类与 host/prove 等状态定义。
`https://github.com/ZacharyZhang-NY/Ely-GPUI-Components/blob/main/TASKS.md`
`https://git.zacharyzhang.com/ZacharyZhang-NY/Ely-GPUI-Components/blob/main/TASKS.md`
[S3] LibreOfficeKit 官方文档,C/C++ 接口、分块渲染和输入回调。
`https://docs.libreoffice.org/libreofficekit.html`
+27 -6
View File
@@ -39,7 +39,7 @@ site/ 官网(Vite 8、pnpm、TypeScript,无框架;等轴 SVG 积木
## 组件映射
依赖 `ely-gpui-component`(pin 69265b4,gpui 为 crates.io 的 `gpui-pre` =0.3.8)。名字取自 `reference/Ely-GPUI-Components/src`。gpui 用法规则见该仓库 `AGENTS.md`。`tests/scripts/agents_md.py` 核对下表每个名字都是组件库公开项。
依赖 `ely-gpui-component`(pin 5d6efd4,gpui 为 crates.io 的 `gpui-pre` =0.3.8)。名字取自 `reference/Ely-GPUI-Components/src`。gpui 用法规则见该仓库 `AGENTS.md`。`tests/scripts/agents_md.py` 核对下表每个名字都是组件库公开项。
| 需要 | 用 |
| --- | --- |
@@ -139,7 +139,10 @@ packaging/icons/build.sh 由 assets/icons 的母版渲染 icns、png、ico
tests/scripts/icons.sh 八个图标齐全、未过期,macOS 为 squircle,其余无底形
tests/scripts/release-macos.sh dist 里首批六个 .app:以访达的方式打开文件(启动与运行中),引擎都取自包内,带齐许可,不含系统会登记的内嵌包,每个二进制要求的系统不高于应用所写;源码包齐全
tests/scripts/hardened-macos.sh ELY_SIGN_IDENTITY 签名(hardened runtime)的 ElyMark 照样画出页面
tests/engines/*.sh 引擎探测(LOK、MuPDF、libetpan)
tests/engines/*.sh 引擎探测(LOK、MuPDF、libetpan);LOK 探测本构建的内核,不挂载官方镜像
scripts/inert-lo.sh 路径.app 构建出的 LibreOffice.app 去掉文档类型、URL 类型、快速查看与聚焦插件并注销(build-libreoffice.sh 调用)
scripts/extract-official-lo.sh 用 7zz 把官方镜像的 Frameworks 与 Resources 解到 engines/lo-official(不挂载,无包,“未打补丁即拒绝”的单测用)
tests/scripts/lo-unregistered.sh “打开方式”里没有 LibreOffice,构建出的包不声明任何文件类型
tests/scripts/lokview.sh 真窗口里的 LokView:输入法、键入、点击、拖动,AX 树里的段落文本;ELY_CLIPBOARD_TEST=1 再测复制粘贴(会覆盖系统剪贴板)
tests/scripts/doc-shell.sh 真窗口 ElyDoc:空白标签进 AX 树,启动后 Cmd+N 打开新建对话框(需辅助功能权限)
tests/scripts/doc-props.sh 真窗口 ElyDoc 属性栏:段前段后连续键入、回车、失焦,读 AX 值与命令数(需辅助功能权限)
@@ -155,6 +158,9 @@ tests/scripts/mark-output.sh 真窗口 ElyMark:专注模式与外观持久
tests/scripts/mark-outside.sh 真窗口 ElyMark:外部替换、改名、删除、冲突比较、自动保存、退出与崩溃后的恢复(需辅助功能权限)
tests/scripts/mark-tools.sh 真窗口 ElyMark:查找替换、正则、Tab、列表、表格、拖放与粘贴图片(需辅助功能权限;ELY_CLIPBOARD_TEST=1 再测粘贴)
tests/scripts/comments-rules.sh comments.py 对长注释与跨行注释报错
tests/scripts/bad-settings.sh 通用设置读不出时 ElyDoc 照样启动,文件不被覆盖
tests/scripts/one-instance.sh 第二份 ElyDoc 被拒,第一份的工作目录不动
tests/scripts/update.sh 装好的 ElyTree 从本机服务的新版下载、替换、重新打开(需辅助功能权限)
tests/scripts/settings.sh 真窗口:ElyPDF 设置里选深色,ElyTree 即刻变深;作者名写入、不丢外观;ElyTree 拒绝非 Git 程序;设置文件读不出时提示且不覆盖;主窗口重开回到原处(需辅助功能与屏幕录制权限)
tests/scripts/privacy.sh 真窗口 ElyDoc:键入的文字不进日志;worker 的日志进应用日志;设置里的诊断先列出所含内容,导出的文件去掉家目录与姓名、不含正文(需辅助功能权限)
tests/scripts/panels.sh 真窗口 ElyDoc:左侧栏默认不宽于 230、拖动内侧边缘变宽、宽度存入设置、重启后照旧(需辅助功能权限)
@@ -163,12 +169,14 @@ tests/scripts/recovery.sh 真窗口 ElyDoc:恢复点、崩溃后副本、
tests/scripts/pdf-recovery.sh 真窗口 ElyPDF:加锁文件的封存恢复点、空闲引擎退出后重开时再问密码(需辅助功能权限)
tests/scripts/autosave.sh 真窗口 ElyDoc:自动保存开关、停手即写、外部改动不覆盖(需辅助功能权限)
tests/scripts/print.sh 真窗口 ElyDoc:打印用文档自己的纸张,取消不动文档(需辅助功能权限)
tests/scripts/show-fullscreen.sh 真窗口 ElyShow:F5 放映的窗口盖住整块屏幕(菜单栏与程序坞之上,需辅助功能权限)
tests/scripts/types.sh packaging/types.tsv 的文件类型在 Linux 桌面项、Windows 安装程序与 macOS 文档类型里一致,从不设为默认
tests/scripts/layout.sh 真窗口:六个应用在 640、800、1100 宽下无元素越出窗口左右,留截图(需辅助功能与屏幕录制权限)
tests/scripts/ooxml.py <用例> <文件> 不经 LibreOffice 读 DOCX、XLSX、PPTX 并按自算的预期核对(往返用例调用)
tests/scripts/webview.sh 真窗口 CEF 页面:输入法组字与提交、键入、焦点、主题变量、缩放、不可离开所在文件夹
cd site && pnpm deploy 官网构建并经 wrangler 发到 Cloudflare Workers(只有静态资源),地址 https://ely-office.zhangyanghaha0407.workers.dev
cd site && pnpm test && pnpm e2e 官网单测(几何、道路连通)与 Playwright 端到端(悬停、聚焦、按压、命中归属)
cd site/video/scenes && npm run verify 发布视频:群像与离场两个渲染器在切场处屏幕角点一致,离场全程各屏播自己的录屏帧(真页面渲染)
cargo check --workspace
cargo test --workspace
rm -rf target/debug/incremental 每次构建或测试后都删(用户定:增量缓存会占满磁盘)
@@ -179,8 +187,8 @@ cargo run -p ely-doc 启动一个应用(ElyDoc 先 cargo build -p ely
## 决策
- 2026-10-01:上游版本以 `scripts/fetch-references.sh` 为准。LibreOffice 26.2.6(8221e31)、MuPDF 1.28.5(8ad45e9)、gpui 为 `gpui-pre` =0.3.8 与 `gpui-pre-platform` =0.3.8(crates.io,2026-10-07 起,随组件库 K01)、组件库 69265b4(2026-10-08 起)。
- 2026-10-02:组件库 7380afb 起:对话框与面板的 Enter 提交改走字段的 key-down 动作(macOS IME 天然守卫,不再提前提交);面板族文案经组件 `i18n::text`(内建 en/zh-CN,应用目录可覆盖);核心控件带 role/aria;对话框带角色、名称与说明,Cancel/Close 与禁用说明本地化。同仓库 `~/Documents/GitHub/Ely-GPUI-Components` 修复并经 SSH 推送(本机 HTTPS keychain 令牌失效)。2026-10-04 组件库 b6cb94c:`NumberInput::on_commit` 只在 Enter、失焦、步进、拖动时触发,键入不触发;改文档的数值框用它,否则每个键入数字都成一条内核命令与一步撤销。同批带入上游的 Checkbox、Switch、Select 等 role/aria 与 RenderSurface。c0f17ee:`ToggleButton::disabled`(不可按、无 Tab 停靠、说明不可用,提示可写原因)。967d1e4:`ContextMenu::manual`(按属主编号的请求在某点打开,右键不开),供行在按下之后才到的菜单,如内核给的拼写建议。
- 2026-10-01:上游版本以 `scripts/fetch-references.sh` 为准。LibreOffice 26.2.6(8221e31)、MuPDF 1.28.5(8ad45e9)、gpui 为 `gpui-pre` =0.3.8 与 `gpui-pre-platform` =0.3.8(crates.io,2026-10-07 起,随组件库 K01)、组件库 5d6efd4(2026-10-09 起)。
- 2026-10-02:组件库 7380afb 起:对话框与面板的 Enter 提交改走字段的 key-down 动作(macOS IME 天然守卫,不再提前提交);面板族文案经组件 `i18n::text`(内建 en/zh-CN,应用目录可覆盖);核心控件带 role/aria;对话框带角色、名称与说明,Cancel/Close 与禁用说明本地化。同仓库 `~/Documents/GitHub/Ely-GPUI-Components` 修复并推送(2026-10-09 起推到 git.zacharyzhang.com,HTTPS,令牌在本机钥匙串)。2026-10-04 组件库 b6cb94c:`NumberInput::on_commit` 只在 Enter、失焦、步进、拖动时触发,键入不触发;改文档的数值框用它,否则每个键入数字都成一条内核命令与一步撤销。同批带入上游的 Checkbox、Switch、Select 等 role/aria 与 RenderSurface。c0f17ee:`ToggleButton::disabled`(不可按、无 Tab 停靠、说明不可用,提示可写原因)。967d1e4:`ContextMenu::manual`(按属主编号的请求在某点打开,右键不开),供行在按下之后才到的菜单,如内核给的拼写建议。
- 2026-10-06:审查者为探针复制的源码树须用自己的 `CARGO_TARGET_DIR`(`scripts/review.sh` 写明);写完结论前删掉这些副本与其构建目录(曾积到 /tmp 近 900 GB,磁盘写满、链接失败):曾编进本仓库 `target/`,ely-lok 里烘焙的源码路径指向已删的副本,单测找不到 worker。
- 2026-10-03:每条任务由 `scripts/review.sh` 在 herdr 分栏里交给 codex(gpt-6.1-sol,effort high;本机 `codex` 别名已带 `--yolo`,重复传参会报错)审查,最多三轮。此前各轮用 gpt-6-astra xhigh。
- 2026-10-01:macOS 的 LOK 用自建 LibreOffice 26.2.6.3 加 `patches/libreoffice/0001-lok-macos-tile-painting.patch`(已验证出图块)。2026-10-03 加 `0002-lok-dispatch-to-document-frame.patch`:`postUnoCommand` 原发往桌面的活动框架,另一文档关闭后命令落空或落到别的文档;改发本文档的框架。2026-10-04 加 `0003-lok-char-style-and-spacing-states.patch`:LOK 原不发当前字符样式与段前段后,属性栏无从同步;补发 `.uno:CharStyle`(界面名,无字符样式为空)与 `.uno:ULSpacing`(`上,下`,1/100 mm);混合选区的状态发 `{"commandName","dontcare":true}`,`ely_lok::MIXED` 表示,段落样式跨段不一致也算混合(原样报首段),字符样式带来的字体、字号、粗斜体等在选区内不一致也算混合(原样只看直接格式)。`.uno:ULSpacing` 缺的成员归零,故两值同发;属性栏记住已发未回显的两值状态(段距、页边距),连续编辑以它为底。同日加 `0004-lok-panel-states.patch`:补发页面尺寸、页面项(横向、版式、页码格式)、页边距、分栏、页眉页脚开关与版式、四种锚点与六种环绕(真假或禁用)、标题行重复;页面项缺的成员同样归零,故转向时页面项与尺寸都发。`0005-jsdialog-skip-disposed-dialogs.patch`:对话框守卫关闭对话框后,JSDialog 空闲任务仍为它生成整窗更新,读已释放窗口崩溃(实测崩溃报告),补丁让已释放的对话框不再生成消息。`0006-page-size-takes-the-page-item.patch`:`.uno:AttributePageSize` 也收页面项,转向是一次改动、一步撤销。`0007-lok-aqua-anyinput-without-peeking.patch`:worker 的请求经主 GCD 队列派发,而 Aqua 的 `AnyInput` 用 `nextEventMatchingMask` 窥探时会转动 run loop、在内核空闲任务中途执行请求(实测:表格删列与排版空闲任务交错,`SwLayIdle::DoIdleJob_` 段错误,约三成全量测试复现);补丁让 LOK 下的 `AnyInput` 改问客户端,worker 以 `registerAnyInputCallback` 报告是否有待处理请求,请求只在顶层让出时执行(补丁后连续十次全绿)。`0008-lok-toc-caption-formula-without-dialogs.patch`:目录、题注、公式在内核只有对话框入口;补丁给 `.uno:InsertMultiIndex` 加 `Title`(默认目录)、`.uno:InsertCaptionDialog` 加 `Category`(程序名)与 `Text`(照内核题注对话框的选项)、`.uno:InsertObjectStarMath` 加 `Formula`(文字转公式,选中公式时整体替换,一步撤销),并加 `getCommandValues(".uno:Formula")` 读选中公式。插入目录后光标落在目录内(内核原样)。`0009-lok-word-count-values.patch`:`getCommandValues(".uno:WordCount")` 给文档与选区的字数、字符数;内核的 `.uno:StateWordCount` 状态是英文串,只作重读的信号。构建加 `--with-myspell-dicts`,随包词典取自 LibreOffice 的 dictionaries 子模块(core 钉的 9925407,来源与许可见各目录 README 与 license),装在 `Resources/extensions`。构建后只留 `dict-en`(25 MB,英语拼写、断词、同义词):界面语言是英文与简体中文,中文无 Hunspell 词典;全部 65 个(473 MB)时 LOK 首启 5.4 秒、再启 2.3 秒,只留英文为 1.1 秒与 0.7 秒(PERF-01 要求 3 秒内可操作)。词典语种已由用户定:英文。`0010-lok-outline-values.patch`:`getCommandValues(".uno:Outline")` 给各标题的文字、级别、位置(twips)与是否当前(光标所在处按文档顺序之前最近的标题,`GetOutlinePos`;分栏时位置比不出先后),`.uno:Bookmarks` 的每项加位置(版面不显示的书签无位置);导航栏的跳转都按位置。`0011-lok-font-lists-present-when-a-member-is-used.patch`:LOK 把以 `;` 连写的字体列表整串当作字体名,列表中有字体已用上也报缺失(实测报出界面字体的回退列表);补丁让列表中任一成员用上即不算缺失,文档里写的列表全缺时照报。`0012-lok-calc-cursor-references-merge.patch`:Calc 在回调注册后补发单元格光标;`.uno:SheetReferences?sheet=N` 给引用某表的公式格数、命名区域数、第一个公式格,以及用 INDIRECT 的公式与名称数(这类引用运行时才知指向,删除说明里单独列出);合并带 `MoveContents` 时不弹对话框,并修上游“多个数据格的 API 合并什么也不做”。worker 以 `SAL_LOK_OPTIONS=sc_print_twips_msgs`(macOS 另加 `unipoll`)运行,Calc 的光标、选区与 `.uno:SheetGeometryData` 同为文档 twips;视图把可见区经 `setClientVisibleArea` 报给内核。`0013-lok-author-option.patch`:`lo_setOption("author", 名)` 设内核用户全名,新批注与修订以此署名。`0014-lok-calc-formula-entry-and-names.patch`:公式语法错误不弹询问、补全不切走编辑、提交清引用标记、名称的可撤销定Line truncated
@@ -195,8 +203,8 @@ cargo run -p ely-doc 启动一个应用(ElyDoc 先 cargo build -p ely
- 2026-10-01:MailCore 2 的子模块 libetpan 过旧,改钉 libetpan master `4d47862`。
- 2026-10-01:每个应用的全部数据在 `<本机数据目录>/ElyOffice/<slug>/`,路径由 `ely_platform::data_dir` 给出。卸载只动这里,且先问。用户文档永不碰。
- 2026-10-04(用户定):macOS 包标识前缀 `ely.zacharyzhang.office`(`packaging/macos/bundle.sh`);发布者 ZacharyZhang,网址 zacharyzhang.com(macOS `NSHumanReadableCopyright`,Windows 卸载项 `Publisher` 与 `URLInfoAbout`;Linux 桌面文件无此字段)。界面语言英文与简体中文,以后再加。拼写词典只随英文:LibreOffice 的词典库没有中文(中文不用 Hunspell 拼写)。内核界面语言固定英文,函数名照英文;ElyTable 把内核英文的选区统计(Sum、Average 等七个固定名)换成界面语言,数值照内核。批注与修订的作者取各用户的账户全名(无全名用登录名,与内核自身次序一致),由补丁 0013 的 `setOption("author")` 在 worker 启动时设定;作者设置页随设置任务接入。邮件合并字段写法 `«列名»` 由我定(用户交我决定)。
- 2026-10-01:更新清单是 JSON:`{"version", "assets": {"<os>-<arch>": {"url", "sha256"}}}`,只走 https(本机回环除外)。检查、下载、校验在 `ely_platform::update`,从不静默安装。包管理器安装的 Linux 版本不自更新。清单地址由设置给出,尚未配置。
- 2026-10-05(用户定):ElyAgent 的后端与内置模型的登录配置以 Kigi CLI(https://github.com/ZacharyZhang-NY/Kigi-CLI,Rust)为基础,以 Rust 依赖直接嵌入,不用 ACP;沿用其提供商登录(订阅账号或 API 密钥)与模型配置。
- 2026-10-01:更新清单是 JSON:`{"version", "assets": {"<os>-<arch>": {"url", "sha256"}}}`,只走 https(本机回环除外)。检查、下载、校验在 `ely_platform::update`,从不静默安装。包管理器安装的 Linux 版本不自更新。2026-10-09 起(用户定:0.1.2 加自动更新):每个应用一份清单,`<slug>.json`,随发布上传,应用经 git.zacharyzhang.com 的 API 读最新发布(`api/v1/repos/ZacharyZhang-NY/ElyOffice/releases/latest`),在其文件里找 `<slug>.json`(`ely_platform::release::asset_url`;Gitea 没有 `releases/latest/download` 路径;`ELY_UPDATE_MANIFEST` 直接给清单地址,测试用);只在从 `.app` 运行时可用(开发构建没有);照 PRD §4.2 自动检查默认关闭:设置“通用”的“启动时检查更新”(通用设置 `check_updates`)打开后启动时查一次、查不到只记日志,应用菜单的“检查更新…”随时手动查(已是最新或查不到都以提示写明);有新版即在窗口上方显示组件库的 `UpdateBanner`(文案进内建中英目录,组件库 5d6efd4):横幅在标题栏下方(`Shell` 的页眉里,`Updates` 自己是一个视图);下载(进度)、校验散列、“重新启动以更新”只走正常的退出流程(有未保存的照常询问;取消即什么也不装,按钮仍在);应用真正退出时(`on_app_quit`)以本程序的安装模式(`--ely-install-update dmg 包 进程号`,`ely_ui::run` 最先识别)起一个独立进程:等本进程结束,`ely_platform::install` 挂载 dmg、把同名 .app 拷到旁边再换掉原包(换上前失败即放回原包),无论成败都 `open` 该包;失败的原因写在数据目录 `updates/failed.txt`,重开的应用以提示写明。下载完成只归属于它下载的那个版本;下载中或已下载时再查不覆盖。`packaging/macos/release.sh` 为每个应用写出清单(版本、本机架构的 dmg 地址与 SHA-256),dmg 里另有指向“应用程序”的替身,可直接拖入。新包换上即为装好,旧副本删不掉只记警告。`tests/scripts/update.sh`:装好的 ElyMark 在默认设置下启动不发任何请求;按“检查更新…”后从本机服务的 9.9.9 下载;有未保存的文字时“重新启动以更新”先问,取消则原包不动,“不保存”后装上新版并重新打开(新版本身的进程在跑)。
- 2026-10-05(用户定):ElyAgent 的后端与内置模型的登录配置以 Kigi CLI(https://git.zacharyzhang.com/ZacharyZhang-NY/Kigi-CLI,Rust)为基础,以 Rust 依赖直接嵌入,不用 ACP;沿用其提供商登录(订阅账号或 API 密钥)与模型配置。
- 2026-10-05(用户定):八个应用都不许卡顿:键入、选择、滚动、文档渲染都要即时(GPUI 的 120 FPS 手感),树莓派 3 上也要流畅。输入延迟与帧时间是验收项,要实测;界面线程不等内核、不持 worker 锁做同步请求,空闲不做事。
- 2026-10-05:LOK 的输入与事件路径(实测后定)。原样:视图的事件监听长轮询 worker(持 worker 锁最多 50 毫秒,worker 读线程也随之阻塞最多 250 毫秒),按键排在锁后,键入锁等待中位 290 毫秒、最长 9 秒;输入队列在界面执行器上逐条跳回界面线程,每键约一帧,连续键入积压到 1 至 2 秒。现在:worker 有新事件即主动推送(`tag::EVENTS`,推送线程在输出锁下取批,批次即发送时状态),客户端读线程把回复与事件分开,事件存入 `client::Feed`,视图以异步方式等它(`Feed::next`,有新批次时唤醒,不占线程、不碰 worker 锁;原先每个打开的文档阻塞一个后台线程最多一秒,文档多于核数时会饿死输入与图块;监听任务归视图所有,视图释放即停);每个视图一条后台通道(`view/lane.rs`),输入优先、图块其次,连续执行,界面线程只收落地结果;文档尺寸与页框只在内核报尺寸变化时在后台读;批次弄脏的已显示图块即刻重绘,不等下一帧;视图的 `Reported` 事件只在内核回报或输入落地时发出,滚动与图块到达不触发应用的观察钩子;编辑与光标移动后应用要读的内核列表(ElyDoc 导航、字数、审阅,ElyTable 工作表与几何、单元格规则、格式面板)经 `ely_lok::read_off` 在后台读,一次一个,结果按发起者核对。实测(macOS,`tests/scripts/lag.sh`):按打字速度键入时输入落地 0 至 1 毫秒,图块 1 至 3 毫秒,按键到新图块 ElyDoc 中位 19 毫秒、ElyTable 3 毫秒;连续快速键入(脚本一次送出近百字)时,各次运行在 3 至 225 毫秒的中位之间摆动:新文档首次键入时内核有一次 150 至 230 毫秒的冷启动(首块图块与拼写等初始化),同一批字排在它之后;原为中位 1 秒、p95 1.9 秒。树莓派 3 未实测(本机无设备)。界面线程不碰 worker:应用对内核的读取、保存与另存为的导出、导出 PDF、比较、邮件合并都经 `Tabs::read_in`(或 `ely_lok::read_off`)在后台执行,回到窗口时按发起的标签与读取时的状态核对;保存导出期间标签状态为“正在保存”,同一标签的后续保存排队到它结束;另存为在写入前按文件身份再查一次目标是否已被别的标签持有;导出期间又有编辑时,“保存后关闭”不关闭,回到关闭询问;关闭标签时的撤销历史也在后台读;邮件合并预览与比较在发起时就保留自己的标签号与工作目录;读取失败不立即重试,等下一次状态变化;载入时一并在后台读版面与撤销历史(`ely_lok::layout`,`LokView::open` 接收版面)。窗口关闭回调先不放行,在后台逐个读标签的撤销历史并关闭(有改动的照常询问),最后一个标签关闭后移除窗口;内核文档的关闭也在后台(2026-10-06 起,原先同步读历史、在界面线程持 worker 锁关闭)。
- 2026-10-04(用户定):八个应用的内容区一律随系统深浅色:Doc 页面、Table 网格、Show 幻灯片、PDF 页面、邮件正文、Mark 编辑区、Agent 输出。自动颜色随之翻转,文件里写明的颜色照原样;打印与导出 PDF 仍为浅色。各引擎(LOK、MuPDF、CEF)接入应用主题,不留引擎默认色。LOK:`ely.xcd` 定义 `COLOR_SCHEME_ELY_DARK` 与 `COLOR_SCHEME_ELY_LIGHT`(文档底色、自动文字色、网格、链接等取 Ely 默认色板;内核自带的深色方案颜色留空、按应用外观取默认值,传方案名不改外观,所以不用它),`LokView` 在主题深浅变化时经有序队列发 `.uno:ChangeTheme`(不算编辑),页面底色深色取 `surface`、浅色取 `paper`;Omarchy 色板与这两套固定色可能略有差别。导出 PDF 实测仍为白底。图块作废时旧图仍显示,新图到达后替换,编辑与主题切换都不闪。
@@ -257,3 +265,16 @@ cargo run -p ely-doc 启动一个应用(ElyDoc 先 cargo build -p ely
- 2026-10-06:ElyPDF 文字、图片与对象编辑(C11.3,PDF-03、04,§11.3)。字体(用户定):文档自带字体(能写新字时)或 MuPDF 内置的 Helvetica、Times、Courier(不嵌入,WinAnsi)与 Noto 中日韩(不嵌入,UTF-16 的 Adobe CJK 字体),不扫描系统字体;自带字体以 CID 字体(Identity-H,按字形号写)写入。对象(用户定):图片与表单 XObject。文字块以 MuPDF 的 stext 为准(同一读法,块序号稳定);可编辑的块须横排,且每个字形都在页面自身的内容流里(以不落盘的过滤试跑核对,表单里的字不可改)。改字是一步:用内容过滤的 `text_filter` 去掉该块的字形(按字形原点在用户空间 0.5 点内且字符相符,不靠白块遮盖),再在原首行基线处按框宽排版写新字(空格处折行,太长的词断开,行距沿用原块);所有检查(块文字未变、横排、字形都在页面内容里、字体画得出每个字、排版)都在开步之前,拒绝时文档与重做都不动;画不出某字即告知是哪个字,界面请用户换字体;换了字体、字号改变或新文字越出原块的框时先出预览(在快照副本上改并画出该区域,文档与撤销历史都不动),确认后才写。行距取首行与下一条不同基线的距离(同一基线的几段不算行),没有即字号的 1.2 倍。新文字在点击处起框。新增内容第一次写入时把页面原内容包进 `q … Q`(以 `%Ely` 标记,只包一次)。图片与表单:清点处理器按 `q`、`Q`、`cm` 跟踪,列出页面顶层的每次 `Do` 与其页面框;移动、缩放(右下角柄,保持比例、左上不动)以 `X = C·T·C⁻¹` 包住该次绘制重写内容流,删除即不写该次 `Do`,替换图片是新图片资源、按比例放进原框中央;添加图片落在当前页中央(像素按点、缩到页面一半以内)。MuPDF 的字体与图片资源缓存不随撤销与放弃回退(实测:预览后再写,字体引用指向已不存在的对象),每次放弃、撤销、重做后清空。编辑工具在“编辑”菜单(编辑文字和图片、添加文字、添加图片…),Esc 退出(键位上下文在窗口根上,页面与面板里都管用);替换、添加与删除图片和表单、拖动移动与缩放、写字与预览的确认都绑定发起的标签与视图版本,执行前视图须未变且无排队的编辑,否则提示不执行;任何编辑落地即关掉此前的预览;图层读取在回来时总清掉进行中的标记,编辑之前发出的读取作废后重读;右侧编辑面板:文字、字体、字号、颜色、框宽,应用、删除文字;对象:替换图片…、删除。真窗口(macOS)改过一次字:同字体同位置替换,标签为已编辑。
- 2026-10-06:ElyPDF 页面组织(C11.2,PDF-02)。worker 打开即开 MuPDF journal;插入空白页、从文件插入(整份 PDF 嫁接)、删除、移动、旋转(90 度倍数,写页面的 `/Rotate`)、裁剪(按所见的上右下左边距设 `/CropBox`,全零即去掉)、撤销与重做都是一步,回复带历史标记(worker 按 MuPDF 的撤销位置记每步是编辑还是保存,标记是最后一个已做的编辑;撤销重做跳过保存步)。删除时指向已删页的书签保留但失去跳转,链接移除,表单字段去掉已删页上的控件;页码标签由 MuPDF 的删除与插入随之平移。坏的编辑(删光、页码乱序、非 90 度、边距超出页面)拒绝并回滚整步。保存(Save、Save As 走外壳)先 `pdf_save_snapshot` 写出(不动内存中的文档与撤销历史,靠补丁 0001),再打开该副本以 `garbage=2` 紧缩写到工作目录(已删页的对象不留在文件里),加密文件以用户输入的密码重开副本、照原加密写出(密码只在 worker 内存);外壳读回字节、原子写入。提取(选中页写新文件,经 `ely_files::export`,不覆盖打开着的文件,被别的标签持有即拒绝)在快照副本上删去其余页再紧缩写出,原文档的撤销与重做都不动;拆分按每份页数写到所选文件夹(`名称-序号.pdf`,先以 `ely_files::claim_all` 占下全部目标,任一已存在即一个不写;原 ElyShow 的同名函数移入 ely-files 共用)。合并即从文件插入到末尾再另存;插入的页带着自己的批注、链接与表单字段(指向源文件自身页的链接改指插入后的页,字段并入表单,重名的加序号,如 `field0 2`(名称按需分配,长名也终止),源表单的默认外观 `/DA` 与默认对齐 `/Q` 给到没有自己值的字段树根,源表单的字体资源并入目标 `/DR`,同名而不同的字体改名为 `名称_2` 并改写字段外观里的引用(按 PDF 名称语法解 `#xx` 转义,写出时照样转义);源文件的书签不并入)。删除时表单控件按被删页的 `/Annots` 认定,不只看可省略的 `/P`。裁剪边距以所见为准:先按视图旋转、再按页面 `/Rotate` 换到页面自身方向,并按 `/UserUnit` 换算。编辑失败也通知外壳队列已动,等着的保存、关闭不会挂住。结构编辑后区间点选的起点作废。应用:每个视图一条编辑队列,一次一条、按序执行,落地后重读页数、尺寸与书签,清掉图块、文字、缩略图、找到的词与选择,视图版本加一,此前发出的读取回来即丢;查找在编辑后重查。修改标记是当前历史与载入或上次保存时的历史不同,撤销回到保存点即为已保存(外壳新增 `Engine::saved` 与 `Session::reverted`:引擎回报未修改时 Dirty 回到 Saved,保存中、冲突、失败不变)。左栏是页面缩略图(`side.rs`;有书签时上方分段切换到书签):点选、Shift 连选、Cmd 增减,右键菜单,拖到某页之前即移动(移动后仍选中),Delete 删除;无选中时作用于当前页。“页面”菜单与“编辑”菜单的撤销(Cmd+Z)、重做(Shift+Cmd+Z)。裁剪对话框以毫米输入。MuPDF 的构建改为在 `engines/mupdf-src`(reference 只读)打 `patches/mupdf` 后编译。
- 2026-10-06:ElyPDF 阅读(C11.1,PDF-01)。MuPDF 只链进 `ely-pdf-worker`(`crates/ely-pdf-engine`,build.rs 把 C 垫片 `shim/ely_mupdf.c` 与 `libmupdf.a`、`libmupdf-third.a` 只链给这个二进制),应用不链 MuPDF。build.rs 以协议、垫片与 worker 源码的散列为版本戳,应用启动 worker 先握手(`HELLO`),戳不同即拒绝(单测不重建 worker,旧二进制曾被误用)。worker 在打开第一个文件时才启动(PERF-01),`tests/scripts/pdf-idle.sh` 查空白窗口无子进程。垫片每个调用都在 `fz_try`/`fz_catch` 里,返回码加最后一条错误信息,MuPDF 的跳转从不越过 Rust。worker 与应用之间是 `ely-ipc` 的帧(从 ely-lok 抽出,两者共用):打开(锁定即报)、解锁、页数、页框、渲染一块(设备像素、缩放、旋转、深色)、按阅读顺序的字符与外框、页内搜索(每处命中及其全部四边形,跨行短语算一处,数量不设上限)、书签(JSON)、关闭;文件读不出只报错,worker 照常工作。查看器:打开时只读页数、前 100 页尺寸与书签,其余尺寸后台每批 100 页补齐;视图只排屏上的页(连续、单页、双页;适合宽度、适合页面、实际大小与缩放档;视图旋转 90°),按 512 设备像素一块请求,一次一块、由近及远,只留屏上的块(横纵两向),后台回来的块不在屏上即弃;画不出的块记下不再请求,换文档或重开前不重试;深色外观下页面按亮度反相(MuPDF `fz_invert_pixmap_luminance`,色相保留)。文字选择按字符、可跨页,复制按行换行,未读的页先读;查找每批 20 页在后台进行,命中逐个跳转并标出,Esc 关闭(组件库 617a8d6);书签栏用 `lists::Outline`,点即跳到页与位置。切换视图、缩放、旋转后仍停在正在读的那页。加密文件打开时问密码(外壳的密码框,见上一条),错了再问,取消即不打开。没有页的文件报错并关闭,不开标签。双页时同一行在视口内的两页都可为当前页;当前页只在横纵两向都可见的页里定,跳转在目标页左缘不在视口时横向移过去。图块按视口半开区间取。首次按下时文字未读,读到后照原按下处起选;查找结果按查找实例与所属标签核对,只在该标签为当前时跳转。书签为空时不留左栏。启动参数里的文件直接打开。
- 2026-10-09(用户定:“打开方式”里不得出现 LibreOffice):系统会登记磁盘上能找到的 .app、挂载镜像里的 .app 与运行过的包,构建目录里的 `LibreOffice.app` 与测试挂载的官方镜像曾因此成为 xlsx 等的默认程序。现构建后由 `scripts/inert-lo.sh` 去掉其全部文件与 URL 声明、快速查看与聚焦插件,注销它,并在 `engines/` 放 `.metadata_never_index`;Ely 只取其 Frameworks 与 Resources。任何脚本与测试都不挂载 LibreOffice 镜像:LOK 探测用本构建的内核,单测所需的官方内核由 `scripts/extract-official-lo.sh` 以 7zz 解成无包的文件夹。`tests/scripts/lo-unregistered.sh` 以 NSWorkspace 核对 docx、xlsx、pptx、odt、csv 的“打开方式”里没有 LibreOffice。
- 2026-10-09(用户报:ElyTable 点格跳到别处、拖不出选区):Calc 在 `sc_print_twips_msgs` 下以打印 twips(行高原值)报光标、选区与 `.uno:SheetGeometryData`,图块与鼠标却在图块 twips(每行按 `ScViewData::ToPixel` 截成整像素),两者随行号漂移(5000 行处约 140 行)。视图对外一律打印 twips;`LokView::set_geometry` 收下工作表几何后,`sheet::Axis::tile`、`print` 照内核的截断换算(每像素 twips 取图块的像素与 twips 之比),绘制、显示、跳转与冻结都先换成图块 twips,鼠标以图块 twips 发出(`tile_point`),拖动句柄仍为打印 twips;`.uno:` 读回与应用(表头、填充柄)照旧用打印 twips,表头的起点取 `LokView::scrolled_start`。内核读鼠标用的比例原取最后一块图块,worker 现于每次 `setClientVisibleArea` 前以 `setClientZoom` 告知图块比例,点击不再依赖先画过图块。
- 2026-10-09(用户报:ElyPDF 改字报“这种字体画不出 V”):文档自带的子集字体常无可用的 Unicode 表(LibreOffice 导出的子集表为占位,0x00 起逐一对应字形号),按 Unicode 找字形一律失败。现以“文档自带字体”写字时直接用页面上的那个字体对象(`shim/ely_pen.c`;`pdf_load_font` 按对象缓存,与文字层的字体同一对象),以它自己的编码写:按文字提取的读法(ToUnicode,缺项或坏值退回 cid_to_ucs,同 pdf-op-run.c)倒出 Unicode 到编码的表,排版取它的宽度(`pdf_lookup_hmtx`),原有的 ToUnicode 与宽度不动,两个字共用一个字形时各写各的编码(原先按字形号写、重建 ToUnicode,共用字形的字被改写,且 CMap 漏写条目数,PDFKit 读不出字)。删去原文字块后页面资源里可能已无该字体,故按对象号以新名字重新引用。只支持编码即 CID 的字体(简单字体与 Identity-H),其余拒绝并说明;页面上没有的字仍报缺字。排版按同一套宽度量出的框,比较时留 0.01 点的余量(原块宽度即这些宽度之和,浮点误差曾使末字折行)。
- 2026-10-09:ElyTable 的自动筛选(R2.9)。内核会重新推算未命名的自动筛选区:每次打开筛选列表时向下扩到紧邻的数据行(`ExtendDataArea`、`ExtendBackColorArea`,为接上后来追加的行),命令从单格找到它时按连续数据区重算(`ScDocShell::GetDBData`:应用条件、关闭筛选及其撤销);选区下方紧邻的合计行因此进了列表、随数据一起被隐藏,存后重开的筛选区同样会扩。补丁 `0040-lok-calc-autofilter-keeps-its-rows.patch`:LOK 下已有的自动筛选区保持设定时的行(同 Excel),不再隐式扩展(光标在区内时;光标在同表另一块数据里即按那一块);单格开筛选时仍取整个数据区。代价:紧贴在筛选区下方追加的行不自动并入,需重新选定后再开筛选。
- 2026-10-09:ElyTree 的差异按文件类型着色(R2.12)。组件库 7f2ac3e 至 b0dbfd4:`DiffViewer`(建立时按路径定下读法) 按路径的扩展名判定散文与纯文本(md、markdown、txt、rst、adoc、org、csv、tsv、log 等,无扩展名同,不着色),代码按语言着色(组件库 b0dbfd4 的 `forms::syntax`:Rust、JavaScript/TypeScript、类 C、Python、Ruby、Shell、YAML、INI、SQL、Lua、Haskell、Lisp、Erlang、TeX 与其他 `#` 语言各有行注释记号、关键字与常量;Shell 与 YAML 的 `#` 只在词首起注释;Makefile、Dockerfile、CMakeLists.txt 先按文件名认),不是完整的语法分析器(字符串插值、块注释、多行字符串照通用词法)(原先一律套 `//` 的通用词法,Markdown 的 `#`、Python 的注释都被当作代码上色)。同批带入上游的块编辑器跨块选择、浮层滚轮、输入法候选框位置、插入点按设备像素对齐与格式修正。
- 2026-10-09:ElyMark 的表格(R2.13)。表格的空格与分隔行写法有许多种(`|a|b|`、`|---|`、对齐空格),逐字重现做不到,原先凡写不回原样的表格都成了原文块。现在一块的序列化与原文在把其中每张表格化成规范形式(各列对齐方式加各格的原文,`tables.js` 的 `canon`)后相同,即为可视块(`preserve.js` 的 `kept`),引用与列表里的表格同样;格内有 Milkdown 会改写的写法(`[[…]]`、引用式链接等)即不同,整块仍为原文块,与段落的规则一致。Milkdown 的列表项必须以段落开头,表格作列表项的第一块时无法放进编辑器,照原文块保留。未改的表格照旧逐字写回,改过的表格按文档多数表格的写法重写(`style.js` 按表格的行节点投票:单元格两侧有无空格、是否按列对齐,经 remark-gfm 的 `tableCellPadding` 与 `tablePipeAlign`;原先投票的解析器不认 GFM,表格从未计票),分隔行随之重写(如 `|---|` 成 `| - |`)。
- 2026-10-09:ElyTable 新插图表的位置(R2.10)。内核按“定位区域”把图表放在其旁、并挤回当前可见区;带参数的请求(Ely 经 `FN_PARAM_5` 给区域)原把定位区域取为光标格,图表压在数据上或旁边的另一块数据上。补丁 `0041-lok-calc-chart-beside-its-data.patch`:LOK 下有请求区域时,图表放进数据区右侧(隔一列)第一块够大、无合并格的空单元格(逐列向右找,跨过旁边的数据块),右侧没有依次找下方、左侧、上方,再按行带找全表第一块够大的空处(尺寸从候选格起累加,表尾也快),不受可见区限制;空处按图表所在的工作表查,数据在别的表时从光标起找;整张表没有空处即插入失败、文档不动;`LokView` 在新选中对象(原先无选中)时把它滚入视口,拖动中的对象不滚动。
- 2026-10-09:ElyPDF 编辑与缩放不闪白(R2.6)。旧图块不再随编辑或比例变化即刻丢弃:编辑落地时全部当前图块、比例变化时离开视图的同页图块,连同当时的页面尺寸进入“底图”(`apps/ely-pdf/src/backdrop.rs`),按其在页面中的比例位置画在该页新图块之下,直到该页在视口里的新图块到齐、或页面尺寸与旋转变了才释放;每页画什么由 `PdfView::pieces` 决定,绘制与测试同用它。只有改内容的编辑保留底图并沿用已测的页面尺寸(前 100 页以外不再被占位尺寸覆盖);增删、移动、旋转、裁剪页面与撤销重做(`PdfView::edit_pages`)清空底图,因同一序号可能已是另一页。关闭标签时底图随图块交给窗口释放。原先比较整份尺寸表(超过 100 页的混合纸张文档尺寸表后段为占位,比较失败即全部清空)且只认同比例的图块(编辑后右栏收起、比例变化即清空),都会闪白。
- 2026-10-09:文档的缩放锚点(R2.7)。窄于视口的文档居中,缩放原按视口坐标求锚点、漏了居中的偏移,锚点随缩放漂移;现锚点先减去缩放前的偏移,缩放后按新的偏移(`LokView::slack`,绘制同用)换回。按键与菜单的缩放(无指针)另保持首页左缘在视口内;指针与捏合的缩放保持指针下的点不动(文档边界以外即止)。
- 2026-10-09:退出(缺陷清单 X-01)。Cmd+Q 与应用菜单的“退出”由应用级动作接收:主窗口的宿主在 `Closing::own_window` 里登记自己的退出流程(`ely_ui::commands::route_quit`),任何窗口(含设置窗口)发出的退出都经它逐个关闭标签、询问未保存的;宿主的窗口已不在时才直接退出;没有宿主的应用(ElyTree)直接退出。`Host::quitting` 在退出开始时运行(ElyMark 先记下打开的标签)。原先只有主窗口根上截退出,设置窗口在前时 Cmd+Q 不问即退,并把这次运行记为干净结束、删掉恢复点。
- 2026-10-09:作者名与读不出的设置(缺陷清单 X-02)。签名用的名字取启动时读入的通用设置(`ely_ui::settings::current`;文件读不出时为默认值,设置窗口另以 Banner 写明),`ely_platform::user::named(作者名)` 为空即用账户名;不再在引擎启动时重读文件(原先 `settings.json` 读不出时 Doc、Table、Show 以致命错误退出)。LOK worker 记下设定的作者名,引擎重启照用它。`tests/scripts/bad-settings.sh` 核对读不出的设置下 ElyDoc 照样启动、文件不被覆盖。
- 2026-10-09:每个应用只跑一份(缺陷清单 X-03)。`ely_ui::run` 在写日志之前取应用数据目录的 `instance.lock`(`ely_platform::instance::hold`;Unix 为 fcntl 记录锁,进程结束即放,被拒时以 `F_GETLK` 向系统问出持锁的进程号,不另存进程号文件,同时启动的几份也报得准;Windows 为 LockFileEx,不报进程号);已有一份在跑时第二份不启动,报“已在运行(进程号)”。原先第二份启动即清空第一份的工作目录、把它的恢复点当作干净结束删掉、改写崩溃锁。macOS 经访达打开文件本就交给运行中的那份;`open -n` 与 Linux 每文件一个进程时第二份被拒,文件须在已开的窗口里打开(未做转交)。`tests/scripts/one-instance.sh` 核对。
- 2026-10-09(用户定):代码与发布从 GitHub 搬到自建的 Gitea(git.zacharyzhang.com;GitHub 账号被封,推送与发布都被拒)。公开仓库 `ZacharyZhang-NY/ElyOffice`(原样推上 main、缺陷清单分支与 v0.1.0、v0.1.1 标签),组件库为同站的 `ZacharyZhang-NY/Ely-GPUI-Components`(Cargo 的 git 依赖与 `fetch-references.sh` 随之改址,钉的提交不变)。v0.1.1 的六个 dmg 与两个源码包重新发在 Gitea 的 v0.1.1 发布里。官网的下载与源码链接指向 Gitea(`releases/latest` 会跳到最新发布页)。`.github/workflows` 删去(它们靠 GitHub 的 macOS 机器与 `gh`,发布改在本机以 `packaging/macos/release.sh` 构建、经 Gitea API 上传)。发布视频里写的地址已在源文件改为 Gitea,已发布的成片仍是旧地址,重渲染后才更新。上游项目(LibreOffice、MuPDF、git-lfs、tessdata 等)照旧从它们自己的 GitHub 地址取。
+9 -8
View File
@@ -24,17 +24,18 @@ impl Docs {
let Some(counts) = self.active_tab().and_then(|tab| tab.extra.counts) else {
return status.when_some(zoom, |status, zoom| status.right(zoom));
};
let (words, characters) = (counts.words.to_string(), counts.characters.to_string());
let count = |key, n: u64| ely_ui::i18n::counted(cx, key, n, &[("n", &n.to_string())]);
let label = match counts.selected_words {
0 => Self::text(
cx,
"doc.count.words",
&[("words", &words), ("characters", &characters)],
),
selected => Self::text(
0 => {
let words = count("doc.count.word", counts.words);
let characters = count("doc.count.character", counts.characters);
Self::text(cx, "doc.count.words", &[("words", &words), ("characters", &characters)])
}
selected => ely_ui::i18n::counted(
cx,
"doc.count.selected",
&[("selected", &selected.to_string()), ("words", &words)],
counts.words,
&[("selected", &selected.to_string()), ("words", &counts.words.to_string())],
),
};
status.right(StatusBarItem::new("doc-count").label(label)).when_some(zoom, |status, zoom| status.right(zoom))
+9 -2
View File
@@ -85,6 +85,14 @@ impl Host for Docs {
self.offer_spelling(id, view, cx);
}
/// A dialog about a closed tab goes with it.
fn tab_closed(&mut self, tab: &ely_office::Tab<Extra, ely_office::Lok>, cx: &mut Context<Self>) {
if matches!(self.dialog, Some(Dialog::Output { tab: of, .. }) if of == tab.id) {
self.dialog = None;
cx.notify();
}
}
fn search_leaves(&mut self, cx: &mut Context<Self>) {
self.mark_place(cx);
}
@@ -126,7 +134,7 @@ pub fn open(app: AppId, window: &mut Window, cx: &mut App) -> Entity<Root> {
let root = ely_ui::document_root(app, docs.clone().into(), &ely_ui::commands::FILE, menus, window, cx);
docs.update(cx, |docs, cx| {
docs.core.root = root.downgrade();
docs.core.window = Some(window.window_handle());
docs.own_window(window, cx);
window.focus(&docs.core.focus, cx);
});
let launched = ely_ui::launch_files(cx);
@@ -209,7 +217,6 @@ impl Render for Docs {
.on_action(cx.listener(Self::on_open))
.on_action(cx.listener(Self::on_save))
.on_action(cx.listener(Self::on_save_as))
.on_action(cx.listener(Self::on_quit))
.on_action(cx.listener(Self::on_close_tab))
.child(shell)
.children(self.core_dialog(cx))
+29 -9
View File
@@ -36,6 +36,10 @@ pub fn menu(cx: &gpui::App) -> gpui::Menu {
pub struct Merge {
docs: WeakEntity<Docs>,
pub table: Option<Table>,
/// The template's tab, active when the data was chosen.
pub source: Option<u64>,
/// Tabs opened as previews; none is a template.
pub previews: std::collections::HashSet<u64>,
/// The record to preview, from 1.
record: usize,
pdf: bool,
@@ -46,6 +50,8 @@ impl Merge {
Merge {
docs,
table: None,
source: None,
previews: std::collections::HashSet::new(),
record: 1,
pdf: false,
}
@@ -62,11 +68,20 @@ impl Docs {
}
pub(crate) fn choose_csv(&mut self, cx: &mut Context<Self>) {
self.pick(false, cx, |docs, path, cx| match read_csv(&path) {
let Some(source) = self.core.active else {
let text = Docs::text(cx, "command.blocked.no_document", &[]);
return self.toast(text, Severity::Warning, cx);
};
if self.merge.read(cx).previews.contains(&source) {
let text = Docs::text(cx, "doc.merge.from_preview", &[]);
return self.toast(text, Severity::Warning, cx);
}
self.pick(false, cx, move |docs, path, cx| match read_csv(&path) {
Ok(table) => {
log::info!("doc: merge data has {} rows", table.rows.len());
docs.merge.update(cx, |merge, cx| {
merge.table = Some(table);
merge.source = Some(source);
merge.record = 1;
cx.notify();
});
@@ -84,20 +99,20 @@ impl Docs {
});
}
/// The tab a merge starts from: the active one.
/// The template's tab, while it is open.
fn source(&self, cx: &mut Context<Self>) -> Option<u64> {
if self.core.active.is_none() {
let text = Docs::text(cx, "command.blocked.no_document", &[]);
let source = self.merge.read(cx).source.filter(|source| self.tab(*source).is_some());
if source.is_none() {
let text = Docs::text(cx, "doc.merge.gone", &[]);
self.toast(text, Severity::Warning, cx);
}
self.core.active
source
}
/// Types a field's marker at the cursor.
/// Types a field's marker at the template's cursor.
pub(crate) fn insert_field(&mut self, header: &str, cx: &mut Context<Self>) {
let Some(tab) = self.active_tab() else {
let text = Docs::text(cx, "command.blocked.no_document", &[]);
return self.toast(text, Severity::Warning, cx);
let Some(tab) = self.source(cx).and_then(|source| self.tab(source)) else {
return;
};
tab.view.update(cx, |view, _| view.insert(&marker(header)));
}
@@ -194,7 +209,12 @@ impl Render for Merge {
})
};
let row = || div().flex().flex_wrap().items_center().gap_1();
let template = self.source.and_then(|source| {
let docs = self.docs.upgrade()?;
Some(docs.read(cx).tab(source)?.name.clone())
});
let group = PropertyGroup::new(table.name.clone())
.row(text("doc.merge.template"), div().child(template.unwrap_or_else(|| text("doc.merge.gone"))))
.row(text("doc.merge.data"), choose)
.row(text("doc.merge.fields"), row().children(fields))
.row(
+3 -3
View File
@@ -164,6 +164,7 @@ impl Docs {
cx: &mut Context<Self>,
) {
log::info!("doc: previewing merge record {}", at + 1);
self.merge.update(cx, |merge, _| merge.previews.insert(into));
self.load_into(into, Source::Copy(copy), cx);
self.core.waiting.push((
into,
@@ -260,9 +261,8 @@ impl Docs {
let folder = folder.display().to_string();
let text = match written {
Ok(count) => {
let count = count.to_string();
let text =
Docs::text(cx, "doc.merge.done", &[("n", &count), ("folder", &folder)]);
let n = count.to_string();
let text = ely_ui::i18n::counted(cx, "doc.merge.done", count as u64, &[("n", &n), ("folder", &folder)]);
return docs.toast(text, Severity::Success, cx);
}
Err((n, error)) => Docs::text(
+49 -4
View File
@@ -22,9 +22,9 @@ fn records_fill_previews_and_files() {
let csv = dir.path().join("people.csv");
std::fs::write(&csv, "Name,City\nAda,London\n«City»,上海\n").expect("the csv writes");
let table = read_csv(&csv).expect("the csv reads");
cx.update(|app| docs.update(app, |docs, cx| docs.insert_field("Name", cx)));
cx.update(|app| docs.update(app, |docs, cx| docs.field_here("Name", cx)));
type_into(&mut cx, &docs, " of ");
cx.update(|app| docs.update(app, |docs, cx| docs.insert_field("City", cx)));
cx.update(|app| docs.update(app, |docs, cx| docs.field_here("City", cx)));
let source = cx.update(|app| docs.read(app).core.tabs[0].name.to_string());
cx.update(|app| {
docs.update(app, |docs, cx| {
@@ -171,7 +171,7 @@ fn a_merge_keeps_its_source_when_the_tab_changes() {
let table = read_csv(&csv).expect("the csv reads");
cx.update(|app| {
docs.update(app, |docs, cx| {
docs.insert_field("Name", cx);
docs.field_here("Name", cx);
docs.preview_record(source, &table, 0, cx);
docs.core.active = Some(other);
})
@@ -191,6 +191,14 @@ fn a_merge_keeps_its_source_when_the_tab_changes() {
});
let preview = dir.path().join("preview.odt");
let id = cx.update(|app| docs.read(app).core.tabs[2].id);
// The preview is active now; the template stays.
cx.update(|app| {
docs.update(app, |docs, cx| {
docs.core.active = Some(id);
assert_eq!(docs.source(cx), Some(source), "the template stays after a preview");
assert!(docs.merge.read(cx).previews.contains(&id), "the preview is known");
})
});
with_window(&mut cx, &docs, |docs, window, cx| {
docs.write_as(id, preview.clone(), None, window, cx)
});
@@ -227,7 +235,7 @@ fn two_generations_keep_their_own_templates() {
for text in ["SourceA ", "SourceB "] {
sources.push(blank(&mut cx, &docs));
type_into(&mut cx, &docs, text);
cx.update(|app| docs.update(app, |docs, cx| docs.insert_field("Name", cx)));
cx.update(|app| docs.update(app, |docs, cx| docs.field_here("Name", cx)));
settled(&cx, &docs);
}
let csv = dir.path().join("one.csv");
@@ -265,3 +273,40 @@ fn two_generations_keep_their_own_templates() {
);
}
}
#[test]
fn the_template_chosen_with_the_data_stays_through_a_preview() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut cx = TestAppContext::single();
let Some(docs) = docs(&mut cx, dir.path()) else {
eprintln!("SKIP: no LOK build");
return;
};
let template = blank(&mut cx, &docs);
type_into(&mut cx, &docs, "Dear ");
let csv = dir.path().join("two.csv");
std::fs::write(&csv, "Name\nAda\nGrace\n").expect("the csv writes");
cx.update(|app| docs.update(app, |docs, cx| docs.choose_csv(cx)));
cx.simulate_path_prompt_response(move |_| Some(vec![csv]));
settle(&cx, |app| docs.read(app).merge.read(app).table.is_some());
cx.update(|app| docs.update(app, |docs, cx| docs.insert_field("Name", cx)));
let table = cx.update(|app| docs.read(app).merge.read(app).table.clone().expect("the data"));
// As the panel's buttons do: preview, then generate.
cx.update(|app| docs.update(app, |docs, cx| {
let source = docs.source(cx).expect("the template");
docs.preview_record(source, &table, 0, cx);
}));
settle(&cx, |app| tabs(app, &docs) == 2 && docs.read(app).core.active != Some(template));
let out = dir.path().join("out");
std::fs::create_dir(&out).expect("the folder");
cx.update(|app| docs.update(app, |docs, cx| {
let source = docs.source(cx).expect("the template, not the preview");
assert_eq!(source, template);
docs.generate(source, table.clone(), false, out.clone(), cx);
}));
let stem = cx.update(|app| docs.read(app).tab(template).expect("a tab").name.to_string());
let target = |n: usize| out.join(format!("{stem} {n}.docx"));
settle(&cx, |_| target(2).exists());
let (first, second) = (text_of(&mut cx, &docs, &target(1)), text_of(&mut cx, &docs, &target(2)));
assert!(first.contains("Dear Ada") && second.contains("Dear Grace"), "{first:?} {second:?}");
}
+1 -1
View File
@@ -29,7 +29,7 @@ impl Docs {
self.ask_output(true, cx);
}
fn ask_output(&mut self, print: bool, cx: &mut Context<Self>) {
pub(crate) fn ask_output(&mut self, print: bool, cx: &mut Context<Self>) {
let Some(tab) = self.active_tab() else {
let text = Docs::text(cx, "command.blocked.no_document", &[]);
return self.toast(text, Severity::Warning, cx);
+9
View File
@@ -463,3 +463,12 @@ fn an_outside_change_asks_and_keep_mine_overwrites() {
mod find;
mod more;
mod overlap;
impl Docs {
/// Chooses the active tab as template, then types a field.
pub(crate) fn field_here(&mut self, header: &str, cx: &mut gpui::Context<Self>) {
let active = self.core.active;
self.merge.update(cx, |merge, _| merge.source = active);
self.insert_field(header, cx);
}
}
+48
View File
@@ -215,3 +215,51 @@ fn an_edit_that_just_landed_still_asks_and_selection_does_not() {
});
settle(&cx, |app| docs.read(app).tab(id).is_none());
}
#[test]
fn a_quit_from_either_window_asks_first() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut cx = TestAppContext::single();
let Some(docs) = docs(&mut cx, dir.path()) else {
eprintln!("SKIP: no LOK build");
return;
};
let id = blank(&mut cx, &docs);
commit(&mut cx, &docs, "Unsaved");
let view = cx.update(|app| docs.read(app).active_tab().expect("a tab").view.clone());
settle(&cx, |app| view.read(app).settled());
cx.update(ely_ui::commands::bind_quit);
let home = cx.add_window(|_, _| Blank);
cx.update_window(home.into(), |_, window, app| docs.update(app, |docs, cx| docs.own_window(window, cx)))
.expect("the window lives");
// The settings window has no quit of its own.
let settings = cx.add_window(|_, _| Blank);
for from in [home.into(), settings.into()] {
cx.dispatch_action(from, ely_ui::commands::Quit);
settle(&cx, |app| matches!(docs.read(app).core.dialog, Some(Dialog::Unsaved { .. })));
assert!(cx.update(|app| docs.read(app).tab(id).is_some()), "the tab waits for an answer");
assert_eq!(cx.update(|app| app.active_window()), Some(home.into()), "the question's window comes forward");
// Cancel, as the dialog's button does.
cx.update(|app| docs.update(app, |docs, cx| {
docs.close_cancelled(cx);
docs.core.dialog = None;
}));
}
}
#[test]
fn closing_a_tab_takes_its_export_dialog() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut cx = TestAppContext::single();
let Some(docs) = docs(&mut cx, dir.path()) else {
eprintln!("SKIP: no LOK build");
return;
};
let id = blank(&mut cx, &docs);
cx.update(|app| docs.update(app, |docs, cx| docs.ask_output(false, cx)));
assert!(cx.update(|app| matches!(docs.read(app).dialog, Some(crate::actions::Dialog::Output { .. }))));
with_window(&mut cx, &docs, |docs, window, cx| docs.request_close(id, After::Tab, window, cx));
settle(&cx, |app| docs.read(app).tab(id).is_none());
// Drawn now, a dialog for the gone tab would crash.
assert!(cx.update(|app| docs.read(app).dialog.is_none()), "the dialog went with its tab");
}
+2 -2
View File
@@ -86,10 +86,10 @@ fn interleaved_previews_keep_their_sources() {
};
let alpha = blank(&mut cx, &docs);
type_into(&mut cx, &docs, "SourceAlpha ");
update_doc(&mut cx, &docs, |docs, cx| docs.insert_field("Name", cx));
update_doc(&mut cx, &docs, |docs, cx| docs.field_here("Name", cx));
let beta = blank(&mut cx, &docs);
type_into(&mut cx, &docs, "SourceBeta ");
update_doc(&mut cx, &docs, |docs, cx| docs.insert_field("Name", cx));
update_doc(&mut cx, &docs, |docs, cx| docs.field_here("Name", cx));
settled(&cx, &docs);
let csv = dir.path().join("two.csv");
std::fs::write(&csv, "Name\nAda\nGrace\n").expect("the csv writes");
+13
View File
@@ -56,6 +56,19 @@ const CHECK: &str = r#"
inline: seen(view.querySelector('.milkdown p .katex')),
display: seen(view.querySelector('.milkdown p .katex-display')),
tasks: view.querySelectorAll('li[data-item-type="task"]').length,
boxes: [...view.querySelectorAll('li[data-item-type="task"]')].map((item) => {
const mark = getComputedStyle(item, '::before');
const range = document.createRange();
range.selectNodeContents(item.querySelector('p'));
const line = range.getClientRects()[0];
const top = item.getBoundingClientRect().top + parseFloat(mark.marginTop);
const size = parseFloat(getComputedStyle(item).fontSize);
const shown = mark.display !== 'none' && mark.visibility === 'visible' && parseFloat(mark.opacity) > 0;
// A laid-out box pushes the text 1.5em in.
const inset = (item.querySelector('p').getBoundingClientRect().left - item.getBoundingClientRect().left) / size;
const drawn = shown && mark.content !== 'none' && parseFloat(mark.borderTopWidth) > 0 && Math.abs(inset - 1.5) < 0.05;
return [parseFloat(mark.width) / size, parseFloat(mark.height) / size, top + parseFloat(mark.height) / 2 - (line.top + line.height / 2), drawn];
}),
cells: view.querySelectorAll('.milkdown td').length,
notes: view.querySelectorAll('[data-type="footnote_definition"]').length,
blocks,
+8
View File
@@ -29,6 +29,14 @@ impl Desk {
return;
}
tab.extra.heard = changed;
self.save_after_pause(id, cx);
}
/// Counts unsaved text as an edit; saves after the pause.
pub fn save_after_pause(&mut self, id: u64, cx: &mut Context<Self>) {
let Some(tab) = self.tab_mut(id) else {
return;
};
tab.extra.policy.edit(Instant::now());
cx.spawn(async move |desk, cx| {
let wait = DEBOUNCE + Duration::from_millis(50);
+3 -3
View File
@@ -2,7 +2,7 @@
use std::rc::Rc;
use ely_files::{Fingerprint, Policy, PolicyEngine};
use ely_files::Fingerprint;
use ely_gpui_component::{
buttons::{Button, ButtonVariant},
git::{self as merging, Region, Take, ThreeWayMerge},
@@ -102,7 +102,7 @@ impl Desk {
Choice::Mine => {
if let Some(tab) = self.tab_mut(id) {
tab.session.rebase(fingerprint);
tab.extra.policy = PolicyEngine::new(Policy::MarkAutoSave, true);
tab.extra.restart_autosave();
}
self.set_outside(id, Outside::Clear, cx);
self.save(id, None, window, cx);
@@ -120,7 +120,7 @@ impl Desk {
return self.set_outside(id, Outside::Unread(why), cx);
}
tab.extra.base = disk.text.clone();
tab.extra.policy = PolicyEngine::new(Policy::MarkAutoSave, true);
tab.extra.restart_autosave();
tab.doc.lock().expect("the text lock").source = disk;
let view = tab.view.clone();
view.update(cx, |view, cx| view.adopt(merged, cx));
+6 -5
View File
@@ -81,6 +81,11 @@ impl Host for Desk {
&mut self.core
}
/// A quit records the open tabs first.
fn quitting(&mut self, cx: &mut Context<Self>) {
self.leave(cx);
}
/// A quit or close stopped: the kept list follows again.
fn close_cancelled(&mut self, cx: &mut Context<Self>) {
self.keeping.leaving = false;
@@ -215,7 +220,7 @@ pub fn open(app: AppId, window: &mut Window, cx: &mut App) -> Entity<Root> {
let asked = ely_ui::launch_files(cx);
desk.update(cx, |desk, cx| {
desk.core.root = root.downgrade();
desk.core.window = Some(window.window_handle());
desk.own_window(window, cx);
window.focus(&desk.core.focus, cx);
// Launch files stand alone; unsaved text still returns.
if asked.is_empty() {
@@ -403,10 +408,6 @@ impl Render for Desk {
.on_action(cx.listener(Self::on_export))
.on_action(cx.listener(Self::on_print))
.on_action(cx.listener(Self::on_close_tab))
.on_action(cx.listener(|desk, quit, window, cx| {
desk.leave(cx);
desk.on_quit(quit, window, cx)
}))
.on_action(cx.listener(|desk, _: &InsertTable, _, cx| desk.table("insert", cx)))
.on_action(cx.listener(|desk, _: &RowAbove, _, cx| desk.table("row-above", cx)))
.on_action(cx.listener(|desk, _: &RowBelow, _, cx| desk.table("row-below", cx)))
+86 -4
View File
@@ -55,6 +55,14 @@ pub struct Extra {
pub restored: bool,
}
impl Extra {
/// Autosave from scratch; a write in flight no longer counts.
pub fn restart_autosave(&mut self) {
self.policy = PolicyEngine::new(Policy::MarkAutoSave, true);
self.writing = None;
}
}
impl Default for Extra {
fn default() -> Self {
Extra {
@@ -217,11 +225,26 @@ impl Desk {
Ok(read) => read,
Err(error) => return self.set_outside(id, Outside::Unread(error.to_string()), cx),
};
// Keys the page has not sent yet count first.
if !self.settled(id, cx) {
return self.when_settled(id, move |desk, _, cx| desk.disk_read(id, path, Ok((fingerprint, disk)), cx));
}
let current = tab.doc.lock().expect("the text lock").current.clone();
let kept = disk.text == tab.extra.base;
let dirty = tab.dirty(cx);
log::info!("mark: {} changed outside; unsaved {dirty}", path.display());
match (disk.text == current, dirty) {
(true, _) | (false, false) => self.take_disk(id, disk, fingerprint, cx),
// The same text: only the file underneath is new.
(true, _) => {
if let Some(view) = self.adopt_disk(id, &disk, fingerprint, cx) {
// What shows is now saved: the tab is clean.
let saved = crate::engine::mark(&disk.text);
view.update(cx, |view, cx| view.saved(&saved, cx));
}
}
// The text as last saved: the edits stay unsaved.
(false, true) if kept => self.keep_edits(id, disk, fingerprint, cx),
(false, false) => self.take_disk(id, disk, fingerprint, cx),
(false, true) => {
let tab = self.tab_mut(id).expect("open");
tab.session.external_modified();
@@ -247,14 +270,47 @@ impl Desk {
fingerprint: Fingerprint,
cx: &mut Context<Self>,
) {
if let Some(view) = self.adopt_disk(id, &disk, fingerprint, cx) {
view.update(cx, |view, cx| view.refresh(disk, cx));
}
}
/// A new file with the saved text; edits stay.
fn keep_edits(&mut self, id: u64, disk: Source, fingerprint: Fingerprint, cx: &mut Context<Self>) {
let Some(tab) = self.tab_mut(id) else {
return;
};
tab.session.rebase(fingerprint);
tab.doc.lock().expect("the text lock").source = disk;
// A conflict stopped autosave, maybe mid-write; it resumes.
tab.extra.restart_autosave();
let (registry, path) = (tab.registry, tab.session.path().map(Path::to_path_buf));
if let (Some(registry), Some(path)) = (registry, path)
&& let Err(error) = self.core.sessions.track(registry, &path)
{
log::warn!("mark: the replaced file did not register: {error}");
}
self.set_outside(id, Outside::Clear, cx);
self.save_after_pause(id, cx);
}
/// The tab takes the file as saved; returns its view.
fn adopt_disk(
&mut self,
id: u64,
disk: &Source,
fingerprint: Fingerprint,
cx: &mut Context<Self>,
) -> Option<gpui::Entity<crate::view::MarkView>> {
let tab = self.tab_mut(id)?;
if let Err(error) = tab.session.reload_at(fingerprint) {
return self.set_outside(id, Outside::Unread(error.to_string()), cx);
self.set_outside(id, Outside::Unread(error.to_string()), cx);
return None;
}
tab.extra.base = disk.text.clone();
tab.extra.policy = PolicyEngine::new(Policy::MarkAutoSave, true);
tab.extra.restart_autosave();
// Its bytes (BOM, line ends) are what saves keep now.
tab.doc.lock().expect("the text lock").source = disk.clone();
let (view, registry) = (tab.view.clone(), tab.registry);
let path = tab.session.path().map(Path::to_path_buf);
// An atomic replace is a new file underneath.
@@ -263,8 +319,8 @@ impl Desk {
{
log::warn!("mark: the replaced file did not register: {error}");
}
view.update(cx, |view, cx| view.refresh(disk, cx));
self.set_outside(id, Outside::Clear, cx);
Some(view)
}
pub fn set_outside(&mut self, id: u64, outside: Outside, cx: &mut Context<Self>) {
@@ -345,3 +401,29 @@ fn watch(dirs: &[PathBuf], cx: &mut Context<Desk>) -> notify::Result<Recommended
log::info!("mark: watching {} folders", dirs.len());
Ok(watcher)
}
#[cfg(test)]
mod tests {
use std::time::{Duration, Instant};
use ely_files::Action;
use super::Extra;
#[test]
fn a_restarted_autosave_saves_the_next_edit() {
let mut extra = Extra::default();
extra.policy.set_has_path();
extra.policy.edit(Instant::now());
// A write was in flight when the disk changed.
extra.writing = Some(1);
extra.restart_autosave();
// As autosave settles a heard write, then edits.
if let Some(revision) = extra.writing.take() {
extra.policy.save_finished(revision, true);
}
let now = Instant::now();
extra.policy.edit(now);
assert!(matches!(extra.policy.tick(now + Duration::from_secs(5)), Action::SaveDue(_)));
}
}
+12 -2
View File
@@ -116,12 +116,22 @@ a {
list-style: none;
}
/* A text-sized box, centred on the first line. */
.milkdown li[data-item-type='task']::before {
content: '☐ ';
content: '';
flex: none;
box-sizing: border-box;
width: 1em;
height: 1em;
margin-top: calc(0.25em + (1lh - 1em) / 2);
border: 0.09em solid var(--ely-fg-muted);
border-radius: 0.2em;
}
.milkdown li[data-item-type='task'][data-checked='true']::before {
content: '☑ ';
border-color: var(--ely-link);
background: var(--ely-link);
box-shadow: inset 0 0 0 0.18em var(--ely-bg);
}
.milkdown hr {
+7 -2
View File
@@ -1,5 +1,6 @@
// Blocks Milkdown cannot write back stay raw text (§14.3).
import { editorViewCtx, remarkCtx, schemaCtx, serializerCtx } from '@milkdown/kit/core'
import { canon } from './tables.js'
import { Fragment } from '@milkdown/kit/prose/model'
import { Selection } from '@milkdown/kit/prose/state'
import { $nodeSchema } from '@milkdown/kit/utils'
@@ -51,6 +52,11 @@ export function faithful(ctx, original) {
const schema = ctx.get(schemaCtx)
const serializer = ctx.get(serializerCtx)
const written = (nodes) => serializer(schema.topNodeType.create(null, nodes)).replace(/\n+$/, '')
// Table spacing is free; every cell's source must match.
const kept = (node, text) => {
const own = written([node])
return own === text || canon(own) === canon(text)
}
const rawOf = ([from, to]) => {
const text = original.slice(from, to)
return schema.nodes.ely_raw.create(null, text ? schema.text(text) : null)
@@ -68,8 +74,7 @@ export function faithful(ctx, original) {
if (!blank)
parsed.forEach((node, _, index) => {
gap(last, at[index][0])
const exact = written([node]) === original.slice(...at[index])
nodes.push(exact ? node : rawOf(at[index]))
nodes.push(kept(node, original.slice(...at[index])) ? node : rawOf(at[index]))
places.push(at[index])
last = at[index][1]
})
+14 -2
View File
@@ -1,16 +1,17 @@
// The document's own markers, so blocks write back unchanged.
import { unified } from 'unified'
import remarkParse from 'remark-parse'
import remarkGfm from 'remark-gfm'
import { visit } from 'unist-util-visit'
/** remark-stringify options most of `text` already uses. */
/** Writing options most of `text` already uses; tables' for remark-gfm. */
export function style(text) {
const votes = {}
const vote = (key, value) => {
votes[key] ??= new Map()
votes[key].set(value, (votes[key].get(value) ?? 0) + 1)
}
visit(unified().use(remarkParse).parse(text), (node) => {
visit(unified().use(remarkParse).use(remarkGfm).parse(text), (node) => {
const at = node.position?.start.offset
if (at === undefined) return
const head = text.slice(at, at + 12)
@@ -34,6 +35,17 @@ export function style(text) {
case 'heading':
if (node.depth <= 2) vote('setext', head[0] !== '#')
break
case 'table': {
// Row nodes leave out quote and list prefixes.
const rows = node.children.map((row) => text.slice(row.position.start.offset, row.position.end.offset).trim())
const padded = /\| /.test(rows[0])
const cells = rows.flatMap((row) => row.replace(/^\||\|$/g, '').split('|'))
const inner = (cell) => (padded ? cell.replace(/^ | $/g, '') : cell)
vote('tableCellPadding', padded)
// Aligned cells carry spaces beyond the padding.
vote('tablePipeAlign', cells.some((cell) => /^\s|\s$/.test(inner(cell))))
break
}
}
})
const most = (key) => [...votes[key].entries()].sort((a, b) => b[1] - a[1])[0][0]
+35
View File
@@ -0,0 +1,35 @@
// Tables compare by alignment and cell source, not spacing.
import { unified } from 'unified'
import remarkParse from 'remark-parse'
import remarkGfm from 'remark-gfm'
import { SKIP, visit } from 'unist-util-visit'
const reader = unified().use(remarkParse).use(remarkGfm)
/** A cell's own source, without its padding. */
function cell(text, node) {
const kids = node.children
return kids.length ? text.slice(kids[0].position.start.offset, kids.at(-1).position.end.offset) : ''
}
/** `text` with each table's spacing made canonical. */
export function canon(text) {
const tables = []
visit(reader.parse(text), 'table', (node) => {
tables.push(node)
return SKIP
})
let out = text
// Later tables first, so earlier offsets hold.
for (const table of tables.reverse()) {
const width = table.children[0].children.length
// GFM fills a short row with empty cells.
const rows = table.children.map((row) => {
const cells = row.children.map((node) => cell(text, node))
return [...cells, ...Array(Math.max(0, width - cells.length)).fill('')].join('|')
})
const shape = [table.align.join(','), ...rows].join('\n')
out = `${out.slice(0, table.position.start.offset)}\u0000${shape}\u0000${out.slice(table.position.end.offset)}`
}
return out
}
+4 -2
View File
@@ -19,7 +19,7 @@ import { keymap } from '@milkdown/kit/prose/keymap'
import { liftListItem, sinkListItem } from '@milkdown/kit/prose/schema-list'
import { redo, redoDepth, undoDepth } from '@milkdown/kit/prose/history'
import { $prose, callCommand } from '@milkdown/kit/utils'
import { insertTableCommand } from '@milkdown/kit/preset/gfm'
import { insertTableCommand, remarkGFMPlugin } from '@milkdown/kit/preset/gfm'
import {
addColumnAfter,
addColumnBefore,
@@ -87,7 +87,9 @@ export async function visual(root, markdown, editable, texts, changed, edge) {
.config((ctx) => {
ctx.set(rootCtx, root)
ctx.set(defaultValueCtx, markdown)
ctx.update(remarkStringifyOptionsCtx, (prev) => ({ ...prev, ...style(markdown) }))
const { tableCellPadding, tablePipeAlign, ...marks } = style(markdown)
ctx.update(remarkStringifyOptionsCtx, (prev) => ({ ...prev, ...marks }))
ctx.set(remarkGFMPlugin.options.key, { tableCellPadding, tablePipeAlign })
ctx.update(editorViewOptionsCtx, (prev) => ({ ...prev, editable: () => editable }))
})
.use(commonmark)
+3 -2
View File
@@ -12,7 +12,7 @@ use crate::pages::{rect_on, to_view};
use crate::view::PdfView;
/// How far a click may move, in window pixels.
const CLICK: f32 = 3.0;
pub(crate) const CLICK: f32 = 3.0;
/// Pages read for their annotations at once.
const BATCH: usize = 20;
@@ -253,8 +253,9 @@ impl PdfView {
if annots.is_empty() {
return;
}
let author = ely_ui::settings::current(cx).author.clone();
self.settled_edit(what, cx, move |worker, doc| {
let name = ely_platform::user::name()?;
let name = ely_platform::user::named(&author)?;
annots.iter_mut().for_each(|annot| annot.author = name.clone());
worker.annotate(doc, &annots)
});
+4 -5
View File
@@ -72,7 +72,7 @@ impl Viewer {
let turned = unturn(margins, view.read(cx).rotate);
let points = turned.map(|side| side * MM);
view.update(cx, |view, cx| {
view.edit("cropping pages", move |worker, doc| worker.crop_pages(doc, &pages, points), cx)
view.edit_pages("cropping pages", move |worker, doc| worker.crop_pages(doc, &pages, points), cx)
});
cx.notify();
}
@@ -136,7 +136,7 @@ impl Viewer {
}
fn failed_write(&self, name: &str, error: &io::Error, cx: &mut App) {
if error.kind() == io::ErrorKind::PermissionDenied {
if ely_pdf_engine::refused(error).is_some() {
return self.failed(error, cx);
}
let text = Self::text(cx, "office.error.save", &[("name", name), ("error", &error.to_string())]);
@@ -183,7 +183,7 @@ impl Viewer {
written.map(|()| targets.len())
},
move |viewer, done, _, cx| match done {
Ok(count) => viewer.toast_output(Self::text(cx, "pdf.split.done", &[("count", &count.to_string())]), opened.clone(), cx),
Ok(count) => viewer.toast_output(ely_ui::i18n::counted(cx, "pdf.split.done", count as u64, &[("count", &count.to_string())]), opened.clone(), cx),
Err(error) => viewer.failed_write(&stem, &error, cx),
},
cx,
@@ -205,8 +205,7 @@ impl Viewer {
};
let card = match self.ask.as_ref()? {
Ask::Crop { pages, margins, .. } => {
let count = pages.len().to_string();
let title = Self::text(cx, "pdf.crop.title", &[("count", &count)]);
let title = ely_ui::i18n::counted(cx, "pdf.crop.title", pages.len() as u64, &[("count", &pages.len().to_string())]);
let sides = ["top", "right", "bottom", "left"];
let rows = sides.iter().enumerate().fold(DescriptionList::new(), |rows, (at, side)| {
let name = label(&format!("pdf.crop.{side}"));
+132
View File
@@ -0,0 +1,132 @@
//! Old tiles stay under a page until new ones land.
use std::sync::Arc;
use gpui::RenderImage;
use crate::layout::{Placed, visible};
use crate::pages::{TILE, TileKey};
use crate::view::PdfView;
/// A tile no longer current and its page's size then.
pub struct Old {
pub key: TileKey,
pub image: Arc<RenderImage>,
pub size: (f32, f32),
}
/// A page on screen: place, device size, tiles in view.
pub struct Showing {
pub place: Placed,
pub device: (i32, i32),
pub keys: Vec<(TileKey, [i32; 4])>,
}
/// Where `key`'s tile sat in its page, as fractions.
fn fraction(key: &TileKey, size: (f32, f32)) -> [f32; 4] {
let (w, h) = match key.rotate.rem_euclid(180) {
90 => (size.1, size.0),
_ => size,
};
let scale = key.scale as f32 / 1000.0;
let (dw, dh) = ((w * scale).ceil(), (h * scale).ceil());
let (x, y) = ((key.tx * TILE) as f32, (key.ty * TILE) as f32);
[x / dw, y / dh, (TILE as f32).min(dw - x) / dw, (TILE as f32).min(dh - y) / dh]
}
impl PdfView {
/// The pages in view and the tiles each needs.
pub fn showing(&self, sf: f32, dark: bool) -> Vec<Showing> {
let laid = self.laid_out();
let (room_w, room_h) = (f32::from(self.room.size.width), f32::from(self.room.size.height));
let (left, top) = (-f32::from(self.scroll.offset().x), -f32::from(self.scroll.offset().y));
let scale = (laid.scale * sf * 1000.0).round() as u32;
visible(&laid, top, top + room_h)
.filter(|p| p.x < left + room_w && p.x + p.w > left)
.map(|place| {
let (dw, dh) = ((place.w * sf).ceil() as i32, (place.h * sf).ceil() as i32);
let ys = crate::pages::span(top - place.y, top + room_h - place.y, sf, dh);
let xs = crate::pages::span(left - place.x, left + room_w - place.x, sf, dw);
let keys = ys
.flat_map(|ty| xs.clone().map(move |tx| (tx, ty)))
.map(|(tx, ty)| {
let key = TileKey { page: place.page, scale, rotate: self.rotate, dark, tx, ty };
(key, [tx * TILE, ty * TILE, TILE.min(dw - tx * TILE), TILE.min(dh - ty * TILE)])
})
.collect();
Showing { place: *place, device: (dw, dh), keys }
})
.collect()
}
/// What a page draws, bottom first, in page fractions.
pub fn pieces(&self, showing: &Showing) -> Vec<(Arc<RenderImage>, [f32; 4])> {
let (dw, dh) = (showing.device.0 as f32, showing.device.1 as f32);
let current = showing.keys.iter().filter_map(|(key, rect)| {
let at = [rect[0] as f32 / dw, rect[1] as f32 / dh, rect[2] as f32 / dw, rect[3] as f32 / dh];
self.tiles.get(key).map(|image| (image.clone(), at))
});
if showing.keys.iter().all(|(key, _)| self.tiles.contains_key(key)) {
return current.collect();
}
// Old tiles of this page fill in underneath.
let page = showing.place.page;
let size = self.sizes[page];
let scale = showing.keys.first().map(|(key, _)| key.scale);
let rescaled = self
.tiles
.iter()
.filter(|(key, _)| key.page == page && key.rotate == self.rotate && Some(key.scale) != scale)
.map(|(key, image)| (image.clone(), fraction(key, size)));
let kept = self
.backdrop
.iter()
.filter(|old| old.key.page == page && old.key.rotate == self.rotate && old.size == size)
.map(|old| (old.image.clone(), fraction(&old.key, old.size)));
kept.chain(rescaled).chain(current).collect()
}
/// Keeps every tile under its page, as before an edit.
pub fn keep_all(&mut self) {
let sizes = &self.sizes;
let old = self.tiles.drain().map(|(key, image)| Old { key, image, size: sizes[key.page] });
self.backdrop.extend(old);
}
/// Moves unseen tiles under their page; drops covered ones.
pub fn settle(&mut self, showing: &[Showing]) {
let shown = |page: usize| showing.iter().find(|s| s.place.page == page);
let seen = |key: &TileKey| shown(key.page).is_some_and(|s| s.keys.iter().any(|(k, _)| k == key));
let leaving: Vec<TileKey> = self.tiles.keys().filter(|key| !seen(key)).copied().collect();
for key in leaving {
let image = self.tiles.remove(&key).expect("a tile just listed");
match shown(key.page) {
Some(_) => self.backdrop.push(Old { key, image, size: self.sizes[key.page] }),
None => self.retired.push(image),
}
}
let covered = |page: usize| shown(page).is_none_or(|s| s.keys.iter().all(|(key, _)| self.tiles.contains_key(key)));
let (sizes, rotate) = (&self.sizes, self.rotate);
let (gone, kept): (Vec<Old>, Vec<Old>) = std::mem::take(&mut self.backdrop).into_iter().partition(|old| {
covered(old.key.page) || old.key.rotate != rotate || sizes.get(old.key.page) != Some(&old.size)
});
self.backdrop = kept;
for old in gone {
self.retired.push(old.image);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_tile_keeps_its_place_as_a_fraction_of_its_page() {
let key = TileKey { page: 0, scale: 2000, rotate: 0, dark: false, tx: 1, ty: 0 };
// A 612 by 792 page at 2x: 1224 by 1584.
assert_eq!(fraction(&key, (612.0, 792.0)), [512.0 / 1224.0, 0.0, 512.0 / 1224.0, 512.0 / 1584.0]);
let turned = TileKey { rotate: 90, ..key };
assert_eq!(fraction(&turned, (612.0, 792.0)), [512.0 / 1584.0, 0.0, 512.0 / 1584.0, 512.0 / 1224.0]);
}
}
+24 -7
View File
@@ -76,6 +76,10 @@ pub struct Drag {
pub from: (f32, f32),
pub now: (f32, f32),
pub scale: bool,
/// Where the press landed, in window pixels.
pub pressed: (f32, f32),
/// The pointer went past a click's slack.
pub moved: bool,
}
/// The corner handle's reach, in page points.
@@ -107,6 +111,11 @@ fn inside(rect: &[f32; 4], (x, y): (f32, f32)) -> bool {
x >= rect[0] && x <= rect[2] && y >= rect[1] && y <= rect[3]
}
/// Whether `outer` holds all of `inner`.
fn covers(outer: &[f32; 4], inner: &[f32; 4]) -> bool {
outer[0] <= inner[0] && outer[1] <= inner[1] && outer[2] >= inner[2] && outer[3] >= inner[3]
}
impl PdfView {
/// A drag or drawing is under way.
pub fn gesturing(&self) -> bool {
@@ -174,16 +183,21 @@ impl PdfView {
Some(Aim::Object { page: on, index }) if on == page => layer.drawn.get(index).filter(|d| corner(&d.rect)).map(|_| (index, true)),
_ => None,
};
let hit = held.or_else(|| layer.drawn.iter().rposition(|d| inside(&d.rect, point)).map(|index| (index, false)));
let text = layer.blocks.iter().position(|b| b.editable && inside(&b.rect, point));
// Text wins over an object drawn all around it.
let around = |rect: &[f32; 4]| text.is_some_and(|t| covers(rect, &layer.blocks[t].rect));
let hit = held.or_else(|| {
let object = layer.drawn.iter().rposition(|d| inside(&d.rect, point) && !around(&d.rect));
object.map(|index| (index, false))
});
self.aim = match hit {
Some((index, scale)) => {
let rect = layer.drawn[index].rect;
self.drag = Some(Drag { page, index, rect, from: point, now: point, scale });
let pressed = (f32::from(at.x), f32::from(at.y));
self.drag = Some(Drag { page, index, rect, from: point, now: point, scale, pressed, moved: false });
Some(Aim::Object { page, index })
}
None => (layer.blocks.iter())
.position(|b| b.editable && inside(&b.rect, point))
.map(|index| Aim::Text { page, index }),
None => text.map(|index| Aim::Text { page, index }),
};
cx.notify();
}
@@ -193,6 +207,8 @@ impl PdfView {
return;
};
if let Some(drag) = self.drag.as_mut().filter(|drag| drag.page == page) {
let far = (f32::from(at.x) - drag.pressed.0).abs() + (f32::from(at.y) - drag.pressed.1).abs();
drag.moved |= far >= crate::annotate::CLICK;
drag.now = point;
cx.notify();
}
@@ -203,7 +219,8 @@ impl PdfView {
let Some(drag) = self.drag.take() else {
return;
};
if (drag.now.0 - drag.from.0).abs() < 1.0 && (drag.now.1 - drag.from.1).abs() < 1.0 {
// A hand that shakes a little still clicks.
if !drag.moved {
return cx.notify();
}
// A queued edit may renumber what was dragged.
@@ -264,7 +281,7 @@ mod tests {
#[test]
fn a_drag_moves_or_scales_from_the_top_left() {
let mut drag = Drag { page: 0, index: 0, rect: [10.0, 20.0, 110.0, 70.0], from: (50.0, 40.0), now: (60.0, 45.0), scale: false };
let mut drag = Drag { page: 0, index: 0, rect: [10.0, 20.0, 110.0, 70.0], from: (50.0, 40.0), now: (60.0, 45.0), scale: false, pressed: (0.0, 0.0), moved: true };
assert_eq!(drag.change(), [1.0, 0.0, 0.0, 1.0, 10.0, 5.0]);
assert_eq!(drag.shown(), [20.0, 25.0, 120.0, 75.0]);
drag = Drag { from: (110.0, 70.0), now: (210.0, 80.0), scale: true, ..drag };
+36 -12
View File
@@ -17,6 +17,8 @@ pub struct Queued {
op: Op,
pick: Option<BTreeSet<usize>>,
doc: Doc,
/// The edit may add, drop, move or reshape pages.
pages: bool,
}
/// The document as an edit left it.
@@ -36,20 +38,31 @@ impl PdfView {
op: impl FnOnce(&mut Worker, Doc) -> io::Result<String> + Send + 'static,
cx: &mut Context<Self>,
) {
self.edit_picking(what, None, op, cx);
self.queue_edit(what, None, false, op, cx);
}
/// Queues an edit to the pages themselves.
pub fn edit_pages(
&mut self,
what: &'static str,
op: impl FnOnce(&mut Worker, Doc) -> io::Result<String> + Send + 'static,
cx: &mut Context<Self>,
) {
self.queue_edit(what, None, true, op, cx);
}
/// Queues `op`; once it lands, `pick` is picked.
pub fn edit_picking(
pub fn queue_edit(
&mut self,
what: &'static str,
pick: Option<BTreeSet<usize>>,
pages: bool,
op: impl FnOnce(&mut Worker, Doc) -> io::Result<String> + Send + 'static,
cx: &mut Context<Self>,
) {
log::info!("pdf: queues {what}");
// Aimed at what is shown now; later states refuse it.
self.queue.push_back(Queued { what, op: Box::new(op), pick, doc: self.doc });
self.queue.push_back(Queued { what, op: Box::new(op), pick, doc: self.doc, pages });
self.next_edit(cx);
}
@@ -57,7 +70,7 @@ impl PdfView {
if self.editing {
return;
}
let Some(Queued { what, op, pick, doc }) = self.queue.pop_front() else {
let Some(Queued { what, op, pick, doc, pages }) = self.queue.pop_front() else {
return;
};
self.editing = true;
@@ -73,7 +86,7 @@ impl PdfView {
view.editing = false;
match fresh {
Ok(fresh) => {
view.refresh(fresh, cx);
view.refresh(fresh, pages, cx);
if let Some(pick) = pick {
view.anchor = pick.first().copied();
view.picked = pick;
@@ -93,19 +106,30 @@ impl PdfView {
}
/// Everything read before the edit goes.
fn refresh(&mut self, fresh: Fresh, cx: &mut Context<Self>) {
fn refresh(&mut self, fresh: Fresh, pages: bool, cx: &mut Context<Self>) {
self.version += 1;
self.edited += 1;
(self.doc, self.mark) = (fresh.doc, fresh.mark);
self.sizes = sizes(fresh.pages, &fresh.first);
let measured = sizes(fresh.pages, &fresh.first);
if pages || fresh.pages != self.sizes.len() {
// A page may now stand where another stood.
self.retire_tiles();
self.sizes = measured;
self.thumbs_stale.clear();
for (_, image) in self.thumbs.drain() {
self.retired.push(image);
}
} else {
// Same pages: old pictures stay until repainted.
self.keep_all();
self.thumbs_stale.extend(self.thumbs.keys().copied());
let read = fresh.first.len();
self.sizes[..read].copy_from_slice(&measured[..read]);
}
self.marks = fresh.marks;
self.retire_tiles();
self.failed.clear();
self.text.clear();
self.asking_text.clear();
for (_, image) in self.thumbs.drain() {
self.retired.push(image);
}
self.thumbs_failed.clear();
// Indices shift with any edit; aims start over.
(self.layers, self.aim, self.drag) = (Default::default(), None, None);
@@ -144,6 +168,6 @@ impl PdfView {
pub fn undo(&mut self, redo: bool, cx: &mut Context<Self>) {
let what = if redo { "redo" } else { "undo" };
self.edit(what, move |worker, doc| worker.undo(doc, redo), cx);
self.edit_pages(what, move |worker, doc| worker.undo(doc, redo), cx);
}
}
+1
View File
@@ -1,6 +1,7 @@
mod annotate;
mod ask;
mod attach;
mod backdrop;
mod content;
mod document;
mod editing;
+1 -1
View File
@@ -161,7 +161,7 @@ impl Viewer {
cx.notify();
let pages: Vec<(usize, Vec<OcrLine>)> = run.read.into_iter().filter(|(_, lines)| replace || !lines.is_empty()).collect();
let (read, skipped) = (pages.len().to_string(), run.skipped.to_string());
let summary = Self::text(cx, "pdf.ocr.done", &[("read", &read), ("skipped", &skipped)]);
let summary = ely_ui::i18n::counted(cx, "pdf.ocr.done", pages.len() as u64, &[("read", &read), ("skipped", &skipped)]);
let Some(view) = self.tab(tab).map(|tab| tab.view.clone()).filter(|_| !pages.is_empty()) else {
return self.toast(summary, Severity::Info, cx);
};
+5 -5
View File
@@ -81,7 +81,7 @@ impl PdfView {
let pages = self.chosen_pages();
let before = pages.iter().filter(|page| **page < to).count();
let landed = (to - before..to - before + pages.len()).collect();
self.edit_picking("moving pages", Some(landed), move |worker, doc| worker.move_pages(doc, &pages, to), cx);
self.queue_edit("moving pages", Some(landed), true, move |worker, doc| worker.move_pages(doc, &pages, to), cx);
}
}
@@ -105,14 +105,14 @@ impl Viewer {
}
view.update(cx, |view, cx| {
view.picked.clear();
view.edit("deleting pages", move |worker, doc| worker.delete_pages(doc, &pages), cx);
view.edit_pages("deleting pages", move |worker, doc| worker.delete_pages(doc, &pages), cx);
});
}
fn turn_pages(&mut self, by: i32, cx: &mut Context<Self>) {
self.on_pages(cx, |view, cx| {
let pages = view.chosen_pages();
view.edit("turning pages", move |worker, doc| worker.rotate_pages(doc, &pages, by), cx);
view.edit_pages("turning pages", move |worker, doc| worker.rotate_pages(doc, &pages, by), cx);
});
}
@@ -136,7 +136,7 @@ impl Viewer {
self.on_pages(cx, |view, cx| {
let at = view.chosen_pages().last().copied().expect("one page at least");
let size = view.sizes[at];
view.edit("inserting a page", move |worker, doc| worker.insert_blank(doc, at + 1, size), cx);
view.edit_pages("inserting a page", move |worker, doc| worker.insert_blank(doc, at + 1, size), cx);
});
}
@@ -148,7 +148,7 @@ impl Viewer {
self.pick(false, cx, |viewer, path: PathBuf, cx| {
viewer.on_pages(cx, |view, cx| {
let at = view.chosen_pages().last().copied().expect("one page at least") + 1;
view.edit(
view.edit_pages(
"inserting pages",
move |worker, doc| worker.insert_file(doc, at, &path).map(|(_, mark)| mark),
cx,
+1 -1
View File
@@ -177,7 +177,7 @@ impl Viewer {
},
move |viewer, done, _, cx| match done {
Ok(count) => {
let text = Self::text(cx, "pdf.export.images_done", &[("count", &count.to_string())]);
let text = ely_ui::i18n::counted(cx, "pdf.export.images_done", count as u64, &[("count", &count.to_string())]);
match folder.clone() {
Some(folder) => viewer.toast_output(text, folder, cx),
None => viewer.toast(text, Severity::Success, cx),
+41 -57
View File
@@ -1,6 +1,6 @@
//! Only the pages on screen, drawn in tiles (PDF-01, PERF-05).
use std::{collections::HashSet, sync::Arc};
use std::sync::Arc;
use ely_gpui_component::theme::ActiveTheme as _;
use gpui::{
@@ -10,7 +10,7 @@ use gpui::{
};
use image::{Frame, ImageBuffer, Rgba};
use crate::layout::{GAP, Layout, Mode, Placed, layout, visible};
use crate::layout::{GAP, Layout, Mode, Placed, layout};
use crate::view::{PdfView, Reported};
/// A tile's side in device pixels.
@@ -58,7 +58,7 @@ pub fn rect_on(rect: [f32; 4], size: (f32, f32), rotate: i32, scale: f32) -> (f3
}
/// Tiles covering `[from, to)` view pixels of a `side`-pixel page.
fn span(from: f32, to: f32, sf: f32, side: i32) -> std::ops::RangeInclusive<i32> {
pub(crate) fn span(from: f32, to: f32, sf: f32, side: i32) -> std::ops::RangeInclusive<i32> {
let first = (from.max(0.0) * sf).floor() as i32 / TILE;
let last = ((to * sf).ceil() as i32 - 1).min(side - 1).max(0) / TILE;
first..=last
@@ -69,11 +69,13 @@ fn drawn_tile(image: Arc<RenderImage>, page: usize, view: gpui::Entity<PdfView>)
canvas(
|_, _, _| {},
move |bounds, _, window, cx| match window.paint_image(bounds, bounds, Default::default(), image, 0, false) {
Ok(()) if !view.read(cx).drawn => {
view.update(cx, |view, _| view.drawn = true);
log::info!("pdf: first tile drawn, page {page}");
}
Ok(()) => {}
Ok(()) => view.update(cx, |view, _| {
let area = f64::from(f32::from(bounds.size.width) * f32::from(bounds.size.height));
if view.painted == 0.0 && area > 0.0 {
log::info!("pdf: first tile drawn, page {page}");
}
view.painted += area;
}),
Err(error) => log::error!("pdf: drawing a page failed: {error}"),
},
)
@@ -127,18 +129,14 @@ impl PdfView {
(colors.sunken, if dark { colors.surface } else { colors.paper })
};
let laid = self.laid_out();
let (room_w, room_h) = (f32::from(self.room.size.width), f32::from(self.room.size.height));
if let Some((x, y)) = self.go_to.take() {
self.scroll.set_offset(point(px(-x), px(-y)));
}
let (left, top) = (-f32::from(self.scroll.offset().x), -f32::from(self.scroll.offset().y));
let shown: Vec<Placed> = visible(&laid, top, top + room_h)
.filter(|p| p.x < left + room_w && p.x + p.w > left)
.copied()
.collect();
let top = -f32::from(self.scroll.offset().y);
let showing = self.showing(sf, dark);
// The current page: first showing more than a sliver.
if let Some(first) = shown.iter().find(|p| p.y + p.h > top + GAP * 3.0) {
let paired = shown.iter().any(|p| p.page == self.current) && first.page / 2 == self.current / 2;
if let Some(first) = showing.iter().map(|s| s.place).find(|p| p.y + p.h > top + GAP * 3.0) {
let paired = showing.iter().any(|s| s.place.page == self.current) && first.page / 2 == self.current / 2;
let now = match self.mode {
Mode::Single => self.current,
// Either page of a pair in view may be current.
@@ -150,47 +148,33 @@ impl PdfView {
cx.emit(Reported);
}
}
let scale = (laid.scale * sf * 1000.0).round() as u32;
let (mut wanted, mut pages, mut seen) = (Vec::new(), Vec::new(), HashSet::new());
for place in &shown {
let (dw, dh) = ((place.w * sf).ceil() as i32, (place.h * sf).ceil() as i32);
let (ys, xs) = (
span(top - place.y, top + room_h - place.y, sf, dh),
span(left - place.x, left + room_w - place.x, sf, dw),
);
let mut tiles = Vec::new();
for ty in ys {
for tx in xs.clone() {
let key = TileKey { page: place.page, scale, rotate: self.rotate, dark, tx, ty };
let rect = [tx * TILE, ty * TILE, TILE.min(dw - tx * TILE), TILE.min(dh - ty * TILE)];
seen.insert(key);
match self.tiles.get(&key) {
Some(image) => tiles.push(
drawn_tile(image.clone(), place.page, cx.entity())
.absolute()
.left(px(rect[0] as f32 / sf))
.top(px(rect[1] as f32 / sf))
.w(px(rect[2] as f32 / sf))
.h(px(rect[3] as f32 / sf))
.into_any_element(),
),
None if !self.failed.contains(&key) => wanted.push((key, rect)),
None => {}
}
}
}
pages.push((*place, tiles));
}
// Tiles out of view go.
let retired = &mut self.retired;
self.tiles.retain(|key, image| {
let kept = seen.contains(key);
if !kept {
retired.push(image.clone());
}
kept
});
let pages_shown: Vec<usize> = shown.iter().map(|place| place.page).collect();
let wanted: Vec<(TileKey, [i32; 4])> = showing
.iter()
.flat_map(|s| s.keys.iter().copied())
.filter(|(key, _)| !self.tiles.contains_key(key) && !self.failed.contains(key))
.collect();
let pages: Vec<(Placed, Vec<AnyElement>)> = showing
.iter()
.map(|s| {
let (w, h) = (s.place.w, s.place.h);
let tiles = self
.pieces(s)
.into_iter()
.map(|(image, at)| {
drawn_tile(image, s.place.page, cx.entity())
.absolute()
.left(px(at[0] * w))
.top(px(at[1] * h))
.w(px(at[2] * w))
.h(px(at[3] * h))
.into_any_element()
})
.collect();
(s.place, tiles)
})
.collect();
self.settle(&showing);
let pages_shown: Vec<usize> = showing.iter().map(|s| s.place.page).collect();
self.ask_layers(&pages_shown, cx);
self.ask_notes(pages_shown.iter().copied(), cx);
self.paint(wanted, cx);
+3 -3
View File
@@ -46,9 +46,9 @@ fn masked(window: &mut Window, cx: &mut Context<Viewer>) -> Entity<TextInput> {
impl Viewer {
/// A refusal names what is missing.
pub(crate) fn failed(&self, error: &io::Error, cx: &mut App) {
match error.kind() {
io::ErrorKind::PermissionDenied => self.toast(crate::view::restricted(&error.to_string(), cx), Severity::Warning, cx),
_ => self.panel_failed(&error.to_string(), cx),
match ely_pdf_engine::refused(error) {
Some(needed) => self.toast(crate::view::restricted(needed, cx), Severity::Warning, cx),
None => self.panel_failed(&error.to_string(), cx),
}
}
+3 -3
View File
@@ -185,7 +185,7 @@ impl Viewer {
},
move |viewer, done, _, cx| match done {
Ok(0) => viewer.toast_output(Self::text(cx, "pdf.clean.done", &[("name", &shown)]), opened.clone(), cx),
Ok(n) => viewer.toast_output(Self::text(cx, "pdf.redact.done", &[("name", &shown), ("count", &n.to_string())]), opened.clone(), cx),
Ok(n) => viewer.toast_output(ely_ui::i18n::counted(cx, "pdf.redact.done", n as u64, &[("name", &shown), ("count", &n.to_string())]), opened.clone(), cx),
Err(error) => viewer.failed(&error, cx),
},
cx,
@@ -200,8 +200,8 @@ impl Viewer {
let (title, body) = match removal {
Removal::Clean { reach, what, .. } => ("pdf.clean.title", self.clean_rows(reach, *what, &this, cx)),
Removal::Redact { regions, .. } => {
let count = regions.len().to_string();
("pdf.redact.title", div().child(Self::text(cx, "pdf.redact.count", &[("count", &count)])).into_any_element())
let count = ely_ui::i18n::counted(cx, "pdf.redact.count", regions.len() as u64, &[("count", &regions.len().to_string())]);
("pdf.redact.title", div().child(count).into_any_element())
}
};
let title = Self::text(cx, title, &[("name", &name)]);
+13 -4
View File
@@ -1,6 +1,6 @@
//! Page pictures, and bookmarks if any (PDF-01, PDF-02).
use std::{collections::BTreeSet, ops::Range};
use std::{collections::BTreeSet, ops::Range, sync::Arc};
use ely_gpui_component::{
buttons::SegmentedControl,
@@ -9,7 +9,7 @@ use ely_gpui_component::{
theme::{ActiveTheme as _, ControlSize},
};
use gpui::{
Action, App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, Role,
Action, App, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render, RenderImage, Role,
StatefulInteractiveElement as _, Styled as _, WeakEntity, Window, div, img, prelude::FluentBuilder as _, px,
uniform_list,
};
@@ -104,7 +104,8 @@ impl PdfView {
if self.thumbing {
return;
}
let Some(page) = rows.clone().find(|page| !self.thumbs.contains_key(&(*page, dark)) && !self.thumbs_failed.contains(page)) else {
let due = |page: &usize| !self.thumbs.contains_key(&(*page, dark)) || self.thumbs_stale.contains(&(*page, dark));
let Some(page) = rows.clone().find(|page| due(page) && !self.thumbs_failed.contains(page)) else {
return;
};
let (w, h) = self.sizes[page];
@@ -127,6 +128,7 @@ impl PdfView {
});
match painted.map(|bgra| crate::pages::picture((tile[2] as u32, tile[3] as u32), bgra)) {
Ok(Some(image)) => {
view.thumbs_stale.remove(&(page, dark));
if let Some(old) = view.thumbs.insert((page, dark), image) {
view.retired.push(old);
}
@@ -145,13 +147,20 @@ impl PdfView {
}
}
impl PdfView {
/// The picture a row draws; an old one until repainted.
pub fn picture(&self, page: usize, dark: bool) -> Option<Arc<RenderImage>> {
self.thumbs.get(&(page, dark)).cloned()
}
}
/// One row: the page number and its picture.
fn row(view: &Entity<PdfView>, page: usize, dark: bool, cx: &App) -> gpui::AnyElement {
let read = view.read(cx);
let colors = &cx.theme().colors;
let (w, h) = read.sizes[page];
let picked = read.picked.contains(&page);
let picture = read.thumbs.get(&(page, dark)).cloned();
let picture = read.picture(page, dark);
let count = read.sizes.len();
let label = Viewer::text(cx, "pdf.page.label", &[("n", &(page + 1).to_string())]);
let (clicked, pressed, dropped) = (view.clone(), view.clone(), view.clone());
+59 -1
View File
@@ -1,6 +1,6 @@
//! Editing text and objects from the app (C11.3).
use ely_pdf_engine::sample::{Extras, pdf_with};
use ely_pdf_engine::sample::{Extras, one_page, pdf_with};
use gpui::{Entity, Modifiers, MouseButton, TestAppContext, VisualTestContext};
use super::input::over;
@@ -339,3 +339,61 @@ fn a_drag_follows_the_hand_when_the_page_shifts_under_it() {
let rect = cx.update(|_, app| view.read(app).layers[&0].drawn[1].rect);
assert!((rect[0] - 122.0).abs() < 0.5, "moved as far as the hand: {rect:?}");
}
#[test]
fn text_on_a_full_page_picture_aims_at_the_text_and_a_shake_stays_a_click() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut cx = TestAppContext::single();
let path = dir.path().join("scan.pdf");
let extras = Extras { picture: true, backdrop: true, ..Extras::default() };
std::fs::write(&path, pdf_with(&[(612.0, 792.0, &["Hello world"])], &[], &extras)).expect("writes");
let (viewer, cx) = windowed(&mut cx, dir.path(), &[path], true);
let view = shown(cx, &viewer);
settle(cx, |app| view.read(app).room.size.width > gpui::px(100.0));
cx.update(|_, app| view.update(app, |view, cx| {
view.zoom = crate::layout::Zoom::Scale(1.0);
view.set_tool(Tool::Edit, cx)
}));
settle(cx, |app| view.read(app).layers.contains_key(&0));
click(cx, &view, (80.0, 66.0));
assert!(matches!(cx.update(|_, app| view.read(app).aim), Some(Aim::Text { .. })), "the text, not the picture under it");
// A two-pixel wobble on the picture moves nothing.
let from = over(cx, &view, 0, (300.0, 400.0));
cx.simulate_mouse_down(from, MouseButton::Left, Modifiers::none());
let to = from + gpui::point(gpui::px(2.0), gpui::px(0.0));
cx.simulate_mouse_move(to, MouseButton::Left, Modifiers::none());
cx.simulate_mouse_up(to, MouseButton::Left, Modifiers::none());
frames(cx);
assert!(matches!(cx.update(|_, app| view.read(app).aim), Some(Aim::Object { .. })), "the picture is aimed");
assert_eq!(cx.update(|_, app| view.read(app).edited), 0, "and not moved");
}
#[test]
fn a_small_picture_on_text_under_a_page_form_still_aims() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut cx = TestAppContext::single();
let path = dir.path().join("layered.pdf");
// The page-size form comes last, on top of both.
let content = "q 10 0 0 10 80 722 cm /Im1 Do Q BT /F1 18 Tf 72 720 Td (Hello world) Tj ET q /Fm1 Do Q";
let form = "0 0 1 rg 500 50 20 20 re f";
let objects = [
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string(),
format!("<< /Type /XObject /Subtype /Form /BBox [0 0 612 792] /Length {} >>\nstream\n{form}\nendstream", form.len()),
"<< /Type /XObject /Subtype /Image /Width 1 /Height 1 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 1 >>\nstream\nA\nendstream".to_string(),
];
let page = " /Resources << /Font << /F1 5 0 R >> /XObject << /Fm1 6 0 R /Im1 7 0 R >> >>";
std::fs::write(&path, one_page("", page, content, &objects)).expect("writes");
let (viewer, cx) = windowed(&mut cx, dir.path(), &[path], true);
let view = shown(cx, &viewer);
settle(cx, |app| view.read(app).room.size.width > gpui::px(100.0));
cx.update(|_, app| view.update(app, |view, cx| {
view.zoom = crate::layout::Zoom::Scale(1.0);
view.set_tool(Tool::Edit, cx)
}));
settle(cx, |app| view.read(app).layers.contains_key(&0));
// The picture sits at 80..90 across, 60..70 down.
click(cx, &view, (85.0, 65.0));
assert!(matches!(cx.update(|_, app| view.read(app).aim), Some(Aim::Object { index: 0, .. })), "the small picture");
click(cx, &view, (140.0, 66.0));
assert!(matches!(cx.update(|_, app| view.read(app).aim), Some(Aim::Text { .. })), "the text, not the form around it");
}
+169
View File
@@ -185,3 +185,172 @@ fn tiles_beside_the_view_are_neither_asked_nor_kept() {
}));
settle(cx, |app| columns(app).contains(&last) && !columns(app).contains(&0));
}
/// Flags any notify leaving a shown page with nothing drawn.
fn never_bare(cx: &mut VisualTestContext, view: &Entity<PdfView>) -> (gpui::Subscription, std::rc::Rc<std::cell::Cell<bool>>) {
let (sf, dark) = cx.update(|window, app| (window.scale_factor(), ely_gpui_component::theme::ActiveTheme::theme(app).is_dark()));
let bare = std::rc::Rc::new(std::cell::Cell::new(false));
let seen = bare.clone();
let watch = cx.update(|_, app| {
app.observe(view, move |view, app| {
let read = view.read(app);
if read.showing(sf, dark).iter().any(|page| read.pieces(page).is_empty()) {
seen.set(true);
}
})
});
(watch, bare)
}
/// Only new tiles drawn, and none on its way.
fn repainted(view: &PdfView) -> bool {
view.backdrop.is_empty() && !view.painting && !view.tiles.is_empty()
}
fn note() -> ely_pdf_engine::NewAnnot {
ely_pdf_engine::NewAnnot {
page: 0,
shape: ely_pdf_engine::Shape::Note((100.0, 500.0)),
rgb: None,
contents: "Look".into(),
author: String::new(),
}
}
#[test]
fn an_edit_keeps_the_page_drawn_until_its_repaint_lands() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut cx = TestAppContext::single();
let (viewer, cx) = windowed(&mut cx, dir.path(), &[file(dir.path(), "one.pdf", &[(612.0, 792.0, &["Hello"])])], true);
let view = shown(cx, &viewer);
settle(cx, |app| repainted(view.read(app)));
let before: Vec<_> = cx.update(|_, app| view.read(app).tiles.values().cloned().collect());
let (_watch, bare) = never_bare(cx, &view);
cx.update(|_, app| view.update(app, |view, cx| view.annotate("adding a note", vec![note()], cx)));
settle(cx, |app| view.read(app).edited == 1 && repainted(view.read(app)));
assert!(!bare.get(), "the page never goes blank");
let after = cx.update(|_, app| view.read(app).tiles.values().cloned().collect::<Vec<_>>());
assert!(
after.iter().all(|image| before.iter().all(|old| !std::sync::Arc::ptr_eq(old, image))),
"every tile was painted again"
);
}
#[test]
fn a_new_scale_keeps_the_old_tiles_until_new_ones_land() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut cx = TestAppContext::single();
let (viewer, cx) = windowed(&mut cx, dir.path(), &[file(dir.path(), "one.pdf", &[(612.0, 792.0, &["Hello"])])], true);
let view = shown(cx, &viewer);
settle(cx, |app| repainted(view.read(app)));
let scale = cx.update(|_, app| view.read(app).laid_out().scale);
let (_watch, bare) = never_bare(cx, &view);
cx.simulate_resize(gpui::size(px(700.), px(800.)));
// The new size lays out before any new tile lands.
cx.run_until_parked();
let (sf, dark) = cx.update(|window, app| (window.scale_factor(), ely_gpui_component::theme::ActiveTheme::theme(app).is_dark()));
let now = cx.update(|_, app| {
let read = view.read(app);
read.showing(sf, dark).iter().map(|page| read.pieces(page).len()).collect::<Vec<_>>()
});
assert!(now.iter().all(|count| *count > 0), "drawn right after the resize: {now:?}");
settle(cx, |app| view.read(app).laid_out().scale != scale && repainted(view.read(app)));
assert!(!bare.get(), "the page never goes blank");
}
#[test]
fn an_edit_past_the_first_hundred_sizes_keeps_the_page_drawn() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut pages: Vec<(f32, f32, &[&str])> = vec![(612.0, 792.0, &["Page"]); 100];
pages.push((612.0, 900.0, &["Taller"]));
let mut cx = TestAppContext::single();
let (viewer, cx) = windowed(&mut cx, dir.path(), &[file(dir.path(), "mixed.pdf", &pages)], true);
let view = shown(cx, &viewer);
settle(cx, |app| view.read(app).sizes[100] == (612.0, 900.0) && repainted(view.read(app)));
let (_watch, bare) = never_bare(cx, &view);
cx.update(|_, app| view.update(app, |view, cx| view.annotate("adding a note", vec![note()], cx)));
settle(cx, |app| view.read(app).edited == 1 && repainted(view.read(app)));
assert!(!bare.get(), "the page never goes blank");
}
#[test]
fn an_edit_on_page_101_keeps_its_measured_size_and_its_tiles() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut pages: Vec<(f32, f32, &[&str])> = vec![(612.0, 792.0, &["Page"]); 100];
pages.push((612.0, 900.0, &["Taller"]));
let mut cx = TestAppContext::single();
let (viewer, cx) = windowed(&mut cx, dir.path(), &[file(dir.path(), "mixed.pdf", &pages)], true);
let view = shown(cx, &viewer);
settle(cx, |app| view.read(app).sizes[100] == (612.0, 900.0));
cx.update(|_, app| view.update(app, |view, cx| view.show(100, 0.0, cx)));
settle(cx, |app| view.read(app).current == 100 && repainted(view.read(app)));
let (_watch, bare) = never_bare(cx, &view);
let late = ely_pdf_engine::NewAnnot { page: 100, ..note() };
cx.update(|_, app| view.update(app, |view, cx| view.annotate("adding a note", vec![late], cx)));
settle(cx, |app| view.read(app).edited == 1 && repainted(view.read(app)));
assert!(!bare.get(), "page 101 never goes blank");
assert_eq!(cx.update(|_, app| view.read(app).sizes[100]), (612.0, 900.0), "its measured size holds");
}
#[test]
fn old_tiles_are_painted_and_freed_with_their_tab() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut cx = TestAppContext::single();
let (viewer, cx) = windowed(&mut cx, dir.path(), &[file(dir.path(), "one.pdf", &[(612.0, 792.0, &["Hello"])])], true);
let view = shown(cx, &viewer);
settle(cx, |app| repainted(view.read(app)));
// Nothing new is asked; only old tiles can paint.
let before = cx.update(|_, app| {
view.update(app, |view, cx| {
let keys: Vec<_> = view.tiles.keys().copied().collect();
view.failed.extend(keys);
view.keep_all();
cx.notify();
view.painted
})
});
cx.run_until_parked();
let (painted, kept) = cx.update(|_, app| (view.read(app).painted, view.read(app).backdrop.len()));
// Old tiles cover what shows of the page.
let shown = cx.update(|window, app| {
let read = view.read(app);
let room = read.room;
read.showing(window.scale_factor(), false).iter().map(|s| {
let (left, top) = (-f32::from(read.scroll.offset().x), -f32::from(read.scroll.offset().y));
let w = (s.place.x + s.place.w).min(left + f32::from(room.size.width)) - s.place.x.max(left);
let h = (s.place.y + s.place.h).min(top + f32::from(room.size.height)) - s.place.y.max(top);
f64::from(w.max(0.0) * h.max(0.0))
}).sum::<f64>()
});
assert!(kept > 0 && painted - before >= shown * 0.99, "{kept} old tiles painted {} of {shown}", painted - before);
cx.update(|_, app| view.update(app, |view, _| view.retire_all()));
assert!(cx.update(|_, app| view.read(app).backdrop.is_empty()), "closing hands every old tile over");
}
#[test]
fn an_edit_keeps_page_pictures_until_they_repaint() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut cx = TestAppContext::single();
let (viewer, cx) = windowed(&mut cx, dir.path(), &[file(dir.path(), "one.pdf", &[(612.0, 792.0, &["Hello"])])], true);
let view = shown(cx, &viewer);
let dark = cx.update(|_, app| ely_gpui_component::theme::ActiveTheme::theme(app).is_dark());
settle(cx, |app| view.read(app).picture(0, dark).is_some() && repainted(view.read(app)));
let old = cx.update(|_, app| view.read(app).picture(0, dark).expect("a picture"));
// A picture on its way holds back the repaint.
cx.update(|_, app| view.update(app, |view, _| view.thumbing = true));
cx.update(|_, app| view.update(app, |view, cx| view.annotate("adding a note", vec![note()], cx)));
settle(cx, |app| view.read(app).edited == 1 && repainted(view.read(app)));
// Dropped from the atlas, it returns only if drawn.
cx.update(|window, _| window.drop_image(old.clone())).expect("drops");
super::frames(cx);
assert!(cx.update(|window, _| window.has_image_atlas_entry(&old)), "the old picture shows meanwhile");
cx.update(|_, app| view.update(app, |view, cx| {
view.thumbing = false;
cx.notify()
}));
settle(cx, |app| view.read(app).thumbs_stale.is_empty());
let new = cx.update(|_, app| view.read(app).picture(0, dark).expect("a picture"));
assert!(!std::sync::Arc::ptr_eq(&new, &old), "the new picture replaces it");
super::frames(cx);
assert!(cx.update(|window, _| window.has_image_atlas_entry(&new)), "and is drawn");
}
+33
View File
@@ -33,6 +33,39 @@ fn pages_export_as_images_and_text() {
assert!(text.contains("First") && text.contains("Second"), "{text}");
}
#[cfg(unix)]
#[test]
fn a_write_the_system_refuses_reports_it_without_a_crash() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().expect("a temp dir");
let mut cx = TestAppContext::single();
let path = file(dir.path(), "doc.pdf", &[(612.0, 792.0, &["First"])]);
let (viewer, cx) = windowed(&mut cx, dir.path(), &[path], true);
shown(cx, &viewer);
let locked = dir.path().join("locked");
std::fs::create_dir(&locked).expect("a folder");
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o500)).expect("read-only");
let id = cx.update(|_, app| viewer.read(app).core.tabs[0].id);
let txt = locked.join("doc.txt");
let how = Optimizing { compress: true, from: 300, to: 0 };
// The window's toasts live on its root.
let root = cx.update(|window, app| {
let root = ely_ui::document_root(ely_platform::AppId::Pdf, viewer.clone().into(), &ely_ui::commands::FILE, Vec::new(), window, app);
viewer.update(app, |viewer, _| viewer.core.root = root.downgrade());
root
});
cx.update(|_, app| viewer.update(app, |viewer, cx| viewer.write_export(id, Kind::Text, how, txt.clone(), cx)));
let failed = |app: &gpui::App| {
let toasts = root.read(app).toasts(app);
toasts.iter().any(|(text, severity)| {
*severity == Some(ely_gpui_component::primitives::Severity::Danger) && text.contains("Permission denied")
})
};
settle(cx, failed);
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o700)).expect("writable again");
assert!(!txt.exists(), "nothing is written");
}
#[test]
fn a_damaged_file_opens_repaired_and_saves_as_a_new_file() {
let dir = tempfile::tempdir().expect("a temp dir");
+17 -7
View File
@@ -37,10 +37,12 @@ pub struct PdfView {
pub tiles: HashMap<TileKey, Arc<RenderImage>>,
/// Images no longer drawn, freed at the next render.
pub retired: ely_gpui_component::primitives::Retired,
/// A tile reached the screen; logged once (PERF-05).
pub drawn: bool,
/// Tile pixels painted; the first paint is logged (PERF-05).
pub painted: f64,
/// Tiles the worker could not draw; not asked again.
pub failed: HashSet<TileKey>,
/// Old tiles shown under their page until covered.
pub backdrop: Vec<crate::backdrop::Old>,
pub text: HashMap<usize, Arc<Vec<Char>>>,
pub asking_text: HashSet<usize>,
pub marks: Vec<Bookmark>,
@@ -69,6 +71,8 @@ pub struct PdfView {
/// Page pictures for the side panel, by page and darkness.
pub thumbs: HashMap<(usize, bool), Arc<RenderImage>>,
pub thumbs_failed: HashSet<usize>,
/// Pictures from before an edit; shown until repainted.
pub thumbs_stale: HashSet<(usize, bool)>,
/// A picture is on its way from the worker.
pub thumbing: bool,
/// Pages picked in the side panel, and the anchor.
@@ -143,7 +147,8 @@ impl PdfView {
pub fn retire_all(&mut self) -> ely_gpui_component::primitives::Retired {
let mut images = std::mem::take(&mut self.retired);
let tiles = self.tiles.drain().map(|(_, image)| image);
for image in tiles.chain(self.thumbs.drain().map(|(_, image)| image)) {
let old = self.backdrop.drain(..).map(|old| old.image);
for image in tiles.chain(old).chain(self.thumbs.drain().map(|(_, image)| image)) {
images.push(image);
}
images
@@ -164,8 +169,9 @@ impl PdfView {
scroll: ScrollHandle::new(),
tiles: HashMap::new(),
retired: Default::default(),
drawn: false,
painted: 0.0,
failed: HashSet::new(),
backdrop: Vec::new(),
text: HashMap::new(),
asking_text: HashSet::new(),
marks: loaded.marks,
@@ -184,6 +190,7 @@ impl PdfView {
mark: loaded.mark,
thumbs: HashMap::new(),
thumbs_failed: HashSet::new(),
thumbs_stale: HashSet::new(),
thumbing: false,
picked: BTreeSet::new(),
anchor: None,
@@ -223,10 +230,10 @@ impl PdfView {
pub fn fail(&self, what: &str, error: &io::Error, cx: &mut Context<Self>) {
// Engine text may quote the document: the user sees it.
log::error!("pdf: {what} failed ({:?})", error.kind());
let text = match error.kind() {
let text = match ely_pdf_engine::refused(error) {
_ if ely_pdf_engine::is_stale(error) => ely_ui::i18n::text(cx, "pdf.object.changed", &[]),
io::ErrorKind::PermissionDenied => restricted(&error.to_string(), cx),
_ => ely_ui::i18n::text(cx, "pdf.failed", &[("what", what), ("error", &error.to_string())]),
Some(needed) => restricted(needed, cx),
None => ely_ui::i18n::text(cx, "pdf.failed", &[("what", what), ("error", &error.to_string())]),
};
cx.emit(Failed(text.to_string()));
}
@@ -311,6 +318,9 @@ impl PdfView {
/// Every page tile goes; images are freed next render.
pub fn retire_tiles(&mut self) {
for old in self.backdrop.drain(..) {
self.retired.push(old.image);
}
for (_, image) in self.tiles.drain() {
self.retired.push(image);
}
+1 -2
View File
@@ -115,7 +115,7 @@ pub fn open(app: AppId, window: &mut Window, cx: &mut App) -> Entity<Root> {
let root = ely_ui::document_root(app, viewer.clone().into(), &commands::FILE, crate::keys::menus(cx), window, cx);
viewer.update(cx, |viewer, cx| {
viewer.core.root = root.downgrade();
viewer.core.window = Some(window.window_handle());
viewer.own_window(window, cx);
window.focus(&viewer.core.focus, cx);
});
for path in ely_ui::launch_files(cx) {
@@ -247,7 +247,6 @@ impl Render for Viewer {
.on_action(cx.listener(Self::on_save_as))
.on_action(cx.listener(Self::on_export))
.on_action(cx.listener(Self::on_print))
.on_action(cx.listener(Self::on_quit))
.on_action(cx.listener(Self::on_close_tab))
.child(shell)
.children(self.core_dialog(cx))
+13 -57
View File
@@ -1,16 +1,15 @@
//! ElyShow's window: decks over one LOK worker (§10.1).
use std::{
collections::{HashMap, HashSet},
collections::HashSet,
path::PathBuf,
sync::{Arc, Mutex},
};
use ely_gpui_component::{feedback::EmptyState, primitives::IconName, shell::StatusBar};
use ely_lok::{
LokView, Sheets, Worker,
history::Step,
show::{Design, Objects},
LokView, Worker,
show::Design,
};
use ely_office::{Core, Kind, prelude::*};
use ely_platform::AppId;
@@ -18,61 +17,13 @@ use ely_ui::{Root, Shell, commands};
use gpui::prelude::FluentBuilder as _;
use gpui::{
AnyElement, App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, Render, RenderImage, SharedString, Styled as _, Window, div,
ParentElement as _, Render, SharedString, Styled as _, Window, div,
};
use crate::design::Panel;
use crate::slides::Strip;
/// Parts, edits, caret and selected frame.
pub type Seen = (u64, u64, bool, Option<ely_lok::Rect>);
/// What ElyShow keeps per deck.
#[derive(Default)]
pub struct Extra {
pub slides: Sheets,
/// The document as the last read saw it.
pub read_at: Option<ely_lok::Doc>,
/// What the view showed at the last read.
pub read: Option<Seen>,
pub reading: bool,
pub design: Option<Design>,
pub objects: Option<Objects>,
pub notes: Option<ely_lok::show::Notes>,
pub remarks: Vec<ely_lok::show::Remark>,
/// The shown slide's transition and effects; none on a master.
pub motion: Option<(ely_lok::show::Transition, Vec<ely_lok::show::Effect>)>,
pub media: Vec<ely_lok::show::Media>,
/// Counts completed reads.
pub reads: u64,
/// The slide size in twips.
pub size: (i64, i64),
/// Undo and redo lists at the last read.
pub history: Option<(Vec<Step>, Vec<Step>)>,
/// A size sent, in 1/100 mm, until read back.
pub size_asked: Option<(i64, i64)>,
/// A transition sent for a slide, until read back.
pub transition_asked: Option<(String, ely_lok::show::Transition, u64)>,
/// Pictures by slide name; stale ones show until repainted.
pub thumbs: HashMap<String, Arc<RenderImage>>,
pub retired: ely_gpui_component::primitives::Retired,
pub stale: HashSet<String>,
/// Pictures that failed; retried after the next read.
pub failed: HashSet<String>,
pub painting: bool,
/// The parts are masters.
pub masters: bool,
/// The scheme the pictures were painted with.
pub dark: Option<bool>,
}
impl Extra {
/// The size to show, in 1/100 mm: asked, else read.
pub fn shown_size(&self) -> (i64, i64) {
self.size_asked
.unwrap_or_else(|| crate::design::mm100(self.size))
}
}
pub use crate::extra::Extra;
pub struct Deck {
pub core: Core<Deck>,
@@ -137,7 +88,13 @@ impl Host for Deck {
}
fn observed(&mut self, id: u64, view: &Entity<LokView>, cx: &mut Context<Self>) {
view.update(cx, |view, cx| view.fit_page(cx));
// A new deck fits once; a zoom then stays.
if let Some(tab) = self.tab_mut(id)
&& !tab.extra.fitted
{
tab.extra.fitted = true;
view.update(cx, |view, cx| view.fit_page(cx));
}
// Pictures follow the kernel's light or dark scheme.
let dark = view.read(cx).dark();
if let Some(tab) = self.tab_mut(id)
@@ -176,7 +133,7 @@ pub fn open(app: AppId, window: &mut Window, cx: &mut App) -> Entity<Root> {
let root = ely_ui::document_root(app, deck.clone().into(), &ely_ui::commands::FILE, menus, window, cx);
deck.update(cx, |deck, cx| {
deck.core.root = root.downgrade();
deck.core.window = Some(window.window_handle());
deck.own_window(window, cx);
window.focus(&deck.core.focus, cx);
});
let launched = ely_ui::launch_files(cx);
@@ -491,7 +448,6 @@ impl Render for Deck {
.on_action(cx.listener(Self::on_save_as))
.on_action(cx.listener(Self::on_export))
.on_action(cx.listener(Self::on_print))
.on_action(cx.listener(Self::on_quit))
.on_action(cx.listener(Self::on_close_tab))
.child(shell)
.children(self.core_dialog(cx))
+65
View File
@@ -0,0 +1,65 @@
//! What ElyShow keeps per deck.
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use ely_lok::{
Sheets,
history::Step,
show::{Design, Objects},
};
use gpui::RenderImage;
/// Parts, edits, caret and selected frame.
pub type Seen = (u64, u64, bool, Option<ely_lok::Rect>);
/// What ElyShow keeps per deck.
#[derive(Default)]
pub struct Extra {
pub slides: Sheets,
/// The document as the last read saw it.
pub read_at: Option<ely_lok::Doc>,
/// What the view showed at the last read.
pub read: Option<Seen>,
pub reading: bool,
pub design: Option<Design>,
pub objects: Option<Objects>,
pub notes: Option<ely_lok::show::Notes>,
pub remarks: Vec<ely_lok::show::Remark>,
/// The shown slide's transition and effects; none on a master.
pub motion: Option<(ely_lok::show::Transition, Vec<ely_lok::show::Effect>)>,
pub media: Vec<ely_lok::show::Media>,
/// Counts completed reads.
pub reads: u64,
/// The slide size in twips.
pub size: (i64, i64),
/// Undo and redo lists at the last read.
pub history: Option<(Vec<Step>, Vec<Step>)>,
/// A size sent, in 1/100 mm, until read back.
pub size_asked: Option<(i64, i64)>,
/// A transition sent for a slide, until read back.
pub transition_asked: Option<(String, ely_lok::show::Transition, u64)>,
/// Pictures by slide name; stale ones show until repainted.
pub thumbs: HashMap<String, Arc<RenderImage>>,
pub retired: ely_gpui_component::primitives::Retired,
pub stale: HashSet<String>,
/// Pictures that failed; retried after the next read.
pub failed: HashSet<String>,
pub painting: bool,
/// The parts are masters.
pub masters: bool,
/// The scheme the pictures were painted with.
pub dark: Option<bool>,
/// The view was fitted to the slide once.
pub fitted: bool,
}
impl Extra {
/// The size to show, in 1/100 mm: asked, else read.
pub fn shown_size(&self) -> (i64, i64) {
self.size_asked
.unwrap_or_else(|| crate::design::mm100(self.size))
}
}
+1
View File
@@ -3,6 +3,7 @@ mod check;
mod deck;
mod design;
mod dialog;
mod extra;
mod guides;
mod insert;
mod list;
+2 -2
View File
@@ -292,8 +292,8 @@ impl Deck {
},
move |deck, written, _, cx| match written {
Ok(count) => {
let count = count.to_string();
let text = Deck::text(cx, "show.output.pictures_done", &[("n", &count), ("folder", &shown)]);
let n = count.to_string();
let text = ely_ui::i18n::counted(cx, "show.output.pictures_done", count as u64, &[("n", &n), ("folder", &shown)]);
deck.toast_output(text, opened.clone(), cx);
}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
+38 -3
View File
@@ -18,8 +18,8 @@ use ely_lok::{Doc, Worker, show::ShowSlide};
use ely_office::prelude::*;
use ely_platform::AppId;
use gpui::{
AnyElement, AnyWindowHandle, App, AppContext as _, Context, Entity, EntityId, IntoElement,
ParentElement as _, PlatformDisplay, Window, WindowBounds, WindowOptions,
AnyElement, AnyWindowHandle, App, AppContext as _, Bounds, Context, Entity, EntityId, IntoElement,
ParentElement as _, Pixels, PlatformDisplay, Window, WindowBounds, WindowOptions,
};
use super::{Show, audience::Audience, presenter::Presenter};
@@ -80,9 +80,20 @@ fn copy(
}
}
/// macOS covers its menu bar and Dock by simple fullscreen.
const SIMPLE: bool = cfg!(target_os = "macos");
/// A show window's bounds: fullscreen, or macOS's simple kind.
fn bounds(area: Bounds<Pixels>) -> WindowBounds {
match SIMPLE {
true => WindowBounds::Windowed(area),
false => WindowBounds::Fullscreen(area),
}
}
fn options(display: &Rc<dyn PlatformDisplay>) -> WindowOptions {
WindowOptions {
window_bounds: Some(WindowBounds::Fullscreen(display.bounds())),
window_bounds: Some(bounds(display.bounds())),
display_id: Some(display.id()),
titlebar: None,
focus: true,
@@ -91,6 +102,13 @@ fn options(display: &Rc<dyn PlatformDisplay>) -> WindowOptions {
}
}
/// Hides the menu bar and Dock over a macOS show.
fn cover(window: &mut Window) {
if SIMPLE {
window.toggle_simple_fullscreen();
}
}
/// Opens one show window; its root scope holds the keys.
pub fn show_window(
show: &Entity<Show>,
@@ -102,6 +120,7 @@ pub fn show_window(
Ok(match presenter {
true => cx
.open_window(options(display), |window, cx| {
cover(window);
let view = cx.new(|cx| Presenter::new(show, cx));
window.focus(&view.read(cx).focus.clone(), cx);
view
@@ -109,6 +128,7 @@ pub fn show_window(
.into(),
false => cx
.open_window(options(display), |window, cx| {
cover(window);
let view = cx.new(|cx| Audience::new(show, cx));
window.focus(&view.read(cx).focus.clone(), cx);
view
@@ -313,3 +333,18 @@ impl Deck {
.into_any_element()
}
}
#[cfg(test)]
mod tests {
use gpui::{Bounds, WindowBounds, point, px, size};
#[test]
fn a_show_covers_the_display_on_every_platform() {
let area = Bounds::new(point(px(0.), px(0.)), size(px(1920.), px(1080.)));
let want = match cfg!(target_os = "macos") {
true => WindowBounds::Windowed(area),
false => WindowBounds::Fullscreen(area),
};
assert_eq!(super::bounds(area), want);
}
}
+24
View File
@@ -384,3 +384,27 @@ fn a_comment_picked_on_another_slide_shows_its_slide_again() {
settle(&cx, |app| current(app) == Some(0));
assert_eq!(cx.update(|app| deck.read(app).shown_remark()), Some(key));
}
#[test]
fn a_zoom_stays_through_later_reports() {
use ely_gpui_component::shell::ZoomStep;
let dir = tempfile::tempdir().expect("a temp dir");
let mut cx = TestAppContext::single();
let Some(deck) = blank(&mut cx, dir.path()) else {
eprintln!("SKIP: no LOK build");
return;
};
let view = |app: &gpui::App| deck.read(app).active_tab().expect("a tab").view.clone();
settle(&cx, |app| view(app).read(app).fitting());
update(&mut cx, &deck, |deck, cx| deck.zoom(ZoomStep::In, cx));
let zoom = cx.update(|app| view(app).read(app).zoom());
update(&mut cx, &deck, |deck, cx| {
let (id, view) = deck.active_tab().map(|tab| (tab.id, tab.view.clone())).expect("a tab");
deck.observed(id, &view, cx);
});
cx.update(|app| {
let view = view(app);
assert!(!view.read(app).fitting(), "a report does not fit the slide again");
assert_eq!(view.read(app).zoom(), zoom, "the zoom stays");
});
}
+5 -3
View File
@@ -143,7 +143,7 @@ pub fn open(app: AppId, window: &mut Window, cx: &mut App) -> Entity<Root> {
let root = ely_ui::document_root(app, book.clone().into(), &ely_ui::commands::FILE, menus, window, cx);
book.update(cx, |book, cx| {
book.core.root = root.downgrade();
book.core.window = Some(window.window_handle());
book.own_window(window, cx);
window.focus(&book.core.focus, cx);
});
let launched = ely_ui::launch_files(cx);
@@ -229,7 +229,10 @@ impl Book {
match read {
Ok((sheets, geometry, at)) => {
log::info!("table: tab {id} has {} sheets", sheets.list.len());
view.update(cx, |view, _| view.set_part(sheets.current));
view.update(cx, |view, cx| {
view.set_part(sheets.current);
view.set_geometry(geometry.clone(), cx);
});
let extra = &mut tab.extra;
extra.sheets = sheets;
extra.geometry = geometry;
@@ -369,7 +372,6 @@ impl Render for Book {
.on_action(cx.listener(Self::on_open_file))
.on_action(cx.listener(Self::on_save))
.on_action(cx.listener(Self::on_save_as))
.on_action(cx.listener(Self::on_quit))
.on_action(cx.listener(Self::on_close_tab))
.on_action(cx.listener(Self::on_export))
.on_action(cx.listener(Self::on_print))
+1 -1
View File
@@ -311,7 +311,7 @@ impl Book {
move |book, picked, _, window, cx| {
let (c1, _, c2, _) = picked.area.expect("a data area");
if c1 != c2 {
return book.warn_key("table.columns.one", cx);
return book.warn_key("table.columns.same", cx);
}
let other = cx.new(|cx| TextInput::new(window, cx));
book.dialog = Some(Dialog::Columns {
+27 -2
View File
@@ -58,8 +58,8 @@ pub fn label(status: &str, cx: &App) -> SharedString {
if let Some((_, key)) = ERRORS.iter().find(|(known, _)| *known == status) {
return Book::text(cx, key, &[]);
}
let parts: Vec<String> = status
.split("; ")
let parts: Vec<String> = fields(status)
.into_iter()
.map(|part| {
let known = part.split_once(": ").and_then(|(name, value)| {
let (_, key) = FIGURES.iter().find(|(known, _)| *known == name)?;
@@ -74,6 +74,24 @@ pub fn label(status: &str, cx: &App) -> SharedString {
parts.join(" ").into()
}
/// The status split at each "Name: "; values keep semicolons.
fn fields(status: &str) -> Vec<&str> {
let starts = |rest: &str| {
rest.split_once(": ")
.is_some_and(|(name, _)| !name.is_empty() && name.chars().all(|c| c.is_ascii_alphabetic() || c == ' '))
};
let mut out = Vec::new();
let mut from = 0;
for (at, _) in status.match_indices("; ") {
if starts(&status[at + 2..]) {
out.push(&status[from..at]);
from = at + 2;
}
}
out.push(&status[from..]);
out
}
#[cfg(test)]
mod tests {
#[test]
@@ -89,6 +107,13 @@ mod tests {
super::Book::text(app, "table.figure.sum", &[("value", "42")])
);
assert_eq!(label.as_ref(), expect, "known names relabel, others stay");
// The kernel's formatted values pass through untouched.
ely_ui::i18n::install_as("en-US", app);
let custom = super::label("Average: 8128.00 kg; net; Sum: 16256.00 kg; net", app);
assert_eq!(custom.as_ref(), "Average 8128.00 kg; net Sum 16256.00 kg; net", "a format's own semicolons stay");
for value in ["8128.00", "8128.33333333333", "0.0000000001", "1234567890.25", "$1,234.50"] {
assert_eq!(super::label(&format!("Sum: {value}"), app).as_ref(), format!("Sum {value}"));
}
for (english, key) in super::ERRORS {
assert_eq!(super::label(english, app), super::Book::text(app, key, &[]));
}
+2 -2
View File
@@ -99,7 +99,7 @@ impl Book {
};
let length = if column { width } else { height };
let pick = |pair: (i32, i32)| if column { pair.0 } else { pair.1 };
let (frozen, scroll) = (pick(read.frozen()), pick(read.scroll()));
let (frozen, first) = (pick(read.frozen()), pick(read.scrolled_start()));
let mut spans = Vec::new();
let mut take = |index: u32| {
let (start, end) = (along(axis.start(index)), along(axis.start(index + 1)));
@@ -114,7 +114,7 @@ impl Book {
0
};
(0..held).for_each(&mut take);
let mut index = axis.at(frozen + scroll).max(held);
let mut index = axis.at(first).max(held);
while index < axis.count() && along(axis.start(index)) < length {
take(index);
index += 1;
+6 -10
View File
@@ -114,19 +114,15 @@ pub(crate) fn delete(
let mut detail = if references.formulas + references.names == 0 {
Book::text(cx, "table.delete.alone", &[])
} else {
Book::text(
cx,
"table.delete.refs",
&[
("formulas", &references.formulas.to_string()),
("first", &references.first),
("names", &references.names.to_string()),
],
)
let count = |key, n: u64| ely_ui::i18n::counted(cx, key, n, &[("n", &n.to_string())]);
let formulas = count("table.delete.formulas", references.formulas);
let names = count("table.delete.names", references.names);
let args = [("formulas", formulas.as_ref()), ("first", &references.first), ("names", &names)];
Book::text(cx, "table.delete.refs", &args)
};
if references.dynamic > 0 {
let count = references.dynamic.to_string();
let dynamic = Book::text(cx, "table.delete.dynamic", &[("count", &count)]);
let dynamic = ely_ui::i18n::counted(cx, "table.delete.dynamic", references.dynamic, &[("count", &count)]);
detail = format!("{detail} {dynamic}").into();
}
let label = Book::text(cx, "table.delete.go", &[]);
+2 -1
View File
@@ -95,9 +95,10 @@ impl Tree {
Ask::Force { repo, plan } => {
let lost = match plan.lost.len() {
0 => label("tree.force.nothing"),
n => text(
n => ely_ui::i18n::counted(
cx,
"tree.force.lost",
n as u64,
&[("n", &n.to_string()), ("commits", &plan.lost.join("\n"))],
),
};
+2 -2
View File
@@ -101,8 +101,8 @@ impl Tree {
};
let lines = (!shown.picked.is_empty() && self.partial(shown)).then(|| {
let this = this.clone();
let n = shown.picked.len().to_string();
Button::new("tree-lines", text(cx, key, &[("n", &n)]))
let n = shown.picked.len();
Button::new("tree-lines", ely_ui::i18n::counted(cx, key, n as u64, &[("n", &n.to_string())]))
.variant(ButtonVariant::Primary)
.size(ControlSize::Sm)
.on_click(move |_, _, cx| {
+2 -1
View File
@@ -205,9 +205,10 @@ impl Tree {
let short = |oid: &str| oid[..oid.len().min(7)].to_string();
let left = match plan.left.len() {
0 => label("tree.move.nothing"),
n => text(
n => ely_ui::i18n::counted(
cx,
"tree.move.left",
n as u64,
&[("n", &n.to_string()), ("commits", &plan.left.join("\n"))],
),
};
+23 -7
View File
@@ -209,13 +209,7 @@ impl Tree {
.iter()
.filter(|entry| entry.state != State::Ignored)
.count();
let (icon, title) = match changed {
0 => (IconName::CircleCheck, text(cx, "tree.clean", &[])),
n => (
IconName::GitBranch,
text(cx, "tree.changed", &[("n", &n.to_string())]),
),
};
let (icon, title) = summary(changed, cx);
EmptyState::new(("tree-summary", opened.id), icon, title).into_any_element()
}
}
@@ -263,3 +257,25 @@ impl Render for Tree {
.children(self.dialog(cx))
}
}
/// The work tree's line: clean, or how many files changed.
pub(crate) fn summary(changed: usize, cx: &App) -> (IconName, SharedString) {
match changed {
0 => (IconName::CircleCheck, text(cx, "tree.clean", &[])),
n => (IconName::GitBranch, ely_ui::i18n::counted(cx, "tree.changed", n as u64, &[("n", &n.to_string())])),
}
}
#[cfg(test)]
mod tests {
#[gpui::test]
fn the_summary_counts_files_in_both_languages(cx: &mut gpui::TestAppContext) {
cx.update(|cx| {
ely_ui::i18n::install_as("en-US", cx);
let said = |n: usize, cx: &gpui::App| super::summary(n, cx).1.to_string();
assert_eq!([said(0, cx), said(1, cx), said(2, cx)], ["Nothing to commit", "1 file changed", "2 files changed"]);
ely_ui::i18n::install_as("zh-CN", cx);
assert_eq!([said(1, cx), said(2, cx)], ["1 个文件有改动", "2 个文件有改动"]);
});
}
}
+16 -37
View File
@@ -16,6 +16,7 @@ mod doc;
mod feed;
mod frames;
mod install;
mod load;
pub use install::{install_dir, templates};
use install::worker_bin;
pub use doc::{Pdf, Sheet, Sheets};
@@ -37,6 +38,8 @@ pub struct Worker {
session: u64,
stderr: ely_ipc::Relay,
check: Check,
/// The name new comments sign with, once set.
author: Option<String>,
}
/// The start-up check: to run, passed, or why it failed.
@@ -73,9 +76,16 @@ pub struct Doc {
id: u64,
/// The document's revision when this handle was taken.
pub(crate) rev: u64,
/// LOK_DOCTYPE: 0 text, 1 spreadsheet, 2 presentation.
kind: u64,
}
impl Doc {
/// Whether this is a spreadsheet.
pub fn is_sheet(&self) -> bool {
self.kind == 1
}
/// Whether this handle saw a later state than `other`.
pub fn newer_than(&self, other: &Doc) -> bool {
self.rev > other.rev
@@ -181,6 +191,7 @@ impl Worker {
session: SESSIONS.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
stderr,
check: Check::Pending(profile_dir.to_path_buf()),
author: None,
};
Ok(worker)
}
@@ -194,47 +205,15 @@ impl Worker {
/// The name new comments and tracked changes carry.
pub fn set_author(&mut self, name: &str) -> io::Result<()> {
log::info!("lok: the author is set");
// Wanted even if this worker fails; a restart sends it.
self.author = Some(name.to_string());
self.request(tag::SET_AUTHOR, &Pack::new().str(name).bytes())?;
Ok(())
}
/// Loads `url`; macros never run (LOK-11).
pub fn load(&mut self, url: &str) -> io::Result<Doc> {
self.unlock(url, "")
}
/// Loads text `url` as a sheet, read as `how` says.
pub fn import(&mut self, url: &str, how: &crate::sheet::csv::Import) -> io::Result<Doc> {
use crate::sheet::csv::{COLUMNS, ENCODINGS};
let at = |found: Option<usize>| found.expect("a listed choice") as u64;
let pack = Pack::new()
.str(url)
.u64(u64::from(how.separator))
.u64(how.quote.map_or(0, u64::from))
.u64(at(ENCODINGS.iter().position(|e| *e == how.encoding)))
.u64(how.columns.len() as u64);
let pack = how.columns.iter().fold(pack, |pack, column| {
pack.u64(at(COLUMNS.iter().position(|c| c == column)))
});
let payload = self.request(tag::IMPORT, &pack.bytes())?;
let id = Unpack::new(&payload).u64()?;
self.feed.opened(id);
Ok(Doc { worker: self.session, id, rev: 0 })
}
/// Loads `url` with its password; a locked one is PermissionDenied.
pub fn unlock(&mut self, url: &str, password: &str) -> io::Result<Doc> {
let request = Pack::new().str(url).str(password).bytes();
let payload = self.request(tag::LOAD, &request).map_err(|error| {
if error.to_string() == crate::ipc::LOCKED {
io::Error::new(io::ErrorKind::PermissionDenied, error.to_string())
} else {
error
}
})?;
let id = Unpack::new(&payload).u64()?;
self.feed.opened(id);
Ok(Doc { worker: self.session, id, rev: 0 })
/// The name last asked for; a restart signs with it.
pub fn author(&self) -> Option<&str> {
self.author.as_deref()
}
/// Runs a macro by its URL (LOK-11 probe).
+36 -3
View File
@@ -55,14 +55,16 @@ impl Doc {
Ok(Sheets { current, list })
}
/// Tells the kernel the area the view shows, in twips.
pub fn visible_area(&self, worker: &mut Worker, (x, y, w, h): Rect) -> io::Result<()> {
/// Tells the kernel the shown area and the tile scale.
pub fn visible_area(&self, worker: &mut Worker, (x, y, w, h): Rect, (tile, tile_twips): (u32, i32)) -> io::Result<()> {
let request = Pack::new()
.u64(worker.doc_id(self)?)
.i64(x.into())
.i64(y.into())
.i64(w.into())
.i64(h.into())
.i64(tile.into())
.i64(tile_twips.into())
.bytes();
worker.request(tag::VISIBLE_AREA, &request)?;
Ok(())
@@ -178,7 +180,38 @@ impl Doc {
.u64(u64::from(pixels.0))
.u64(u64::from(pixels.1))
.bytes();
crate::show::layers(&worker.request(tag::SLIDE_LAYERS, &request)?)
let head = worker.request(tag::SLIDE_LAYERS, &request)?;
let mut unpack = Unpack::new(&head);
let (width, height, count) = (unpack.u64()?, unpack.u64()?, unpack.u64()?);
// Layers arrive in pieces that keep each frame small.
let mut whole = Pack::new().u64(width).u64(height).u64(count);
for index in 0..count {
let (json, painted) = (unpack.str()?, unpack.u64()?);
whole = whole.str(&json).u64(painted);
if painted != 0 {
whole = whole.blob(&self.slide_layer(worker, index)?);
}
}
crate::show::layers(&whole.bytes())
}
/// Layer `index` of the last layers read, piece by piece.
fn slide_layer(&self, worker: &mut Worker, index: u64) -> io::Result<Vec<u8>> {
let id = worker.doc_id(self)?;
let mut pixels = Vec::new();
loop {
let ask = Pack::new().u64(id).u64(index).u64(pixels.len() as u64).bytes();
let reply = worker.request(tag::SLIDE_LAYER, &ask)?;
let mut unpack = Unpack::new(&reply);
let (total, piece) = (unpack.u64()?, unpack.blob()?);
pixels.extend_from_slice(&piece);
if pixels.len() as u64 >= total {
return Ok(pixels);
}
if piece.is_empty() {
return Err(io::Error::other(format!("layer {index} stopped at byte {}", pixels.len())));
}
}
}
/// Saves to `url` as `format`; failure surfaces (LOK-09).
+3 -3
View File
@@ -181,17 +181,17 @@ mod tests {
};
feed.push(1, first);
feed.push(1, second);
let batch = feed.wait(&Doc { worker: 0, id: 1, rev: 0 }, 0, 0).expect("a batch");
let batch = feed.wait(&Doc { worker: 0, id: 1, rev: 0, kind: 0 }, 0, 0).expect("a batch");
assert_eq!((batch.seq, batch.all, batch.rects.len()), (2, true, 1));
assert_eq!(
batch.states,
[("b".to_string(), "1".to_string()), ("a".into(), "2".into())]
);
let idle = feed.wait(&Doc { worker: 0, id: 1, rev: 0 }, 2, 0).expect("the snapshot");
let idle = feed.wait(&Doc { worker: 0, id: 1, rev: 0, kind: 0 }, 2, 0).expect("the snapshot");
assert!(idle.rects.is_empty() && idle.states.is_empty() && idle.seq == 2);
feed.closed(1);
assert!(
feed.wait(&Doc { worker: 0, id: 1, rev: 0 }, 2, 0).is_err(),
feed.wait(&Doc { worker: 0, id: 1, rev: 0, kind: 0 }, 2, 0).is_err(),
"a closed document"
);
}
+51
View File
@@ -0,0 +1,51 @@
//! Loading documents: by URL, with a password, or as text.
use std::io;
use super::{Doc, Worker};
use crate::ipc::{Pack, Unpack, tag};
impl Worker {
/// Loads `url`; macros never run (LOK-11).
pub fn load(&mut self, url: &str) -> io::Result<Doc> {
self.unlock(url, "")
}
/// Loads text `url` as a sheet, read as `how` says.
pub fn import(&mut self, url: &str, how: &crate::sheet::csv::Import) -> io::Result<Doc> {
use crate::sheet::csv::{COLUMNS, ENCODINGS};
let at = |found: Option<usize>| found.expect("a listed choice") as u64;
let pack = Pack::new()
.str(url)
.u64(u64::from(how.separator))
.u64(how.quote.map_or(0, u64::from))
.u64(at(ENCODINGS.iter().position(|e| *e == how.encoding)))
.u64(how.columns.len() as u64);
let pack = how.columns.iter().fold(pack, |pack, column| {
pack.u64(at(COLUMNS.iter().position(|c| c == column)))
});
let payload = self.request(tag::IMPORT, &pack.bytes())?;
self.opened(&payload)
}
/// Loads `url` with its password; a locked one is PermissionDenied.
pub fn unlock(&mut self, url: &str, password: &str) -> io::Result<Doc> {
let request = Pack::new().str(url).str(password).bytes();
let payload = self.request(tag::LOAD, &request).map_err(|error| {
if error.to_string() == crate::ipc::LOCKED {
io::Error::new(io::ErrorKind::PermissionDenied, error.to_string())
} else {
error
}
})?;
self.opened(&payload)
}
/// A load's reply: the document's number and kind.
fn opened(&mut self, payload: &[u8]) -> io::Result<Doc> {
let mut reply = Unpack::new(payload);
let (id, kind) = (reply.u64()?, reply.u64()?);
self.feed.opened(id);
Ok(Doc { worker: self.session, id, rev: 0, kind })
}
}
+14 -21
View File
@@ -6,6 +6,7 @@ mod analysis;
mod charts;
mod check;
mod commands;
mod filter;
mod format;
mod formula;
mod handouts;
@@ -282,30 +283,22 @@ fn a_production_worker_refuses_run_macro() {
#[cfg(target_os = "macos")]
#[test]
fn an_unpatched_build_is_rejected() {
let dmg = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../engines/LibreOffice_26.2.6_MacOS_aarch64.dmg");
if !dmg.try_exists().expect("the dmg check") {
eprintln!("SKIP: no official dmg");
// A plain folder: a mounted .app would be registered.
let frameworks = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../engines/lo-official/Contents/Frameworks");
if !frameworks.try_exists().expect("the folder check") {
eprintln!("SKIP: run scripts/extract-official-lo.sh");
return;
}
let mount = tempfile::tempdir().expect("a temp dir");
let attached = std::process::Command::new("hdiutil")
.args(["attach", "-nobrowse", "-readonly", "-mountpoint"])
.arg(mount.path())
.arg(&dmg)
.status()
.expect("hdiutil runs");
assert!(attached.success(), "the official dmg mounts");
let frameworks = mount.path().join("LibreOffice.app/Contents/Frameworks");
let dir = tempfile::tempdir().expect("a temp dir");
let outcome = Worker::spawn(&frameworks, &dir.path().join("profile"));
assert!(outcome.is_err(), "the unpatched build must be rejected");
let detached = std::process::Command::new("hdiutil")
.args(["detach", "-quiet"])
.arg(mount.path())
.status()
.expect("hdiutil detaches");
assert!(detached.success());
let Err(error) = Worker::spawn(&frameworks, &dir.path().join("profile")) else {
panic!("the unpatched build must be rejected");
};
assert_eq!(error.kind(), std::io::ErrorKind::InvalidData, "{error}");
assert!(
error.to_string().contains("does not paint tiles (unpatched)"),
"rejected for the tile check, not {error}"
);
}
#[test]
@@ -3,6 +3,8 @@ use super::sheet::open_book;
use super::*;
use crate::sheet::{self, Layout, Look};
const SETTLE: std::time::Duration = std::time::Duration::from_secs(3);
/// Region, Year, Sales; four rows.
fn data() -> String {
let rows: String = [
@@ -331,3 +333,99 @@ fn undoing_a_new_kind_brings_the_whole_chart_back() {
"the stacking came back"
);
}
/// A sheet of ones filling each `(columns, rows)` block.
fn blocks(filled: &[(std::ops::RangeInclusive<usize>, std::ops::RangeInclusive<usize>)]) -> String {
sheet(&rows_of(filled))
}
/// Rows of ones filling each `(columns, rows)` block.
fn rows_of(filled: &[(std::ops::RangeInclusive<usize>, std::ops::RangeInclusive<usize>)]) -> String {
let height = filled.iter().map(|(_, rows)| *rows.end()).max().unwrap_or(0);
(1..=height)
.map(|r| {
let cells: String = (0..20)
.map(|c| match filled.iter().any(|(cols, rows)| cols.contains(&c) && rows.contains(&r)) {
true => r#"<table:table-cell office:value-type="float" office:value="1"><text:p>1</text:p></table:table-cell>"#,
false => "<table:table-cell/>",
})
.collect();
format!("<table:table-row>{cells}</table:table-row>")
})
.collect()
}
/// Charts `source` and checks it clears each data block.
fn charted(sheet: &str, visible: (i32, i32, i32, i32), (source, stand): (&str, &str), data: &[(&str, &str)]) {
let (_dir, mut worker, doc) = open_book(sheet);
doc.visible_area(&mut worker, visible, (256, 3840)).expect("the area");
let mut seen = poll_until(&mut worker, &doc, &Events::default(), SETTLE, |_| false);
let mut cell = |worker: &mut Worker, name: &str| {
worker.run(&doc, "cell.goto", &[name]).expect("the cell");
let before = seen.cell.cursor;
seen = poll_until(worker, &doc, &seen, SETTLE, |now| now.cell.cursor.is_some() && now.cell.cursor != before);
seen.cell.cursor.expect("the cell's rect")
};
let spans: Vec<_> = data.iter().map(|(from, to)| (cell(&mut worker, from), cell(&mut worker, to))).collect();
let all = written(&mut worker, &doc, source);
worker.run(&doc, "cell.goto", &[stand]).expect("where the chart goes");
worker.run(&doc, "chart.insert", &[&all, "false", &Look { kind: "column".into(), ..Look::default() }.to_json()]).expect("inserts");
let framed = poll_until(&mut worker, &doc, &seen, SETTLE, |now| now.graphic.is_some());
let (x, y, w, h) = framed.graphic.expect("the chart is selected");
for ((a, b), (from, to)) in spans.iter().zip(data) {
let clear = x >= b.0 + b.2 || x + w <= a.0 || y >= b.1 + b.3 || y + h <= a.1;
assert!(clear, "the chart {:?} covers {from}:{to}", (x, y, w, h));
}
}
/// A sheet body as flat XML.
fn sheet(rows: &str) -> String {
sheets(&[("S", rows)])
}
/// Named sheets as one flat XML book.
fn sheets(tables: &[(&str, &str)]) -> String {
let tables: String = tables.iter().map(|(name, rows)| format!(r#"<table:table table:name="{name}">{rows}</table:table>"#)).collect();
format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.spreadsheet">
<office:body><office:spreadsheet>{tables}</office:spreadsheet></office:body>
</office:document>"#
)
}
const ONE: &str = r#"<table:table-cell office:value-type="float" office:value="1"><text:p>1</text:p></table:table-cell>"#;
#[test]
fn a_new_chart_lands_beside_its_data() {
if skip() {
return;
}
// Its own data, a neighbour past two empty columns.
charted(&blocks(&[(0..=2, 1..=5), (5..=15, 1..=20)]), (0, 0, 15000, 10000), ("A1:C5", "A1"), &[("A1", "C5"), ("F1", "P20")]);
// Data wider and taller than the view.
charted(&blocks(&[(0..=15, 1..=50)]), (0, 0, 15000, 10000), ("A1:P50", "A1"), &[("A1", "P50")]);
// A view narrower than the chart.
charted(&blocks(&[(0..=2, 1..=5)]), (0, 0, 6000, 3500), ("A1:C5", "A1"), &[("A1", "C5")]);
// A merged block beside the data is taken, not free.
let merged = format!(
r#"<table:table-row>{ONE}{ONE}{ONE}<table:table-cell table:number-columns-spanned="13" table:number-rows-spanned="20"><text:p>MERGED</text:p></table:table-cell></table:table-row><table:table-row table:number-rows-repeated="4">{ONE}{ONE}{ONE}</table:table-row>"#
);
charted(&sheet(&merged), (0, 0, 15000, 10000), ("A1:C5", "A1"), &[("A1", "C5"), ("D1", "D1")]);
// Data in the last cells: left or above.
let corner = |above: usize| {
let empty = 1048574 - above;
format!(
r#"<table:table-row table:number-rows-repeated="{empty}"><table:table-cell table:number-columns-repeated="16384"/></table:table-row><table:table-row table:number-rows-repeated="2"><table:table-cell table:number-columns-repeated="16382"/>{ONE}{ONE}</table:table-row>"#
)
};
charted(&sheet(&corner(0)), (0, 0, 15000, 10000), ("XFC1048575:XFD1048576", "A1"), &[("XFC1048575", "XFD1048576")]);
// Corner data, a block at A1: room elsewhere.
let full = format!("{}{}", rows_of(&[(0..=15, 1..=20)]), corner(20));
charted(&sheet(&full), (0, 0, 15000, 10000), ("XFC1048575:XFD1048576", "A1"), &[("A1", "P20"), ("XFC1048575", "XFD1048576")]);
// Data on S, chart on T: T's cells stay clear.
let two = sheets(&[("S", &rows_of(&[(0..=2, 1..=5)])), ("T", &rows_of(&[(0..=15, 1..=20)]))]);
charted(&two, (0, 0, 15000, 10000), ("S!A1:C5", "T!A1"), &[("T!A1", "T!P20")]);
}
+154
View File
@@ -0,0 +1,154 @@
//! An AutoFilter range keeps its rows (TABLE-08).
use super::sheet::open_book;
use super::*;
use crate::sheet;
/// A header, three numbers and their total right under them.
const BLOCK: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.spreadsheet">
<office:body><office:spreadsheet><table:table table:name="S">
<table:table-row><table:table-cell><text:p>Name</text:p></table:table-cell></table:table-row>
<table:table-row><table:table-cell office:value-type="float" office:value="1"><text:p>1</text:p></table:table-cell></table:table-row>
<table:table-row><table:table-cell office:value-type="float" office:value="2"><text:p>2</text:p></table:table-cell></table:table-row>
<table:table-row><table:table-cell office:value-type="float" office:value="3"><text:p>3</text:p></table:table-cell></table:table-row>
<table:table-row><table:table-cell office:value-type="float" office:value="6"><text:p>6</text:p></table:table-cell></table:table-row>
</table:table></office:spreadsheet></office:body>
</office:document>"#;
/// Two blocks: A1:A5 as in `BLOCK`, and D1:D3.
const TWO: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.spreadsheet">
<office:body><office:spreadsheet><table:table table:name="S">
<table:table-row><table:table-cell><text:p>Name</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell><text:p>Other</text:p></table:table-cell></table:table-row>
<table:table-row><table:table-cell office:value-type="float" office:value="1"><text:p>1</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell office:value-type="float" office:value="9"><text:p>9</text:p></table:table-cell></table:table-row>
<table:table-row><table:table-cell office:value-type="float" office:value="2"><text:p>2</text:p></table:table-cell><table:table-cell table:number-columns-repeated="2"/><table:table-cell office:value-type="float" office:value="10"><text:p>10</text:p></table:table-cell></table:table-row>
<table:table-row><table:table-cell office:value-type="float" office:value="3"><text:p>3</text:p></table:table-cell></table:table-row>
<table:table-row><table:table-cell office:value-type="float" office:value="6"><text:p>6</text:p></table:table-cell></table:table-row>
</table:table></office:spreadsheet></office:body>
</office:document>"#;
/// The book saved as flat XML.
fn saved(worker: &mut Worker, doc: &Doc, dir: &std::path::Path) -> String {
let out = dir.join("kept.fods");
doc.save_as(worker, &crate::file_url(&out), "fods").expect("saves");
std::fs::read_to_string(&out).expect("the saved book")
}
/// Whether the row holding `value` is hidden by a filter.
fn hidden(xml: &str, value: &str) -> bool {
let before = &xml[..xml.find(&format!("office:value=\"{value}\"")).expect("the value")];
before[before.rfind("<table:table-row").expect("its row")..].contains("table:visibility=\"filter\"")
}
/// Column A's filter entries.
fn entries(worker: &mut Worker, doc: &Doc) -> Vec<String> {
let query = sheet::cell_query(sheet::FILTER, 0, 0);
let json = worker.values(doc, &query).expect("the entries");
sheet::filter_values(&json).expect("parses").entries.into_iter().map(|e| e.text).collect()
}
/// A book with an AutoFilter set on `marked`.
fn filtered(marked: &str) -> (tempfile::TempDir, Worker, Doc) {
let (dir, mut worker, doc) = open_book(BLOCK);
worker.run(&doc, "cell.goto", &[marked]).expect("marks the cells");
worker.run(&doc, "data.autofilter", &[]).expect("filters");
(dir, worker, doc)
}
/// Keeps 1: the saved range, and whether the total hides.
fn keep_one(worker: &mut Worker, doc: &Doc, dir: &std::path::Path) -> (String, bool) {
worker.run(doc, "cell.goto", &["A1"]).expect("A1");
let one = r#"{"column":0,"conditions":[{"op":"values","values":["1"]}]}"#;
worker.run(doc, "data.filter", &[one]).expect("keeps 1");
let xml = saved(worker, doc, dir);
let range = xml.split("table:target-range-address=\"").nth(1).expect("a filter range");
(range[..range.find('"').expect("closed")].to_string(), hidden(&xml, "6"))
}
#[test]
fn an_autofilter_on_a_marked_block_leaves_the_row_below_out() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = filtered("A1:A4");
assert_eq!(entries(&mut worker, &doc), ["1", "2", "3"], "the total below stays out");
assert_eq!(keep_one(&mut worker, &doc, dir.path()), ("S.A1:S.A4".into(), false), "applied from one cell");
}
#[test]
fn an_autofilter_on_one_cell_takes_the_data_area() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = filtered("A1");
assert_eq!(entries(&mut worker, &doc), ["1", "2", "3", "6"], "the whole column of data");
}
#[test]
fn off_and_undone_or_set_on_a_filtered_block_the_rows_stay() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = filtered("A1:A4");
worker.run(&doc, "cell.goto", &["A1"]).expect("A1");
worker.run(&doc, "data.autofilter", &[]).expect("off");
worker.run(&doc, "edit.undo", &[]).expect("back on");
assert_eq!(entries(&mut worker, &doc), ["1", "2", "3"], "undo keeps the rows");
let (_dir, mut worker, doc) = open_book(BLOCK);
worker.run(&doc, "cell.goto", &["A1:A4"]).expect("marks the block");
let one = r#"{"conditions":[{"field":0,"op":"equals","value":"1"}]}"#;
worker.run(&doc, "data.filter", &[one]).expect("a standard filter");
worker.run(&doc, "cell.goto", &["A1:A4"]).expect("marks it again");
worker.run(&doc, "data.autofilter", &[]).expect("filters");
assert_eq!(entries(&mut worker, &doc), ["1", "2", "3"], "a filtered block keeps its rows");
}
#[test]
fn a_saved_autofilter_range_keeps_its_rows_when_reopened() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
for format in ["xlsx", "ods"] {
let (dir, mut worker, doc) = filtered("A1:A4");
let path = dir.path().join(format!("book.{format}"));
doc.save_as(&mut worker, &crate::file_url(&path), format).expect("saves");
worker.close_doc(doc).expect("closes");
let doc = worker.load(&crate::file_url(&path)).expect("reopens");
assert_eq!(entries(&mut worker, &doc), ["1", "2", "3"], "{format}");
assert_eq!(keep_one(&mut worker, &doc, dir.path()), ("S.A1:S.A4".into(), false), "{format}");
}
}
#[test]
fn one_cell_in_another_block_filters_that_block() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (dir, mut worker, doc) = open_book(TWO);
worker.run(&doc, "cell.goto", &["A1:A4"]).expect("marks the block");
worker.run(&doc, "data.autofilter", &[]).expect("filters A");
worker.run(&doc, "cell.goto", &["D1"]).expect("D1");
let nine = r#"{"conditions":[{"field":3,"op":"equals","value":"9"}]}"#;
worker.run(&doc, "data.filter", &[nine]).expect("keeps 9");
let xml = saved(&mut worker, &doc, dir.path());
assert!(hidden(&xml, "10") && !hidden(&xml, "9"), "D keeps 9 alone");
assert!(!hidden(&xml, "3") && !hidden(&xml, "6"), "A's rows past D stay");
let (_dir, mut worker, doc) = open_book(TWO);
worker.run(&doc, "cell.goto", &["A1:A4"]).expect("marks the block");
worker.run(&doc, "data.autofilter", &[]).expect("filters A");
worker.run(&doc, "cell.goto", &["D1"]).expect("D1");
worker.run(&doc, "data.autofilter", &[]).expect("filters D");
let json = worker.values(&doc, &sheet::cell_query(sheet::FILTER, 3, 0)).expect("D's entries");
let entries: Vec<String> = sheet::filter_values(&json).expect("parses").entries.into_iter().map(|e| e.text).collect();
assert_eq!(entries, ["9", "10"], "an AutoFilter from D1 is D's");
}
@@ -360,3 +360,20 @@ fn names_are_defined_changed_removed_and_flag_breaks() {
.expect("a removal");
assert!(!read(&mut worker).iter().any(|name| name.name == "Local"));
}
#[test]
fn selection_figures_follow_the_cells_number_format() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc, seen) = open();
enter(&mut worker, &doc, &[("H1", "8128.33333333333"), ("H2", "8128.33333333333")]);
worker.run(&doc, "cell.goto", &["H1:H2"]).expect("both");
worker.run(&doc, "number.code", &["0.00"]).expect("two decimals");
let figures = |seen: &Events| {
seen.states.iter().rfind(|(name, _)| name == ".uno:StateTableCell").map(|(_, value)| value.clone())
};
let state = poll_until(&mut worker, &doc, &seen, SETTLE, |seen| figures(seen).is_some_and(|v| v.contains("8128.33;")));
assert!(figures(&state).is_some_and(|v| v.contains("Average: 8128.33;")), "{:?}", figures(&state));
}
+59
View File
@@ -220,3 +220,62 @@ fn an_animated_object_is_its_own_layer_under_its_effect_hash() {
#[test]
fn layers_larger_than_one_frame_arrive_one_by_one() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
worker.run(&doc, "draw.shape", &["rectangle", "true"]).expect("draws");
let json = serde_json::json!({ "preset": "ooo-entrance-fade-in" }).to_string();
worker.run(&doc, "animation.add", &[&json]).expect("adds");
// Three layers at this size pass one 64 MB frame.
let layers = doc.slide_layers(&mut worker, 0, (5000, 2812)).expect("layers");
let (w, h) = layers.size;
let bytes = w as usize * h as usize * 4;
assert!(layers.list.len() * bytes > crate::ipc::MAX_FRAME, "{} layers of {bytes}", layers.list.len());
assert!(layers.list.iter().all(|layer| layer.pixels.len() == bytes), "every layer arrives whole");
}
#[test]
fn a_layer_larger_than_one_frame_arrives_in_pieces() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
worker.run(&doc, "slide.size", &["10000", "120000", "true"]).expect("a tall slide");
worker.run(&doc, "draw.shape", &["rectangle", "true"]).expect("draws");
let layers = doc.slide_layers(&mut worker, 0, (1280, 15360)).expect("layers");
let (w, h) = layers.size;
let bytes = w as usize * h as usize * 4;
assert!(bytes > crate::ipc::MAX_FRAME, "one layer of {bytes} bytes");
assert!(layers.list.iter().all(|layer| layer.pixels.len() == bytes), "every layer arrives whole");
// The rectangle lands where the kernel put it.
let objects = show::objects(&worker.values(&doc, show::OBJECTS).expect("reads")).expect("parses");
let shape = objects.objects.iter().find(|o| o.selected).expect("the new rectangle");
let want = ((shape.rect.1 + shape.rect.3 / 2) as f64 / 120000.0 * f64::from(h)) as usize;
let row = |layer: &show::Layer, y: usize| layer.pixels[y * w as usize * 4..(y + 1) * w as usize * 4].chunks(4).any(|px| px[3] != 0);
let inked = |layer: &show::Layer| (0..h as usize).filter(|y| row(layer, *y)).collect::<Vec<_>>();
assert!(want > 16 * 1024 * 1024 / (w as usize * 4), "the shape lies past the first piece");
let around = want - 20..want + 20;
let found = layers.list.iter().map(inked).any(|rows| around.clone().all(|y| rows.contains(&y)) && rows.len() < h as usize);
assert!(found, "no layer inks rows {around:?}");
}
#[test]
fn closing_a_deck_drops_its_waiting_layers() {
if install().is_none() {
eprintln!("SKIP: no pinned LOK build");
return;
}
let (_dir, mut worker, doc) = open_deck();
let id = worker.doc_id(&doc).expect("the id");
let ask = crate::ipc::Pack::new().u64(id).u64(0).u64(1920).u64(1080).bytes();
worker.request(crate::ipc::tag::SLIDE_LAYERS, &ask).expect("layers wait");
worker.close_doc(doc).expect("closes");
let late = crate::ipc::Pack::new().u64(id).u64(0).u64(0).bytes();
assert!(worker.request(crate::ipc::tag::SLIDE_LAYER, &late).is_err(), "no layer outlives its deck");
}
+1 -1
View File
@@ -176,7 +176,7 @@ pub(super) fn open_book(text: &str) -> (tempfile::TempDir, Worker, Doc) {
let doc = worker
.load(&format!("file://{}", source.display()))
.expect("the book loads");
doc.visible_area(&mut worker, (0, 0, 15000, 10000))
doc.visible_area(&mut worker, (0, 0, 15000, 10000), (256, 3840))
.expect("the area");
(dir, worker, doc)
}
+7
View File
@@ -247,6 +247,13 @@ impl Document {
call!(class, 69, F, self.doc, view, true);
}
/// Tells the kernel a tile's size in pixels and twips.
pub fn set_client_zoom(&self, pixels: i32, twips: i32) {
let class = unsafe { (*self.doc).class };
type F = unsafe extern "C" fn(*mut Doc, i32, i32, i32, i32);
call!(class, 23, F, self.doc, pixels, pixels, twips, twips);
}
/// Tells the kernel the area the client shows, in twips.
pub fn set_visible_area(&self, x: i32, y: i32, width: i32, height: i32) {
let class = unsafe { (*self.doc).class };
+2
View File
@@ -86,6 +86,8 @@ pub mod tag {
/// Refuses unless the document is still at a revision.
pub const EXPECT: u8 = 33;
pub const REVISION: u8 = 34;
/// One layer's pixels from the last `SLIDE_LAYERS`.
pub const SLIDE_LAYER: u8 = 35;
pub const OK: u8 = 100;
pub const ERR: u8 = 101;
}
+85
View File
@@ -71,6 +71,66 @@ impl Axis {
}
}
impl Axis {
/// Where `index` starts in tile pixels.
fn tile_start(&self, index: u32, ppt: f64) -> i64 {
let (mut at, mut first) = (0i64, 0u32);
for &(last, size) in &self.runs {
let pixels = i64::from(to_pixels(size, ppt));
if index <= last {
return at + i64::from(index - first) * pixels;
}
at += i64::from(last - first + 1) * pixels;
first = last + 1;
}
at
}
/// A print-twips position in tile twips at `ppt`.
pub fn tile(&self, print: i32, ppt: f64) -> i32 {
let end = self.start(self.count());
if print >= end {
return clamp(twips_of(self.tile_start(self.count(), ppt), ppt) + i64::from(print - end));
}
let index = self.at(print);
let (from, size) = (self.start(index), self.size(index));
let start = twips_of(self.tile_start(index, ppt), ppt);
let span = twips_of(self.tile_start(index + 1, ppt), ppt) - start;
clamp(start + i64::from(print - from) * span / i64::from(size))
}
/// The print-twips position under tile twips `tile`.
pub fn print(&self, tile: i32, ppt: f64) -> i32 {
let pixel = (f64::from(tile.max(0)) * ppt) as i64;
let (mut at, mut first) = (0i64, 0u32);
for &(last, size) in &self.runs {
let pixels = i64::from(to_pixels(size, ppt));
let span = i64::from(last - first + 1) * pixels;
if pixels > 0 && pixel < at + span {
let index = first + u32::try_from((pixel - at) / pixels).expect("inside a run");
let start = twips_of(self.tile_start(index, ppt), ppt);
let width = twips_of(self.tile_start(index + 1, ppt), ppt) - start;
let into = i64::from(tile) - start;
return clamp(i64::from(self.start(index)) + into * i64::from(size) / width.max(1));
}
at += span;
first = last + 1;
}
let end = twips_of(self.tile_start(self.count(), ppt), ppt);
clamp(i64::from(self.start(self.count())) + i64::from(tile) - end)
}
}
/// The kernel's `ScViewData::ToPixel`: truncates, never to 0.
fn to_pixels(twips: i32, ppt: f64) -> i32 {
let pixels = (f64::from(twips) * ppt) as i32;
if pixels == 0 && twips != 0 { 1 } else { pixels }
}
fn twips_of(pixels: i64, ppt: f64) -> i64 {
(pixels as f64 / ppt).round() as i64
}
fn clamp(twips: i64) -> i32 {
i32::try_from(twips).unwrap_or(i32::MAX)
}
@@ -371,4 +431,29 @@ mod tests {
assert_eq!(flags("1:2 5").expect("flags"), [(2, 1), (5, 0)]);
assert!(merge(&[(3, 10)], &[(5, 0)]).is_err(), "lengths must agree");
}
#[test]
fn tiles_round_each_row_to_whole_pixels() {
// 293 twips at 2/15 px per twip truncate to 39.
let rows = Axis { runs: vec![(9999, 293)] };
let ppt = 2.0 / 15.0;
assert_eq!(to_pixels(293, ppt), 39);
let row = 4997u32;
let print = rows.start(row);
let tile = rows.tile(print, ppt);
assert_eq!(tile, (f64::from(39 * row) / ppt).round() as i32, "row tops line up");
assert_eq!(rows.print(tile, ppt), print, "and come back");
let mid = rows.tile(print + 146, ppt);
assert_eq!(rows.at(rows.print(mid, ppt)), row, "a point inside stays in its row");
assert!(tile < print, "rounding down pulls far rows up");
}
#[test]
fn hidden_rows_take_no_tile_space_and_tiny_rows_take_a_pixel() {
let rows = Axis { runs: vec![(1, 300), (3, 0), (4, 3)] };
let ppt = 1.0 / 15.0;
assert_eq!(rows.tile(rows.start(4), ppt), rows.tile(rows.start(2), ppt), "hidden rows fold");
assert_eq!(to_pixels(3, ppt), 1, "never 0 for a shown row");
}
}
+9 -2
View File
@@ -28,6 +28,7 @@ mod render;
mod zoom;
pub use zoom::{ZOOM_STEPS, Zoomed};
mod scroll;
mod sheet;
pub use input::{CONTEXT, Copy, Cut, Paste, init};
pub use off::read_off;
pub use render::scheme;
@@ -89,13 +90,15 @@ pub struct LokView {
fetching: HashSet<(i32, i32)>,
failed: HashSet<((i32, i32), u64)>,
/// The area last told to the kernel.
shown: Option<Rect>,
shown: Option<(Rect, (u32, i32))>,
viewport: (f32, f32),
origin: Point<Pixels>,
/// Pixels a small document sits in: left, top.
spare: (f32, f32),
/// Frozen columns and rows, in twips from the top left.
frozen: (i32, i32),
/// A spreadsheet's rows and columns, in print twips.
sheet: Option<crate::sheet::Geometry>,
/// The farthest point a jump needed; Calc grows to it.
reach: (i32, i32),
pages: Vec<Rect>,
@@ -210,6 +213,7 @@ impl LokView {
origin: Point::default(),
spare: (0.0, 0.0),
frozen: (0, 0),
sheet: None,
reach: (0, 0),
pages,
focus: cx.focus_handle().tab_stop(true),
@@ -371,8 +375,9 @@ impl LokView {
}
if batch.cursor != self.cursor {
self.moves += 1;
// A moved cursor stays in view.
// A moved cursor stays in view, but not mid-drag.
if self.viewport.1 > 0.0
&& !self.dragging
&& let Some(cursor) = batch.cursor
{
self.show(cursor, cx);
@@ -381,10 +386,12 @@ impl LokView {
// A moved cell cursor stays in view too.
if batch.cell.cursor != self.cell.cursor
&& self.viewport.1 > 0.0
&& !self.dragging
&& let Some(cell) = batch.cell.cursor
{
self.show(cell, cx);
}
self.follow_graphic(batch.graphic, cx);
self.cursor = batch.cursor;
self.cursor_visible = batch.cursor_visible;
self.selection = batch.selection;
+7 -6
View File
@@ -60,8 +60,8 @@ pub(super) enum Input {
from: (i32, i32),
to: (i32, i32),
},
/// The area the view shows, in twips.
Visible(Rect),
/// The area shown in twips, and the tile scale.
Visible(Rect, (u32, i32)),
/// Shows sheet or slide `part`, from 0.
Part(usize),
}
@@ -74,7 +74,7 @@ impl Input {
Input::Key { key_code, .. } => !matches!(key_code & 0x0FFF, 1024..=1031 | 1281),
Input::Mouse(_)
| Input::Copy { cut: false }
| Input::Visible(_)
| Input::Visible(..)
| Input::Part(_)
| Input::Theme(_) => false,
Input::Run { commands, .. } => commands.iter().any(|(id, _)| *id != "edit.select_all"),
@@ -171,7 +171,7 @@ fn lok_button(button: MouseButton) -> Option<i32> {
/// Runs one input; gives a copy's mark and the revision.
pub(super) fn run(worker: &Mutex<Worker>, doc: &Doc, input: Input) -> (io::Result<Option<String>>, Option<u64>) {
let mut worker = worker.lock().expect("the worker lock");
let counts = !matches!(input, Input::Visible(_));
let counts = !matches!(input, Input::Visible(..));
let copied = apply(&mut worker, doc, input);
// A failed input may have moved the revision too.
let now = match counts {
@@ -189,7 +189,7 @@ fn apply(worker: &mut Worker, doc: &Doc, input: Input) -> io::Result<Option<Stri
} => worker.post_key(doc, char_code, key_code),
Input::Mouse(event) => worker.post_mouse(doc, event),
Input::Drag { from, to } => worker.drag_graphic(doc, from, to),
Input::Visible(area) => doc.visible_area(worker, area),
Input::Visible(area, scale) => doc.visible_area(worker, area, scale),
Input::Part(part) => doc.show_sheet(worker, part),
Input::Complete(name) => doc.complete_function(worker, &name),
Input::Theme(scheme) => worker.run(doc, "view.theme", &[scheme]),
@@ -280,7 +280,8 @@ impl LokView {
count: usize,
modifiers: &Modifiers,
) {
let (x, y) = self.doc_point(position);
// The kernel reads clicks in tile twips.
let (x, y) = self.tile_point(position);
self.send(Input::Mouse(Mouse {
kind,
x,
+9 -3
View File
@@ -23,7 +23,8 @@ pub(super) struct Job {
/// What came back from the lane.
enum Landed {
Input(u64, bool, (io::Result<Option<String>>, Option<u64>)),
/// Sequence, whether it edits, whether it switched part, outcome.
Input(u64, bool, bool, (io::Result<Option<String>>, Option<u64>)),
Tile(Job, io::Result<Tile>),
}
@@ -46,6 +47,7 @@ impl LokView {
input = input_queue.next() => {
let Some((seq, input, sent)) = input else { break };
let (waited, edits) = (sent.elapsed().as_millis(), input.edits());
let switched = matches!(input, super::input::Input::Part(_));
let outcome = super::input::run(&worker, &doc, input);
let took = sent.elapsed().as_millis();
if took > SLOW_MS {
@@ -53,7 +55,7 @@ impl LokView {
} else {
log::debug!("lok: input {seq} waited {waited}, took {took} ms");
}
Landed::Input(seq, edits, outcome)
Landed::Input(seq, edits, switched, outcome)
}
job = tile_queue.next() => {
let Some(job) = job else { break };
@@ -96,8 +98,12 @@ impl LokView {
let mut reported = false;
for landed in batch {
match landed {
Landed::Input(seq, edits, outcome) => {
Landed::Input(seq, edits, switched, outcome) => {
self.applied = seq;
// Same tile keys, another slide or sheet.
if switched {
self.invalidate(cx);
}
self.edited += u64::from(edits);
let (outcome, now) = outcome;
if edits {
+21 -17
View File
@@ -40,7 +40,7 @@ impl Render for LokView {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let dpi = window.scale_factor();
if dpi != self.geom.dpi {
self.geom.dpi = dpi;
self.keep_scroll(|view| view.geom.dpi = dpi);
self.retire_tiles();
}
self.follow_theme(cx.theme().is_dark());
@@ -210,7 +210,7 @@ impl LokView {
let down = self.viewport.1 * TWIPS_PER_PIXEL / h as f32;
let zoom = (across.min(down) * MARGIN).min(4.0);
if (zoom - self.geom.zoom).abs() > 0.001 {
self.geom.zoom = zoom;
self.keep_scroll(|view| view.geom.zoom = zoom);
self.retire_tiles();
self.failed.clear();
}
@@ -249,6 +249,19 @@ impl LokView {
}
}
/// Room beside a narrow document, which sits centred.
pub(super) fn slack(&self) -> (f32, f32) {
// A sheet's grid grows with the view; it starts left.
if self.doc.is_sheet() {
return (0.0, 0.0);
}
let extent = self.extent();
let slack = |view: f32, doc: i32| (view - self.geom.px_of(doc)).max(0.0) / 2.0;
// A fitted page sits centred both ways.
let down = if self.fit { slack(self.viewport.1, extent.1) } else { 0.0 };
(slack(self.viewport.0, extent.0), down)
}
/// The page mask and visible tiles; requests the missing ones.
pub(super) fn prepare(&mut self, bounds: Bounds<Pixels>) -> Painted {
self.viewport = (bounds.size.width.into(), bounds.size.height.into());
@@ -259,20 +272,10 @@ impl LokView {
self.clamp_scroll();
let geom = self.geom;
let (sx, sy) = self.scroll;
// A narrow document sits centered.
let extent = self.extent();
let slack = |view: f32, doc: i32| (view - geom.px_of(doc)).max(0.0) / 2.0;
// A fitted page sits centred both ways.
self.spare = (
slack(self.viewport.0, extent.0),
if self.fit {
slack(self.viewport.1, extent.1)
} else {
0.0
},
);
self.spare = self.slack();
let pages = if self.pages.is_empty() {
vec![self.screen_rect((0, 0, extent.0, extent.1))]
vec![self.tile_screen_rect((0, 0, extent.0, extent.1))]
} else {
self.pages
.iter()
@@ -283,10 +286,11 @@ impl LokView {
geom.twips_of(bounds.size.width.into()),
geom.twips_of(bounds.size.height.into()),
);
if self.shown != Some((sx, sy, vw, vh)) {
self.shown = Some((sx, sy, vw, vh));
let scale = (geom.tile_pixels(), TILE_TWIPS);
if self.shown != Some(((sx, sy, vw, vh), scale)) {
self.shown = Some(((sx, sy, vw, vh), scale));
self.failed.clear();
self.send(input::Input::Visible((sx, sy, vw, vh)));
self.send(input::Input::Visible((sx, sy, vw, vh), scale));
}
let (ax, ay) = self.axes();
let side = px(geom.px_of(TILE_TWIPS));
+56 -25
View File
@@ -41,29 +41,37 @@ impl LokView {
self.scroll_by(dx, dy, cx);
}
/// Scrolls `rect` into view; frozen parts always show.
pub fn show(&mut self, (x, y, w, h): Rect, cx: &mut Context<Self>) {
let (fx, fy) = self.frozen;
/// A newly selected object, such as a chart, shows.
pub(super) fn follow_graphic(&mut self, frame: Option<Rect>, cx: &mut Context<Self>) {
if let (None, Some(frame), true) = (self.graphic, frame, self.viewport.1 > 0.0) {
self.show(frame, cx);
}
}
/// Scrolls print-twips `rect` into view; frozen parts always show.
pub fn show(&mut self, rect: Rect, cx: &mut Context<Self>) {
let (x, y, w, h) = self.tile_rect(rect);
let (fx, fy) = self.frozen_tiles();
let (vw, vh) = (
self.geom.twips_of(self.viewport.0) - fx,
self.geom.twips_of(self.viewport.1) - fy,
);
// Room past the target, so the clamp lets it show.
self.reach = (
self.reach.0.max(x + w + vw + fx),
self.reach.1.max(y + h + vh + fy),
);
if x >= fx && (x < fx + self.scroll.0 || x + w > fx + self.scroll.0 + vw) {
self.scroll.0 = x - fx - vw / 2;
// Only a sheet grows where it jumps.
if self.sheet.is_some() {
let need = self.print_of((x + w + vw + fx, y + h + vh + fy));
self.reach = (self.reach.0.max(need.0), self.reach.1.max(need.1));
}
if y >= fy && (y < fy + self.scroll.1 || y + h > fy + self.scroll.1 + vh) {
self.scroll.1 = y - fy - vh / 3;
if x >= fx {
self.scroll.0 = least(x - fx, w, self.scroll.0, vw);
}
if y >= fy {
self.scroll.1 = least(y - fy, h, self.scroll.1, vh);
}
self.clamp_scroll();
cx.notify();
}
/// Freezes what lies before `frozen`, in twips.
/// Freezes what lies before `frozen`, in print twips.
pub fn set_frozen(&mut self, frozen: (i32, i32), cx: &mut Context<Self>) {
if self.frozen != frozen {
log::info!("lok: frozen at {frozen:?}");
@@ -75,7 +83,8 @@ impl LokView {
/// Scrolls `rect` into view and puts the cursor there.
pub fn reveal(&mut self, rect: Rect, cx: &mut Context<Self>) {
self.show(rect, cx);
let (x, y, _, h) = rect;
// Clicks land in tile twips.
let (x, y, _, h) = self.tile_rect(rect);
log::info!("lok: reveal at {x},{y}");
for kind in [0, 1] {
let (count, buttons, modifiers) = (1, 1, 0);
@@ -102,14 +111,19 @@ impl LokView {
if self.fit {
return self.doc_size;
}
(
self.tile_of((
self.doc_size.0.max(self.reach.0),
self.doc_size.1.max(self.reach.1),
)
))
}
/// The document point under a view position (LOK-04).
/// The print-twips document point under a view position (LOK-04).
pub fn doc_point(&self, position: Point<Pixels>) -> (i32, i32) {
self.print_of(self.tile_point(position))
}
/// The tile-twips point under a view position.
pub(super) fn tile_point(&self, position: Point<Pixels>) -> (i32, i32) {
let local = position - self.origin;
let (ax, ay) = self.axes();
(
@@ -121,14 +135,17 @@ impl LokView {
/// The panes of each axis.
pub(super) fn axes(&self) -> (super::panes::Axis, super::panes::Axis) {
let axis = |frozen, scroll| super::panes::Axis { frozen, scroll };
(
axis(self.frozen.0, self.scroll.0),
axis(self.frozen.1, self.scroll.1),
)
let (fx, fy) = self.frozen_tiles();
(axis(fx, self.scroll.0), axis(fy, self.scroll.1))
}
/// The window point of a document point in twips (LOK-04).
pub fn window_point(&self, (x, y): (i32, i32)) -> gpui::Point<Pixels> {
/// The window point of a print-twips document point (LOK-04).
pub fn window_point(&self, at: (i32, i32)) -> gpui::Point<Pixels> {
self.tile_window_point(self.tile_of(at))
}
/// The window point of a tile-twips point.
pub(super) fn tile_window_point(&self, (x, y): (i32, i32)) -> gpui::Point<Pixels> {
let (ax, ay) = self.axes();
let (x, y) = (self.geom.px_of(ax.show(x)), self.geom.px_of(ay.show(y)));
self.origin + point(px(self.spare.0 + x), px(self.spare.1 + y))
@@ -139,12 +156,26 @@ impl LokView {
Bounds::from_corners(self.window_point((x, y)), self.window_point((x + w, y + h)))
}
/// A tile-twips rect in window pixels.
pub(super) fn tile_screen_rect(&self, (x, y, w, h): crate::Rect) -> Bounds<Pixels> {
Bounds::from_corners(self.tile_window_point((x, y)), self.tile_window_point((x + w, y + h)))
}
/// The cursor rect in window pixels.
pub fn cursor_bounds(&self) -> Option<Bounds<Pixels>> {
let (x, y, w, h) = self.cursor?;
let origin = self.window_point((x, y));
let end = self.window_point((x + w, y + h));
Some(Bounds {
origin: self.window_point((x, y)),
size: size(px(self.geom.px_of(w.max(1))), px(self.geom.px_of(h))),
origin,
size: size((end.x - origin.x).max(px(self.geom.px_of(1))), end.y - origin.y),
})
}
}
/// The scroll nearest `scroll` that shows `start..start + len`.
fn least(start: i32, len: i32, scroll: i32, view: i32) -> i32 {
// A span wider than the view keeps covering it.
let end = start + len - view;
scroll.clamp(start.min(end), start.max(end))
}
+64
View File
@@ -0,0 +1,64 @@
//! Calc reports print twips; tiles and clicks take tile twips.
use gpui::Context;
use super::{LokView, TILE_TWIPS};
use crate::{Rect, sheet::Geometry};
impl LokView {
/// Lays the sheet out the kernel's way.
pub fn set_geometry(&mut self, geometry: Geometry, cx: &mut Context<Self>) {
if self.sheet.as_ref() != Some(&geometry) {
self.sheet = Some(geometry);
self.clamp_scroll();
cx.notify();
}
}
/// Device pixels per twip, as the kernel paints our tiles.
fn ppt(&self) -> f64 {
f64::from(self.geom.tile_pixels()) / f64::from(TILE_TWIPS)
}
/// A print-twips point in tile twips.
pub(super) fn tile_of(&self, (x, y): (i32, i32)) -> (i32, i32) {
match &self.sheet {
Some(sheet) => (sheet.columns.tile(x, self.ppt()), sheet.rows.tile(y, self.ppt())),
None => (x, y),
}
}
/// A tile-twips point in print twips.
pub(super) fn print_of(&self, (x, y): (i32, i32)) -> (i32, i32) {
match &self.sheet {
Some(sheet) => (sheet.columns.print(x, self.ppt()), sheet.rows.print(y, self.ppt())),
None => (x, y),
}
}
/// A print-twips rect in tile twips.
pub(super) fn tile_rect(&self, (x, y, w, h): Rect) -> Rect {
let (left, top) = self.tile_of((x, y));
let (right, bottom) = self.tile_of((x + w, y + h));
(left, top, right - left, bottom - top)
}
/// The frozen extent in tile twips.
pub(super) fn frozen_tiles(&self) -> (i32, i32) {
self.tile_of(self.frozen)
}
/// Rescales, keeping the scrolling pane's start in place.
pub(super) fn keep_scroll(&mut self, change: impl FnOnce(&mut Self)) {
let start = self.scrolled_start();
change(self);
let ((x, y), (fx, fy)) = (self.tile_of(start), self.frozen_tiles());
self.scroll = (x - fx, y - fy);
}
/// Where the scrolling pane starts, in print twips.
pub fn scrolled_start(&self) -> (i32, i32) {
let (fx, fy) = self.frozen_tiles();
self.print_of((fx + self.scroll.0, fy + self.scroll.1))
}
}
-39
View File
@@ -359,45 +359,6 @@ fn a_moved_cursor_scrolls_into_view_and_a_still_one_does_not() {
view.scroll_by(0.0, 1_000_000.0, cx);
view.apply_batch(batch(), None, cx);
assert_eq!(view.scroll.1, 0, "a still cursor leaves the scroll alone");
let far = view.doc_size.1 + 20_000;
let cell = crate::Cell {
cursor: Some((1418, far, 1280, 277)),
..crate::Cell::default()
};
view.apply_batch(
crate::Events {
cell,
..crate::Events::default()
},
None,
cx,
);
let height = view.geom.twips_of(view.viewport.1);
assert!(
view.scroll.1 <= far && far + 277 <= view.scroll.1 + height,
"a cell past the kernel's size still comes into view"
);
view.scroll = (0, 0);
let width = view.geom.twips_of(view.viewport.0);
view.show((width - 200, 0, 1280, 256), cx);
assert!(
view.scroll.0 > 0 && width - 200 + 1280 <= view.scroll.0 + width,
"a cell cut at the right edge comes into view"
);
view.scroll = (0, 0);
view.frozen = (0, 600);
view.show((1418, 300, 1280, 277), cx);
assert_eq!(view.scroll.1, 0, "a frozen row needs no scroll");
view.show((1418, 9000, 1280, 277), cx);
let scrolled = view.scroll.1;
assert!(scrolled > 0, "a far row scrolls the rest");
let row = view.place((0, 300)).y;
assert_eq!(f32::from(row), view.geom.px_of(300), "the frozen row stays");
let far = view.twips_at(view.place((0, 9000)));
assert!(
(far.1 - 9000).abs() <= 15,
"a scrolled row maps back: {far:?}"
);
});
});
}
+74
View File
@@ -88,3 +88,77 @@ fn a_resized_slide_reaches_the_view_and_still_fits() {
})
});
}
#[test]
fn a_page_stays_centred_when_the_cursor_moves() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let (view, _) = live_view(app, &install);
view.update(app, |view, cx| {
let wide = Bounds { origin: point(px(0.0), px(0.0)), size: size(px(2400.0), px(900.0)) };
view.prepare(wide);
let centred = view.spare.0;
assert!(centred > 0.0, "a page narrower than the view sits centred");
view.show((1440, 1440, 20, 300), cx);
view.prepare(wide);
assert_eq!(view.spare.0, centred, "moving the cursor keeps it centred");
let narrow = Bounds { origin: point(px(0.0), px(0.0)), size: size(px(800.0), px(900.0)) };
view.prepare(narrow);
view.set_zoom(2.0, cx);
view.prepare(narrow);
let right = view.scroll.0 + view.geom.twips_of(view.viewport.0);
assert!(right <= view.doc_size.0, "no grey past the page: {right} > {}", view.doc_size.0);
})
});
}
#[test]
fn zooming_keeps_the_left_page_edge_or_the_pointed_spot() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let (view, _) = live_view(app, &install);
view.update(app, |view, cx| {
let room = Bounds { origin: point(px(0.0), px(0.0)), size: size(px(1200.0), px(900.0)) };
view.prepare(room);
let page = *view.pages.first().expect("a laid out page");
// Unclamped, so a cut edge reads below zero.
let left = |view: &LokView| view.spare.0 + view.geom.px_of(view.tile_of((page.0, page.1)).0 - view.scroll.0);
for _ in 0..3 {
view.zoom_step(true, cx);
view.prepare(room);
assert!(left(view) >= 0.0, "at {}% the left edge is at {}", view.zoom() * 100.0, left(view));
}
view.set_zoom(1.0, cx);
view.prepare(room);
view.set_zoom(2.0, cx);
view.prepare(room);
assert!(left(view) >= 0.0, "a set zoom keeps the left edge: {}", left(view));
view.set_zoom(1.0, cx);
view.prepare(room);
let at = point(px(600.0), px(400.0));
let before = view.doc_point(at);
view.zoom_at(1.5, Some(at), cx);
view.prepare(room);
let after = view.doc_point(at);
assert!((after.0 - before.0).abs() < 30 && (after.1 - before.1).abs() < 30, "{before:?} moved to {after:?}");
// Wheel steps that land within one frame.
view.set_zoom(1.0, cx);
view.prepare(room);
let before = view.doc_point(at);
for zoom in [1.25, 1.5, 2.0] {
view.zoom_at(zoom, Some(at), cx);
}
view.prepare(room);
let after = view.doc_point(at);
assert!((after.0 - before.0).abs() < 30 && (after.1 - before.1).abs() < 30, "bunched: {before:?} moved to {after:?}");
})
});
}
+52
View File
@@ -269,3 +269,55 @@ fn the_clipboard_moves_html_tables_and_images() {
let xml = std::fs::read_to_string(&out).expect("the save reads");
assert!(xml.contains("<draw:image"), "the image lands");
}
/// Two slides, each with one line of text.
const DECK: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"
office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.presentation">
<office:body><office:presentation>
<draw:page draw:name="one"><draw:frame svg:x="2cm" svg:y="2cm" svg:width="10cm" svg:height="3cm"><draw:text-box><text:p>One</text:p></draw:text-box></draw:frame></draw:page>
<draw:page draw:name="two"><draw:frame svg:x="2cm" svg:y="8cm" svg:width="10cm" svg:height="3cm"><draw:text-box><text:p>Two</text:p></draw:text-box></draw:frame></draw:page>
</office:presentation></office:body>
</office:document>"#;
/// Paints until tile (0, 0) is fresh, then its bytes.
fn fresh_corner(view: &Entity<LokView>, cx: &mut TestAppContext, not: Option<&[u8]>) -> Vec<u8> {
let bounds = Bounds { origin: point(px(0.0), px(0.0)), size: size(px(800.0), px(600.0)) };
for _ in 0..400 {
let bytes = cx.update(|app| {
view.update(app, |view, _| view.prepare(bounds));
let read = view.read(app);
let entry = read.tiles.get(&(0, 0)).filter(|entry| !entry.stale)?;
let bytes = entry.image.as_bytes(0).expect("a frame").to_vec();
(Some(bytes.as_slice()) != not).then_some(bytes)
});
if let Some(bytes) = bytes {
return bytes;
}
cx.executor().tick();
}
panic!("tile (0, 0) never repainted");
}
#[test]
fn switching_slides_repaints_the_shown_tiles() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let mut cx = TestAppContext::single();
let (view, worker) = cx.update(|app| live_view_of(app, &install, "deck.fodp", DECK));
let one = fresh_corner(&view, &mut cx, None);
cx.update(|app| view.update(app, |view, _| view.show_part(1)));
let two = fresh_corner(&view, &mut cx, Some(&one));
let painted = cx.update(|app| {
let read = view.read(app);
let side = read.geom.tile_pixels();
let mut worker = worker.lock().expect("the worker lock");
read.doc.paint_tile(&mut worker, (0, 0, TILE_TWIPS, TILE_TWIPS), (side, side)).expect("paints")
});
assert_eq!(two, painted.pixels, "the corner shows slide two");
}
+194
View File
@@ -60,3 +60,197 @@ fn a_tall_sheet_paints_and_keeps_only_tiles_near_the_screen() {
});
});
}
/// 6000 rows of 0.5 cm; tiles round each to pixels.
const SHORT_ROWS: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"
xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"
xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"
xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" office:version="1.3" office:mimetype="application/vnd.oasis.opendocument.spreadsheet">
<office:automatic-styles><style:style style:name="ro1" style:family="table-row"><style:table-row-properties style:row-height="0.5cm" style:use-optimal-row-height="false"/></style:style></office:automatic-styles>
<office:body><office:spreadsheet><table:table table:name="S">
<table:table-row table:style-name="ro1" table:number-rows-repeated="6000"><table:table-cell table:number-columns-repeated="4"/></table:table-row>
</table:table></office:spreadsheet></office:body>
</office:document>"#;
/// A short-row sheet at 2× DPI, scrolled to `cell`'s row.
fn far_down(cx: &mut gpui::TestAppContext, install: &std::path::Path) -> (Entity<LokView>, crate::sheet::Geometry) {
let (view, worker) = cx.update(|app| live_view_of(app, install, "short.fods", SHORT_ROWS));
let json = cx.update(|app| {
let read = view.read(app);
worker.lock().expect("the worker lock").values(&read.doc, crate::sheet::GEOMETRY).expect("geometry")
});
let geometry = crate::sheet::geometry(&json).expect("parsed");
let row = cell(&geometry, 1, 4997);
cx.update(|app| {
view.update(app, |view, cx| {
view.geom.dpi = 2.0;
view.set_geometry(geometry.clone(), cx);
view.prepare(Bounds { origin: point(px(0.0), px(0.0)), size: size(px(800.0), px(600.0)) });
view.show(row, cx);
})
});
(view, geometry)
}
/// Column `x`, row `y` in print twips.
fn cell(geometry: &crate::sheet::Geometry, x: u32, y: u32) -> crate::Rect {
(geometry.columns.start(x), geometry.rows.start(y), geometry.columns.size(x), geometry.rows.size(y))
}
/// Waits until the kernel reports `want` as the selection.
fn selected(view: &Entity<LokView>, cx: &mut gpui::TestAppContext, want: &str) -> String {
let mut address = String::new();
for _ in 0..200 {
cx.executor().tick();
address = cx.update(|app| view.read(app).cell().address.clone());
if address == want {
break;
}
}
address
}
#[test]
fn a_click_far_down_a_sheet_selects_the_cell_under_it() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let mut cx = gpui::TestAppContext::single();
let (view, geometry) = far_down(&mut cx, &install);
let (x, y, w, h) = cell(&geometry, 1, 4997);
cx.update(|app| {
view.update(app, |view, _| {
let at = view.window_point((x + w / 2, y + h / 2));
for kind in [0, 1] {
view.mouse(kind, at, 1, 1, &gpui::Modifiers::default());
}
})
});
assert_eq!(selected(&view, &mut cx, "B4998"), "B4998");
}
#[test]
fn a_drag_far_down_a_sheet_selects_the_range_under_it() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let mut cx = gpui::TestAppContext::single();
let (view, geometry) = far_down(&mut cx, &install);
let middle = |(x, y, w, h): crate::Rect| (x + w / 2, y + h / 2);
let (from, to) = (middle(cell(&geometry, 1, 4997)), middle(cell(&geometry, 3, 5000)));
cx.update(|app| {
view.update(app, |view, _| {
let modifiers = gpui::Modifiers::default();
view.mouse(0, view.window_point(from), 1, 1, &modifiers);
view.mouse(2, view.window_point(((from.0 + to.0) / 2, (from.1 + to.1) / 2)), 1, 1, &modifiers);
view.mouse(2, view.window_point(to), 1, 1, &modifiers);
view.mouse(1, view.window_point(to), 1, 1, &modifiers);
})
});
assert_eq!(selected(&view, &mut cx, "B4998:D5001"), "B4998:D5001");
}
#[test]
fn zooming_far_down_a_sheet_keeps_the_rows_in_view() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let mut cx = gpui::TestAppContext::single();
let (view, geometry) = far_down(&mut cx, &install);
let middle = |cx: &mut gpui::TestAppContext| {
cx.update(|app| {
let read = view.read(app);
let (w, h) = read.viewport();
let at = read.origin() + point(px(w / 2.0), px(h / 2.0));
geometry.rows.at(read.doc_point(at).1)
})
};
let before = middle(&mut cx);
cx.update(|app| view.update(app, |view, cx| view.set_zoom(0.8, cx)));
let after = middle(&mut cx);
assert!(before.abs_diff(after) <= 1, "row {before} became {after}");
}
#[test]
fn a_sheet_brings_far_cut_and_frozen_cells_into_view() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let (view, worker) = live_view_of(app, &install, "short.fods", SHORT_ROWS);
let json = worker.lock().expect("the worker lock").values(&view.read(app).doc, crate::sheet::GEOMETRY).expect("geometry");
view.update(app, |view, cx| {
let wide = Bounds { origin: point(px(0.0), px(0.0)), size: size(px(6000.0), px(200.0)) };
view.prepare(wide);
assert_eq!(view.spare, (0.0, 0.0), "before its geometry a sheet starts left");
view.set_geometry(crate::sheet::geometry(&json).expect("parsed"), cx);
view.prepare(wide);
assert_eq!(view.spare, (0.0, 0.0), "and stays left after it");
view.viewport = (800.0, 200.0);
let (width, height) = (view.geom.twips_of(view.viewport.0), view.geom.twips_of(view.viewport.1));
let shows = |view: &LokView, rect: crate::Rect| {
let (x, y, w, h) = view.tile_rect(rect);
let (fx, fy) = view.frozen_tiles();
x + w <= fx + view.scroll.0 + width && y >= fy + view.scroll.1 && y + h <= fy + view.scroll.1 + height
};
let far = (1418, view.doc_size.1 + 20_000, 1280, 277);
let cell = crate::Cell { cursor: Some(far), ..crate::Cell::default() };
view.apply_batch(crate::Events { cell, ..crate::Events::default() }, None, cx);
assert!(shows(view, far), "a cell past the kernel's size still comes into view");
view.scroll = (0, 0);
let cut = (width - 200, 0, 1280, 256);
view.show(cut, cx);
assert!(view.scroll.0 > 0 && shows(view, cut), "a cell cut at the right edge comes into view");
let (x, _, w, _) = view.tile_rect(cut);
assert_eq!(view.scroll.0, x + w - width, "it scrolls no further than the cell's edge");
let before = view.scroll;
view.show((0, 0, view.print_of((x + w + width, 0)).0, 256), cx);
assert_eq!(view.scroll, before, "a cell wider than the view and covering it keeps still");
view.dragging = true;
let cell = crate::Cell { cursor: Some((1418, 90_000, 1280, 277)), ..crate::Cell::default() };
view.apply_batch(crate::Events { cell, ..crate::Events::default() }, None, cx);
assert_eq!(view.scroll, before, "a drag does not scroll under the pointer");
view.dragging = false;
view.scroll = (0, 0);
view.set_frozen((0, 600), cx);
let frozen = view.place((0, 300)).y;
view.show((1418, 300, 1280, 277), cx);
assert_eq!(view.scroll.1, 0, "a frozen row needs no scroll");
view.show((1418, 9000, 1280, 277), cx);
assert!(view.scroll.1 > 0, "a far row scrolls the rest");
assert_eq!(view.place((0, 300)).y, frozen, "the frozen row stays");
let back = view.twips_at(view.place((0, 9000)));
assert!((back.1 - 9000).abs() <= 15, "a scrolled row maps back: {back:?}");
});
});
}
#[test]
fn a_newly_selected_object_comes_into_view_a_moved_one_stays() {
let Some(install) = crate::client::tests::install() else {
eprintln!("SKIP: no pinned LOK build");
return;
};
let cx = gpui::TestAppContext::single();
cx.update(|app| {
let (view, _) = live_view_of(app, &install, "tall.fods", TALL);
view.update(app, |view, cx| {
let bounds = Bounds { origin: point(px(0.0), px(0.0)), size: size(px(800.0), px(600.0)) };
view.prepare(bounds);
let far = (60_000, 40_000, 9_000, 5_000);
let chart = |graphic| crate::Events { graphic, ..crate::Events::default() };
view.apply_batch(chart(Some(far)), None, cx);
view.prepare(bounds);
let (x, y) = (view.scroll.0, view.scroll.1);
assert!(x > 0 && y > 0, "the new chart is shown: scroll {x},{y}");
view.apply_batch(chart(Some((61_000, 40_000, 9_000, 5_000))), None, cx);
assert_eq!((view.scroll.0, view.scroll.1), (x, y), "dragging it does not scroll");
});
});
}
+11 -2
View File
@@ -47,14 +47,23 @@ impl LokView {
Some(at) => (f32::from(at.x - self.origin.x), f32::from(at.y - self.origin.y)),
None => (self.viewport.0 / 2.0, self.viewport.1 / 2.0),
};
let under = (self.scroll.0 + self.geom.twips_of(ax), self.scroll.1 + self.geom.twips_of(ay));
// The offset now, not the last frame's: zooms may bunch.
let spare = self.slack();
let (sx, sy) = (ax - spare.0, ay - spare.1);
// Anchored in print twips: tile twips change with the zoom.
let under = self.print_of((self.scroll.0 + self.geom.twips_of(sx), self.scroll.1 + self.geom.twips_of(sy)));
self.fit = false;
if (zoom - self.geom.zoom).abs() > 0.0001 {
self.geom.zoom = zoom;
self.retire_tiles();
self.failed.clear();
}
self.scroll = (under.0 - self.geom.twips_of(ax), under.1 - self.geom.twips_of(ay));
let (under, spare) = (self.tile_of(under), self.slack());
self.scroll = (under.0 - self.geom.twips_of(ax - spare.0), under.1 - self.geom.twips_of(ay - spare.1));
// Keys and menus keep the page's left edge in view.
if let (None, Some(page)) = (at, self.pages.first()) {
self.scroll.0 = self.scroll.0.min(self.tile_of((page.0, page.1)).0);
}
self.clamp_scroll();
log::debug!("lok: zoom {:.0}%", zoom * 100.0);
cx.emit(Zoomed);
+18 -4
View File
@@ -187,8 +187,8 @@ fn answer(lok: &Lok, tag: u8, id: u64, payload: &[u8]) {
.str()
.and_then(|url| Ok((url, unpack.str()?)))
.and_then(|(url, password)| load(lok, &url, password, ""))
.map(|id| Pack::new().u64(id).bytes()),
tag::IMPORT => text::import(lok, unpack).map(|id| Pack::new().u64(id).bytes()),
.and_then(loaded),
tag::IMPORT => text::import(lok, unpack).and_then(loaded),
tag::EXPORT_TEXT => text::export(unpack).map(|()| Vec::new()),
tag::DOC_SIZE => unpack
.u64()
@@ -205,6 +205,7 @@ fn answer(lok: &Lok, tag: u8, id: u64, payload: &[u8]) {
tag::PAINT_TILE => input::painted(unpack),
tag::PAINT_PART => input::part_painted(unpack),
tag::SLIDE_LAYERS => slides::slide_layers(unpack),
tag::SLIDE_LAYER => slides::slide_layer(unpack),
tag::VERIFY => unpack
.str()
.and_then(|url| verify(lok, &url))
@@ -246,9 +247,15 @@ fn answer(lok: &Lok, tag: u8, id: u64, payload: &[u8]) {
.u64()
.and_then(|id| {
let mut number = || i32::try_from(unpack.i64()?).map_err(io::Error::other);
Ok((id, (number()?, number()?, number()?, number()?)))
Ok((id, (number()?, number()?, number()?, number()?), (number()?, number()?)))
})
.and_then(|(id, (x, y, w, h), (pixels, twips))| {
// Calc reads clicks at this scale, not the last tile's.
with_doc(id, |doc| {
doc.set_client_zoom(pixels, twips);
doc.set_visible_area(x, y, w, h)
})
})
.and_then(|(id, (x, y, w, h))| with_doc(id, |doc| doc.set_visible_area(x, y, w, h)))
.map(|()| Vec::new()),
tag::SELECTION_TEXT => unpack
.u64()
@@ -332,6 +339,12 @@ fn load(lok: &Lok, url: &str, password: String, filter: &str) -> io::Result<u64>
Ok(id)
}
/// The reply to a load: the number and LOK_DOCTYPE.
fn loaded(id: u64) -> io::Result<Vec<u8>> {
let kind = with_doc(id, |doc| doc.kind())?;
Ok(Pack::new().u64(id).u64(kind as u64).bytes())
}
/// Stops watching and frees document `id`.
fn close(id: u64) {
let mut docs = docs().lock().expect("the docs lock");
@@ -340,6 +353,7 @@ fn close(id: u64) {
}
docs.remove(&id);
revision::forget(id);
slides::forget(id);
log::info!("lok-worker: {} documents open", docs.len());
}
+60 -9
View File
@@ -1,9 +1,32 @@
use std::io;
use std::{
collections::HashMap,
io,
sync::{LazyLock, Mutex, MutexGuard},
};
use super::with_doc;
use crate::ipc::{self, Pack, Unpack};
use crate::ipc::{Pack, Unpack};
/// Slide `part`'s slideshow layers at about the asked pixels.
/// The most a slide's layers may take in memory.
const LAYER_MEMORY: usize = 512 * 1024 * 1024;
/// The most pixel bytes one reply carries.
const CHUNK: usize = 16 * 1024 * 1024;
/// Rendered layers by document; each leaves as it is read.
type Waiting = HashMap<u64, Vec<Option<Vec<u8>>>>;
fn waiting() -> MutexGuard<'static, Waiting> {
static WAITING: LazyLock<Mutex<Waiting>> = LazyLock::new(Mutex::default);
WAITING.lock().expect("the layers lock")
}
/// Drops document `id`'s waiting layers.
pub(super) fn forget(id: u64) {
waiting().remove(&id);
}
/// Slide `part`'s layers, its pixels held back.
pub(super) fn slide_layers(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
let (id, part) = (unpack.u64()?, unpack.u64()?);
let (width, height) = (unpack.u64()?, unpack.u64()?);
@@ -20,18 +43,46 @@ pub(super) fn slide_layers(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
let hash = slide
.and_then(|slide| slide["hash"].as_str())
.ok_or_else(|| bad("no such slide"))?;
let ((width, height), layers) =
doc.slide_layers((part, hash), (width, height), ipc::MAX_FRAME - 1024)?;
let ((width, height), layers) = doc.slide_layers((part, hash), (width, height), LAYER_MEMORY)?;
let mut body = Pack::new()
.u64(u64::from(width))
.u64(u64::from(height))
.u64(layers.len() as u64);
for layer in &layers {
let mut pixels = Vec::with_capacity(layers.len());
for layer in layers {
body = body.str(&layer.json).u64(u64::from(layer.pixels.is_some()));
if let Some(pixels) = &layer.pixels {
body = body.blob(pixels);
}
pixels.push(layer.pixels);
}
waiting().insert(id, pixels);
Ok(body.bytes())
})?
}
/// Hands over layer `index` from byte `from`; read layers free.
pub(super) fn slide_layer(unpack: &mut Unpack) -> io::Result<Vec<u8>> {
let (id, index, from) = (unpack.u64()?, unpack.u64()?, unpack.u64()?);
let mut waiting = waiting();
let Some((total, bytes)) = piece(waiting.get_mut(&id), index, from) else {
// A request off the batch ends it.
waiting.remove(&id);
let what = format!("no layer {index} from byte {from} waits");
return Err(io::Error::new(io::ErrorKind::InvalidInput, what));
};
if waiting.get(&id).is_some_and(|layers| layers.iter().all(Option::is_none)) {
waiting.remove(&id);
}
Ok(Pack::new().u64(total).blob(&bytes).bytes())
}
/// Up to `CHUNK` bytes of a layer and its length.
fn piece(layers: Option<&mut Vec<Option<Vec<u8>>>>, index: u64, from: u64) -> Option<(u64, Vec<u8>)> {
let slot = layers?.get_mut(usize::try_from(index).ok()?)?;
let pixels = slot.as_ref()?;
let from = usize::try_from(from).ok().filter(|from| *from < pixels.len() || *from == 0)?;
let to = (from + CHUNK).min(pixels.len());
let read = (pixels.len() as u64, pixels[from..to].to_vec());
if to == pixels.len() {
*slot = None;
}
Some(read)
}
+26 -3
View File
@@ -3,7 +3,7 @@
use std::path::PathBuf;
use ely_gpui_component::primitives::Severity;
use ely_ui::commands::{CloseTab, Open, Quit, Save, SaveAs};
use ely_ui::commands::{CloseTab, Open, Save, SaveAs};
use gpui::{App, AppContext as _, Context, PathPromptOptions, TaskExt as _, Window};
use crate::{Dialog, Engine, Host, Opening, Saving, Tabs, in_window, text};
@@ -41,8 +41,31 @@ pub trait Closing: Host {
}
}
fn on_quit(&mut self, _: &Quit, window: &mut Window, cx: &mut Context<Self>) {
self.proceed(After::Quit, window, cx);
/// Takes `window` as home; quit anywhere asks here first.
fn own_window(&mut self, window: &Window, cx: &mut Context<Self>) {
let handle = window.window_handle();
self.core_mut().window = Some(handle);
let host = cx.entity().downgrade();
ely_ui::commands::route_quit(cx, move |cx| {
let host = host.clone();
// The asking window is busy until its action ends.
cx.defer(move |cx| {
let asked = handle.update(cx, |_, window, cx| {
// The question shows in front, with the keys.
window.activate_window();
host.update(cx, |host, cx| {
host.quitting(cx);
host.proceed(After::Quit, window, cx);
})
});
match asked {
Ok(Ok(())) => {}
// No home window is left to ask in.
_ if handle.update(cx, |_, _, _| ()).is_err() => cx.quit(),
Ok(Err(error)) | Err(error) => log::error!("office: the quit was not asked: {error}"),
}
});
});
}
fn no_document(&self, cx: &mut Context<Self>) {
+2
View File
@@ -72,6 +72,8 @@ pub trait Host: Sized + 'static {
fn observed(&mut self, id: u64, view: &Entity<View<Self>>, cx: &mut Context<Self>);
/// Runs before a search first moves the cursor.
fn search_leaves(&mut self, _: &mut Context<Self>) {}
/// Runs as a quit starts, before any tab closes.
fn quitting(&mut self, _: &mut Context<Self>) {}
/// Runs when a close stops: question or save cancelled.
fn close_cancelled(&mut self, _: &mut Context<Self>) {}
/// An outside change met a save; true if shown.
+25 -11
View File
@@ -77,9 +77,14 @@ impl Engine for Lok {
}
fn restart(app: AppId, worker: &mut Worker) -> io::Result<()> {
*worker = spawn(app)?;
worker.ready()?;
worker.set_author(&ely_platform::user::name()?)
let author = worker.author().map(str::to_string);
let author = author.ok_or_else(|| io::Error::other("the ended worker had no author"))?;
// The ended worker stays until the new one is ready.
let mut fresh = spawn(app)?;
fresh.ready()?;
fresh.set_author(&author)?;
*worker = fresh;
Ok(())
}
fn settled(view: &LokView) -> bool {
@@ -129,10 +134,13 @@ pub fn start(app: AppId, cx: &mut App) -> io::Result<(Arc<Mutex<Worker>>, PathBu
let worker = Arc::new(Mutex::new(spawn(app)?));
// The window opens now; the kernel finishes starting behind it.
let starting = Arc::clone(&worker);
// Settings as read at launch; defaults if unreadable.
let wanted = Arc::new(Mutex::new(ely_ui::settings::current(cx).author.clone()));
let first = Arc::clone(&wanted);
let started = cx.background_executor().spawn(async move {
let mut worker = starting.lock().expect("the worker lock");
worker.ready()?;
worker.set_author(&ely_platform::user::name()?)
sign(&mut worker, &first)
});
cx.spawn(async move |_| {
if let Err(error) = started.await {
@@ -140,10 +148,16 @@ pub fn start(app: AppId, cx: &mut App) -> io::Result<(Arc<Mutex<Worker>>, PathBu
}
})
.detach();
follow_author(&worker, cx);
follow_author(&worker, wanted, cx);
Ok((worker, work))
}
/// Sends the newest wanted name, read under the worker lock.
fn sign(worker: &mut Worker, wanted: &Mutex<String>) -> io::Result<()> {
let author = wanted.lock().expect("the author lock").clone();
worker.set_author(&ely_platform::user::named(&author)?)
}
/// A worker process on the app's profile, not yet checked.
fn spawn(app: AppId) -> io::Result<Worker> {
let data = ely_platform::data_dir(app).map_err(io::Error::other)?;
@@ -154,19 +168,19 @@ fn spawn(app: AppId) -> io::Result<Worker> {
}
/// A new author name signs from the next comment on.
fn follow_author(worker: &Arc<Mutex<Worker>>, cx: &mut App) {
fn follow_author(worker: &Arc<Mutex<Worker>>, wanted: Arc<Mutex<String>>, cx: &mut App) {
let worker = Arc::clone(worker);
let mut signed = ely_ui::settings::current(cx).author.clone();
cx.observe_global::<ely_ui::settings::Current>(move |cx| {
let author = ely_ui::settings::current(cx).author.clone();
if author == signed {
if *wanted.lock().expect("the author lock") == author {
return;
}
signed = author;
let worker = Arc::clone(&worker);
*wanted.lock().expect("the author lock") = author;
let (worker, wanted) = (Arc::clone(&worker), Arc::clone(&wanted));
cx.background_executor()
.spawn(async move {
let set = ely_platform::user::name().and_then(|name| worker.lock().expect("the worker lock").set_author(&name));
// Any order of these tasks ends on the newest name.
let set = sign(&mut worker.lock().expect("the worker lock"), &wanted);
if let Err(error) = set {
log::error!("lok: the new author name is not set: {error}");
}
+36
View File
@@ -0,0 +1,36 @@
//! A failed engine restart keeps the author for retries.
use ely_office::{Engine as _, Lok};
use ely_platform::AppId;
#[test]
fn a_restart_signs_with_the_newest_name_and_survives_a_failure() {
let Ok(install) = ely_lok::install_dir() else {
eprintln!("SKIP: no LOK build");
return;
};
let home = tempfile::tempdir().expect("a temp dir");
// The one test here: nothing else reads HOME.
unsafe { std::env::set_var("HOME", home.path()) };
let profile = ely_platform::data_dir(AppId::Doc).expect("a data dir").join("lok-profile");
std::fs::create_dir_all(&profile).expect("the profile");
let mut worker = ely_lok::Worker::launch(&install, &profile).expect("the worker");
worker.ready().expect("checks");
worker.set_author("Ada").expect("signs");
// The new worker's check cannot write its sample here.
let blocker = profile.join("lok-verify.fodt");
if blocker.exists() {
std::fs::remove_file(&blocker).expect("the last sample goes");
}
std::fs::create_dir(&blocker).expect("a folder in the way");
assert!(Lok::restart(AppId::Doc, &mut worker).is_err(), "the check fails");
assert_eq!(worker.author(), Some("Ada"), "the author survives a failed restart");
std::fs::remove_dir(&blocker).expect("cleared");
Lok::restart(AppId::Doc, &mut worker).expect("the next try restarts");
assert_eq!(worker.author(), Some("Ada"));
// A name asked while down signs after the restart.
worker.shutdown().expect("stops");
assert!(worker.set_author("Latest").is_err(), "a stopped engine cannot take it");
Lok::restart(AppId::Doc, &mut worker).expect("restarts");
assert_eq!(worker.author(), Some("Latest"), "the newest name signs");
}
+2
View File
@@ -13,6 +13,7 @@ fn main() {
"shim/ely_insert.c",
"shim/ely_text.c",
"shim/ely_write.c",
"shim/ely_pen.c",
"shim/ely_place.c",
"shim/ely_annot.c",
"shim/ely_form.c",
@@ -68,6 +69,7 @@ fn main() {
.file("shim/ely_insert.c")
.file("shim/ely_text.c")
.file("shim/ely_write.c")
.file("shim/ely_pen.c")
.file("shim/ely_place.c")
.file("shim/ely_annot.c")
.file("shim/ely_form.c")
+197
View File
@@ -0,0 +1,197 @@
/* The font new text is written in (PDF-03). */
#include <string.h>
#include "ely_shim.h"
/* The script face for typed signatures, from the worker. */
static const unsigned char *script_data;
static size_t script_len;
void ely_script_font(const unsigned char *data, size_t len)
{
script_data = data;
script_len = len;
}
/* `cid` as text extraction reads it (pdf-op-run.c), or -1. */
static int unicode_of(pdf_font_desc *desc, int cid)
{
int ucs[PDF_MRANGE_CAP], n = 0;
if (desc->to_unicode)
n = pdf_lookup_cmap_full(desc->to_unicode, cid, ucs);
if (n == 1 && ucs[0] >= 8 && ucs[0] <= 13)
ucs[0] = ' ';
if (n == 1 && (ucs[0] < 32 || (ucs[0] >= 127 && ucs[0] < 160)))
n = 0;
if (n == 0 && cid < (int)desc->cid_to_ucs_len)
ucs[0] = desc->cid_to_ucs[cid], n = 1;
return n == 1 && ucs[0] > 0 && ucs[0] != FZ_REPLACEMENT_CHARACTER ? ucs[0] : -1;
}
/* Unicode and code pairs of `desc`; its codes are CIDs. */
static void own_codes(fz_context *ctx, pdf_font_desc *desc, ely_pen *p)
{
pdf_cmap *enc = desc->encoding;
int cid, end;
if (!enc || strcmp(enc->cmap_name, "Identity-H") || enc->codespace_len != 1 || enc->codespace[0].n > 2)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the document's font uses codes Ely cannot write");
p->bytes = enc->codespace[0].n;
end = 1 << (8 * p->bytes);
p->map = fz_malloc_array(ctx, 2 * end, int);
for (cid = 0; cid < end; cid++)
{
int u = unicode_of(desc, cid);
if (u > 0 && pdf_font_cid_to_gid(ctx, desc, cid) > 0)
p->map[2 * p->mapped] = u, p->map[2 * p->mapped + 1] = cid, p->mapped++;
}
}
/* The page font drawn as `own`, with its codes. */
static void own_font(fz_context *ctx, pdf_page *page, fz_font *own, ely_pen *p)
{
pdf_obj *res = pdf_page_resources(ctx, page);
pdf_resource_stack stack = { NULL, res };
pdf_obj *fonts = pdf_dict_get(ctx, res, PDF_NAME(Font));
int i, n = pdf_dict_len(ctx, fonts);
for (i = 0; i < n && !p->desc; i++)
{
pdf_font_desc *desc = pdf_load_font(ctx, page->doc, &stack, pdf_dict_get_val(ctx, fonts, i));
if (desc->font != own)
{
pdf_drop_font(ctx, desc);
continue;
}
p->desc = desc;
p->num = pdf_to_num(ctx, pdf_dict_get_val(ctx, fonts, i));
if (!p->num)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the document's font is not an object of its own");
own_codes(ctx, desc, p);
}
if (!p->desc)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the block's font is not a font of its page");
}
void ely_choose_pen(fz_context *ctx, const char *choice, fz_font *own, pdf_page *page, ely_pen *p)
{
static const struct { const char *choice, *name; } latin[] = {
{ "helvetica", "Helvetica" }, { "times", "Times-Roman" }, { "courier", "Courier" } };
static const struct { const char *choice; int ordering; } cjk[] = {
{ "cjk-sc", FZ_ADOBE_GB }, { "cjk-tc", FZ_ADOBE_CNS }, { "cjk-jp", FZ_ADOBE_JAPAN }, { "cjk-kr", FZ_ADOBE_KOREA } };
size_t i;
if (!strcmp(choice, "script"))
{
if (!script_data)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no script font was given");
p->kind = PEN_CID;
p->font = fz_new_font_from_memory(ctx, "GreatVibes", script_data, (int)script_len, 0, 0);
return;
}
if (!strcmp(choice, "original"))
{
if (!own)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the block has no font of its own");
p->kind = PEN_OWN;
own_font(ctx, page, own, p);
return;
}
for (i = 0; i < nelem(latin); i++)
if (!strcmp(choice, latin[i].choice))
{
p->kind = PEN_SIMPLE;
p->font = fz_new_base14_font(ctx, latin[i].name);
return;
}
for (i = 0; i < nelem(cjk); i++)
if (!strcmp(choice, cjk[i].choice))
{
p->kind = PEN_CJK;
p->ordering = cjk[i].ordering;
p->font = fz_new_cjk_font(ctx, cjk[i].ordering);
return;
}
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no font %s", choice);
}
const char *ely_pen_resource(fz_context *ctx, pdf_document *pdf, pdf_page *page, ely_pen *p, char *name, size_t room)
{
pdf_drop_obj(ctx, p->ref);
p->ref = NULL;
switch (p->kind)
{
case PEN_OWN:
/* Removing the block may drop the font from the page. */
p->ref = pdf_new_indirect(ctx, pdf, p->num, 0);
break;
case PEN_CID:
p->ref = pdf_add_cid_font(ctx, pdf, p->font);
break;
case PEN_SIMPLE:
p->ref = pdf_add_simple_font(ctx, pdf, p->font, PDF_SIMPLE_ENCODING_LATIN);
break;
case PEN_CJK:
p->ref = pdf_add_cjk_font(ctx, pdf, p->font, p->ordering, 0, 0);
break;
}
return ely_add_resource(ctx, pdf, page->obj, PDF_NAME(Font), "ElyF", p->ref, name, room);
}
/* The own font's code for `u`, or -1. */
static int own_code(ely_pen *p, int u)
{
int i;
for (i = 0; i < p->mapped; i++)
if (p->map[2 * i] == u)
return p->map[2 * i + 1];
return -1;
}
/* The new font's glyph for `u`, or 0. */
static int glyph(fz_context *ctx, ely_pen *p, int u)
{
if (p->kind == PEN_SIMPLE && fz_windows_1252_from_unicode(u) < 0)
return 0;
return fz_encode_character(ctx, p->font, u);
}
int ely_pen_has(fz_context *ctx, ely_pen *p, int u)
{
return p->kind == PEN_OWN ? own_code(p, u) >= 0 : glyph(ctx, p, u) > 0;
}
float ely_pen_advance(fz_context *ctx, ely_pen *p, int u, float size)
{
if (p->kind == PEN_OWN)
return pdf_lookup_hmtx(ctx, p->desc, own_code(p, u)).w * size / 1000;
return fz_advance_glyph(ctx, p->font, glyph(ctx, p, u), 0) * size;
}
void ely_pen_code(fz_context *ctx, fz_buffer *buf, ely_pen *p, int u)
{
switch (p->kind)
{
case PEN_OWN:
fz_append_printf(ctx, buf, p->bytes == 1 ? "%02x" : "%04x", own_code(p, u));
break;
case PEN_CID:
fz_append_printf(ctx, buf, "%04x", glyph(ctx, p, u));
break;
case PEN_SIMPLE:
fz_append_printf(ctx, buf, "%02x", fz_windows_1252_from_unicode(u));
break;
case PEN_CJK:
if (u > 0xffff)
fz_append_printf(ctx, buf, "%04x%04x", 0xd800 + ((u - 0x10000) >> 10), 0xdc00 + ((u - 0x10000) & 0x3ff));
else
fz_append_printf(ctx, buf, "%04x", u);
break;
}
}
void ely_drop_pen(fz_context *ctx, ely_pen *p)
{
fz_drop_font(ctx, p->font);
pdf_drop_obj(ctx, p->ref);
pdf_drop_font(ctx, p->desc);
fz_free(ctx, p->map);
}
+30
View File
@@ -53,4 +53,34 @@ int ely_watch_end(fz_context *ctx);
const char *ely_open_warnings(void);
void ely_drop_alt(fz_context *ctx, pdf_document *pdf, pdf_page *page);
/* A font to write with: new, or the page's own. */
typedef enum
{
PEN_CID,
PEN_SIMPLE,
PEN_CJK,
PEN_OWN
} ely_pen_kind;
typedef struct
{
ely_pen_kind kind;
fz_font *font;
int ordering;
pdf_obj *ref;
/* The page's own font: object number, description, code width. */
int num;
pdf_font_desc *desc;
int bytes;
/* Unicode and code pairs of the own font. */
int *map, mapped;
} ely_pen;
void ely_choose_pen(fz_context *ctx, const char *choice, fz_font *own, pdf_page *page, ely_pen *p);
const char *ely_pen_resource(fz_context *ctx, pdf_document *pdf, pdf_page *page, ely_pen *p, char *name, size_t room);
int ely_pen_has(fz_context *ctx, ely_pen *p, int u);
float ely_pen_advance(fz_context *ctx, ely_pen *p, int u, float size);
void ely_pen_code(fz_context *ctx, fz_buffer *buf, ely_pen *p, int u);
void ely_drop_pen(fz_context *ctx, ely_pen *p);
#endif
+102 -11
View File
@@ -29,6 +29,12 @@ typedef struct
int *c;
int n;
int hit;
/* Page-wide: each target's block, and hits per block. */
int *owner;
int *hits;
/* The glyph each block last counted, so once each. */
int *seen;
int glyph;
} targets;
/* The glyphs of `block` with their user-space origins. */
@@ -58,19 +64,32 @@ static int take_glyph(fz_context *ctx, void *opaque, int *ucs, int ucslen, fz_ma
{
targets *t = opaque;
fz_point at = fz_transform_point(fz_transform_point(fz_make_point(0, 0), trm), ctm);
int i, k;
int i, k, found = 0;
t->glyph++;
for (i = 0; i < t->n; i++)
{
int match = 0;
if (fabsf(at.x - t->at[i].x) > 0.5f || fabsf(at.y - t->at[i].y) > 0.5f)
continue;
for (k = 0; k < ucslen; k++)
if (ucs[k] == t->c[i] || t->c[i] == FZ_REPLACEMENT_CHARACTER)
{
t->hit++;
return 1;
}
for (k = 0; k < ucslen && !match; k++)
match = ucs[k] == t->c[i] || t->c[i] == FZ_REPLACEMENT_CHARACTER;
if (!match)
continue;
if (!t->owner)
{
t->hit++;
return 1;
}
/* Every block this glyph matches counts it once. */
if (t->seen[t->owner[i]] != t->glyph)
{
t->seen[t->owner[i]] = t->glyph;
t->hits[t->owner[i]]++;
}
found = 1;
}
return 0;
t->hit += found;
return found;
}
/* Runs the glyph filter over the page; `dry` changes nothing. */
@@ -99,7 +118,7 @@ fz_matrix ely_to_user(fz_context *ctx, pdf_page *page)
/* Whether all of `block` sits in the page's own content. */
static int reachable(fz_context *ctx, pdf_document *pdf, pdf_page *page, fz_stext_block *block)
{
targets t = { NULL, NULL, 0, 0 };
targets t = { NULL, NULL, 0, 0, NULL, NULL, NULL, 0 };
int ok = 0;
fz_var(t.at);
fz_var(t.c);
@@ -122,6 +141,70 @@ static int reachable(fz_context *ctx, pdf_document *pdf, pdf_page *page, fz_stex
return ok;
}
/* Each text block's glyphs found in page content, one pass. */
static void reachable_all(fz_context *ctx, pdf_document *pdf, pdf_page *page, fz_stext_page *text, int n, int *ok)
{
targets t = { NULL, NULL, 0, 0, NULL, NULL, NULL, 0 };
int *count = NULL, all = 0, b;
fz_matrix to_user = ely_to_user(ctx, page);
fz_stext_block *block;
fz_stext_line *line;
fz_stext_char *ch;
fz_var(t.at);
fz_var(t.c);
fz_var(t.owner);
fz_var(t.hits);
fz_var(t.seen);
fz_var(count);
pdf_begin_operation(ctx, pdf, "Look at text");
fz_try(ctx)
{
for (block = text->first_block; block; block = block->next)
if (block->type == FZ_STEXT_BLOCK_TEXT)
for (line = block->u.t.first_line; line; line = line->next)
for (ch = line->first_char; ch; ch = ch->next)
all++;
t.at = fz_malloc_array(ctx, all + 1, fz_point);
t.c = fz_malloc_array(ctx, all + 1, int);
t.owner = fz_malloc_array(ctx, all + 1, int);
t.hits = fz_calloc(ctx, n + 1, sizeof(int));
t.seen = fz_calloc(ctx, n + 1, sizeof(int));
count = fz_calloc(ctx, n + 1, sizeof(int));
b = 0;
for (block = text->first_block; block; block = block->next)
{
if (block->type != FZ_STEXT_BLOCK_TEXT)
continue;
for (line = block->u.t.first_line; line; line = line->next)
for (ch = line->first_char; ch; ch = ch->next)
if (!(ch->flags & FZ_STEXT_SYNTHETIC))
{
t.at[t.n] = fz_transform_point(ch->origin, to_user);
t.c[t.n] = ch->c;
t.owner[t.n++] = b;
count[b]++;
}
b++;
}
filter_glyphs(ctx, pdf, page, &t, 1);
for (b = 0; b < n; b++)
ok[b] = count[b] > 0 && t.hits[b] == count[b];
}
fz_always(ctx)
{
pdf_abandon_operation(ctx, pdf);
ely_forget_resources(ctx, pdf);
fz_free(ctx, t.at);
fz_free(ctx, t.c);
fz_free(ctx, t.owner);
fz_free(ctx, t.hits);
fz_free(ctx, t.seen);
fz_free(ctx, count);
}
fz_catch(ctx)
fz_rethrow(ctx);
}
/* The text of `block`, lines on lines. */
static void block_text(fz_context *ctx, fz_buffer *buf, fz_stext_block *block)
{
@@ -153,18 +236,24 @@ int ely_text_blocks(fz_context *ctx, fz_document *doc, int number, unsigned char
pdf_page *page = NULL;
fz_buffer *buf = NULL, *words = NULL;
fz_output *out = NULL;
int *reached = NULL;
fz_var(text);
fz_var(page);
fz_var(buf);
fz_var(words);
fz_var(out);
fz_var(reached);
fz_try(ctx)
{
pdf_document *pdf = ely_pdf_of(ctx, doc);
fz_stext_block *block;
int first = 1;
int first = 1, n = 0, at = 0;
text = read_text(ctx, doc, number);
page = pdf_load_page(ctx, pdf, number);
for (block = text->first_block; block; block = block->next)
n += block->type == FZ_STEXT_BLOCK_TEXT;
reached = fz_calloc(ctx, n + 1, sizeof(int));
reachable_all(ctx, pdf, page, text, n, reached);
buf = fz_new_buffer(ctx, 1024);
out = fz_new_output_with_buffer(ctx, buf);
fz_write_string(ctx, out, "[");
@@ -175,7 +264,8 @@ int ely_text_blocks(fz_context *ctx, fz_document *doc, int number, unsigned char
if (block->type != FZ_STEXT_BLOCK_TEXT)
continue;
ch = block->u.t.first_line->first_char;
editable = upright(block) && reachable(ctx, pdf, page, block);
editable = reached[at++];
editable = editable && upright(block);
fz_drop_buffer(ctx, words);
words = NULL;
words = fz_new_buffer(ctx, 256);
@@ -198,6 +288,7 @@ int ely_text_blocks(fz_context *ctx, fz_document *doc, int number, unsigned char
fz_drop_buffer(ctx, words);
fz_drop_page(ctx, (fz_page *)page);
fz_drop_stext_page(ctx, text);
fz_free(ctx, reached);
}
fz_catch(ctx)
return ely_fail(ctx);
+14 -134
View File
@@ -5,22 +5,6 @@
#include "ely_shim.h"
typedef enum
{
PEN_CID,
PEN_SIMPLE,
PEN_CJK
} pen_kind;
/* A font to write with and its resource. */
typedef struct
{
pen_kind kind;
fz_font *font;
int ordering;
pdf_obj *ref;
} pen;
/* What to write, where, in what. */
typedef struct
{
@@ -32,103 +16,6 @@ typedef struct
float box[3];
} text_args;
/* The script face for typed signatures, from the worker. */
static const unsigned char *script_data;
static size_t script_len;
void ely_script_font(const unsigned char *data, size_t len)
{
script_data = data;
script_len = len;
}
/* The pen named `choice`; "original" writes in `own`. */
static void choose_pen(fz_context *ctx, const char *choice, fz_font *own, pen *p)
{
static const struct { const char *choice, *name; } latin[] = {
{ "helvetica", "Helvetica" }, { "times", "Times-Roman" }, { "courier", "Courier" } };
static const struct { const char *choice; int ordering; } cjk[] = {
{ "cjk-sc", FZ_ADOBE_GB }, { "cjk-tc", FZ_ADOBE_CNS }, { "cjk-jp", FZ_ADOBE_JAPAN }, { "cjk-kr", FZ_ADOBE_KOREA } };
size_t i;
if (!strcmp(choice, "script"))
{
if (!script_data)
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no script font was given");
p->kind = PEN_CID;
p->font = fz_new_font_from_memory(ctx, "GreatVibes", script_data, (int)script_len, 0, 0);
return;
}
if (!strcmp(choice, "original"))
{
if (!own || !pdf_font_writing_supported(ctx, own))
fz_throw(ctx, FZ_ERROR_ARGUMENT, "the document's font cannot write new text");
p->kind = PEN_CID;
p->font = fz_keep_font(ctx, own);
return;
}
for (i = 0; i < nelem(latin); i++)
if (!strcmp(choice, latin[i].choice))
{
p->kind = PEN_SIMPLE;
p->font = fz_new_base14_font(ctx, latin[i].name);
return;
}
for (i = 0; i < nelem(cjk); i++)
if (!strcmp(choice, cjk[i].choice))
{
p->kind = PEN_CJK;
p->ordering = cjk[i].ordering;
p->font = fz_new_cjk_font(ctx, cjk[i].ordering);
return;
}
fz_throw(ctx, FZ_ERROR_ARGUMENT, "no font %s", choice);
}
/* The pen's font as a resource of `pdf`. */
static void add_pen(fz_context *ctx, pdf_document *pdf, pen *p)
{
switch (p->kind)
{
case PEN_CID:
p->ref = pdf_add_cid_font(ctx, pdf, p->font);
break;
case PEN_SIMPLE:
p->ref = pdf_add_simple_font(ctx, pdf, p->font, PDF_SIMPLE_ENCODING_LATIN);
break;
case PEN_CJK:
p->ref = pdf_add_cjk_font(ctx, pdf, p->font, p->ordering, 0, 0);
break;
}
}
/* The pen's glyph for `u`; 0 when it has none. */
static int glyph(fz_context *ctx, pen *p, int u)
{
if (p->kind == PEN_SIMPLE && fz_windows_1252_from_unicode(u) < 0)
return 0;
return fz_encode_character(ctx, p->font, u);
}
/* `u` as the pen's code, in hex. */
static void code(fz_context *ctx, fz_buffer *buf, pen *p, int u, int gid)
{
switch (p->kind)
{
case PEN_CID:
fz_append_printf(ctx, buf, "%04x", gid);
break;
case PEN_SIMPLE:
fz_append_printf(ctx, buf, "%02x", fz_windows_1252_from_unicode(u));
break;
case PEN_CJK:
if (u > 0xffff)
fz_append_printf(ctx, buf, "%04x%04x", 0xd800 + ((u - 0x10000) >> 10), 0xdc00 + ((u - 0x10000) & 0x3ff));
else
fz_append_printf(ctx, buf, "%04x", u);
break;
}
}
/* `text` as code points; the count is returned. */
static int runes(fz_context *ctx, const char *text, int **out)
{
@@ -142,13 +29,8 @@ static int runes(fz_context *ctx, const char *text, int **out)
return n;
}
static float advance(fz_context *ctx, pen *p, int u, float size)
{
return fz_advance_glyph(ctx, p->font, glyph(ctx, p, u), 0) * size;
}
/* Lines no wider than `width`: [from, to) each. */
static int lay_out(fz_context *ctx, pen *p, const int *u, int n, float size, float width, int *from, int *to,
static int lay_out(fz_context *ctx, ely_pen *p, const int *u, int n, float size, float width, int *from, int *to,
float *widest)
{
int i = 0, lines = 0;
@@ -159,8 +41,9 @@ static int lay_out(fz_context *ctx, pen *p, const int *u, int n, float size, flo
float run = 0, before = 0;
for (j = i; j < n && u[j] != '\n'; j++)
{
float w = advance(ctx, p, u[j], size);
if (run + w > width && j > i)
float w = ely_pen_advance(ctx, p, u[j], size);
/* A box measured from these widths fits them. */
if (run + w > width + 0.01f && j > i)
break;
if (u[j] == ' ')
space = j, before = run;
@@ -257,7 +140,7 @@ pdf_obj *ely_append_content(fz_context *ctx, pdf_document *pdf, pdf_obj *page, f
/* Text laid out: the pen, code points, lines, placement. */
typedef struct
{
pen p;
ely_pen p;
int *u, n;
int *from, *to, lines;
float widest;
@@ -267,21 +150,20 @@ typedef struct
static void drop_laid(fz_context *ctx, laid *l)
{
fz_drop_font(ctx, l->p.font);
pdf_drop_obj(ctx, l->p.ref);
ely_drop_pen(ctx, &l->p);
fz_free(ctx, l->u);
fz_free(ctx, l->from);
fz_free(ctx, l->to);
}
/* Lays `a` out from `first`, or names a missing glyph. */
static int lay_text(fz_context *ctx, text_args *a, fz_font *own, fz_point first, float gap, laid *l)
static int lay_text(fz_context *ctx, text_args *a, fz_font *own, pdf_page *page, fz_point first, float gap, laid *l)
{
int i;
choose_pen(ctx, a->font, own, &l->p);
ely_choose_pen(ctx, a->font, own, page, &l->p);
l->n = runes(ctx, a->text, &l->u);
for (i = 0; i < l->n; i++)
if (l->u[i] != '\n' && !glyph(ctx, &l->p, l->u[i]))
if (l->u[i] != '\n' && !ely_pen_has(ctx, &l->p, l->u[i]))
return l->u[i];
l->from = fz_malloc_array(ctx, l->n + 2, int);
l->to = fz_malloc_array(ctx, l->n + 2, int);
@@ -307,10 +189,7 @@ static void draw_laid(fz_context *ctx, pdf_document *pdf, pdf_page *page, laid *
fz_matrix to_user = ely_to_user(ctx, page);
char name[32];
int i, line;
pdf_drop_obj(ctx, l->p.ref);
l->p.ref = NULL;
add_pen(ctx, pdf, &l->p);
ely_add_resource(ctx, pdf, page->obj, PDF_NAME(Font), "ElyF", l->p.ref, name, sizeof name);
ely_pen_resource(ctx, pdf, page, &l->p, name, sizeof name);
buf = fz_new_buffer(ctx, 256);
fz_append_string(ctx, buf, "q\n");
for (line = 0; line < l->lines; line++)
@@ -320,7 +199,7 @@ static void draw_laid(fz_context *ctx, pdf_document *pdf, pdf_page *page, laid *
((a->rgb >> 16) & 255) / 255.0f, ((a->rgb >> 8) & 255) / 255.0f, (a->rgb & 255) / 255.0f,
tm.a, tm.b, tm.c, tm.d, tm.e, tm.f);
for (i = l->from[line]; i < l->to[line]; i++)
code(ctx, buf, &l->p, l->u[i], glyph(ctx, &l->p, l->u[i]));
ely_pen_code(ctx, buf, &l->p, l->u[i]);
fz_append_string(ctx, buf, "> Tj ET\n");
}
fz_append_string(ctx, buf, "Q\n");
@@ -388,11 +267,12 @@ int ely_put_text(fz_context *ctx, fz_document *doc, int number, int block, const
pdf_document *pdf = NULL;
pdf_page *page = NULL;
ely_shape shape = { NULL };
laid l = { { PEN_SIMPLE, NULL, 0, NULL } };
laid l;
int begun = 0;
fz_var(pdf);
fz_var(page);
fz_var(begun);
memset(&l, 0, sizeof l);
*pixels = NULL;
*grew = 0;
fz_try(ctx)
@@ -409,7 +289,7 @@ int ely_put_text(fz_context *ctx, fz_document *doc, int number, int block, const
first = shape.first;
gap = shape.gap;
}
*missing = lay_text(ctx, &a, shape.font, first, gap, &l);
*missing = lay_text(ctx, &a, shape.font, page, first, gap, &l);
if (!*missing)
{
fz_rect drawn = laid_area(&l, size), region = drawn;
+23 -3
View File
@@ -293,10 +293,30 @@ impl Drop for Worker {
}
}
/// A permission refusal is `PermissionDenied`, named by what it needs.
/// A request the document's permissions refused, by what it needs.
#[derive(Debug)]
pub struct Refused(pub &'static str);
impl std::fmt::Display for Refused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}{}", crate::proto::may::REFUSED, self.0)
}
}
impl std::error::Error for Refused {}
/// What a permission refusal needs; none for other errors.
pub fn refused(error: &io::Error) -> Option<&'static str> {
error.get_ref()?.downcast_ref::<Refused>().map(|refused| refused.0)
}
/// A worker error; a refusal names a permission it knows.
fn refusal(text: String) -> io::Error {
match text.strip_prefix(crate::proto::may::REFUSED) {
Some(needed) => io::Error::new(io::ErrorKind::PermissionDenied, needed.to_string()),
let named = text
.strip_prefix(crate::proto::may::REFUSED)
.and_then(|needed| crate::proto::may::NAMES.iter().find(|(_, name)| *name == needed));
match named {
Some((_, name)) => io::Error::other(Refused(name)),
None => io::Error::other(text),
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ pub mod proto;
#[cfg(any(test, feature = "test-support"))]
pub mod sample;
pub use client::{Doc, Opened, Tile, Worker, is_stale};
pub use client::{Doc, Opened, Refused, Tile, Worker, is_stale, refused};
pub use content::{Drawn, TextBlock, Writing, Wrote};
pub use ocr::{OcrLine, tessdata};
pub use output::Optimizing;
+7 -1
View File
@@ -26,6 +26,8 @@ pub struct Extras<'a> {
pub stamp: Option<&'a str>,
/// Page one: a 2x2 image, 100x50 at 72, 500.
pub picture: bool,
/// With `picture`: page one draws it full-page first.
pub backdrop: bool,
/// Fields hang under one parent of this name.
pub parent: Option<&'a str>,
/// A parent and child field with no widget.
@@ -95,7 +97,11 @@ pub fn pdf_with(pages: &[(f32, f32, &[&str])], marks: &[Mark], extras: &Extras)
_ => b"<< /Type /Outlines /Count 0 >>".to_vec(),
});
for (n, (w, h, lines)) in pages.iter().enumerate() {
let mut stream = String::from("BT /F1 18 Tf 72 0 Td\n");
let mut stream = match n == 0 && extras.backdrop {
true => format!("q {w} 0 0 {h} 0 0 cm /Im1 Do Q\n"),
false => String::new(),
};
stream.push_str("BT /F1 18 Tf 72 0 Td\n");
for (at, line) in lines.iter().enumerate() {
let y = h - 72.0 - at as f32 * 24.0;
stream.push_str(&format!("1 0 0 1 72 {y} Tm ({line}) Tj\n"));
+159 -1
View File
@@ -4,7 +4,7 @@ use std::path::Path;
use ely_pdf_engine::{
Doc, Worker, Writing, Wrote,
sample::{Extras, pdf_with},
sample::{Extras, one_page, pdf_with},
};
fn worker() -> Worker {
@@ -275,3 +275,161 @@ fn runs_on_one_baseline_still_wrap_onto_new_lines() {
tops.dedup();
assert!(tops.len() >= 3, "each wrapped line has its own baseline: {tops:?}");
}
#[test]
fn a_subset_font_writes_with_its_own_glyphs_and_reads_back() {
// LibreOffice's export: a subset font whose own tables are placeholders.
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/office/t.pdf");
let mut worker = worker();
let mut doc = worker.open(&path).expect("opens").doc;
let at = worker.text_blocks(doc, 0).expect("blocks").iter().position(|b| b.text.contains("BUNDLE")).expect("the block");
let mut writing = rewrite(&mut worker, doc, at, "TEXT BUNDLE", "original");
// Room for one line; the space stays a space.
writing.bx[2] *= 2.0;
assert!(matches!(worker.put_text(doc, 0, &writing, 0.0).expect("answers"), Wrote::Done(_)), "the page's glyphs suffice");
doc = worker.now(doc).expect("the state");
let now = page_text(&mut worker, doc);
assert!(now.contains("TEXT BUNDLE"), "the new words read back: {now:?}");
}
/// A PDF of `objects`, numbered from 1.
fn assembled(objects: &[Vec<u8>]) -> Vec<u8> {
let mut pdf = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (at, body) in objects.iter().enumerate() {
offsets.push(pdf.len());
pdf.extend([format!("{} 0 obj\n", at + 1).as_bytes(), body, b"\nendobj\n"].concat());
}
let xref = pdf.len();
pdf.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes());
offsets.iter().for_each(|at| pdf.extend(format!("{at:010} 00000 n \n").as_bytes()));
pdf.extend(format!("trailer\n<</Size {}/Root 1 0 R>>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).as_bytes());
pdf
}
/// "AB" in WinAnsi Helvetica whose ToUnicode maps only "A".
fn partial_unicode_pdf() -> Vec<u8> {
let stream = |data: &[u8]| [format!("<</Length {}>>stream\n", data.len()).as_bytes(), data, b"\nendstream"].concat();
let unicode = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /U def\n1 begincodespacerange <00> <FF> endcodespacerange\n1 beginbfchar <41> <0041> endbfchar\nendcmap CMapName currentdict /CMap defineresource pop end end";
assembled(&[
b"<</Type/Catalog/Pages 2 0 R>>".to_vec(),
b"<</Type/Pages/Kids[3 0 R]/Count 1>>".to_vec(),
b"<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]/Resources<</Font<</F1 4 0 R>>>>/Contents 5 0 R>>".to_vec(),
b"<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding/ToUnicode 6 0 R>>".to_vec(),
stream(b"BT /F1 24 Tf 72 700 Td (AB) Tj ET"),
stream(unicode),
])
}
/// "AyB", where "x" and "y" share one glyph.
fn shared_glyph_pdf() -> Vec<u8> {
let font = std::fs::read(Path::new(env!("CARGO_MANIFEST_DIR")).join("fonts/GreatVibes-Regular.ttf")).expect("the font");
let stream = |dict: &str, data: &[u8]| [format!("<<{dict}/Length {}>>stream\n", data.len()).as_bytes(), data, b"\nendstream"].concat();
let unicode = b"/CIDInit /ProcSet findresource begin 12 dict begin begincmap /CMapName /U def\n1 begincodespacerange <0000> <FFFF> endcodespacerange\n4 beginbfchar <0001> <0041> <0002> <0078> <0003> <0079> <0004> <0042> endbfchar\nendcmap CMapName currentdict /CMap defineresource pop end end";
let gids: Vec<u8> = [0u16, 36, 16, 16, 37].iter().flat_map(|g| g.to_be_bytes()).collect();
let objects = [
b"<</Type/Catalog/Pages 2 0 R>>".to_vec(),
b"<</Type/Pages/Kids[3 0 R]/Count 1>>".to_vec(),
b"<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]/Resources<</Font<</F1 4 0 R>>>>/Contents 5 0 R>>".to_vec(),
b"<</Type/Font/Subtype/Type0/BaseFont/GreatVibes/Encoding/Identity-H/DescendantFonts[6 0 R]/ToUnicode 7 0 R>>".to_vec(),
stream("", b"BT /F1 24 Tf 72 700 Td <000100030004> Tj ET"),
b"<</Type/Font/Subtype/CIDFontType2/BaseFont/GreatVibes/CIDSystemInfo<</Registry(Adobe)/Ordering(Identity)/Supplement 0>>/FontDescriptor 8 0 R/CIDToGIDMap 9 0 R/DW 600>>".to_vec(),
stream("", unicode),
b"<</Type/FontDescriptor/FontName/GreatVibes/Flags 4/FontBBox[-200 -300 1200 1000]/ItalicAngle 0/Ascent 900/Descent -300/CapHeight 700/StemV 80/FontFile2 10 0 R>>".to_vec(),
stream("", &gids),
stream(&format!("/Length1 {}", font.len()), &font),
];
assembled(&objects)
}
#[test]
fn a_letter_that_shares_its_glyph_keeps_its_own_code() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = dir.path().join("shared.pdf");
std::fs::write(&path, shared_glyph_pdf()).expect("writes");
let mut worker = worker();
let mut doc = worker.open(&path).expect("opens").doc;
assert_eq!(page_text(&mut worker, doc), "AyB", "the sample reads as written");
let writing = rewrite(&mut worker, doc, 0, "ByA", "original");
assert!(matches!(worker.put_text(doc, 0, &writing, 0.0).expect("answers"), Wrote::Done(_)));
doc = worker.now(doc).expect("the state");
assert_eq!(page_text(&mut worker, doc), "ByA", "y stays y, not the glyph's other letter");
}
#[test]
fn a_partial_to_unicode_falls_back_as_reading_does() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = dir.path().join("partial.pdf");
std::fs::write(&path, partial_unicode_pdf()).expect("writes");
let mut worker = worker();
let mut doc = worker.open(&path).expect("opens").doc;
assert_eq!(page_text(&mut worker, doc), "AB", "the sample reads as written");
let writing = rewrite(&mut worker, doc, 0, "BA", "original");
assert!(matches!(worker.put_text(doc, 0, &writing, 0.0).expect("answers"), Wrote::Done(_)), "B is in the font");
doc = worker.now(doc).expect("the state");
let out = dir.path().join("saved.pdf");
worker.save(doc, &out).expect("saves");
let doc = worker.open(&out).expect("reopens").doc;
assert_eq!(page_text(&mut worker, doc), "BA", "saved and read again");
}
#[test]
fn a_dense_page_lists_its_blocks_in_one_pass() {
let dir = tempfile::tempdir().expect("a temp dir");
let mut content = String::new();
for col in 0..10 {
for row in 0..100 {
content.push_str(&format!("BT /F1 2 Tf {} {} Td (Cell {col} {row}) Tj ET\n", 20 + col * 58, 780 - row * 7));
}
}
let font = "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string();
let path = dir.path().join("dense.pdf");
std::fs::write(&path, one_page("", " /Resources << /Font << /F1 5 0 R >> >>", &content, &[font])).expect("writes");
let mut worker = worker();
let doc = worker.open(&path).expect("opens").doc;
let started = std::time::Instant::now();
let blocks = worker.text_blocks(doc, 0).expect("blocks");
let took = started.elapsed();
assert_eq!((blocks.len(), blocks.iter().filter(|b| b.editable).count()), (1000, 1000));
// Per block took 1.5 s here; one pass 0.1 s.
assert!(took < std::time::Duration::from_millis(750), "{took:?}");
}
/// One page: `content`, font F1, and form Fm1 drawing `form`.
fn layered(dir: &Path, content: &str, form: &str) -> (Worker, Doc) {
let objects = [
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_string(),
format!("<< /Type /XObject /Subtype /Form /BBox [0 0 612 792] /Resources << /Font << /F1 5 0 R >> >> /Length {} >>\nstream\n{form}\nendstream", form.len()),
];
let page = " /Resources << /Font << /F1 5 0 R >> /XObject << /Fm1 6 0 R >> >>";
let path = dir.join("layered.pdf");
std::fs::write(&path, one_page("", page, content, &objects)).expect("writes");
let mut worker = worker();
let doc = worker.open(&path).expect("opens").doc;
(worker, doc)
}
fn editable(worker: &mut Worker, doc: Doc) -> Vec<(String, bool)> {
let blocks = worker.text_blocks(doc, 0).expect("blocks");
blocks.into_iter().map(|b| (b.text, b.editable)).collect()
}
#[test]
fn turned_text_first_leaves_the_later_blocks_their_own_answer() {
let dir = tempfile::tempdir().expect("a temp dir");
let content = "BT /F1 18 Tf 0 1 -1 0 50 500 Tm (ROTATED) Tj ET q 1 0 0 1 300 400 cm /Fm1 Do Q BT /F1 18 Tf 72 200 Td (OWN) Tj ET";
let (mut worker, doc) = layered(dir.path(), content, "BT /F1 12 Tf 0 10 Td (STAMP) Tj ET");
let mut got = editable(&mut worker, doc);
got.sort();
assert_eq!(got, [("OWN".into(), true), ("ROTATED".into(), false), ("STAMP".into(), false)]);
}
#[test]
fn blocks_that_share_a_glyph_origin_each_count_it() {
let dir = tempfile::tempdir().expect("a temp dir");
let content = "q /Fm1 Do Q BT /F1 18 Tf 72 300 Td (BREAK) Tj ET BT /F1 18 Tf 72 700 Td (AB) Tj ET";
let (mut worker, doc) = layered(dir.path(), content, "BT /F1 36 Tf 72 700 Td (AX) Tj ET");
let got = editable(&mut worker, doc);
assert!(got.contains(&("AB".into(), true)), "{got:?}");
assert!(got.contains(&("AX".into(), false)), "{got:?}");
}
@@ -61,3 +61,28 @@ fn text_a_field_and_page_order_read_back_elsewhere() {
assert!(pages[1].0.contains("Changed words") && !pages[1].0.contains("First page"), "{pages:?}");
assert_eq!(pages[1].1, vec!["Ada".to_string()]);
}
#[test]
fn text_in_a_subset_font_reads_back_elsewhere() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/office/t.pdf");
let mut worker = worker();
let mut doc = worker.open(&path).expect("opens").doc;
let blocks = worker.text_blocks(doc, 0).expect("blocks");
let (block, read) = blocks.iter().enumerate().find(|(_, b)| b.text.contains("BUNDLE")).expect("the block");
let writing = Writing {
block: Some(block),
expected: read.text.clone(),
text: "TEXT BUNDLE".into(),
font: "original".into(),
size: read.size,
rgb: read.rgb,
bx: [read.rect[0], read.rect[1], (read.rect[2] - read.rect[0]) * 2.0],
};
assert!(matches!(worker.put_text(doc, 0, &writing, 0.0).expect("writes"), Wrote::Done(_)));
doc = worker.now(doc).expect("the state");
let out = dir.path().join("edited.pdf");
worker.save(doc, &out).expect("saves");
let pages = read_back(&out);
assert!(pages[0].0.contains("TEXT BUNDLE"), "{pages:?}");
}
Loaded 100 of 251 files, more files were not shown because too many files have changed in this diff. Show more