mirror of
https://github.com/xiaoqidun/ofdgo.git
synced 2026-10-30 21:25:56 +08:00
Compare commits
239
Commits
92785cea4f
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
26bad97aab | ||
|
|
f7233616f7 | ||
|
|
8a4967c064 | ||
|
|
cffc78626b | ||
|
|
2350504cfe | ||
|
|
86e4d7d6ae | ||
|
|
f05275c6b8 | ||
|
|
ad23f0f8b0 | ||
|
|
f4a7516985 | ||
|
|
c8aaaca773 | ||
|
|
035da09334 | ||
|
|
1abeba6f99 | ||
|
|
12b04c184c | ||
|
|
47c593286d | ||
|
|
e519bb0527 | ||
|
|
b9f3274967 | ||
|
|
37b3e59282 | ||
|
|
f284a40897 | ||
|
|
8d6db4f91d | ||
|
|
3404677b15 | ||
|
|
8d435fe109 | ||
|
|
385d7aa531 | ||
|
|
94157b10c3 | ||
|
|
aebcda51a3 | ||
|
|
19084bb40b | ||
|
|
545b697310 | ||
|
|
1a25472b43 | ||
|
|
af80fcc9ba | ||
|
|
838a769c5b | ||
|
|
5b4f2472f7 | ||
|
|
fb51fd3b07 | ||
|
|
80e548f93e | ||
|
|
9c3a04b7eb | ||
|
|
9bb6c9141a | ||
|
|
4320b53d4a | ||
|
|
e5d7f577c7 | ||
|
|
7a23dcc6dd | ||
|
|
12aaada982 | ||
|
|
62631472ea | ||
|
|
9d6bf3e87f | ||
|
|
f8c8259502 | ||
|
|
f4429b126a | ||
|
|
50898934dc | ||
|
|
c2b0339fdf | ||
|
|
e5658de69d | ||
|
|
057bcba868 | ||
|
|
89a7ef04c7 | ||
|
|
e35533859c | ||
|
|
1215f7aa08 | ||
|
|
48d1d29b7e | ||
|
|
ba68acbc60 | ||
|
|
a75b90dffc | ||
|
|
da3f64c74a | ||
|
|
7e3f2c468a | ||
|
|
d384527371 | ||
|
|
2dcbafb70d | ||
|
|
f246b0f543 | ||
|
|
dfea3d60fd | ||
|
|
e91e146b50 | ||
|
|
f2c71c5acf | ||
|
|
b59d82a68a | ||
|
|
44eb9e20b9 | ||
|
|
bc71750c78 | ||
|
|
143d5e7f92 | ||
|
|
f76a1ecd1a | ||
|
|
af8b64e748 | ||
|
|
e67f329776 | ||
|
|
7bc31b6b84 | ||
|
|
dfd4f733f9 | ||
|
|
88adea348b | ||
|
|
20374f52f1 | ||
|
|
6dae7bdc20 | ||
|
|
9ee47731c9 | ||
|
|
4fee3dfd8e | ||
|
|
f322daa616 | ||
|
|
04efce42d8 | ||
|
|
41a50d9e96 | ||
|
|
f1864952ad | ||
|
|
413d41c31d | ||
|
|
fb4f03465b | ||
|
|
04d7d2d672 | ||
|
|
15a532a1ca | ||
|
|
1061b07942 | ||
|
|
01e29618f4 | ||
|
|
51ab8846e3 | ||
|
|
05d9657c7c | ||
|
|
cc7858b536 | ||
|
|
4fc468a27d | ||
|
|
630306e871 | ||
|
|
c351b80344 | ||
|
|
e66afe6b07 | ||
|
|
cc274bc571 | ||
|
|
730586b98f | ||
|
|
6832554ea3 | ||
|
|
6601340fcc | ||
|
|
47347e5364 | ||
|
|
7414a00305 | ||
|
|
4573cb942b | ||
|
|
15c64ed6f2 | ||
|
|
3816226ba5 | ||
|
|
3607c15162 | ||
|
|
8cbf0546ee | ||
|
|
411171bc60 | ||
|
|
2eaf5366bf | ||
|
|
17383adab6 | ||
|
|
f77899e576 | ||
|
|
94983ee23c | ||
|
|
d9c334e8aa | ||
|
|
6063492bd7 | ||
|
|
2cec0b17d3 | ||
|
|
986295ae57 | ||
|
|
92326d0a14 | ||
|
|
0d6a21fe9a | ||
|
|
1de949abfc | ||
|
|
1c576bde18 | ||
|
|
8774ac67f1 | ||
|
|
3ef0e36026 | ||
|
|
19aa5523f8 | ||
|
|
f0c0b9db94 | ||
|
|
df81d41d95 | ||
|
|
82b5275ad7 | ||
|
|
299229c584 | ||
|
|
75995cd8dc | ||
|
|
b875b885f1 | ||
|
|
c4345420d5 | ||
|
|
3f8240d3c1 | ||
|
|
410df7c3b0 | ||
|
|
89e080a9fc | ||
|
|
8e8aca399b | ||
|
|
a82d5858bd | ||
|
|
297e093457 | ||
|
|
7b4eb5ff60 | ||
|
|
2984b07c83 | ||
|
|
865ddd47f4 | ||
|
|
a022c3e636 | ||
|
|
615f94bcac | ||
|
|
e73db10de1 | ||
|
|
0ae9ad6562 | ||
|
|
799041171b | ||
|
|
86f34bbdea | ||
|
|
0021228898 | ||
|
|
a9b26b3257 | ||
|
|
5eed2d4e07 | ||
|
|
f830bcefa7 | ||
|
|
4c475e9b67 | ||
|
|
c10aa4dda7 | ||
|
|
69e2e52b96 | ||
|
|
571f8426fc | ||
|
|
7682a7dd5d | ||
|
|
68c58ef8c9 | ||
|
|
62206c7a4b | ||
|
|
850057f46f | ||
|
|
3a39fb293f | ||
|
|
bafc3e399f | ||
|
|
f6338784e1 | ||
|
|
2016b85256 | ||
|
|
629ff60efd | ||
|
|
7ddb67ea41 | ||
|
|
d717b704d8 | ||
|
|
76125e19d8 | ||
|
|
ac2eb2b5c7 | ||
|
|
85baeda7f9 | ||
|
|
49e5445ccd | ||
|
|
5b6dbd4afc | ||
|
|
de03bdfc6a | ||
|
|
f15b40545a | ||
|
|
a73d08d328 | ||
|
|
dacdf0b3c9 | ||
|
|
c2d525e77f | ||
|
|
bcac3673f6 | ||
|
|
0aa7575980 | ||
|
|
361a2b3fd3 | ||
|
|
fb23d92d08 | ||
|
|
89e7f09de8 | ||
|
|
9cb3a898c4 | ||
|
|
b680f0bc27 | ||
|
|
3bed2bfe77 | ||
|
|
3d3220a0ad | ||
|
|
50da1d9144 | ||
|
|
5183ba2ab0 | ||
|
|
994988d425 | ||
|
|
72a85e26cc | ||
|
|
2063745224 | ||
|
|
9b362d2f02 | ||
|
|
67f4cf9d2c | ||
|
|
974b515374 | ||
|
|
c250ca914e | ||
|
|
201082daa0 | ||
|
|
b4d566019d | ||
|
|
580592bbf8 | ||
|
|
764e8a750a | ||
|
|
3f774056da | ||
|
|
3227134bfc | ||
|
|
6ca44cd9a5 | ||
|
|
753149260f | ||
|
|
7c870d09e7 | ||
|
|
5f1a4e7dcc | ||
|
|
92a0957de2 | ||
|
|
8cf8303088 | ||
|
|
d9fb144e35 | ||
|
|
6b0332224f | ||
|
|
eac5a659e6 | ||
|
|
1abfdaf431 | ||
|
|
90514f2e18 | ||
|
|
075797402d | ||
|
|
eb20f66ffb | ||
|
|
4f530eb5b8 | ||
|
|
66aa87304b | ||
|
|
010ab9f314 | ||
|
|
83d936e9f8 | ||
|
|
ea55e997ee | ||
|
|
5fd3854af8 | ||
|
|
a882e3e137 | ||
|
|
a29b37ddef | ||
|
|
010baf3370 | ||
|
|
13b074c922 | ||
|
|
20d8dcebde | ||
|
|
f0094e2af6 | ||
|
|
e8ac15b0f9 | ||
|
|
83159a475c | ||
|
|
f3cc35e78c | ||
|
|
bfecdeb0d6 | ||
|
|
1a8de5a3f1 | ||
|
|
ec24b6a17d | ||
|
|
84808cda61 | ||
|
|
aab5d40f93 | ||
|
|
e222cddabb | ||
|
|
b06df462ea | ||
|
|
73889edefb | ||
|
|
d97c6f4e6f | ||
|
|
151ddb0a20 | ||
|
|
6a4b322e2c | ||
|
|
b7d852d879 | ||
|
|
dd0b14be77 | ||
|
|
f952c5d91d | ||
|
|
a2de650b52 | ||
|
|
627a06cda3 | ||
|
|
460701f4d9 | ||
|
|
a4f979ed2f |
No files matched your search
@@ -1,5 +1,6 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
set -e
|
set -e
|
||||||
export TZ=Asia/Shanghai
|
export TZ=Asia/Shanghai
|
||||||
|
export Version="$(git show -s --format='%ct-%H' HEAD)"
|
||||||
GOOS=js GOARCH=wasm CGO_ENABLED=0 go build -o assets/webui/wasm/ofdgo.wasm -trimpath -ldflags "-s -w -buildid=" ./cmd/webui/wasm.go
|
GOOS=js GOARCH=wasm CGO_ENABLED=0 go build -o assets/webui/wasm/ofdgo.wasm -trimpath -ldflags "-s -w -buildid=" ./cmd/webui/wasm.go
|
||||||
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main -trimpath -ldflags "-s -w -buildid=" ./cmd/webui/webui.go
|
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o main -trimpath -ldflags "-s -w -buildid= -X github.com/xiaoqidun/ofdgo/internal/build.Version=$Version" ./cmd/webui/webui.go
|
||||||
+2
-1
@@ -1,8 +1,9 @@
|
|||||||
.idea/
|
.idea/
|
||||||
.vscode/
|
.vscode/
|
||||||
.devcontainer/
|
.devcontainer/
|
||||||
|
releases/
|
||||||
go.work
|
go.work
|
||||||
go.work.sum
|
go.work.sum
|
||||||
assets/webui/wasm/ofdgo.wasm
|
|
||||||
*.exe
|
*.exe
|
||||||
*.exe~
|
*.exe~
|
||||||
|
assets/webui/wasm/ofdgo.wasm
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
# 基础镜像
|
# 基础镜像
|
||||||
FROM alpine:3.24.2
|
FROM alpine:3.24.3
|
||||||
|
|
||||||
# 作者信息
|
# 作者信息
|
||||||
LABEL authors="肖其顿 (XIAO QI DUN)"
|
LABEL authors="肖其顿 (XIAO QI DUN)"
|
||||||
|
|||||||
@@ -3,23 +3,28 @@
|
|||||||
|
|
||||||
# 主要能力
|
# 主要能力
|
||||||
- 文档处理:创建、读写、拆分、合并、压缩
|
- 文档处理:创建、读写、拆分、合并、压缩
|
||||||
- 渲染转换:矢量、位图、导入、导出、批量
|
- 文档阅读:搜索、缩放、旋转、双页、连续
|
||||||
- 文档安全:签名、签章、验签、加密、解密
|
- 文档管理:新建、导入、切换、排序、删除
|
||||||
- 电子发票:提取、创建、编辑、校验、同步
|
- 版本管理:创建、改名、切换、另存、删除
|
||||||
- 页面管理:添加、导入、复制、排序、删除
|
- 页面管理:添加、导入、复制、排序、删除
|
||||||
- 文字处理:插入、编辑、排版、搜索、提取
|
- 文档编辑:选区、重排、事务、撤销、重做
|
||||||
- 文字样式:选区、混排、装饰、阴影、底色
|
- 文字处理:插入、编辑、替换、排版、提取
|
||||||
|
- 文字样式:混排、粗体、斜体、阴影、底色
|
||||||
- 字体处理:匹配、内嵌、外置、子集、提取
|
- 字体处理:匹配、内嵌、外置、子集、提取
|
||||||
- 图片处理:插入、替换、缩放、裁剪、提取
|
- 图片处理:插入、替换、缩放、裁剪、提取
|
||||||
- 图形处理:绘制、变换、组合、对齐、分布
|
- 图形处理:绘制、变换、组合、对齐、分布
|
||||||
- 色彩管理:空间、配置、转换、渐变、透明
|
- 色彩管理:调色、渐变、图案、透明、转换
|
||||||
- 文档管理:添加、切换、改名、排序、删除
|
- 文档结构:图层、模板、目录、书签、标引
|
||||||
- 版本管理:创建、切换、改名、另存、删除
|
- 资源管理:导入、绑定、替换、提取、清理
|
||||||
- 文档结构:目录、书签、模板、标引、扩展
|
|
||||||
- 资源管理:字体、图片、色彩、媒体、附件
|
|
||||||
- 注解管理:批注、高亮、水印、印章、链接
|
- 注解管理:批注、高亮、水印、印章、链接
|
||||||
- 动作管理:跳转、链接、附件、音频、视频
|
- 交互动作:跳转、链接、附件、音频、视频
|
||||||
|
- 电子发票:提取、创建、编辑、校验、同步
|
||||||
|
- 文档安全:签名、签章、验签、加密、解密
|
||||||
- 三维处理:解析、材质、纹理、动画、渲染
|
- 三维处理:解析、材质、纹理、动画、渲染
|
||||||
|
- 页面渲染:矢量、位图、裁剪、蒙版、合成
|
||||||
|
- 批量转换:选页、并行、进度、取消、打包
|
||||||
|
- 打印输出:预览、双面、合印、小册、海报
|
||||||
|
- 应用交互:标签、链接、关联、拖放、复用
|
||||||
|
|
||||||
# 在线使用
|
# 在线使用
|
||||||
[OFDGo WebUI](https://ofdgo.aite.me/),将OFDGo编译为WASM提供服务
|
[OFDGo WebUI](https://ofdgo.aite.me/),将OFDGo编译为WASM提供服务
|
||||||
@@ -61,7 +66,22 @@ go build -o ofdgo_webui.exe -trimpath -ldflags "-s -w -buildid=" ./cmd/webui/web
|
|||||||
```
|
```
|
||||||
|
|
||||||
# 原生桌面
|
# 原生桌面
|
||||||
|
基于 [GUIGo](https://github.com/xiaoqidun/guigo) 实现,运行前需参照其说明安装系统依赖
|
||||||
|
|
||||||
```batch
|
```batch
|
||||||
|
set CGO_ENABLED=0
|
||||||
|
|
||||||
|
:: 构建Linux arm64(aarch64)
|
||||||
|
set GOOS=linux
|
||||||
|
set GOARCH=arm64
|
||||||
|
go build -o ofdgo_linux_arm64 -trimpath -ldflags "-s -w -buildid=" ./cmd/webview
|
||||||
|
|
||||||
|
:: 构建Linux amd64(x64/x86_64)
|
||||||
|
set GOOS=linux
|
||||||
|
set GOARCH=amd64
|
||||||
|
go build -o ofdgo_linux_amd64 -trimpath -ldflags "-s -w -buildid=" ./cmd/webview
|
||||||
|
|
||||||
|
:: 构建Windows amd64(x64/x86_64)
|
||||||
set GOOS=windows
|
set GOOS=windows
|
||||||
set GOARCH=amd64
|
set GOARCH=amd64
|
||||||
go build -o ofdgo_windows_amd64.exe -trimpath -ldflags "-H windowsgui -s -w -buildid=" ./cmd/webview
|
go build -o ofdgo_windows_amd64.exe -trimpath -ldflags "-H windowsgui -s -w -buildid=" ./cmd/webview
|
||||||
@@ -77,6 +97,7 @@ go get -u github.com/xiaoqidun/ofdgo
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
@@ -105,12 +126,11 @@ func main() {
|
|||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
// 3. 保存文档
|
// 3. 保存文档
|
||||||
ofdFile, err := os.Create("test.ofd")
|
output, err := ofdgo.NewFileOutput("test.ofd")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
defer ofdFile.Close()
|
if _, err := editor.SaveAs(context.Background(), output, ofdgo.WriteOptions{}); err != nil {
|
||||||
if _, err := editor.WriteTo(ofdFile); err != nil {
|
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -121,15 +141,20 @@ func main() {
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/xiaoqidun/ofdgo"
|
"github.com/xiaoqidun/ofdgo"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// 1. 打开文档
|
// 1. 打开文档
|
||||||
reader, err := ofdgo.Open("test.ofd")
|
input, err := ofdgo.OpenFile(context.Background(), "test.ofd", ofdgo.InputOptions{})
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
defer input.Close()
|
||||||
|
reader, err := ofdgo.NewReader(input)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -141,12 +166,11 @@ func main() {
|
|||||||
}
|
}
|
||||||
editor.Info.Title = "编辑后的"
|
editor.Info.Title = "编辑后的"
|
||||||
// 3. 另存文档
|
// 3. 另存文档
|
||||||
ofdFile, err := os.Create("edited.ofd")
|
output, err := ofdgo.NewFileOutput("edited.ofd")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
defer ofdFile.Close()
|
if _, err := editor.SaveAs(context.Background(), output, ofdgo.WriteOptions{}); err != nil {
|
||||||
if _, err := editor.WriteTo(ofdFile); err != nil {
|
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -166,15 +190,11 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// 1. 打开文档
|
// 1. 打开文档
|
||||||
pdfFile, err := os.Open("test.pdf")
|
input, err := ofdgo.OpenFile(context.Background(), "test.pdf", ofdgo.InputOptions{})
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
defer pdfFile.Close()
|
|
||||||
info, err := pdfFile.Stat()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
defer input.Close()
|
||||||
// 2. 创建文件
|
// 2. 创建文件
|
||||||
ofdFile, err := os.Create("test.ofd")
|
ofdFile, err := os.Create("test.ofd")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -182,7 +202,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
defer ofdFile.Close()
|
defer ofdFile.Close()
|
||||||
// 3. 转换文档
|
// 3. 转换文档
|
||||||
report, err := ofdgo.ConvertPDF(context.Background(), pdfFile, info.Size(), ofdFile, ofdgo.PDFImportOptions{})
|
report, err := ofdgo.ConvertPDF(context.Background(), input, ofdFile, ofdgo.PDFImportOptions{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -198,6 +218,7 @@ func main() {
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
@@ -206,7 +227,12 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// 1. 打开OFD文件
|
// 1. 打开OFD文件
|
||||||
reader, err := ofdgo.Open("test.ofd")
|
input, err := ofdgo.OpenFile(context.Background(), "test.ofd", ofdgo.InputOptions{})
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
defer input.Close()
|
||||||
|
reader, err := ofdgo.NewReader(input)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -230,6 +256,7 @@ func main() {
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
@@ -238,12 +265,13 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// 1. 打开OFD文件
|
// 1. 打开OFD文件
|
||||||
data, err := os.ReadFile("test.ofd")
|
input, err := ofdgo.OpenFile(context.Background(), "test.ofd", ofdgo.InputOptions{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
defer input.Close()
|
||||||
// 2. 验证OFD签名
|
// 2. 验证OFD签名
|
||||||
reports, err := ofdgo.VerifySignaturesBytes(data)
|
reports, err := ofdgo.VerifySignatures(input)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -276,6 +304,7 @@ func main() {
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
@@ -285,7 +314,12 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// 1. 打开OFD文件
|
// 1. 打开OFD文件
|
||||||
reader, err := ofdgo.Open("invoice.ofd")
|
input, err := ofdgo.OpenFile(context.Background(), "invoice.ofd", ofdgo.InputOptions{})
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
defer input.Close()
|
||||||
|
reader, err := ofdgo.NewReader(input)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,10 +18,10 @@ import "embed"
|
|||||||
|
|
||||||
// FS WebUI嵌入静态文件
|
// FS WebUI嵌入静态文件
|
||||||
//
|
//
|
||||||
//go:embed index.html ofdgo.css ofdgo.ico ofdgo.js ofdgo.json ofdgo.png ofdgo.svg ofdgo_edit.js ofdgo_font.js ofdgo_host.js ofdgo_wasm.js ofdgo_work.js wasm_exec.js
|
//go:embed index.html ofdgo.css ofdgo.ico ofdgo.js ofdgo.json ofdgo.png ofdgo.svg ofdgo_edit.js ofdgo_font.js ofdgo_host.js ofdgo_print.js ofdgo_theme.js ofdgo_util.js ofdgo_view.js ofdgo_wasm.js ofdgo_work.js wasm_exec.js
|
||||||
var FS embed.FS
|
var FS embed.FS
|
||||||
|
|
||||||
// NativeFS WebView嵌入静态文件
|
// NativeFS WebView嵌入静态文件
|
||||||
//
|
//
|
||||||
//go:embed index.html ofdgo.css ofdgo.ico ofdgo.js ofdgo.json ofdgo.png ofdgo.svg ofdgo_edit.js ofdgo_font.js ofdgo_host.js
|
//go:embed index.html ofdgo.css ofdgo.ico ofdgo.js ofdgo.json ofdgo.png ofdgo.svg ofdgo_edit.js ofdgo_font.js ofdgo_host.js ofdgo_print.js ofdgo_theme.js ofdgo_util.js ofdgo_view.js
|
||||||
var NativeFS embed.FS
|
var NativeFS embed.FS
|
||||||
+129
-24
@@ -8,22 +8,32 @@
|
|||||||
<link rel="manifest" href="./ofdgo.json">
|
<link rel="manifest" href="./ofdgo.json">
|
||||||
<link rel="icon" type="image/x-icon" sizes="16x16 32x32 48x48 64x64 128x128 256x256" href="./ofdgo.ico">
|
<link rel="icon" type="image/x-icon" sizes="16x16 32x32 48x48 64x64 128x128 256x256" href="./ofdgo.ico">
|
||||||
<link rel="icon" type="image/svg+xml" href="./ofdgo.svg">
|
<link rel="icon" type="image/svg+xml" href="./ofdgo.svg">
|
||||||
|
<script src="./ofdgo_theme.js"></script>
|
||||||
<link rel="stylesheet" href="./ofdgo.css">
|
<link rel="stylesheet" href="./ofdgo.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="app">
|
<div class="app">
|
||||||
|
<div id="documentTitleBar" class="document-titlebar">
|
||||||
|
<div id="documentTabs" class="document-tabs"></div>
|
||||||
|
<button id="documentNewTab" class="document-new-tab" type="button" title="新建"><span class="new-icon"></span></button>
|
||||||
|
<div class="document-title-drag"></div>
|
||||||
|
<button id="appearanceButton" class="app-appearance" type="button" title="设置"><span class="settings-icon"></span></button>
|
||||||
|
<button id="refreshAppButton" class="app-update" type="button" title="更新" hidden><span class="update-icon"></span></button>
|
||||||
|
</div>
|
||||||
<header class="toolbar-frame">
|
<header class="toolbar-frame">
|
||||||
<div class="toolbar app-bar">
|
<div class="toolbar app-bar">
|
||||||
<input id="ofdInput" class="file-input" type="file" accept=".ofd,.pdf">
|
<input id="ofdInput" class="file-input" type="file" accept=".ofd,.pdf" multiple>
|
||||||
<input id="fontInput" class="file-input" type="file" accept=".ttf,.otf,.ttc,font/*" multiple>
|
<input id="fontInput" class="file-input" type="file" accept=".ttf,.otf,.ttc,font/*" multiple>
|
||||||
<input id="fontDirectoryInput" class="file-input" type="file" webkitdirectory multiple>
|
<input id="fontDirectoryInput" class="file-input" type="file" webkitdirectory multiple>
|
||||||
<div class="tool-group">
|
<div class="tool-group">
|
||||||
<button id="ofdButton" class="icon-button" type="button" title="打开"><span class="open-icon"></span></button>
|
<button id="ofdButton" class="icon-button" type="button" title="打开"><span class="open-icon"></span></button>
|
||||||
<button id="closeButton" class="icon-button" type="button" title="关闭" disabled><span class="close-icon"></span></button>
|
<button id="closeButton" class="icon-button" type="button" title="关闭文档" disabled><span class="close-icon"></span></button>
|
||||||
<button id="newButton" class="icon-button" type="button" title="新建"><span class="new-icon"></span></button>
|
<button id="newButton" class="icon-button" type="button" title="新建"><span class="new-icon"></span></button>
|
||||||
<button id="saveButton" class="icon-button" type="button" title="保存" disabled><span class="save-icon"></span></button>
|
<button id="saveButton" class="icon-button" type="button" title="保存" disabled><span class="save-icon"></span></button>
|
||||||
|
<button id="saveAsButton" class="icon-button" type="button" title="另存" disabled><span class="save-as-icon"></span></button>
|
||||||
<button id="editButton" class="icon-button" type="button" title="编辑" data-pressed="false" disabled><span class="edit-icon"></span></button>
|
<button id="editButton" class="icon-button" type="button" title="编辑" data-pressed="false" disabled><span class="edit-icon"></span></button>
|
||||||
<button id="convertButton" class="icon-button" type="button" title="转换"><span class="convert-icon"></span></button>
|
<button id="convertButton" class="icon-button" type="button" title="转换"><span class="convert-icon"></span></button>
|
||||||
|
<button id="printButton" class="icon-button" type="button" title="打印" disabled><span class="print-icon"></span></button>
|
||||||
<button id="togglePagesButton" class="icon-button" type="button" title="页面栏" data-pressed="true"><span class="pages-icon"></span></button>
|
<button id="togglePagesButton" class="icon-button" type="button" title="页面栏" data-pressed="true"><span class="pages-icon"></span></button>
|
||||||
<button id="toggleMetaButton" class="icon-button" type="button" title="信息栏" data-pressed="true"><span class="info-icon"></span></button>
|
<button id="toggleMetaButton" class="icon-button" type="button" title="信息栏" data-pressed="true"><span class="info-icon"></span></button>
|
||||||
</div>
|
</div>
|
||||||
@@ -45,10 +55,11 @@
|
|||||||
<button id="fitHeightButton" class="button" type="button" data-short="高" disabled>适高</button>
|
<button id="fitHeightButton" class="button" type="button" data-short="高" disabled>适高</button>
|
||||||
<button id="rotateButton" class="button" type="button" data-short="转" disabled>旋转</button>
|
<button id="rotateButton" class="button" type="button" data-short="转" disabled>旋转</button>
|
||||||
<button id="panButton" class="button" type="button" data-short="拖" data-pressed="false" disabled>拖动</button>
|
<button id="panButton" class="button" type="button" data-short="拖" data-pressed="false" disabled>拖动</button>
|
||||||
<button id="continuousButton" class="button" type="button" data-short="连" data-pressed="false" disabled>连续</button>
|
|
||||||
<button id="annotationButton" class="button" type="button" data-short="注" data-pressed="true">注解</button>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="tool-group">
|
<div class="tool-group">
|
||||||
|
<button id="pageLayoutButton" class="button" type="button" data-short="单" disabled>单页</button>
|
||||||
|
<button id="continuousButton" class="button" type="button" data-short="连" data-pressed="false" disabled>连续</button>
|
||||||
|
<button id="annotationButton" class="button" type="button" data-short="注" data-pressed="true">注解</button>
|
||||||
<button id="renderVectorButton" class="button" type="button" data-short="矢" data-pressed="true" disabled>矢量</button>
|
<button id="renderVectorButton" class="button" type="button" data-short="矢" data-pressed="true" disabled>矢量</button>
|
||||||
<button id="renderRasterButton" class="button" type="button" data-short="位" data-pressed="false" disabled>位图</button>
|
<button id="renderRasterButton" class="button" type="button" data-short="位" data-pressed="false" disabled>位图</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -65,7 +76,6 @@
|
|||||||
<button id="exportButton" class="button" type="button" data-short="多" disabled>文档</button>
|
<button id="exportButton" class="button" type="button" data-short="多" disabled>文档</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button id="refreshAppButton" class="button app-update" type="button" data-short="更" hidden>更新</button>
|
|
||||||
</header>
|
</header>
|
||||||
<div id="editorTools" class="editor-toolbar" hidden>
|
<div id="editorTools" class="editor-toolbar" hidden>
|
||||||
<div class="editor-group editor-actions">
|
<div class="editor-group editor-actions">
|
||||||
@@ -74,7 +84,6 @@
|
|||||||
<span>操作</span>
|
<span>操作</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="editor-group editor-objects">
|
<div class="editor-group editor-objects">
|
||||||
<button id="compositeBackButton" class="button" type="button" hidden>返回</button>
|
|
||||||
<button id="selectObjectButton" class="button" type="button" data-pressed="true">选择</button>
|
<button id="selectObjectButton" class="button" type="button" data-pressed="true">选择</button>
|
||||||
<button id="multiSelectButton" class="button" type="button" data-pressed="false">多选</button>
|
<button id="multiSelectButton" class="button" type="button" data-pressed="false">多选</button>
|
||||||
<button id="editObjectButton" class="button" type="button" disabled>修改</button>
|
<button id="editObjectButton" class="button" type="button" disabled>修改</button>
|
||||||
@@ -115,9 +124,8 @@
|
|||||||
<span>插入</span>
|
<span>插入</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="editor-group">
|
<div class="editor-group">
|
||||||
<div class="text-font"><div class="font-picker"><input id="textFont" type="text" title="字体" autocomplete="off" spellcheck="false" disabled><button id="textFontToggle" type="button" title="选择字体" tabindex="-1" disabled></button></div><button id="textFontAdd" class="icon-button" type="button" title="添加字体">+</button></div>
|
<div class="text-font"><div class="font-picker"><input id="textFont" type="text" title="字体" autocomplete="off" spellcheck="false" disabled><button id="textFontToggle" type="button" title="选择字体" tabindex="-1" disabled></button></div><span class="editor-number"><input id="textSize" type="number" title="字号(pt)" min="1" step="any" required disabled></span><button id="textFontAdd" class="icon-button" type="button" title="添加字体">+</button></div>
|
||||||
<div id="textFontList" class="font-listbox" popover="manual"></div>
|
<div id="textFontList" class="font-listbox" popover="manual"></div>
|
||||||
<label class="editor-field"><span>字号</span><span class="editor-number"><input id="textSize" type="number" min="1" step="any" required disabled><span>pt</span></span></label>
|
|
||||||
<button id="textBold" class="button text-format-bold" data-text-format="bold" type="button" title="粗体" data-pressed="false" disabled>B</button>
|
<button id="textBold" class="button text-format-bold" data-text-format="bold" type="button" title="粗体" data-pressed="false" disabled>B</button>
|
||||||
<button id="textItalic" class="button text-format-italic" data-text-format="italic" type="button" title="斜体" data-pressed="false" disabled>I</button>
|
<button id="textItalic" class="button text-format-italic" data-text-format="italic" type="button" title="斜体" data-pressed="false" disabled>I</button>
|
||||||
<button id="textUnderline" class="button text-format-underline" data-text-format="underline" type="button" title="下划线" data-pressed="false" disabled>U</button>
|
<button id="textUnderline" class="button text-format-underline" data-text-format="underline" type="button" title="下划线" data-pressed="false" disabled>U</button>
|
||||||
@@ -133,7 +141,7 @@
|
|||||||
<option value="left">左齐</option>
|
<option value="left">左齐</option>
|
||||||
<option value="center">居中</option>
|
<option value="center">居中</option>
|
||||||
<option value="right">右齐</option>
|
<option value="right">右齐</option>
|
||||||
<option value="justify">两端</option>
|
<option value="justify">两端</option><option value="distributed">分散</option>
|
||||||
</select>
|
</select>
|
||||||
<label class="editor-field"><span>行距</span><span class="editor-number"><input id="textLineHeight" type="number" min="0" step="any" placeholder="自动" title="行距,0为自动" disabled><span>pt</span></span></label>
|
<label class="editor-field"><span>行距</span><span class="editor-number"><input id="textLineHeight" type="number" min="0" step="any" placeholder="自动" title="行距,0为自动" disabled><span>pt</span></span></label>
|
||||||
<button id="textWrap" class="button" type="button" data-pressed="false" disabled>折行</button>
|
<button id="textWrap" class="button" type="button" data-pressed="false" disabled>折行</button>
|
||||||
@@ -186,9 +194,18 @@
|
|||||||
<button id="batchPagesButton" class="editor-group-action" type="button">页面</button>
|
<button id="batchPagesButton" class="editor-group-action" type="button">页面</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<dialog id="aboutPanel" class="form-dialog about-dialog">
|
||||||
|
<form method="dialog">
|
||||||
|
<h2 id="aboutTitle" class="form-title">软件信息</h2>
|
||||||
|
<div class="about-row"><span>构建版本</span><span id="aboutVersion">develop</span></div>
|
||||||
|
<div class="about-row"><span>项目官网</span><a href="https://ofdgo.aite.me/" target="_blank" rel="noreferrer">https://ofdgo.aite.me/</a></div>
|
||||||
|
<div class="about-row"><span>桌面软件</span><a href="https://ofdgo.aite.me/releases/" target="_blank" rel="noreferrer">https://ofdgo.aite.me/releases/</a></div>
|
||||||
|
<div class="about-row"><span>项目仓库</span><a href="https://github.com/xiaoqidun/ofdgo" target="_blank" rel="noreferrer">https://github.com/xiaoqidun/ofdgo</a></div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
<dialog id="closePanel" class="form-dialog confirm-dialog">
|
<dialog id="closePanel" class="form-dialog confirm-dialog">
|
||||||
<form method="dialog">
|
<form method="dialog">
|
||||||
<h2 class="form-title">关闭文档</h2>
|
<h2 id="closeTitle" class="form-title">关闭文档</h2>
|
||||||
<p class="confirm-message">文档尚未保存</p>
|
<p class="confirm-message">文档尚未保存</p>
|
||||||
<div class="form-actions"><button class="button" value="cancel" autofocus>取消</button><button class="button" value="discard">放弃</button><button class="button" value="save">保存</button></div>
|
<div class="form-actions"><button class="button" value="cancel" autofocus>取消</button><button class="button" value="discard">放弃</button><button class="button" value="save">保存</button></div>
|
||||||
</form>
|
</form>
|
||||||
@@ -206,8 +223,7 @@
|
|||||||
<div class="form-row"><label for="convertCompression">压缩</label><select id="convertCompression"><option value="0">原始</option><option value="1">无损</option><option value="2">轻压</option><option value="3">均衡</option><option value="4">强压</option></select></div>
|
<div class="form-row"><label for="convertCompression">压缩</label><select id="convertCompression"><option value="0">原始</option><option value="1">无损</option><option value="2">轻压</option><option value="3">均衡</option><option value="4">强压</option></select></div>
|
||||||
<div id="convertFontRow" class="form-row" hidden><label for="convertFontMode">字体</label><select id="convertFontMode"><option value="0">保持</option><option value="1">内嵌</option><option value="2">外部</option></select></div>
|
<div id="convertFontRow" class="form-row" hidden><label for="convertFontMode">字体</label><select id="convertFontMode"><option value="0">保持</option><option value="1">内嵌</option><option value="2">外部</option></select></div>
|
||||||
<div id="convertDPIRow" class="form-row" hidden><label for="convertDPI">精度</label><div class="form-select"><select id="convertDPI"><option value="96">96 DPI</option><option value="150">150 DPI</option><option value="300" selected>300 DPI</option><option value="600">600 DPI</option></select><span id="convertDPIValue">300</span></div></div>
|
<div id="convertDPIRow" class="form-row" hidden><label for="convertDPI">精度</label><div class="form-select"><select id="convertDPI"><option value="96">96 DPI</option><option value="150">150 DPI</option><option value="300" selected>300 DPI</option><option value="600">600 DPI</option></select><span id="convertDPIValue">300</span></div></div>
|
||||||
<div class="form-row"><label for="convertDestination">保存</label><select id="convertDestination"><option value="directory">目录</option><option value="archive">打包</option></select></div>
|
<div class="form-row"><label for="convertDestination">输出</label><select id="convertDestination"><option value="directory">目录</option><option value="archive">打包</option></select></div>
|
||||||
<div class="form-row"><label for="convertParallel">并行</label><input id="convertParallel" type="number" min="1" step="1" placeholder="自动"></div>
|
|
||||||
</div>
|
</div>
|
||||||
<button id="convertClose" class="button" type="button">关闭</button><button id="convertCancel" class="button" type="button" hidden>取消</button><button id="convertStart" class="button" type="submit" disabled>转换</button>
|
<button id="convertClose" class="button" type="button">关闭</button><button id="convertCancel" class="button" type="button" hidden>取消</button><button id="convertStart" class="button" type="submit" disabled>转换</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -215,6 +231,7 @@
|
|||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="batchPagesPanel" class="form-dialog">
|
<dialog id="batchPagesPanel" class="form-dialog">
|
||||||
<form id="batchPagesForm">
|
<form id="batchPagesForm">
|
||||||
|
<h2 id="batchPagesTitle" class="form-title">复制页面</h2>
|
||||||
<div class="form-row"><label for="batchPageAction">操作</label><select id="batchPageAction"><option value="copy">复制</option><option value="move">移动</option><option value="delete">删除</option><option value="save">另存</option></select></div>
|
<div class="form-row"><label for="batchPageAction">操作</label><select id="batchPageAction"><option value="copy">复制</option><option value="move">移动</option><option value="delete">删除</option><option value="save">另存</option></select></div>
|
||||||
<div class="form-row"><label for="batchPageRange">页码</label><input id="batchPageRange" type="text" required autocomplete="off" spellcheck="false" autofocus></div>
|
<div class="form-row"><label for="batchPageRange">页码</label><input id="batchPageRange" type="text" required autocomplete="off" spellcheck="false" autofocus></div>
|
||||||
<div id="batchPagePositionRow" class="form-row" hidden><label for="batchPagePosition">位置</label><select id="batchPagePosition"><option value="before">页前</option><option value="after">页后</option><option value="first">开头</option><option value="last">末尾</option></select></div>
|
<div id="batchPagePositionRow" class="form-row" hidden><label for="batchPagePosition">位置</label><select id="batchPagePosition"><option value="before">页前</option><option value="after">页后</option><option value="first">开头</option><option value="last">末尾</option></select></div>
|
||||||
@@ -223,6 +240,7 @@
|
|||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="objectStylePanel" class="form-dialog">
|
<dialog id="objectStylePanel" class="form-dialog">
|
||||||
<form id="objectStyleForm">
|
<form id="objectStyleForm">
|
||||||
|
<h2 id="objectStyleTitle" class="form-title">对象样式</h2>
|
||||||
<div class="form-row"><span>组合</span><div class="form-format"><button id="groupObjectsButton" class="button" type="button">组合</button><button id="ungroupObjectButton" class="button" type="button">解组</button></div></div>
|
<div class="form-row"><span>组合</span><div class="form-format"><button id="groupObjectsButton" class="button" type="button">组合</button><button id="ungroupObjectButton" class="button" type="button">解组</button></div></div>
|
||||||
<div class="form-row"><span>格式</span><div class="form-format"><button id="copyStyleButton" class="button" type="button">复制</button><button id="pasteStyleButton" class="button" type="button">粘贴</button></div></div>
|
<div class="form-row"><span>格式</span><div class="form-format"><button id="copyStyleButton" class="button" type="button">复制</button><button id="pasteStyleButton" class="button" type="button">粘贴</button></div></div>
|
||||||
<details id="objectLinkFields" hidden>
|
<details id="objectLinkFields" hidden>
|
||||||
@@ -284,6 +302,7 @@
|
|||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="structureDialog" class="form-dialog structure-dialog">
|
<dialog id="structureDialog" class="form-dialog structure-dialog">
|
||||||
<form id="structureForm">
|
<form id="structureForm">
|
||||||
|
<h2 id="structureTitle" class="form-title">结构标引</h2>
|
||||||
<div class="form-row"><label for="structureEntry">标引</label><select id="structureEntry"></select></div>
|
<div class="form-row"><label for="structureEntry">标引</label><select id="structureEntry"></select></div>
|
||||||
<div id="structureNodeRow" class="form-row"><label for="structureNodeSelect">节点</label><select id="structureNodeSelect"></select></div>
|
<div id="structureNodeRow" class="form-row"><label for="structureNodeSelect">节点</label><select id="structureNodeSelect"></select></div>
|
||||||
<div id="structureActionRow" class="form-row"><label for="structureAction">操作</label><select id="structureAction"><option value="update">修改</option><option value="add">新增</option><option value="bind">绑定</option><option value="delete">删除</option></select></div>
|
<div id="structureActionRow" class="form-row"><label for="structureAction">操作</label><select id="structureAction"><option value="update">修改</option><option value="add">新增</option><option value="bind">绑定</option><option value="delete">删除</option></select></div>
|
||||||
@@ -304,6 +323,7 @@
|
|||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="outlinePanel" class="form-dialog">
|
<dialog id="outlinePanel" class="form-dialog">
|
||||||
<form id="outlineForm">
|
<form id="outlineForm">
|
||||||
|
<h2 id="outlinePanelTitle" class="form-title">新增目录</h2>
|
||||||
<div class="form-row"><label for="outlineTitle">标题</label><input id="outlineTitle" type="text" required autofocus></div>
|
<div class="form-row"><label for="outlineTitle">标题</label><input id="outlineTitle" type="text" required autofocus></div>
|
||||||
<div class="form-row"><label for="outlineParent">上级</label><select id="outlineParent"></select></div>
|
<div class="form-row"><label for="outlineParent">上级</label><select id="outlineParent"></select></div>
|
||||||
<div class="form-row"><label for="outlinePage">页码</label><input id="outlinePage" type="number" min="1" step="1" placeholder="无"></div>
|
<div class="form-row"><label for="outlinePage">页码</label><input id="outlinePage" type="number" min="1" step="1" placeholder="无"></div>
|
||||||
@@ -313,6 +333,7 @@
|
|||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="objectBoundsPanel" class="form-dialog">
|
<dialog id="objectBoundsPanel" class="form-dialog">
|
||||||
<form id="objectBoundsForm">
|
<form id="objectBoundsForm">
|
||||||
|
<h2 id="objectBoundsTitle" class="form-title">位置尺寸</h2>
|
||||||
<div class="form-pair">
|
<div class="form-pair">
|
||||||
<div class="form-row"><label for="objectX">横向</label><div class="form-unit"><input id="objectX" type="number" step="any" required autofocus><span>mm</span></div></div>
|
<div class="form-row"><label for="objectX">横向</label><div class="form-unit"><input id="objectX" type="number" step="any" required autofocus><span>mm</span></div></div>
|
||||||
<div class="form-row"><label for="objectY">纵向</label><div class="form-unit"><input id="objectY" type="number" step="any" required><span>mm</span></div></div>
|
<div class="form-row"><label for="objectY">纵向</label><div class="form-unit"><input id="objectY" type="number" step="any" required><span>mm</span></div></div>
|
||||||
@@ -327,6 +348,7 @@
|
|||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="createPanel" class="form-dialog">
|
<dialog id="createPanel" class="form-dialog">
|
||||||
<form id="createForm">
|
<form id="createForm">
|
||||||
|
<h2 id="createTitle" class="form-title">新建文档</h2>
|
||||||
<div id="createModeRow" class="form-row"><label for="createMode">来源</label><select id="createMode"><option value="blank">空白</option><option value="images">图片</option></select></div>
|
<div id="createModeRow" class="form-row"><label for="createMode">来源</label><select id="createMode"><option value="blank">空白</option><option value="images">图片</option></select></div>
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<label for="createName">名称</label>
|
<label for="createName">名称</label>
|
||||||
@@ -355,6 +377,7 @@
|
|||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="importPanel" class="form-dialog">
|
<dialog id="importPanel" class="form-dialog">
|
||||||
<form id="importForm">
|
<form id="importForm">
|
||||||
|
<h2 id="importTitle" class="form-title">插入页面</h2>
|
||||||
<div class="form-row"><label for="importFile">文档</label><input id="importFile" type="file" accept=".ofd" required autofocus></div>
|
<div class="form-row"><label for="importFile">文档</label><input id="importFile" type="file" accept=".ofd" required autofocus></div>
|
||||||
<div class="form-row"><label for="importRange">范围</label><select id="importRange"><option value="all">全部</option><option value="custom">指定</option></select></div>
|
<div class="form-row"><label for="importRange">范围</label><select id="importRange"><option value="all">全部</option><option value="custom">指定</option></select></div>
|
||||||
<div id="importDocuments" class="document-list" hidden></div>
|
<div id="importDocuments" class="document-list" hidden></div>
|
||||||
@@ -366,6 +389,7 @@
|
|||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="paragraphPanel" class="form-dialog">
|
<dialog id="paragraphPanel" class="form-dialog">
|
||||||
<form id="paragraphForm">
|
<form id="paragraphForm">
|
||||||
|
<h2 id="paragraphTitle" class="form-title">段落设置</h2>
|
||||||
<div class="form-row"><label for="firstLineIndent">首行</label><div class="form-unit"><input id="firstLineIndent" type="number" step="any" required autofocus><span>mm</span></div></div>
|
<div class="form-row"><label for="firstLineIndent">首行</label><div class="form-unit"><input id="firstLineIndent" type="number" step="any" required autofocus><span>mm</span></div></div>
|
||||||
<div class="form-pair">
|
<div class="form-pair">
|
||||||
<div class="form-row"><label for="leftIndent">左侧</label><div class="form-unit"><input id="leftIndent" type="number" step="any" required><span>mm</span></div></div>
|
<div class="form-row"><label for="leftIndent">左侧</label><div class="form-unit"><input id="leftIndent" type="number" step="any" required><span>mm</span></div></div>
|
||||||
@@ -377,7 +401,7 @@
|
|||||||
<dialog id="resourcePanel" class="form-dialog resource-dialog">
|
<dialog id="resourcePanel" class="form-dialog resource-dialog">
|
||||||
<form id="resourceForm">
|
<form id="resourceForm">
|
||||||
<h2 id="resourceTitle" class="form-title">资源管理</h2>
|
<h2 id="resourceTitle" class="form-title">资源管理</h2>
|
||||||
<div class="form-row"><label for="resourceKind">类型</label><select id="resourceKind"><option value="Font">字体</option><option value="Image">图片</option><option value="Audio">音频</option><option value="Video">视频</option><option value="Attachment">附件</option><option value="ColorSpace">色彩</option><option value="DrawParam">样式</option></select></div>
|
<div id="resourceTabs" class="panel-tabs"></div>
|
||||||
<div class="resource-list-container">
|
<div class="resource-list-container">
|
||||||
<div class="resource-heading"><span>名称</span><span>大小</span><span>引用</span></div>
|
<div class="resource-heading"><span>名称</span><span>大小</span><span>引用</span></div>
|
||||||
<div class="resource-list-body">
|
<div class="resource-list-body">
|
||||||
@@ -421,13 +445,38 @@
|
|||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
<dialog id="appearancePanel" class="form-dialog appearance-dialog">
|
||||||
|
<form method="dialog">
|
||||||
|
<div class="appearance-heading"><h2 id="appearanceTitle" class="form-title">系统设置</h2><button class="appearance-close" type="submit" title="关闭"><span class="close-icon"></span></button></div>
|
||||||
|
<div class="appearance-body">
|
||||||
|
<nav class="appearance-navigation">
|
||||||
|
<button type="button" data-appearance-category="theme" data-selected="true" autofocus>外观主题</button>
|
||||||
|
<button id="associationCategory" type="button" data-appearance-category="association" data-selected="false" hidden>文件关联</button>
|
||||||
|
</nav>
|
||||||
|
<div class="appearance-content">
|
||||||
|
<section data-appearance-page="theme">
|
||||||
|
<div class="appearance-themes">
|
||||||
|
<button type="button" data-theme-choice="system"><span class="theme-system-icon"></span><span>系统</span></button>
|
||||||
|
<button type="button" data-theme-choice="light"><span class="theme-light-icon"></span><span>浅色</span></button>
|
||||||
|
<button type="button" data-theme-choice="dark"><span class="theme-dark-icon"></span><span>深色</span></button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section id="associationSection" data-appearance-page="association" hidden>
|
||||||
|
<div class="association-row" data-scope="user"><span>当前用户</span><span class="association-state"></span><div class="association-actions"><button class="small-button" type="button" data-action="register">注册</button><button class="small-button" type="button" data-action="remove">撤销</button></div></div>
|
||||||
|
<div class="association-row" data-scope="machine"><span>所有用户</span><span class="association-state"></span><div class="association-actions"><button class="small-button" type="button" data-action="register">注册</button><button class="small-button" type="button" data-action="remove">撤销</button></div></div>
|
||||||
|
<div id="associationMessage" class="form-status" hidden></div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
<dialog id="settingsPanel" class="form-dialog settings-dialog">
|
<dialog id="settingsPanel" class="form-dialog settings-dialog">
|
||||||
<form id="settingsForm">
|
<form id="settingsForm">
|
||||||
<header class="settings-header">
|
<header class="settings-header">
|
||||||
<h2 id="settingsTitle" class="form-title">文档配置</h2>
|
<h2 id="settingsTitle" class="form-title">文档配置</h2>
|
||||||
<span id="settingsLocation" class="settings-location"></span>
|
<span id="settingsLocation" class="settings-location"></span>
|
||||||
</header>
|
</header>
|
||||||
<label class="form-row"><span>类型</span><select id="settingsKind"><option value="bookmarks">书签</option><option value="actions">动作</option><option value="templates">模板</option><option value="layers">图层</option><option value="extensions">扩展</option><option value="ColorSpace" hidden>色彩</option><option value="DrawParam" hidden>样式</option></select></label>
|
<div id="settingsTabs" class="panel-tabs"></div>
|
||||||
<div id="settingsBody" class="settings-body">
|
<div id="settingsBody" class="settings-body">
|
||||||
<div id="settingsContext"></div>
|
<div id="settingsContext"></div>
|
||||||
<div id="settingsContent"></div>
|
<div id="settingsContent"></div>
|
||||||
@@ -458,15 +507,28 @@
|
|||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="infoPanel" class="form-dialog">
|
<dialog id="infoPanel" class="form-dialog">
|
||||||
<form id="infoForm">
|
<form id="infoForm">
|
||||||
<label class="form-row"><span>标题</span><input id="infoTitle" type="text" autofocus></label>
|
<h2 id="infoPanelTitle" class="form-title">文档信息</h2>
|
||||||
<label class="form-row"><span>主题</span><input id="infoSubject" type="text"></label>
|
<label class="form-row"><span>文档标识</span><input id="infoDocId" type="text"></label>
|
||||||
<label class="form-row"><span>作者</span><input id="infoAuthor" type="text"></label>
|
<label class="form-row"><span>标题</span><textarea id="infoTitle" rows="1" autofocus></textarea></label>
|
||||||
<details class="info-custom"><summary>扩展</summary><div id="infoCustomRows"></div><button id="infoCustomAdd" class="icon-button" type="button" title="添加字段">+</button></details>
|
<label class="form-row"><span>作者</span><textarea id="infoAuthor" rows="1"></textarea></label>
|
||||||
|
<label class="form-row"><span>主题</span><textarea id="infoSubject" rows="1"></textarea></label>
|
||||||
|
<label class="form-row"><span>摘要</span><textarea id="infoAbstract" rows="2"></textarea></label>
|
||||||
|
<details><summary><span>文档属性</span></summary>
|
||||||
|
<label class="form-row"><span>创建日期</span><input id="infoCreationDate" type="text"></label>
|
||||||
|
<label class="form-row"><span>修改日期</span><input id="infoModDate" type="text"></label>
|
||||||
|
<label class="form-row"><span>文档用途</span><input id="infoDocUsage" type="text"></label>
|
||||||
|
<label class="form-row"><span>封面路径</span><input id="infoCover" type="text"></label>
|
||||||
|
<details><summary><span>关键词</span></summary><div id="infoKeywordRows" class="info-rows"></div><button id="infoKeywordAdd" class="icon-button" type="button" title="添加词条">+</button></details>
|
||||||
|
<label class="form-row"><span>制作软件</span><input id="infoCreator" type="text"></label>
|
||||||
|
<label class="form-row"><span>软件版本</span><input id="infoCreatorVersion" type="text"></label>
|
||||||
|
</details>
|
||||||
|
<details><summary><span>扩展属性</span></summary><div id="infoCustomRows" class="info-rows"></div><button id="infoCustomAdd" class="icon-button" type="button" title="添加属性">+</button></details>
|
||||||
<div class="form-actions"><div id="infoStatus" class="form-status"></div><button id="infoCancel" class="button" type="button">取消</button><button class="button" type="submit">确定</button></div>
|
<div class="form-actions"><div id="infoStatus" class="form-status"></div><button id="infoCancel" class="button" type="button">取消</button><button class="button" type="submit">确定</button></div>
|
||||||
</form>
|
</form>
|
||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="annotationCreate" class="form-dialog">
|
<dialog id="annotationCreate" class="form-dialog">
|
||||||
<form id="annotationCreateForm">
|
<form id="annotationCreateForm">
|
||||||
|
<h2 id="annotationCreateTitle" class="form-title">添加批注</h2>
|
||||||
<label class="form-row" data-annotation="watermark"><span>类型</span><select id="annotationContent"><option value="text">文字</option><option value="image">图片</option></select></label>
|
<label class="form-row" data-annotation="watermark"><span>类型</span><select id="annotationContent"><option value="text">文字</option><option value="image">图片</option></select></label>
|
||||||
<label class="form-row" data-annotation="replace"><span>原文</span><select id="annotationOld"></select></label>
|
<label class="form-row" data-annotation="replace"><span>原文</span><select id="annotationOld"></select></label>
|
||||||
<label class="form-row" data-annotation="replace"><span>字体</span><select id="annotationFont"><option value="keep">原有</option><option value="current">当前</option></select></label>
|
<label class="form-row" data-annotation="replace"><span>字体</span><select id="annotationFont"><option value="keep">原有</option><option value="current">当前</option></select></label>
|
||||||
@@ -496,10 +558,15 @@
|
|||||||
</form>
|
</form>
|
||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="objectPicker" class="form-dialog">
|
<dialog id="objectPicker" class="form-dialog">
|
||||||
<form method="dialog"><div id="objectPickerList" class="object-picker-list"></div><div class="form-actions"><button class="button" type="submit">关闭</button></div></form>
|
<form method="dialog">
|
||||||
|
<h2 id="objectPickerTitle" class="form-title">选择对象</h2>
|
||||||
|
<div id="objectPickerList" class="object-picker-list"></div>
|
||||||
|
<div class="form-actions"><button class="button" type="submit">关闭</button></div>
|
||||||
|
</form>
|
||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="annotationNote" class="form-dialog">
|
<dialog id="annotationNote" class="form-dialog">
|
||||||
<form id="annotationForm" method="dialog">
|
<form id="annotationForm" method="dialog">
|
||||||
|
<h2 id="annotationNoteTitle" class="form-title">注解详情</h2>
|
||||||
<div id="annotationDetail" class="annotation-detail"></div>
|
<div id="annotationDetail" class="annotation-detail"></div>
|
||||||
<div id="annotationFields" hidden>
|
<div id="annotationFields" hidden>
|
||||||
<div class="form-row"><label for="annotationRemark">说明</label><textarea id="annotationRemark" rows="4"></textarea></div>
|
<div class="form-row"><label for="annotationRemark">说明</label><textarea id="annotationRemark" rows="4"></textarea></div>
|
||||||
@@ -510,6 +577,7 @@
|
|||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="pagePanel" class="form-dialog">
|
<dialog id="pagePanel" class="form-dialog">
|
||||||
<form id="pageForm">
|
<form id="pageForm">
|
||||||
|
<h2 id="pageTitle" class="form-title">页面设置</h2>
|
||||||
<div id="pageRangeRow" class="form-row" hidden><span>范围</span><output id="pageRange"></output></div>
|
<div id="pageRangeRow" class="form-row" hidden><span>范围</span><output id="pageRange"></output></div>
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<span id="pageDirectionLabel">方向</span>
|
<span id="pageDirectionLabel">方向</span>
|
||||||
@@ -547,6 +615,7 @@
|
|||||||
</dialog>
|
</dialog>
|
||||||
<dialog id="insertPanel" class="form-dialog">
|
<dialog id="insertPanel" class="form-dialog">
|
||||||
<form id="insertForm">
|
<form id="insertForm">
|
||||||
|
<h2 id="insertTitle" class="form-title">添加图片</h2>
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<label for="insertImage">图片</label>
|
<label for="insertImage">图片</label>
|
||||||
<input id="insertImage" type="file" accept=".png,.jpg,.jpeg,.bmp,.tif,.tiff,image/png,image/jpeg,image/bmp,image/tiff" required autofocus>
|
<input id="insertImage" type="file" accept=".png,.jpg,.jpeg,.bmp,.tif,.tiff,image/png,image/jpeg,image/bmp,image/tiff" required autofocus>
|
||||||
@@ -639,6 +708,43 @@
|
|||||||
<div class="form-actions"><div id="encryptionStatus" class="form-status"></div><button id="encryptionCancel" class="button" type="button">取消</button><button id="encryptionSubmit" class="button" type="submit">确定</button></div>
|
<div class="form-actions"><div id="encryptionStatus" class="form-status"></div><button id="encryptionCancel" class="button" type="button">取消</button><button id="encryptionSubmit" class="button" type="submit">确定</button></div>
|
||||||
</form>
|
</form>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
<dialog id="printPanel" class="form-dialog print-dialog">
|
||||||
|
<form id="printForm">
|
||||||
|
<h2 id="printTitle" class="form-title">文档打印</h2>
|
||||||
|
<div class="print-content">
|
||||||
|
<div class="print-settings-panel">
|
||||||
|
<fieldset id="printSettings" class="print-settings">
|
||||||
|
<div class="form-row"><label for="printPrinter">打印设备</label><div class="print-field"><select id="printPrinter"><option value="browser">系统打印</option><option value="pdf">另存输出</option></select><button id="printProperties" class="small-button" type="button" hidden>设备属性</button></div></div>
|
||||||
|
<div class="form-row" data-print-row="device" hidden><label for="printCopies">打印份数</label><div class="print-field"><input id="printCopies" type="number" min="1" max="999" value="1"><label class="print-check"><input id="printCollation" type="checkbox" checked>逐份打印</label></div></div>
|
||||||
|
<div class="form-row"><label for="printScope">打印范围</label><select id="printScope"><option value="all">全部页面</option><option value="current">当前页面</option><option value="selected">所选页面</option><option value="range">指定页码</option></select></div>
|
||||||
|
<div class="form-row" data-print-row="range" hidden><label for="printRange">指定页码</label><input id="printRange" type="text" placeholder="1-3,5" autocomplete="off" spellcheck="false"></div>
|
||||||
|
<div class="form-row"><label for="printParity">奇偶筛选</label><div class="print-field"><select id="printParity"><option value="all">全部页面</option><option value="odd">奇数页面</option><option value="even">偶数页面</option></select><label class="print-check"><input id="printReverse" type="checkbox">逆序打印</label></div></div>
|
||||||
|
<div class="form-row"><label for="printMode">页面排版</label><select id="printMode"><option value="single">单页打印</option><option value="multiple">多页合印</option><option value="booklet">小册打印</option><option value="poster">海报拼接</option></select></div>
|
||||||
|
<div class="form-row"><label for="printPaper">纸张大小</label><select id="printPaper"><option value="210,297">A4</option><option value="297,420">A3</option><option value="148,210">A5</option><option value="176,250">B5</option><option value="215.9,279.4">Letter</option><option value="215.9,355.6">Legal</option><option value="source">原页尺寸</option><option value="custom">自定尺寸</option></select></div>
|
||||||
|
<div class="form-row" data-print-row="paper" hidden><label for="printWidth">纸张尺寸</label><div class="print-field"><input id="printWidth" type="number" value="210" min="1" max="5000" step="any" title="纸张宽度"><span>×</span><input id="printHeight" type="number" value="297" min="1" max="5000" step="any" title="纸张高度"><span>mm</span></div></div>
|
||||||
|
<div class="form-row"><label for="printOrientation">纸张方向</label><select id="printOrientation"><option value="portrait">纵向纸张</option><option value="landscape">横向纸张</option></select></div>
|
||||||
|
<div class="form-row"><label for="printScaling">页面缩放</label><select id="printScaling"><option value="shrink">缩小大页</option><option value="fit">适合纸张</option><option value="actual">实际大小</option><option value="custom">自定比例</option></select></div>
|
||||||
|
<div class="form-row" data-print-row="scale" hidden><label for="printScale">缩放比例</label><div class="print-field"><input id="printScale" type="number" min="1" max="10000" value="100" step="1"><span>%</span></div></div>
|
||||||
|
<div class="form-row"><span>额外边距</span><div class="print-field print-margins"><input id="printMarginTop" type="number" min="0" value="0" step="0.1" title="上边距"><input id="printMarginRight" type="number" min="0" value="0" step="0.1" title="右边距"><input id="printMarginBottom" type="number" min="0" value="0" step="0.1" title="下边距"><input id="printMarginLeft" type="number" min="0" value="0" step="0.1" title="左边距"><span>mm</span></div></div>
|
||||||
|
<div class="form-row" data-print-row="multiple" hidden><label for="printGrid">每面页数</label><select id="printGrid"><option value="1,2">2 页</option><option value="2,2">4 页</option><option value="2,3">6 页</option><option value="3,3">9 页</option><option value="4,4">16 页</option></select></div>
|
||||||
|
<div class="form-row" data-print-row="multiple" hidden><label for="printPageOrder">排列顺序</label><select id="printPageOrder"><option value="horizontal">横向顺序</option><option value="horizontalReverse">横向逆序</option><option value="vertical">纵向顺序</option><option value="verticalReverse">纵向逆序</option></select></div>
|
||||||
|
<div class="form-row" data-print-row="gap" hidden><label for="printGap">页面间距</label><div class="print-field"><input id="printGap" type="number" min="0" value="4" step="0.1"><span>mm</span></div></div>
|
||||||
|
<div class="form-row" data-print-row="booklet" hidden><label for="printBinding">装订方向</label><select id="printBinding"><option value="left">左侧装订</option><option value="right">右侧装订</option></select></div>
|
||||||
|
<div class="form-row" data-print-row="booklet" hidden><label for="printBookletSheets">每册纸数</label><input id="printBookletSheets" type="number" min="0" max="2500" placeholder="不分册" title="0表示不分册"></div>
|
||||||
|
<div class="form-row" data-print-row="booklet" hidden><label for="printSheetFrom">纸张范围</label><div class="print-field"><input id="printSheetFrom" type="number" min="1" placeholder="起始" title="起始纸张编号"><span>至</span><input id="printSheetTo" type="number" min="1" placeholder="结束" title="结束纸张编号"></div></div>
|
||||||
|
<div class="form-row" data-print-row="poster" hidden><label for="printOverlap">重叠宽度</label><div class="print-field"><input id="printOverlap" type="number" min="0" value="5" step="0.1"><span>mm</span></div></div>
|
||||||
|
<div class="form-row"><label for="printDuplex">双面方式</label><select id="printDuplex"><option value="simplex">单面打印</option><option value="longEdge">自动长边</option><option value="shortEdge">自动短边</option><option value="manualLongEdge">手动长边</option><option value="manualShortEdge">手动短边</option></select></div>
|
||||||
|
<div class="form-row" data-print-row="sides" hidden><label for="printSides">打印纸面</label><select id="printSides"><option value="all">正反两面</option><option value="front">只印正面</option><option value="back">只印背面</option></select></div>
|
||||||
|
<div class="form-row" data-print-row="manual" hidden><span>背面处理</span><div class="print-field"><label class="print-check"><input id="printBackReverse" type="checkbox">倒序送纸</label><label class="print-check" title="背面旋转180°"><input id="printBackRotate" type="checkbox">背面旋转</label></div></div>
|
||||||
|
<div class="form-row"><label for="printContents">打印内容</label><select id="printContents"><option value="documentAndAnnotations">文档注解</option><option value="document">文档表单</option><option value="annotations">仅限注解</option><option value="forms">仅限表单</option></select></div>
|
||||||
|
<div class="print-options"><label><input id="printRotate" type="checkbox" checked>自动旋转</label><label><input id="printGrayscale" type="checkbox">灰度打印</label><label><input id="printBorders" type="checkbox">页面边框</label><label><input id="printCropMarks" type="checkbox">裁切标记</label><label><input id="printRaster" type="checkbox">图像打印</label><div class="form-select"><select id="printDPI" title="图像精度"><option value="96">96 DPI</option><option value="150">150 DPI</option><option value="300" selected>300 DPI</option><option value="600">600 DPI</option></select><span id="printDPIValue">300</span></div><label data-print-row="poster" title="仅拼接超出纸面的页面" hidden><input id="printTileOnlyLarge" type="checkbox" checked>仅拼大页</label><label data-print-row="poster" hidden><input id="printLabels" type="checkbox" checked>拼接标签</label></div>
|
||||||
|
</fieldset>
|
||||||
|
<div class="form-actions"><button id="printCancel" class="button" type="button">关闭</button><button id="printSubmit" class="button" type="submit" disabled>打印</button></div>
|
||||||
|
</div>
|
||||||
|
<div class="print-preview"><div class="print-preview-stage"><div id="printPreview" class="print-preview-page"></div><div id="printProgress" class="progress-panel print-progress"><div id="printSpinner" class="progress-spinner" hidden></div><div id="printStatus" class="progress-label"></div><div id="printProgressTrack" class="progress-track" hidden><div id="printProgressBar" class="progress-bar"></div></div></div></div><div class="print-preview-tools"><button id="printPrevious" class="icon-button arrow-prev" type="button" title="上一页"></button><label id="printPageControl" class="page-control"><input id="printPreviewNumber" type="number" min="1" value="1" title="预览纸面"><span>/</span><span id="printPageCount">0</span></label><button id="printNext" class="icon-button arrow-next" type="button" title="下一页"></button></div></div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
<dialog id="exportPanel" class="form-dialog">
|
<dialog id="exportPanel" class="form-dialog">
|
||||||
<form id="exportForm">
|
<form id="exportForm">
|
||||||
<h2 id="exportTitle" class="form-title">导出文档</h2>
|
<h2 id="exportTitle" class="form-title">导出文档</h2>
|
||||||
@@ -790,7 +896,7 @@
|
|||||||
<section id="signaturePanel" class="signature-panel" hidden>
|
<section id="signaturePanel" class="signature-panel" hidden>
|
||||||
<div class="panel-row">
|
<div class="panel-row">
|
||||||
<div id="signaturePanelTitle" class="panel-title compact">签名</div>
|
<div id="signaturePanelTitle" class="panel-title compact">签名</div>
|
||||||
<span id="signatureSummary" class="count-pill">0</span>
|
<div class="panel-actions"><span id="signatureSummary" class="count-pill">0</span><button id="signatureClear" class="small-button" type="button" hidden>清空</button></div>
|
||||||
</div>
|
</div>
|
||||||
<div id="signatureList" class="signature-list"></div>
|
<div id="signatureList" class="signature-list"></div>
|
||||||
</section>
|
</section>
|
||||||
@@ -818,14 +924,13 @@
|
|||||||
</main>
|
</main>
|
||||||
|
|
||||||
<footer class="app-footer app-bar">
|
<footer class="app-footer app-bar">
|
||||||
<a class="footer-brand" href="https://github.com/xiaoqidun/ofdgo" target="_blank" rel="noreferrer">OFDGo</a>
|
<div class="footer-side"><a class="footer-action" href="https://aite.me/" target="_blank" rel="noreferrer">官方网站</a></div>
|
||||||
<div id="statusText" class="status-text">正在准备引擎</div>
|
<div id="statusText" class="status-text">正在准备引擎</div>
|
||||||
<nav class="footer-links">
|
<div class="footer-side footer-side-right"><button id="aboutButton" class="footer-action" type="button">软件信息</button></div>
|
||||||
<a href="https://aite.me/" target="_blank" rel="noreferrer">官方网站</a>
|
|
||||||
</nav>
|
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div id="ofdgoPrintDocument">请先在OFDGo中打开打印预览,准备完整文档后打印。</div>
|
||||||
<script type="module" src="./ofdgo.js"></script>
|
<script type="module" src="./ofdgo.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
+1082
-308
File diff suppressed because it is too large.
Load diff
+3632
-2752
File diff suppressed because it is too large.
Load diff
+586
-170
File diff suppressed because it is too large.
Load diff
+105
-36
@@ -1,39 +1,59 @@
|
|||||||
|
import { bindDropdownPointer, positionDropdown } from "./ofdgo_util.js";
|
||||||
|
|
||||||
const DATABASE = "ofdgo";
|
const DATABASE = "ofdgo";
|
||||||
|
|
||||||
export class FontPicker {
|
export class FontPicker {
|
||||||
constructor(input, toggle, list, onChange, onOpen) {
|
constructor(input, toggle, list, onChange, onOpen, groupFonts) {
|
||||||
Object.assign(this, { input, toggle, list, onChange, onOpen, fonts: [], value: "", active: -1, open: false });
|
Object.assign(this, { input, toggle, list, onChange, onOpen, groupFonts, fonts: [], groups: [], value: "", active: -1, open: false });
|
||||||
input.addEventListener("input", () => this.show(input.value));
|
input.addEventListener("input", () => this.show(input.value));
|
||||||
input.addEventListener("focus", () => input.select());
|
input.addEventListener("focus", () => input.select());
|
||||||
input.addEventListener("click", () => { if (!this.open) this.show(); });
|
input.addEventListener("pointerdown", event => { if (event.button === 0 && !this.open) event.preventDefault(); });
|
||||||
|
input.addEventListener("click", () => { if (!this.open) { input.focus(); input.select(); this.show(); } });
|
||||||
input.addEventListener("keydown", event => this.keyDown(event));
|
input.addEventListener("keydown", event => this.keyDown(event));
|
||||||
input.addEventListener("blur", () => { this.commitExact(); this.close(); });
|
input.addEventListener("blur", () => { this.commitExact(); this.close(); });
|
||||||
toggle.addEventListener("pointerdown", event => event.preventDefault());
|
toggle.addEventListener("pointerdown", event => event.preventDefault());
|
||||||
toggle.addEventListener("click", () => {
|
toggle.addEventListener("click", () => {
|
||||||
if (this.open) this.close();
|
if (this.open) this.close();
|
||||||
else { input.focus(); this.show(); }
|
else { input.focus(); input.select(); this.show(); }
|
||||||
});
|
|
||||||
list.addEventListener("pointerdown", event => {
|
|
||||||
if (event.target.closest(".font-option")) event.preventDefault();
|
|
||||||
});
|
|
||||||
list.addEventListener("click", event => {
|
|
||||||
const option = event.target.closest(".font-option");
|
|
||||||
if (option) this.choose(Number(option.dataset.index));
|
|
||||||
});
|
});
|
||||||
|
bindDropdownPointer(list, index => this.choose(index));
|
||||||
window.addEventListener("resize", () => this.close());
|
window.addEventListener("resize", () => this.close());
|
||||||
}
|
}
|
||||||
|
|
||||||
setFonts(fonts, selected) {
|
setFonts(fonts, selected, preserve = false) {
|
||||||
this.close();
|
const open = preserve && this.open;
|
||||||
|
if (!open) this.close();
|
||||||
this.fonts = fonts;
|
this.fonts = fonts;
|
||||||
|
this.groups = fonts.map((_, index) => [index]);
|
||||||
this.names = new Map();
|
this.names = new Map();
|
||||||
for (const font of fonts) {
|
for (const font of fonts) {
|
||||||
const name = (font.fullName || font.name).normalize("NFKC").toLocaleLowerCase();
|
const name = (font.menuFamily || font.fullName || font.name).normalize("NFKC").toLocaleLowerCase();
|
||||||
this.names.set(name, (this.names.get(name) || 0) + 1);
|
this.names.set(name, (this.names.get(name) || 0) + 1);
|
||||||
}
|
}
|
||||||
const key = font => font?.id || font?.postscriptName;
|
const key = font => font?.richKey || font?.id || font?.postscriptName;
|
||||||
this.value = !fonts.length ? "" : selected === null ? "-1" : String(Math.max(0, fonts.findIndex(font => key(font) === key(selected))));
|
this.value = !fonts.length ? "" : selected === null ? "-1" : String(Math.max(0, fonts.findIndex(font => key(font) === key(selected))));
|
||||||
this.restore();
|
if (open) {
|
||||||
|
const active = this.matches[this.active]?.font;
|
||||||
|
this.show(this.query, false);
|
||||||
|
const index = active ? this.matches.findIndex(({ font }) => !font.disabled && key(font) === key(active)) : -1;
|
||||||
|
if (index >= 0) this.activate(index);
|
||||||
|
} else this.restore();
|
||||||
|
if (this.groupFonts) this.grouping = this.groupFonts(fonts).then(groups => {
|
||||||
|
if (this.fonts !== fonts) return;
|
||||||
|
this.groups = groups;
|
||||||
|
this.names.clear();
|
||||||
|
for (const group of groups) {
|
||||||
|
const font = fonts[group[0]], name = (font.menuFamily || font.fullName || font.name).normalize("NFKC").toLocaleLowerCase();
|
||||||
|
this.names.set(name, (this.names.get(name) || 0) + 1);
|
||||||
|
}
|
||||||
|
if (this.open) {
|
||||||
|
const active = this.matches[this.active]?.index;
|
||||||
|
this.show(this.query, false);
|
||||||
|
const index = this.matches.findIndex(({ group, font }) => group.includes(active) && !font.disabled);
|
||||||
|
if (index >= 0) this.activate(index);
|
||||||
|
}
|
||||||
|
else this.restore();
|
||||||
|
}).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
setDisabled(disabled) {
|
setDisabled(disabled) {
|
||||||
@@ -43,23 +63,34 @@ export class FontPicker {
|
|||||||
|
|
||||||
restore() {
|
restore() {
|
||||||
const font = this.fonts[Number(this.value)];
|
const font = this.fonts[Number(this.value)];
|
||||||
this.input.value = font?.fullName || font?.name || "";
|
const value = font?.menuFamily || font?.fullName || font?.name || "";
|
||||||
|
if (this.input.value !== value) {
|
||||||
|
this.input.value = value;
|
||||||
|
if (document.activeElement === this.input) this.input.select();
|
||||||
|
}
|
||||||
this.input.scrollLeft = 0;
|
this.input.scrollLeft = 0;
|
||||||
this.input.title = font ? [this.input.value, this.sourceLabel(font)].filter(Boolean).join(" · ") : "";
|
this.input.title = font ? [this.input.value, this.sourceLabel(font)].filter(Boolean).join(" · ") : "";
|
||||||
}
|
}
|
||||||
|
|
||||||
sourceLabel(font) {
|
sourceLabel(font) {
|
||||||
const name = (font.fullName || font.name).normalize("NFKC").toLocaleLowerCase();
|
const name = (font.menuFamily || font.fullName || font.name).normalize("NFKC").toLocaleLowerCase();
|
||||||
if (this.names.get(name) < 2) return "";
|
if (this.names.get(name) < 2) return "";
|
||||||
return font.embedded ? "内嵌" : font.file || ["stored", "upload"].includes(font.source) ? "上传" : "系统";
|
return font.embedded ? "内嵌" : font.file || ["stored", "upload"].includes(font.source) ? "上传" : "系统";
|
||||||
}
|
}
|
||||||
|
|
||||||
show(query = "", load = true) {
|
show(query = "", load = true) {
|
||||||
if (this.input.disabled) return;
|
if (this.input.disabled) return;
|
||||||
|
this.query = query;
|
||||||
const normalize = value => value.normalize("NFKC").toLocaleLowerCase().replace(/\s+/g, " ").trim();
|
const normalize = value => value.normalize("NFKC").toLocaleLowerCase().replace(/\s+/g, " ").trim();
|
||||||
const terms = normalize(query).split(" ").filter(Boolean);
|
const terms = normalize(query).split(" ").filter(Boolean);
|
||||||
this.matches = this.fonts.map((font, index) => ({ font, index })).filter(({ font }) => {
|
this.matches = this.groups.map(group => {
|
||||||
const name = normalize([font.fullName, font.name, font.family, font.style, font.postscriptName, ...(font.names || [])].filter(Boolean).join(" "));
|
const index = group.find(index => !this.fonts[index].bold && !this.fonts[index].italic && !this.fonts[index].disabled) ?? group[0];
|
||||||
|
return { font: this.fonts[index], index, group };
|
||||||
|
}).filter(({ group }) => {
|
||||||
|
const name = normalize(group.flatMap(index => {
|
||||||
|
const font = this.fonts[index];
|
||||||
|
return [font.menuFamily, font.menuStyle, font.fullName, font.name, font.family, font.style, font.postscriptName, ...(font.names || [])];
|
||||||
|
}).filter(Boolean).join(" "));
|
||||||
return terms.every(term => name.includes(term));
|
return terms.every(term => name.includes(term));
|
||||||
});
|
});
|
||||||
this.list.replaceChildren();
|
this.list.replaceChildren();
|
||||||
@@ -70,7 +101,7 @@ export class FontPicker {
|
|||||||
option.dataset.index = String(index);
|
option.dataset.index = String(index);
|
||||||
option.setAttribute("data-disabled", String(Boolean(font.disabled)));
|
option.setAttribute("data-disabled", String(Boolean(font.disabled)));
|
||||||
const name = document.createElement("span");
|
const name = document.createElement("span");
|
||||||
name.textContent = font.fullName || font.name;
|
name.textContent = font.menuFamily || font.fullName || font.name;
|
||||||
option.append(name);
|
option.append(name);
|
||||||
const source = this.sourceLabel(font);
|
const source = this.sourceLabel(font);
|
||||||
if (source) {
|
if (source) {
|
||||||
@@ -91,18 +122,14 @@ export class FontPicker {
|
|||||||
if (!this.open) this.list.showPopover();
|
if (!this.open) this.list.showPopover();
|
||||||
this.open = true;
|
this.open = true;
|
||||||
this.position();
|
this.position();
|
||||||
const selected = this.matches.findIndex(({ font, index }) => !font.disabled && String(index) === this.value);
|
const selected = this.matches.findIndex(({ font, group }) => !font.disabled && group.includes(Number(this.value)));
|
||||||
this.activate(selected < 0 ? this.matches.findIndex(({ font }) => !font.disabled) : selected);
|
this.activate(selected < 0 ? this.matches.findIndex(({ font }) => !font.disabled) : selected);
|
||||||
if (load) this.onOpen?.();
|
if (load) this.onOpen?.();
|
||||||
}
|
}
|
||||||
|
|
||||||
position() {
|
position() {
|
||||||
if (!this.open) return;
|
if (!this.open) return;
|
||||||
const rect = this.input.parentElement.getBoundingClientRect();
|
if (!positionDropdown(this.list, this.input.parentElement)) this.close();
|
||||||
if (rect.right <= 0 || rect.left >= window.innerWidth) { this.close(); return; }
|
|
||||||
const width = Math.min(rect.width, window.innerWidth - 16);
|
|
||||||
Object.assign(this.list.style, { left: `${Math.max(8, Math.min(rect.left, window.innerWidth - width - 8))}px`,
|
|
||||||
top: `${rect.bottom + 4}px`, width: `${width}px`, maxHeight: `${Math.max(40, Math.min(280, window.innerHeight - rect.bottom - 12))}px` });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
activate(index) {
|
activate(index) {
|
||||||
@@ -119,16 +146,27 @@ export class FontPicker {
|
|||||||
const changed = this.value !== String(index);
|
const changed = this.value !== String(index);
|
||||||
this.value = String(index);
|
this.value = String(index);
|
||||||
this.close();
|
this.close();
|
||||||
if (changed) return this.onChange();
|
if (changed) {
|
||||||
|
const task = this.changing = Promise.resolve(this.onChange());
|
||||||
|
return task.finally(() => { if (this.changing === task) this.changing = null; });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
commitExact() {
|
commitExact() {
|
||||||
const value = this.input.value.trim().toLocaleLowerCase();
|
const value = this.input.value.trim().toLocaleLowerCase();
|
||||||
const matches = font => font && !font.disabled
|
const matches = font => font && !font.disabled
|
||||||
&& [font.fullName, font.name, font.postscriptName, ...(font.names || [])].some(name => name?.toLocaleLowerCase() === value);
|
&& [font.menuFamily, font.fullName, font.name, font.postscriptName, ...(font.names || [])].some(name => name?.toLocaleLowerCase() === value);
|
||||||
const selected = Number(this.value);
|
const selected = Number(this.value);
|
||||||
const index = matches(this.fonts[selected]) ? selected : this.fonts.findIndex(matches);
|
const index = matches(this.fonts[selected]) ? selected : this.fonts.findIndex(matches);
|
||||||
if (index >= 0) this.choose(index);
|
if (index >= 0) return this.choose(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
prepareCommit(event) {
|
||||||
|
if (this.open && (!event || ![this.input, this.toggle, this.list].some(node => node.contains(event.target)))) {
|
||||||
|
this.commitExact();
|
||||||
|
this.close();
|
||||||
|
}
|
||||||
|
return this.changing;
|
||||||
}
|
}
|
||||||
|
|
||||||
close() {
|
close() {
|
||||||
@@ -137,7 +175,7 @@ export class FontPicker {
|
|||||||
}
|
}
|
||||||
|
|
||||||
keyDown(event) {
|
keyDown(event) {
|
||||||
if (event.isComposing) return;
|
if (event.isComposing || event.key === "Tab" && (event.ctrlKey || event.metaKey || event.altKey)) return;
|
||||||
if (!["Escape", "Enter", "ArrowDown", "ArrowUp", "Tab"].includes(event.key)) return;
|
if (!["Escape", "Enter", "ArrowDown", "ArrowUp", "Tab"].includes(event.key)) return;
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
if (event.key === "Escape") {
|
if (event.key === "Escape") {
|
||||||
@@ -314,13 +352,44 @@ export class FontManager {
|
|||||||
}), ...this.catalog];
|
}), ...this.catalog];
|
||||||
}
|
}
|
||||||
|
|
||||||
async loadFaces(inspect) {
|
async loadFaces(inspect, current = () => true) {
|
||||||
while (true) {
|
while (current()) {
|
||||||
const file = this.userFonts.find(font => font.enabled && !font.faces);
|
const file = this.userFonts.find(font => font.enabled && !font.faces);
|
||||||
if (!file) return;
|
if (!file) break;
|
||||||
try { file.faces = await inspect(await this.read(file)); }
|
try { file.faces = await inspect(await this.read(file)); }
|
||||||
catch { file.faces = []; }
|
catch { if (!current()) return; file.faces = []; }
|
||||||
}
|
}
|
||||||
|
const pending = this.catalog.filter(font => font.blob && !font.menuFamily && !font.metadataFailed);
|
||||||
|
await Promise.all(Array.from({ length: Math.min(4, pending.length) }, async () => {
|
||||||
|
while (current() && pending.length) {
|
||||||
|
const font = pending.shift();
|
||||||
|
try {
|
||||||
|
const faces = await inspect(await this.read(font));
|
||||||
|
const face = faces.find(face => face.postscriptName === font.postscriptName);
|
||||||
|
if (face) Object.assign(font, { index: face.index, menuFamily: face.menuFamily, menuStyle: face.menuStyle, familyKey: face.familyKey, bold: face.bold, italic: face.italic, names: face.names });
|
||||||
|
else font.metadataFailed = true;
|
||||||
|
} catch { if (current()) font.metadataFailed = true; }
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async defaultFont(order, inspect, current = () => true) {
|
||||||
|
const fonts = this.editorFonts().filter(font => !font.disabled);
|
||||||
|
if (!fonts.length) return;
|
||||||
|
const families = [["DengXian", "等线"], ["Microsoft YaHei", "微软雅黑"], ["PingFang SC", "苹方-简", "苹方 简体"],
|
||||||
|
["Noto Sans SC", "Noto Sans CJK SC"], ["Source Han Sans SC", "Source Han Sans CN", "思源黑体", "思源黑体 CN"]];
|
||||||
|
const indices = await order(fonts, families);
|
||||||
|
let fallback = fonts.length;
|
||||||
|
for (const index of indices) {
|
||||||
|
if (!current()) return;
|
||||||
|
try {
|
||||||
|
await inspect(fonts[index], "中文汉字编辑水印,。!?");
|
||||||
|
if (current()) return fonts[index];
|
||||||
|
} catch (error) {
|
||||||
|
if (error.missingGlyphs) fallback = Math.min(fallback, index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (current()) return fonts[fallback];
|
||||||
}
|
}
|
||||||
|
|
||||||
async add(fonts) {
|
async add(fonts) {
|
||||||
@@ -400,7 +469,7 @@ export class FontManager {
|
|||||||
for (const font of fonts) {
|
for (const font of fonts) {
|
||||||
if (disabled.has(this.localName(font))) continue;
|
if (disabled.has(this.localName(font))) continue;
|
||||||
const names = [this.localName(font), font.postscriptName && `${font.postscriptName}.ttf`,
|
const names = [this.localName(font), font.postscriptName && `${font.postscriptName}.ttf`,
|
||||||
font.family && `${[font.family, font.style].filter(Boolean).join(" ")}.ttf`];
|
font.family && `${[font.family, font.style].filter(Boolean).join(" ")}.ttf`, ...(font.names || []).map(name => `${name}.ttf`)];
|
||||||
for (const name of names) {
|
for (const name of names) {
|
||||||
if (name && !entries.has(name)) entries.set(name, font);
|
if (name && !entries.has(name)) entries.set(name, font);
|
||||||
}
|
}
|
||||||
|
|||||||
+618
-27
@@ -1,19 +1,545 @@
|
|||||||
let engineModule = null;
|
let engineModule = null;
|
||||||
|
let engineScheduler = null;
|
||||||
|
let engineSequence = 0;
|
||||||
|
const engineRuntimes = new Map();
|
||||||
|
|
||||||
export function createEngineWorker() {
|
function requestKey(worker, data) {
|
||||||
if (nativeHost) return nativeHost.worker();
|
return worker.shared ? JSON.stringify([data.engineID, data.id]) : data.id;
|
||||||
const worker = new Worker("./ofdgo_wasm.js");
|
}
|
||||||
worker.addEventListener("message", event => {
|
|
||||||
|
export function engineLimits() {
|
||||||
|
engineScheduler ||= new BrowserScheduler();
|
||||||
|
return {parallelism: engineScheduler.capacity, memoryBytes: engineScheduler.budget};
|
||||||
|
}
|
||||||
|
|
||||||
|
class BrowserScheduler {
|
||||||
|
constructor() {
|
||||||
|
this.budget = Math.max(256, Math.min(2048, (navigator.deviceMemory || 2) * 256)) * 1024 * 1024;
|
||||||
|
this.capacity = Math.max(1, Math.min((navigator.hardwareConcurrency || 2) - 1, Math.floor(this.budget / (128 << 20))));
|
||||||
|
this.limit = Math.min(this.capacity, Math.max(1, Math.floor(this.budget / (512 << 20))));
|
||||||
|
this.workers = new Set();
|
||||||
|
this.queue = [];
|
||||||
|
this.sequence = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
get memory() {
|
||||||
|
return [...this.workers].reduce((total, worker) => total + Math.max(worker.memory, worker.reservation), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
active() {
|
||||||
|
return [...this.workers].reduce((total, worker) => total + new Set([...worker.operations.values()].map(data => data.engineID)).size, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
owner(worker, data) {
|
||||||
|
return worker.shared ? worker.sessions.get(data.engineID) : worker;
|
||||||
|
}
|
||||||
|
|
||||||
|
priority(task) {
|
||||||
|
return Number(task.worker.batch || this.owner(task.worker, task.data)?.foreground === false) + Number(!!task.data.preload || !!task.data.background);
|
||||||
|
}
|
||||||
|
|
||||||
|
submit(worker, data, transfer) {
|
||||||
|
if (data.preload && this.owner(worker, data)?.pagesPaused) {
|
||||||
|
worker.receive({data:{engineID:data.engineID, id:data.id, ok:false, canceled:true, error:"预加载已暂停"}});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.queue.push({worker, data, transfer, queued:performance.now(), order:++this.sequence});
|
||||||
|
this.drain();
|
||||||
|
}
|
||||||
|
|
||||||
|
send(task) {
|
||||||
|
const {worker, data, transfer} = task;
|
||||||
|
worker.requests.set(requestKey(worker, data), performance.now());
|
||||||
|
worker.operations.set(requestKey(worker, data), data);
|
||||||
|
try { worker.worker.postMessage(data, transfer); }
|
||||||
|
catch (error) {
|
||||||
|
worker.requests.delete(requestKey(worker, data));
|
||||||
|
worker.operations.delete(requestKey(worker, data));
|
||||||
|
worker.receive({data:{engineID:data.engineID, id:data.id, ok:false, error:error.message}});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
complete(worker, data) {
|
||||||
|
if (data.memory) worker.memory = data.memory;
|
||||||
|
if (data.id == null || data.type) return;
|
||||||
|
const key = requestKey(worker, data);
|
||||||
|
const started = worker.requests.get(key);
|
||||||
|
const elapsed = data.elapsed ?? (started === undefined ? 0 : performance.now() - started);
|
||||||
|
const operation = worker.operations.get(key), owner = this.owner(worker, data);
|
||||||
|
if (worker.primary && started !== undefined && data.ok && owner) {
|
||||||
|
if (operation?.name === "ofdgoOpen") owner.openTime = elapsed;
|
||||||
|
if (operation?.name === "ofdgoRenderPage") owner.pageTime = owner.pageTime ? owner.pageTime * 0.75 + elapsed * 0.25 : elapsed;
|
||||||
|
}
|
||||||
|
worker.requests.delete(key);
|
||||||
|
worker.operations.delete(key);
|
||||||
|
if (this.memory > this.budget) this.limit = Math.max(1, this.limit - 1);
|
||||||
|
else if (started !== undefined && data.ok && elapsed > 100 && this.memory + Math.max(128 << 20, worker.memory) < this.budget) this.limit = Math.min(this.capacity, this.limit + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
drain() {
|
||||||
|
if (this.draining) return;
|
||||||
|
this.draining = true;
|
||||||
|
try {
|
||||||
|
if (this.queue.length) for (const worker of [...this.workers].sort((a,b) => b.memory-a.memory)) {
|
||||||
|
if (this.memory + (64 << 20) <= this.budget) break;
|
||||||
|
if (!worker.requests.size) worker.reclaim?.();
|
||||||
|
}
|
||||||
|
this.queue.sort((a, b) => this.priority(a) - this.priority(b) + (a.queued - b.queued) / 2000);
|
||||||
|
for (let i = 0; i < this.queue.length;) {
|
||||||
|
const task = this.queue[i];
|
||||||
|
if (task.worker.closed) { this.queue.splice(i, 1); continue; }
|
||||||
|
if (this.queue.some(previous => previous.worker === task.worker && previous.data.engineID === task.data.engineID && previous.order < task.order)) { i++; continue; }
|
||||||
|
const busy = [...task.worker.operations.values()].some(data => data.engineID === task.data.engineID && data.name !== "ofdgoSaveSnapshot");
|
||||||
|
const snapshot = task.data.name === "ofdgoSaveSnapshot" && [...task.worker.operations.values()].some(data => data.engineID === task.data.engineID && data.name === "ofdgoSaveSnapshot");
|
||||||
|
const active = this.active();
|
||||||
|
const interactive = task.worker.primary && this.owner(task.worker, task.data)?.foreground === true && !task.data.preload && !task.data.background;
|
||||||
|
const foregroundActive = [...this.workers].some(worker => [...worker.operations.values()].some(data => data.name !== "ofdgoSaveSnapshot" && worker.primary && this.owner(worker, data)?.foreground === true && !data.preload && !data.background));
|
||||||
|
const continuing = task.worker.primary && [...task.worker.operations.values()].some(data => data.engineID === task.data.engineID);
|
||||||
|
const available = continuing || active < this.limit || interactive && !foregroundActive && active < this.limit + 1;
|
||||||
|
if (busy || snapshot || !available || !task.worker.primary && active && this.memory + (64 << 20) > this.budget) { i++; continue; }
|
||||||
|
this.queue.splice(i, 1);
|
||||||
|
this.send(task);
|
||||||
|
}
|
||||||
|
} finally { this.draining = false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
cancel(worker, data) {
|
||||||
|
const index = this.queue.findIndex(task => task.worker === worker && requestKey(worker, task.data) === requestKey(worker, data));
|
||||||
|
if (index < 0) return false;
|
||||||
|
const task = this.queue.splice(index, 1)[0];
|
||||||
|
worker.receive({data:{engineID:task.data.engineID, id:data.id, ok:false, canceled:true, error:"操作已取消"}});
|
||||||
|
this.drain();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
pause(worker, engineID) {
|
||||||
|
const paused = this.queue.filter(task => task.worker === worker && task.data.engineID === engineID && task.data.preload);
|
||||||
|
this.queue = this.queue.filter(task => !paused.includes(task));
|
||||||
|
for (const task of paused) worker.receive({data:{engineID, id:task.data.id, ok:false, canceled:true, error:"预加载已暂停"}});
|
||||||
|
}
|
||||||
|
|
||||||
|
remove(worker) {
|
||||||
|
this.workers.delete(worker);
|
||||||
|
this.queue = this.queue.filter(task => task.worker !== worker);
|
||||||
|
worker.requests.clear();
|
||||||
|
worker.operations.clear();
|
||||||
|
this.drain();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class BrowserWorker {
|
||||||
|
constructor(options) {
|
||||||
|
engineScheduler ||= new BrowserScheduler();
|
||||||
|
this.primary = !!options.primary;
|
||||||
|
this.shared = !!options.shared;
|
||||||
|
this.engineID = this.shared ? null : `engine-${++engineSequence}`;
|
||||||
|
this.sessions = new Map();
|
||||||
|
this.closingSessions = new Set();
|
||||||
|
this.batch = !options.primary && !options.page;
|
||||||
|
this.requests = new Map();
|
||||||
|
this.operations = new Map();
|
||||||
|
this.foreground = !this.batch;
|
||||||
|
this.pagesPaused = false;
|
||||||
|
this.memory = 64 << 20;
|
||||||
|
this.reservation = 0;
|
||||||
|
this.closed = false;
|
||||||
|
this.url = String(options.url || "./ofdgo_wasm.js");
|
||||||
|
this.worker = new Worker(this.url);
|
||||||
|
engineScheduler.workers.add(this);
|
||||||
|
this.worker.onmessage = event => {
|
||||||
|
if (this.closed || event.data.type === "module") return;
|
||||||
|
engineScheduler.complete(this, event.data);
|
||||||
|
if (event.data.type === "exit" && (!this.shared || !event.data.engineID)) this.terminate();
|
||||||
|
try { this.receive(event); }
|
||||||
|
finally { engineScheduler.drain(); }
|
||||||
|
};
|
||||||
|
this.worker.onerror = event => { this.terminate(); this.fail("onerror", event); };
|
||||||
|
this.worker.onmessageerror = event => { this.terminate(); this.fail("onmessageerror", event); };
|
||||||
|
this.worker.addEventListener("message", event => {
|
||||||
if (event.data.type !== "module") return;
|
if (event.data.type !== "module") return;
|
||||||
event.stopImmediatePropagation();
|
event.stopImmediatePropagation();
|
||||||
engineModule ||= WebAssembly.compileStreaming(fetch("./ofdgo.wasm")).catch(error => { engineModule = null; throw error; });
|
engineModule ||= WebAssembly.compileStreaming(fetch("./ofdgo.wasm")).catch(error => { engineModule = null; throw error; });
|
||||||
engineModule.then(module => worker.postMessage({ type: "module", module }), error => worker.postMessage({ type: "module", error: error.message }));
|
engineModule.then(module => { if (!this.closed) this.worker.postMessage({ type:"module", module }); }, error => { if (!this.closed) this.worker.postMessage({ type:"module", error:error.message }); });
|
||||||
});
|
});
|
||||||
return worker;
|
if (!this.shared) this.worker.postMessage({type:"open", engineID:this.engineID});
|
||||||
|
}
|
||||||
|
|
||||||
|
receive(event) {
|
||||||
|
if (!event.data.engineID && !["progress", "exit"].includes(event.data.type)) return;
|
||||||
|
if (!this.shared) {
|
||||||
|
if (event.data.engineID && event.data.engineID !== this.engineID) return;
|
||||||
|
this.onmessage?.(event);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (event.data.type === "closed") {
|
||||||
|
if (!this.closingSessions.delete(event.data.engineID)) return;
|
||||||
|
for (const [key, data] of this.operations) if (data.engineID === event.data.engineID) {
|
||||||
|
this.requests.delete(key);
|
||||||
|
this.operations.delete(key);
|
||||||
|
}
|
||||||
|
if (!this.sessions.size && !this.closingSessions.size) this.terminate();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const targets = event.data.engineID ? [this.sessions.get(event.data.engineID)] : [...this.sessions.values()];
|
||||||
|
for (const session of targets) session?.receive(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
fail(name, event) {
|
||||||
|
if (!this.shared) { this[name]?.(event); return; }
|
||||||
|
for (const session of [...this.sessions.values()]) {
|
||||||
|
session.terminate();
|
||||||
|
session[name]?.(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
postMessage(data, transfer) {
|
||||||
|
if (this.closed) throw new DOMException("引擎已关闭", "AbortError");
|
||||||
|
if (!this.shared) data = {...data, engineID:this.engineID};
|
||||||
|
if (data.type) {
|
||||||
|
if (data.type === "cancel" && engineScheduler.cancel(this, data)) return;
|
||||||
|
this.worker.postMessage(data, transfer);
|
||||||
|
} else engineScheduler.submit(this, data, transfer);
|
||||||
|
}
|
||||||
|
|
||||||
|
setForeground(foreground) {
|
||||||
|
this.foreground = !!foreground;
|
||||||
|
this.pausePages(!this.foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
pausePages(paused = true) {
|
||||||
|
this.pagesPaused = !!paused;
|
||||||
|
if (this.pagesPaused) engineScheduler.pause(this, this.engineID);
|
||||||
|
engineScheduler.drain();
|
||||||
|
}
|
||||||
|
|
||||||
|
terminate() {
|
||||||
|
if (this.closed) return;
|
||||||
|
this.closed = true;
|
||||||
|
if (engineRuntimes.get(this.url) === this) engineRuntimes.delete(this.url);
|
||||||
|
this.closingSessions.clear();
|
||||||
|
this.worker.terminate();
|
||||||
|
engineScheduler.remove(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class BrowserSession {
|
||||||
|
constructor(options) {
|
||||||
|
const url = String(options.url || "./ofdgo_wasm.js");
|
||||||
|
let runtime = engineRuntimes.get(url);
|
||||||
|
if (!runtime || runtime.closed) {
|
||||||
|
runtime = new BrowserWorker({primary:true, shared:true, url});
|
||||||
|
engineRuntimes.set(url, runtime);
|
||||||
|
}
|
||||||
|
this.runtime = runtime;
|
||||||
|
this.engineID = `engine-${++engineSequence}`;
|
||||||
|
this.requests = new Set();
|
||||||
|
this.foreground = true;
|
||||||
|
this.pagesPaused = false;
|
||||||
|
this.closed = false;
|
||||||
|
runtime.sessions.set(this.engineID, this);
|
||||||
|
runtime.postMessage({type:"open", engineID:this.engineID});
|
||||||
|
}
|
||||||
|
|
||||||
|
receive(event) {
|
||||||
|
if (this.closed) return;
|
||||||
|
if (event.data.id != null && !event.data.type) this.requests.delete(event.data.id);
|
||||||
|
if (event.data.type === "exit") this.terminate();
|
||||||
|
this.onmessage?.(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
postMessage(data, transfer) {
|
||||||
|
if (this.closed) throw new DOMException("引擎已关闭", "AbortError");
|
||||||
|
if (!data.type) this.requests.add(data.id);
|
||||||
|
this.runtime.postMessage({...data, engineID:this.engineID}, transfer);
|
||||||
|
}
|
||||||
|
|
||||||
|
setForeground(foreground) {
|
||||||
|
this.foreground = !!foreground;
|
||||||
|
this.pausePages(!this.foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
pausePages(paused = true) {
|
||||||
|
this.pagesPaused = !!paused;
|
||||||
|
if (this.pagesPaused) engineScheduler.pause(this.runtime, this.engineID);
|
||||||
|
engineScheduler.drain();
|
||||||
|
}
|
||||||
|
|
||||||
|
terminate() {
|
||||||
|
if (this.closed) return;
|
||||||
|
this.closed = true;
|
||||||
|
this.runtime.sessions.delete(this.engineID);
|
||||||
|
engineScheduler.queue = engineScheduler.queue.filter(task => task.worker !== this.runtime || task.data.engineID !== this.engineID);
|
||||||
|
this.requests.clear();
|
||||||
|
if (!this.runtime.closed) {
|
||||||
|
this.runtime.closingSessions.add(this.engineID);
|
||||||
|
this.runtime.postMessage({type:"close", engineID:this.engineID});
|
||||||
|
}
|
||||||
|
engineScheduler.drain();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createEngineWorker(options = {}) {
|
||||||
|
if (nativeHost) return nativeHost.worker();
|
||||||
|
if (options.page || options.batch) return new BrowserWorker(options);
|
||||||
|
if (options.primary) return new BrowserSession(options);
|
||||||
|
return new BrowserEngine(options);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function documentBytes(file) {
|
export async function documentBytes(file) {
|
||||||
return file?.nativeFile ? file : new Uint8Array(await file.arrayBuffer());
|
if (file?.nativeFile) return file;
|
||||||
|
if (file instanceof Blob) return new Response(file.stream()).blob();
|
||||||
|
return new Uint8Array(await file.arrayBuffer());
|
||||||
|
}
|
||||||
|
|
||||||
|
class BrowserEngine {
|
||||||
|
constructor(options) {
|
||||||
|
this.primary = createEngineWorker({primary:true, url:options.url});
|
||||||
|
this.engineID = this.primary.engineID;
|
||||||
|
this.workerURL = options.url;
|
||||||
|
this.primary.onmessage = event => {
|
||||||
|
const data = event.data;
|
||||||
|
if (data.memory) this.memory = data.memory;
|
||||||
|
if (this.source) this.parallelism = engineScheduler.limit;
|
||||||
|
const rendered = data.id != null && !data.type && this.requests.delete(data.id);
|
||||||
|
this.onmessage?.(event);
|
||||||
|
if (rendered && data.ok) this.dispatchPages();
|
||||||
|
};
|
||||||
|
this.primary.onerror = event => this.onerror?.(event);
|
||||||
|
this.primary.onmessageerror = event => this.onmessageerror?.(event);
|
||||||
|
this.requests = new Map();
|
||||||
|
this.fontRequests = new Map();
|
||||||
|
this.primaryPages = new Set();
|
||||||
|
this.slots = new Set();
|
||||||
|
this.sequence = 0;
|
||||||
|
this.revision = 0;
|
||||||
|
this.memory = 0;
|
||||||
|
this.parallelism = 1;
|
||||||
|
this.budget = engineScheduler.budget;
|
||||||
|
this.closed = false;
|
||||||
|
this.source = null;
|
||||||
|
this.pageSource = null;
|
||||||
|
this.foreground = true;
|
||||||
|
this.pagesPaused = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
configurePages(source) {
|
||||||
|
const current = this.pageSource;
|
||||||
|
const fonts = (source?.fonts || []).map(font => font?.data !== undefined ? {name:font.name, data:font.data} : font);
|
||||||
|
const sameNames = JSON.stringify(source?.fontNames || []) === JSON.stringify(current?.fontNames || []);
|
||||||
|
const sameFonts = current && fonts.length === current.fonts.length && fonts.every((font, index) => font === current.fonts[index] || font?.data !== undefined && font.name === current.fonts[index]?.name && font.data === current.fonts[index]?.data);
|
||||||
|
if (source && current && source.file === current.file && !!source.pdf === !!current.pdf && (source.document || 0) === current.document && (source.version || "") === current.version && source.annotations === current.annotations && source.revision === current.revision && sameFonts && sameNames) return;
|
||||||
|
this.invalidatePages();
|
||||||
|
if (!source || this.closed) return;
|
||||||
|
this.pageSource = {...source, fonts, document:source.document || 0, version:source.version || ""};
|
||||||
|
this.source = {...source, file: source.file instanceof Blob ? source.file : new Blob([source.file])};
|
||||||
|
this.parallelism = engineScheduler.limit;
|
||||||
|
}
|
||||||
|
|
||||||
|
setForeground(foreground) {
|
||||||
|
this.foreground = !!foreground;
|
||||||
|
this.primary.setForeground(this.foreground);
|
||||||
|
for (const slot of this.slots) slot.worker.setForeground(this.foreground);
|
||||||
|
this.pausePages(!this.foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
pausePages(paused = true) {
|
||||||
|
this.pagesPaused = !!paused;
|
||||||
|
this.primary.pausePages(this.pagesPaused);
|
||||||
|
for (const slot of this.slots) slot.worker.pausePages(this.pagesPaused);
|
||||||
|
}
|
||||||
|
|
||||||
|
invalidatePages() {
|
||||||
|
this.revision++;
|
||||||
|
this.primaryPages.clear();
|
||||||
|
this.source = null;
|
||||||
|
this.pageSource = null;
|
||||||
|
this.parallelism = 1;
|
||||||
|
this.startupTime = 0;
|
||||||
|
this.primary.pageTime = 0;
|
||||||
|
for (const slot of this.slots) this.closeSlot(slot);
|
||||||
|
}
|
||||||
|
|
||||||
|
closeSlot(slot, error = new DOMException("页面加载已取消", "AbortError")) {
|
||||||
|
if (!this.slots.delete(slot)) return;
|
||||||
|
slot.worker.terminate();
|
||||||
|
for (const [id, request] of this.fontRequests) if (request.worker === slot.worker) this.fontRequests.delete(id);
|
||||||
|
slot.rejectReady(error);
|
||||||
|
for (const pending of slot.pending.values()) pending.reject(error);
|
||||||
|
slot.pending.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
createSlot(source) {
|
||||||
|
const started = performance.now();
|
||||||
|
const worker = createEngineWorker({page:true, url:this.workerURL});
|
||||||
|
worker.setForeground(this.foreground);
|
||||||
|
worker.pausePages(this.pagesPaused);
|
||||||
|
const slot = {worker, pending: new Map(), busy: false, memory: Math.max(128 << 20, this.memory), pages:new Set(), lastPage:0};
|
||||||
|
worker.reservation = slot.memory;
|
||||||
|
worker.reclaim = () => { if (!slot.busy) this.closeSlot(slot); };
|
||||||
|
const ready = new Promise((resolve, reject) => {
|
||||||
|
slot.rejectReady = reject;
|
||||||
|
worker.onmessage = ({data}) => {
|
||||||
|
if (data.memory) slot.memory = data.memory;
|
||||||
|
if (this.source) this.parallelism = engineScheduler.limit;
|
||||||
|
if (data.type === "ready") { resolve(); return; }
|
||||||
|
if (data.type === "exit") { this.closeSlot(slot, new Error("页面加载失败")); return; }
|
||||||
|
if (data.type === "font") {
|
||||||
|
const request = `${slot.worker.engineID}:${data.request}`;
|
||||||
|
this.fontRequests.set(request, {worker:slot.worker, request:data.request});
|
||||||
|
this.onmessage?.({data:{...data, id:slot.requestID, request}});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (data.type) return;
|
||||||
|
const request = slot.pending.get(data.id);
|
||||||
|
if (!request) return;
|
||||||
|
slot.pending.delete(data.id);
|
||||||
|
if (data.ok) request.resolve(data);
|
||||||
|
else request.reject(Object.assign(new Error(data.error), {code:data.code, name:data.canceled ? "AbortError" : "Error"}));
|
||||||
|
};
|
||||||
|
worker.onerror = worker.onmessageerror = () => this.closeSlot(slot, new Error("页面加载失败"));
|
||||||
|
});
|
||||||
|
this.slots.add(slot);
|
||||||
|
slot.ready = ready.then(async () => {
|
||||||
|
let opened = source.pdf
|
||||||
|
? await this.callSlot(slot, "ofdgoOpenPDF", [source.file, source.fonts, null, source.annotations, source.fontNames])
|
||||||
|
: await this.callSlot(slot, "ofdgoOpen", [source.file, source.fonts, source.annotations]);
|
||||||
|
if ((source.document || 0) !== (opened.data.documentIndex || 0)) opened = await this.callSlot(slot, "ofdgoSelectDocument", [source.document]);
|
||||||
|
if ((source.version || "") !== (opened.data.documentVersion || "")) await this.callSlot(slot, "ofdgoSelectVersion", [source.version || ""]);
|
||||||
|
if (this.slots.has(slot)) this.startupTime = performance.now() - started;
|
||||||
|
});
|
||||||
|
slot.ready.catch(() => {});
|
||||||
|
return slot;
|
||||||
|
}
|
||||||
|
|
||||||
|
callSlot(slot, name, args, preload = false) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
if (!this.slots.has(slot)) { reject(new DOMException("页面加载已取消", "AbortError")); return; }
|
||||||
|
const id = --this.sequence;
|
||||||
|
slot.pending.set(id, {resolve, reject});
|
||||||
|
try { slot.worker.postMessage({id, name, args, preload}); }
|
||||||
|
catch (error) { slot.pending.delete(id); reject(error); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pageSlot(data) {
|
||||||
|
if (this.primaryPages.has(data.args[0])) return null;
|
||||||
|
const preferred = [...this.slots].find(slot => !slot.busy && slot.pages.has(data.args[0]));
|
||||||
|
const pending = [...this.requests.values()].filter(slot => slot === null).length - Number(this.requests.has(data.id));
|
||||||
|
if (!preferred && pending <= 0) return null;
|
||||||
|
let slot = preferred || [...this.slots].filter(slot => !slot.busy).sort((a,b) => Math.abs(a.lastPage-data.args[0])-Math.abs(b.lastPage-data.args[0]))[0];
|
||||||
|
const worthwhile = (this.primary.pageTime || 0) * pending >= Math.max(50, this.startupTime || this.primary.openTime || 0);
|
||||||
|
if (!slot && worthwhile && this.foreground && !this.pagesPaused && this.slots.size < this.parallelism - 1
|
||||||
|
&& engineScheduler.memory + Math.max(128 << 20, this.memory) <= this.budget) slot = this.createSlot(this.source);
|
||||||
|
return slot;
|
||||||
|
}
|
||||||
|
|
||||||
|
dispatchPages() {
|
||||||
|
if (this.closed || !this.source || !this.foreground || this.pagesPaused) return;
|
||||||
|
const draining = engineScheduler.draining;
|
||||||
|
engineScheduler.draining = true;
|
||||||
|
try {
|
||||||
|
const queued = engineScheduler.queue.filter(task => task.worker === this.primary.runtime && task.data.engineID === this.engineID).sort((a,b) => a.order-b.order);
|
||||||
|
for (const task of queued) {
|
||||||
|
if (task.data.name !== "ofdgoRenderPage") break;
|
||||||
|
if (this.requests.get(task.data.id) !== null) continue;
|
||||||
|
let slot;
|
||||||
|
try { slot = this.pageSlot(task.data); } catch { break; }
|
||||||
|
if (!slot) break;
|
||||||
|
engineScheduler.queue.splice(engineScheduler.queue.indexOf(task), 1);
|
||||||
|
this.primary.requests.delete(task.data.id);
|
||||||
|
this.renderSlot(slot, task.data, task.transfer);
|
||||||
|
}
|
||||||
|
} finally { engineScheduler.draining = draining; }
|
||||||
|
}
|
||||||
|
|
||||||
|
postMessage(data, transfer) {
|
||||||
|
if (this.closed) return;
|
||||||
|
if (data.type === "font" && typeof data.request === "string") {
|
||||||
|
const request = this.fontRequests.get(data.request);
|
||||||
|
if (request) {
|
||||||
|
this.fontRequests.delete(data.request);
|
||||||
|
request.worker.postMessage({...data, request:request.request}, transfer);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!data.type && data.preload && this.pagesPaused) {
|
||||||
|
this.onmessage?.({data:{engineID:this.engineID, id:data.id, ok:false, canceled:true, error:"预加载已暂停"}});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (data.type === "cancel") {
|
||||||
|
const slot = this.requests.get(data.id);
|
||||||
|
if (slot && slot !== this.primary) this.closeSlot(slot);
|
||||||
|
else this.primary.postMessage(data);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!data.type && data.name !== "ofdgoRenderPage" && ![
|
||||||
|
"ofdgoLoadPDF", "ofdgoDocumentInfo", "ofdgoDocumentVersions", "ofdgoDocumentNavigation", "ofdgoOpenLinks", "ofdgoOutlineLinks", "ofdgoRenderBackends", "ofdgoSVGFontData",
|
||||||
|
"ofdgoSearchPage", "ofdgoPageTextString", "ofdgoResources", "ofdgoResourceReferences", "ofdgoResourceTargets",
|
||||||
|
"ofdgoResourceLocations", "ofdgoFontPreview", "ofdgoFontFaces", "ofdgoFontFace", "ofdgoMatchFontFiles",
|
||||||
|
"ofdgoImages", "ofdgoStructureTargets", "ofdgoStructureObjects", "ofdgoPackageDocuments", "ofdgoVerifySignatures",
|
||||||
|
"ofdgoAnnotationInfos", "ofdgoInvoices", "ofdgoInvoice", "ofdgoExportInvoice", "ofdgoValidateInvoice",
|
||||||
|
"ofdgoActionList", "ofdgoPageSettings", "ofdgoReadAnnotation", "ofdgoPreviewSignatureSeal",
|
||||||
|
"ofdgoExportFormats", "ofdgoOutputFormats", "ofdgoParsePageRange", "ofdgoExportPage", "ofdgoExportDocument",
|
||||||
|
"ofdgoPreparePrint", "ofdgoLayoutPrint", "ofdgoPrintSide", "ofdgoPrintPDF", "ofdgoDiscardPrint",
|
||||||
|
"ofdgoExportAttachment", "ofdgoExportResource", "ofdgoExportMedia", "ofdgoExportVersion"
|
||||||
|
].includes(data.name)) this.invalidatePages();
|
||||||
|
const slot = data.name === "ofdgoRenderPage" && this.source ? this.pageSlot(data) : null;
|
||||||
|
if (!slot) {
|
||||||
|
if (data.name === "ofdgoRenderPage") this.requests.set(data.id, null);
|
||||||
|
this.primary.postMessage(data, transfer);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.renderSlot(slot, data, transfer);
|
||||||
|
}
|
||||||
|
|
||||||
|
renderSlot(slot, data, transfer) {
|
||||||
|
slot.busy = true;
|
||||||
|
slot.requestID = data.id;
|
||||||
|
this.requests.set(data.id, slot);
|
||||||
|
const revision = this.revision;
|
||||||
|
let fallback = false;
|
||||||
|
slot.ready.then(() => this.callSlot(slot, data.name, data.args, !!data.preload)).then(result => {
|
||||||
|
if (revision !== this.revision) throw new DOMException("页面加载已取消", "AbortError");
|
||||||
|
if (this.source.pdf && ((JSON.parse(result.data.annotations || "null") || []).length || result.data.links?.length)) {
|
||||||
|
this.primaryPages.add(data.args[0]);
|
||||||
|
this.requests.set(data.id, this.primary);
|
||||||
|
fallback = true;
|
||||||
|
this.primary.postMessage(data, transfer);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
slot.lastPage = data.args[0];
|
||||||
|
slot.pages.delete(slot.lastPage);
|
||||||
|
slot.pages.add(slot.lastPage);
|
||||||
|
if (slot.pages.size > 16) slot.pages.delete(slot.pages.values().next().value);
|
||||||
|
if (!this.closed) this.onmessage?.({data: {...result, engineID:this.engineID, id: data.id}});
|
||||||
|
}).catch(error => {
|
||||||
|
if (!this.closed && revision === this.revision && error.name !== "AbortError") {
|
||||||
|
this.closeSlot(slot, error);
|
||||||
|
this.parallelism = Math.max(1, this.slots.size + 1);
|
||||||
|
this.requests.set(data.id, this.primary);
|
||||||
|
fallback = true;
|
||||||
|
this.primary.postMessage(data, transfer);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!this.closed) this.onmessage?.({data: {engineID:this.engineID, id: data.id, ok: false, error: error.message, canceled: error.name === "AbortError"}});
|
||||||
|
}).finally(() => {
|
||||||
|
if (!fallback) this.requests.delete(data.id);
|
||||||
|
slot.busy = false;
|
||||||
|
slot.worker.reservation = 0;
|
||||||
|
const memory = engineScheduler.memory;
|
||||||
|
if (memory > this.budget) { this.closeSlot(slot); this.parallelism = Math.max(1, this.slots.size + 1); }
|
||||||
|
this.dispatchPages();
|
||||||
|
engineScheduler.drain();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
terminate() {
|
||||||
|
if (this.closed) return;
|
||||||
|
this.closed = true;
|
||||||
|
this.invalidatePages();
|
||||||
|
this.primary.terminate();
|
||||||
|
this.requests.clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveFilePicker(options) {
|
export function saveFilePicker(options) {
|
||||||
@@ -27,6 +553,7 @@ export function directoryPicker() {
|
|||||||
class NativeFile {
|
class NativeFile {
|
||||||
constructor(value) {
|
constructor(value) {
|
||||||
Object.assign(this, value);
|
Object.assign(this, value);
|
||||||
|
if (value.handle) this.handle = new NativeHandle(nativeHost, value.handle);
|
||||||
this.byteLength = this.size;
|
this.byteLength = this.size;
|
||||||
this.type ||= "application/octet-stream";
|
this.type ||= "application/octet-stream";
|
||||||
if (value.temporary) nativeHost?.resources?.register(this, value.nativeFile);
|
if (value.temporary) nativeHost?.resources?.register(this, value.nativeFile);
|
||||||
@@ -86,6 +613,10 @@ class NativeHandle {
|
|||||||
class NativeHost {
|
class NativeHost {
|
||||||
constructor(bridge) {
|
constructor(bridge) {
|
||||||
this.bridge = bridge;
|
this.bridge = bridge;
|
||||||
|
this.parallelism = 1;
|
||||||
|
this.cacheBytes = 32 * 1024 * 1024;
|
||||||
|
this.reading = 0;
|
||||||
|
this.readQueue = [];
|
||||||
this.resources = typeof FinalizationRegistry === "function" ? new FinalizationRegistry(file => {
|
this.resources = typeof FinalizationRegistry === "function" ? new FinalizationRegistry(file => {
|
||||||
this.call("release", {file}).catch(() => {});
|
this.call("release", {file}).catch(() => {});
|
||||||
}) : null;
|
}) : null;
|
||||||
@@ -95,25 +626,40 @@ class NativeHost {
|
|||||||
return this.bridge.call(`ofdgo.host.${name}`, value, {signal});
|
return this.bridge.call(`ofdgo.host.${name}`, value, {signal});
|
||||||
}
|
}
|
||||||
|
|
||||||
async decode(value, name = "", key = "", signal) {
|
async readResource(file, signal) {
|
||||||
if (value?.nativeFile) {
|
if (this.reading >= this.parallelism) await new Promise(resolve => this.readQueue.push(resolve));
|
||||||
const file = new NativeFile(value);
|
else this.reading++;
|
||||||
if (key === "file" || name === "ofdgoConvertPDF" && key === "bytes") return file;
|
|
||||||
try {
|
try {
|
||||||
const bytes = await file.arrayBuffer(signal);
|
signal?.throwIfAborted();
|
||||||
return key === "blob" ? new Blob([bytes], {type:value.type}) : new Uint8Array(bytes);
|
return await file.arrayBuffer(signal);
|
||||||
} finally {
|
} finally {
|
||||||
await this.call("release", {file:value.nativeFile});
|
try { await this.call("release", {file:file.nativeFile}); }
|
||||||
|
finally {
|
||||||
|
const next = this.readQueue.shift();
|
||||||
|
if (next) next();
|
||||||
|
else this.reading--;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (Array.isArray(value)) {
|
|
||||||
for (let i = 0; i < value.length; i++) value[i] = await this.decode(value[i], name, "", signal);
|
|
||||||
return value;
|
|
||||||
}
|
}
|
||||||
if (value && typeof value === "object") {
|
|
||||||
for (const [field, item] of Object.entries(value)) value[field] = await this.decode(item, name, field, signal);
|
async decode(value, signal) {
|
||||||
return value;
|
const reads = [];
|
||||||
|
const visit = (item, field, replace) => {
|
||||||
|
if (!item || typeof item !== "object" || item instanceof Blob || item instanceof ArrayBuffer || ArrayBuffer.isView(item)) return;
|
||||||
|
if (item.nativeFile) {
|
||||||
|
const file = new NativeFile(item);
|
||||||
|
if (field === "file") replace(file);
|
||||||
|
else reads.push(this.readResource(file, signal).then(bytes => replace(field === "blob" ? new Blob([bytes], {type:item.type}) : new Uint8Array(bytes))));
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
for (const [child, content] of Object.entries(item)) {
|
||||||
|
if (content && typeof content === "object") visit(content, Array.isArray(item) ? "" : child, result => item[child] = result);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
visit(value, "", result => value = result);
|
||||||
|
const results = await Promise.allSettled(reads);
|
||||||
|
const failed = results.find(result => result.status === "rejected");
|
||||||
|
if (failed) throw failed.reason;
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,21 +679,38 @@ class NativeHost {
|
|||||||
let closed = false;
|
let closed = false;
|
||||||
let unsubscribe;
|
let unsubscribe;
|
||||||
let pending = Promise.resolve();
|
let pending = Promise.resolve();
|
||||||
|
let termination = null;
|
||||||
|
const readers = new Set();
|
||||||
|
const inputs = new Set();
|
||||||
const requests = new Map();
|
const requests = new Map();
|
||||||
const completions = new Map();
|
const completions = new Map();
|
||||||
const emit = data => {
|
const emit = data => {
|
||||||
if (data.type === "result") { completions.get(data.id)?.(data.result); return; }
|
if (data.type === "result") { completions.get(data.id)?.(data.result); return; }
|
||||||
if (!closed) worker.onmessage?.({data});
|
if (!closed) worker.onmessage?.({data:{...data, engineID:worker.engineID}});
|
||||||
};
|
};
|
||||||
const ready = host.call("engine.open", {}).then(({engine}) => {
|
const ready = host.call("engine.open", {}).then(({engine, parallelism, cacheBytes}) => {
|
||||||
|
worker.engineID = engine;
|
||||||
if (closed) return engine;
|
if (closed) return engine;
|
||||||
|
host.parallelism = Math.max(1, parallelism || 1);
|
||||||
|
host.cacheBytes = cacheBytes || host.cacheBytes;
|
||||||
unsubscribe = host.bridge.on(`ofdgo.engine.${engine}`, emit);
|
unsubscribe = host.bridge.on(`ofdgo.engine.${engine}`, emit);
|
||||||
emit({type:"ready"});
|
emit({type:"ready"});
|
||||||
return engine;
|
return engine;
|
||||||
}).catch(error => { if (!closed) worker.onerror?.({message:error.message}); throw error; });
|
}).catch(error => { if (!closed) worker.onerror?.({message:error.message}); throw error; });
|
||||||
const worker = {
|
const worker = {
|
||||||
|
engineID:null,
|
||||||
|
foreground:true,
|
||||||
|
pagesPaused:false,
|
||||||
onmessage:null,
|
onmessage:null,
|
||||||
onerror:null,
|
onerror:null,
|
||||||
|
configurePages() {},
|
||||||
|
setForeground(foreground) {
|
||||||
|
worker.foreground = !!foreground;
|
||||||
|
worker.pausePages(!worker.foreground);
|
||||||
|
},
|
||||||
|
pausePages(paused = true) {
|
||||||
|
worker.pagesPaused = !!paused;
|
||||||
|
},
|
||||||
postMessage(data) {
|
postMessage(data) {
|
||||||
if (closed) return;
|
if (closed) return;
|
||||||
if (data.type === "cancel") {
|
if (data.type === "cancel") {
|
||||||
@@ -155,11 +718,18 @@ class NativeHost {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (data.type === "font") return;
|
if (data.type === "font") return;
|
||||||
|
if (["ofdgoDetectFormat", "ofdgoOpen", "ofdgoOpenPDF"].includes(data.name)) {
|
||||||
|
const input = data.args?.[0];
|
||||||
|
if (input?.nativeFile && !input.temporary) inputs.add(input.nativeFile);
|
||||||
|
}
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
requests.set(data.id, controller);
|
requests.set(data.id, controller);
|
||||||
pending = pending.then(async () => {
|
const parallel = data.name === "ofdgoRenderPage";
|
||||||
|
const barrier = parallel ? pending : Promise.all([pending, ...readers]);
|
||||||
|
const operation = barrier.then(async () => {
|
||||||
const engine = await ready;
|
const engine = await ready;
|
||||||
if (closed) return;
|
if (closed) return;
|
||||||
|
if (data.preload && worker.pagesPaused) throw new DOMException("预加载已暂停", "AbortError");
|
||||||
controller.signal.throwIfAborted();
|
controller.signal.throwIfAborted();
|
||||||
const args = {engine, id:data.id, name:data.name, args:data.args};
|
const args = {engine, id:data.id, name:data.name, args:data.args};
|
||||||
let result;
|
let result;
|
||||||
@@ -181,23 +751,30 @@ class NativeHost {
|
|||||||
let decoded;
|
let decoded;
|
||||||
try {
|
try {
|
||||||
controller.signal.throwIfAborted();
|
controller.signal.throwIfAborted();
|
||||||
decoded = await host.decode(result, data.name, "", controller.signal);
|
decoded = await host.decode(result, controller.signal);
|
||||||
controller.signal.throwIfAborted();
|
controller.signal.throwIfAborted();
|
||||||
}
|
}
|
||||||
catch (error) { await host.release(result); throw error; }
|
catch (error) { await host.release(result); throw error; }
|
||||||
if (closed) { await host.release(result); return; }
|
if (closed) { await host.release(result); return; }
|
||||||
emit({id:data.id, ...decoded});
|
emit({id:data.id, ...decoded});
|
||||||
}).catch(error => emit({id:data.id, ok:false, error:error.message, code:error.code, canceled:error.name === "AbortError"})).finally(() => requests.delete(data.id));
|
}).catch(error => emit({id:data.id, ok:false, error:error.message, code:error.code, canceled:error.name === "AbortError"})).finally(() => requests.delete(data.id));
|
||||||
|
if (parallel) {
|
||||||
|
readers.add(operation);
|
||||||
|
operation.finally(() => readers.delete(operation));
|
||||||
|
} else if (data.name !== "ofdgoSaveSnapshot") pending = operation;
|
||||||
},
|
},
|
||||||
terminate() {
|
terminate() {
|
||||||
if (closed) return;
|
if (closed) return termination;
|
||||||
closed = true;
|
closed = true;
|
||||||
for (const controller of requests.values()) controller.abort();
|
for (const controller of requests.values()) controller.abort();
|
||||||
ready.then(engine => host.call("engine.close", {engine})).catch(() => {}).finally(() => {
|
termination = ready.then(engine => host.call("engine.close", {engine})).catch(() => {}).finally(async () => {
|
||||||
unsubscribe?.();
|
unsubscribe?.();
|
||||||
for (const resolve of completions.values()) resolve({ok:false, canceled:true, error:"会话已关闭"});
|
for (const resolve of completions.values()) resolve({ok:false, canceled:true, error:"会话已关闭"});
|
||||||
completions.clear();
|
completions.clear();
|
||||||
|
await Promise.all([...inputs].map(file => host.call("release", {file}).catch(() => {})));
|
||||||
|
inputs.clear();
|
||||||
});
|
});
|
||||||
|
return termination;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
ready.catch(() => {});
|
ready.catch(() => {});
|
||||||
@@ -217,13 +794,27 @@ class NativeHost {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async start(onFiles, onError) {
|
async start(onFiles, onError) {
|
||||||
this.bridge.on("ofdgo.files", values => onFiles(values.map(value => new NativeFile(value))));
|
let launching = Promise.resolve();
|
||||||
|
this.bridge.on("ofdgo.launch", values => {
|
||||||
|
launching = launching.then(async () => {
|
||||||
|
try { await onFiles(values.map(value => new NativeFile(value)), true); }
|
||||||
|
finally { await this.call("launch.done", {}); }
|
||||||
|
}).catch(onError);
|
||||||
|
});
|
||||||
|
this.bridge.on("ofdgo.files", async values => {
|
||||||
|
try { await onFiles(values.map(value => new NativeFile(value))); }
|
||||||
|
catch (error) { onError(error); }
|
||||||
|
});
|
||||||
this.bridge.on("ofdgo.error", message => onError(new Error(message)));
|
this.bridge.on("ofdgo.error", message => onError(new Error(message)));
|
||||||
const title = document.querySelector("title");
|
const title = document.querySelector("title");
|
||||||
if (title) new MutationObserver(() => this.call("title", {title:document.title}).catch(onError)).observe(title, {childList:true});
|
if (title) new MutationObserver(() => this.call("title", {title:document.title}).catch(onError)).observe(title, {childList:true});
|
||||||
await this.call("ready", {});
|
await this.call("ready", {});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async discardFiles(files) {
|
||||||
|
await Promise.all(files.filter(file => file.drop && file.nativeFile).map(file => this.call("drop.release", {file:file.nativeFile})));
|
||||||
|
}
|
||||||
|
|
||||||
installFileInputs(onError) {
|
installFileInputs(onError) {
|
||||||
document.addEventListener("click", async event => {
|
document.addEventListener("click", async event => {
|
||||||
const input = event.target;
|
const input = event.target;
|
||||||
|
|||||||
@@ -0,0 +1,493 @@
|
|||||||
|
let printQueue = Promise.resolve();
|
||||||
|
|
||||||
|
export class PrintDialog {
|
||||||
|
constructor(options) {
|
||||||
|
Object.assign(this, options);
|
||||||
|
const panel = this.panel || document.querySelector("#printPanel");
|
||||||
|
this.el = Object.fromEntries(["Panel", "Form", "Settings", "Printer", "Properties", "Copies", "Collation", "Duplex", "BackReverse", "BackRotate", "Contents", "Scope", "Range", "Parity", "Reverse", "Mode", "Paper", "Width", "Height", "Orientation", "Scaling", "Scale", "MarginTop", "MarginRight", "MarginBottom", "MarginLeft", "Grid", "PageOrder", "Gap", "Binding", "BookletSheets", "SheetFrom", "SheetTo", "Overlap", "Sides", "Rotate", "Grayscale", "Borders", "CropMarks", "Raster", "DPI", "DPIValue", "TileOnlyLarge", "Labels", "Preview", "Previous", "Next", "PreviewNumber", "PageControl", "PageCount", "Status", "Spinner", "ProgressTrack", "ProgressBar", "Cancel", "Submit"].map(name => [name, name === "Panel" ? panel : panel.querySelector(`#print${name}`)]));
|
||||||
|
this.printerOptions = this.el.Printer.innerHTML;
|
||||||
|
this.paperOptions = this.el.Paper.innerHTML;
|
||||||
|
this.settings = new WeakMap();
|
||||||
|
this.queue = Promise.resolve();
|
||||||
|
this.sequence = 0;
|
||||||
|
this.urls = [];
|
||||||
|
this.el.Settings.addEventListener("input", event => { if (event.target === this.el.Printer) this.choosePrinter(); else this.schedule(); });
|
||||||
|
this.el.Properties.addEventListener("click", () => this.properties());
|
||||||
|
this.el.Form.addEventListener("submit", event => { event.preventDefault(); this.print(); });
|
||||||
|
this.el.Cancel.addEventListener("click", () => this.el.Panel.close());
|
||||||
|
this.el.Panel.addEventListener("close", () => this.close());
|
||||||
|
this.el.Panel.addEventListener("cancel", event => { if (this.waiting) event.preventDefault(); });
|
||||||
|
this.el.Previous.addEventListener("click", () => this.preview(this.side - 1));
|
||||||
|
this.el.Next.addEventListener("click", () => this.preview(this.side + 1));
|
||||||
|
this.el.PreviewNumber.addEventListener("change", () => this.preview(Number(this.el.PreviewNumber.value) - 1));
|
||||||
|
this.el.PreviewNumber.addEventListener("keydown", event => {
|
||||||
|
if (event.key !== "Enter") return;
|
||||||
|
event.preventDefault();
|
||||||
|
if (!event.repeat) this.el.PreviewNumber.dispatchEvent(new Event("change"));
|
||||||
|
});
|
||||||
|
this.observer = new ResizeObserver(([entry]) => { this.previewSize = entry.contentRect; this.resize(); });
|
||||||
|
this.observer.observe(this.el.Preview);
|
||||||
|
this.afterPrint = () => { if (this.waiting === "browser") this.finishPrint("打印窗口已关闭"); };
|
||||||
|
this.beforePrint = () => {
|
||||||
|
if (!this.context || !this.el.Panel.open) return;
|
||||||
|
const root = document.querySelector("#ofdgoPrintDocument");
|
||||||
|
if (!root?.children.length) {
|
||||||
|
this.root = root || this.createRoot();
|
||||||
|
this.root.textContent = "请先在OFDGo中打开打印预览,准备完整文档后打印。";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener("afterprint", this.afterPrint);
|
||||||
|
window.addEventListener("beforeprint", this.beforePrint);
|
||||||
|
}
|
||||||
|
|
||||||
|
open(context) {
|
||||||
|
if (this.context) return;
|
||||||
|
const saved = this.settings.get(context.tab)?.get(context.document);
|
||||||
|
this.context = context;
|
||||||
|
this.restoring = true;
|
||||||
|
this.prepared = false;
|
||||||
|
this.layout = null;
|
||||||
|
this.job = this.profile = null;
|
||||||
|
this.side = 0;
|
||||||
|
this.sequence++;
|
||||||
|
this.el.Printer.innerHTML = this.printerOptions;
|
||||||
|
this.el.Paper.innerHTML = this.paperOptions;
|
||||||
|
this.el.Form.reset();
|
||||||
|
this.orientation = saved?.orientation ?? this.el.Orientation.value;
|
||||||
|
this.duplexBeforeBooklet = saved?.duplex ?? this.el.Duplex.value;
|
||||||
|
this.scalingBeforeBooklet = saved?.scaling ?? this.el.Scaling.value;
|
||||||
|
this.restore(saved);
|
||||||
|
this.mode = this.el.Mode.value;
|
||||||
|
if (!saved) this.el.Scope.value = context.selection.length ? "selected" : "all";
|
||||||
|
this.el.Scope.querySelector('option[value="selected"]').disabled = !context.selection.length;
|
||||||
|
this.el.Sides.value = this.manual() ? "front" : "all";
|
||||||
|
if (!saved) this.el.Contents.value = context.annotations ? "documentAndAnnotations" : "document";
|
||||||
|
this.status();
|
||||||
|
this.el.Preview.replaceChildren();
|
||||||
|
this.show(this.el.Panel);
|
||||||
|
this.loadDevices(saved);
|
||||||
|
}
|
||||||
|
|
||||||
|
isDevice() { return this.el.Printer.value.startsWith("device:"); }
|
||||||
|
manual() { return this.el.Duplex.value.startsWith("manual"); }
|
||||||
|
|
||||||
|
async loadDevices(saved) {
|
||||||
|
const sequence = ++this.sequence;
|
||||||
|
const selected = saved?.values.Printer;
|
||||||
|
this.loading = true;
|
||||||
|
this.controls();
|
||||||
|
const browser = this.el.Printer.querySelector('option[value="browser"]');
|
||||||
|
browser.disabled = !!this.nativeHost || typeof window.print !== "function";
|
||||||
|
if (browser.disabled) this.el.Printer.value = "pdf";
|
||||||
|
try {
|
||||||
|
if (this.nativeHost) {
|
||||||
|
this.status("正在读取设备", true);
|
||||||
|
const capabilities = await this.nativeHost.call("print.capabilities", {});
|
||||||
|
if (!this.current(sequence)) return;
|
||||||
|
this.capabilities = capabilities;
|
||||||
|
browser.disabled = !capabilities.systemDialog;
|
||||||
|
const printers = capabilities.direct ? await this.nativeHost.call("print.printers", {}) : [];
|
||||||
|
if (!this.current(sequence)) return;
|
||||||
|
for (const printer of printers) this.el.Printer.add(new Option(printer.name, `device:${printer.name}`));
|
||||||
|
const printer = printers.find(printer => printer.default) || printers[0];
|
||||||
|
this.el.Printer.value = printer ? `device:${printer.name}` : "pdf";
|
||||||
|
}
|
||||||
|
} catch (error) { if (this.current(sequence)) this.status(error.message); }
|
||||||
|
finally {
|
||||||
|
if (this.current(sequence)) {
|
||||||
|
this.loading = false;
|
||||||
|
if ([...this.el.Printer.options].some(option => option.value === selected && !option.disabled)) this.el.Printer.value = selected;
|
||||||
|
await this.choosePrinter(this.el.Printer.value === selected ? saved : null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async choosePrinter(saved) {
|
||||||
|
const sequence = ++this.sequence;
|
||||||
|
const paper = this.el.Paper.value;
|
||||||
|
this.layout = this.job = this.profile = null;
|
||||||
|
this.loading = true;
|
||||||
|
this.status();
|
||||||
|
this.controls();
|
||||||
|
if (!this.isDevice()) {
|
||||||
|
this.el.Paper.innerHTML = this.paperOptions;
|
||||||
|
this.el.Paper.value = paper;
|
||||||
|
if (!this.el.Paper.value) {
|
||||||
|
const [width, height] = paper.split(",").map(Number);
|
||||||
|
if (width > 0 && height > 0 && Number.isFinite(width) && Number.isFinite(height)) {
|
||||||
|
this.el.Paper.value = "custom";
|
||||||
|
this.el.Width.value = width;
|
||||||
|
this.el.Height.value = height;
|
||||||
|
} else this.el.Paper.value = "210,297";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.el.Properties.hidden = true;
|
||||||
|
try {
|
||||||
|
if (this.isDevice()) {
|
||||||
|
this.status("正在读取纸张", true);
|
||||||
|
const profile = await this.nativeHost.call("print.query", {printer:this.el.Printer.value.slice(7), copies:1, duplex:"simplex"});
|
||||||
|
if (!this.current(sequence)) return;
|
||||||
|
this.profile = profile;
|
||||||
|
this.el.Paper.replaceChildren(...profile.papers.map(paper => new Option(paper.name, `${paper.width},${paper.height}`)));
|
||||||
|
if (profile.customPaper) this.el.Paper.add(new Option("自定义", "custom"));
|
||||||
|
this.el.Paper.value = `${profile.options.width},${profile.options.height}`;
|
||||||
|
if (!this.el.Paper.value && profile.customPaper) { this.el.Paper.value = "custom"; this.el.Width.value = profile.options.width; this.el.Height.value = profile.options.height; }
|
||||||
|
if (!this.el.Paper.value) throw new Error("设备默认纸张不在支持列表中");
|
||||||
|
this.el.Orientation.value = profile.options.orientation;
|
||||||
|
this.el.Copies.max = Math.min(999, profile.maxCopies || 999);
|
||||||
|
this.el.Copies.value = 1;
|
||||||
|
this.el.Grayscale.checked = profile.options.color === "grayscale";
|
||||||
|
this.el.Grayscale.disabled = !profile.color;
|
||||||
|
this.el.Properties.hidden = !profile.properties;
|
||||||
|
} else this.el.Grayscale.disabled = false;
|
||||||
|
} catch (error) { if (this.current(sequence)) { this.status(error.message); return; } }
|
||||||
|
finally { if (this.current(sequence)) { this.loading = false; this.controls(); } }
|
||||||
|
if (this.current(sequence)) {
|
||||||
|
this.restore(saved);
|
||||||
|
if (this.el.Scope.value === "selected" && !this.context.selection.length) this.el.Scope.value = "all";
|
||||||
|
this.restoring = false;
|
||||||
|
this.schedule();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async properties() {
|
||||||
|
if (!this.isDevice() || this.running || this.loading) return;
|
||||||
|
const sequence = this.sequence;
|
||||||
|
this.loading = true;
|
||||||
|
this.status("正在打开属性", true);
|
||||||
|
this.controls();
|
||||||
|
try { await this.nativeHost.call("print.properties", {printer:this.el.Printer.value.slice(7)}); }
|
||||||
|
catch (error) { if (this.current(sequence)) this.status(error.message); }
|
||||||
|
finally { if (this.current(sequence)) { this.loading = false; await this.choosePrinter(); } }
|
||||||
|
}
|
||||||
|
|
||||||
|
deviceOptions() {
|
||||||
|
const [width, height] = this.el.Paper.value === "custom" ? [Number(this.el.Width.value), Number(this.el.Height.value)] : this.el.Paper.value.split(",").map(Number);
|
||||||
|
const manual = this.manual(), partial = this.el.Sides.value !== "all";
|
||||||
|
return {printer:this.el.Printer.value.slice(7), width, height, orientation:this.el.Orientation.value,
|
||||||
|
copies:Number(this.el.Copies.value), collation:this.el.Collation.checked ? "collated" : "uncollated",
|
||||||
|
duplex:manual || partial ? "simplex" : this.el.Duplex.value, color:this.el.Grayscale.checked ? "grayscale" : "color",
|
||||||
|
scale:1, pagesPerSide:1, margins:{top:0,right:0,bottom:0,left:0},
|
||||||
|
...(this.capabilities?.backgrounds ? {backgrounds:true} : {}), ...(this.capabilities?.headersFooters ? {headersFooters:false} : {})};
|
||||||
|
}
|
||||||
|
|
||||||
|
options(profile) {
|
||||||
|
const el = this.el;
|
||||||
|
const number = name => {
|
||||||
|
const value = Number(el[name].value);
|
||||||
|
if (!el[name].value.trim() || !Number.isFinite(value)) throw new Error("请输入有效数值");
|
||||||
|
return value;
|
||||||
|
};
|
||||||
|
let [paperWidth, paperHeight] = el.Paper.value === "source" ? [0, 0] : el.Paper.value === "custom" ? [number("Width"), number("Height")] : el.Paper.value.split(",").map(Number);
|
||||||
|
if (el.Orientation.value === "landscape") [paperWidth, paperHeight] = [paperHeight, paperWidth];
|
||||||
|
if (profile) [paperWidth, paperHeight] = [profile.width, profile.height];
|
||||||
|
const scope = el.Scope.value;
|
||||||
|
const [rows, columns] = el.Grid.value.split(",").map(Number);
|
||||||
|
if (scope === "selected" && !this.context.selection.length) throw new Error("未选择页面");
|
||||||
|
if (scope === "range" && !el.Range.value.trim()) throw new Error("请输入页码范围");
|
||||||
|
const manual = this.manual(), duplex = el.Duplex.value.replace("manualL", "l").replace("manualS", "s");
|
||||||
|
if (manual && this.isDevice() && number("Copies") !== 1) throw new Error("手动双面每次仅支持1份");
|
||||||
|
return {
|
||||||
|
...(scope === "current" ? {pages:[this.context.page]} : scope === "selected" ? {pages:this.context.selection} : scope === "range" ? {pageRange:el.Range.value.trim()} : {}),
|
||||||
|
mode:el.Mode.value, scaling:el.Scaling.value, paperWidth, paperHeight,
|
||||||
|
margins:{top:number("MarginTop"), right:number("MarginRight"), bottom:number("MarginBottom"), left:number("MarginLeft")},
|
||||||
|
...(profile ? {printableArea:{x:profile.printableArea.x, y:profile.printableArea.y, w:profile.printableArea.width, h:profile.printableArea.height}} : {}),
|
||||||
|
copies:this.isDevice() ? number("Copies") : 1, collate:el.Collation.checked, duplex,
|
||||||
|
scale:el.Scale.disabled ? 1 : number("Scale") / 100, rotate:el.Rotate.checked, reverse:el.Reverse.checked !== (manual && el.Sides.value === "back" && el.BackReverse.checked), parity:el.Parity.value, sides:el.Sides.value,
|
||||||
|
backRotate:manual && el.BackRotate.checked,
|
||||||
|
rows, columns, pageOrder:el.PageOrder.value, gap:el.Gap.disabled ? 0 : number("Gap"), binding:el.Binding.value, bookletSheets:!el.BookletSheets.disabled && el.BookletSheets.value ? number("BookletSheets") : 0, overlap:el.Overlap.disabled ? 0 : number("Overlap"),
|
||||||
|
...(el.Mode.value === "booklet" ? {sheetFrom:el.SheetFrom.value ? number("SheetFrom") : 0, sheetTo:el.SheetTo.value ? number("SheetTo") : 0} : {}),
|
||||||
|
contents:el.Contents.value, grayscale:el.Grayscale.checked, borders:el.Borders.checked, cropMarks:el.CropMarks.checked, raster:el.Raster.checked, dpi:number("DPI"), tileOnlyLarge:el.TileOnlyLarge.checked, labels:el.Labels.checked
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
schedule() {
|
||||||
|
const el = this.el, mode = el.Mode.value;
|
||||||
|
const source = el.Paper.querySelector('option[value="source"]');
|
||||||
|
if (source) source.disabled = mode !== "single";
|
||||||
|
if (mode !== "single" && el.Paper.value === "source") el.Paper.value = "210,297";
|
||||||
|
if (mode === "booklet" && this.mode !== "booklet") {
|
||||||
|
this.orientation = el.Orientation.value;
|
||||||
|
this.duplexBeforeBooklet = el.Duplex.value;
|
||||||
|
this.scalingBeforeBooklet = el.Scaling.value;
|
||||||
|
el.Scaling.value = "shrink";
|
||||||
|
el.Duplex.value = this.isDevice() && !this.profile?.duplex ? "manualShortEdge" : "shortEdge";
|
||||||
|
} else if (mode !== "booklet" && this.mode === "booklet") {
|
||||||
|
el.Orientation.value = this.orientation;
|
||||||
|
el.Duplex.value = this.duplexBeforeBooklet;
|
||||||
|
el.Scaling.value = this.scalingBeforeBooklet;
|
||||||
|
}
|
||||||
|
if (mode === "booklet") el.Orientation.value = "landscape";
|
||||||
|
this.mode = mode;
|
||||||
|
if (this.isDevice() && !this.profile?.duplex && ["longEdge", "shortEdge"].includes(el.Duplex.value)) el.Duplex.value = el.Duplex.value === "longEdge" ? "manualLongEdge" : "manualShortEdge";
|
||||||
|
if (mode === "booklet" && el.Duplex.value === "simplex") el.Duplex.value = this.isDevice() && !this.profile?.duplex ? "manualShortEdge" : "shortEdge";
|
||||||
|
if (el.Duplex.value === "simplex") el.Sides.value = "all";
|
||||||
|
const isManual = this.manual();
|
||||||
|
el.Sides.querySelector('option[value="all"]').disabled = isManual;
|
||||||
|
if (isManual && el.Sides.value === "all") el.Sides.value = "front";
|
||||||
|
for (const option of el.Duplex.options) option.disabled = this.isDevice() && !this.profile?.duplex && ["longEdge", "shortEdge"].includes(option.value) || mode === "booklet" && ["simplex", "longEdge", "manualLongEdge"].includes(option.value);
|
||||||
|
el.Orientation.disabled = mode === "booklet" || el.Paper.value === "source";
|
||||||
|
const rows = {device:this.isDevice(), sides:el.Duplex.value !== "simplex", manual:isManual, range:el.Scope.value === "range", paper:el.Paper.value === "custom", scale:el.Scaling.value === "custom" || mode === "poster", multiple:mode === "multiple", gap:mode === "multiple" || mode === "booklet", booklet:mode === "booklet", poster:mode === "poster"};
|
||||||
|
for (const row of el.Panel.querySelectorAll("[data-print-row]")) {
|
||||||
|
row.hidden = !rows[row.dataset.printRow];
|
||||||
|
for (const input of row.querySelectorAll("input, select")) input.disabled = row.hidden;
|
||||||
|
}
|
||||||
|
el.Scaling.disabled = mode === "poster" || mode === "booklet";
|
||||||
|
el.DPI.disabled = !el.Raster.checked && !el.Grayscale.checked;
|
||||||
|
const sequence = ++this.sequence;
|
||||||
|
this.layout = null;
|
||||||
|
this.job = null;
|
||||||
|
this.status();
|
||||||
|
this.controls();
|
||||||
|
clearTimeout(this.timer);
|
||||||
|
this.timer = setTimeout(() => {
|
||||||
|
this.queue = this.queue.catch(() => {}).then(() => this.refresh(sequence));
|
||||||
|
}, 160);
|
||||||
|
}
|
||||||
|
|
||||||
|
async refresh(sequence) {
|
||||||
|
if (!this.current(sequence)) return;
|
||||||
|
const context = this.context;
|
||||||
|
try {
|
||||||
|
if (!this.el.Form.checkValidity()) {
|
||||||
|
if (this.el.Panel.open) this.el.Form.reportValidity();
|
||||||
|
else this.status("请检查打印设置");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.status("正在准备预览", true);
|
||||||
|
const deviceOptions = this.isDevice() ? this.deviceOptions() : null;
|
||||||
|
const profile = deviceOptions ? await this.nativeHost.call("print.query", deviceOptions) : null;
|
||||||
|
if (!this.current(sequence)) return;
|
||||||
|
this.profile = profile;
|
||||||
|
const options = this.options(profile);
|
||||||
|
const layout = await context.call(this.prepared ? "ofdgoLayoutPrint" : "ofdgoPreparePrint", options);
|
||||||
|
if (!this.current(sequence)) return;
|
||||||
|
this.prepared = true;
|
||||||
|
this.layout = layout;
|
||||||
|
if (this.isDevice()) this.el.Copies.max = Math.min(999, this.profile.maxCopies || 999, layout.copiesLimit > 0 ? layout.copiesLimit : 999);
|
||||||
|
await this.preview(Math.min(this.side, layout.sides.length - 1));
|
||||||
|
if (!this.current(sequence) || this.layout !== layout) return;
|
||||||
|
this.job = {deviceOptions, fingerprint:profile?.fingerprint, manual:this.manual(), sides:options.sides, backContent:layout.backContent};
|
||||||
|
this.status();
|
||||||
|
if (layout.sides.some(side => side.placements.some(placement => placement.clipped))) this.status("内容超出可打印区域");
|
||||||
|
if (this.manual() && options.sides === "back" && !layout.backContent) this.status("背面为空白");
|
||||||
|
} catch (error) {
|
||||||
|
if (this.current(sequence)) this.status(error.code === "printDenied" ? "文档禁止打印" : error.message);
|
||||||
|
} finally {
|
||||||
|
if (this.current(sequence)) this.controls();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
current(sequence = this.sequence) { return sequence === this.sequence && this.context && !this.context.tab.closed; }
|
||||||
|
|
||||||
|
async preview(index) {
|
||||||
|
if (!this.layout || this.running) return;
|
||||||
|
if (!Number.isInteger(index) || index < 0 || index >= this.layout.sides.length) { this.controls(); return; }
|
||||||
|
const sequence = this.sequence, preview = this.previewSequence = (this.previewSequence || 0) + 1;
|
||||||
|
this.side = index;
|
||||||
|
this.controls();
|
||||||
|
try {
|
||||||
|
let {svg} = await this.context.call("ofdgoPrintSide", index);
|
||||||
|
if (!this.current(sequence) || preview !== this.previewSequence) return;
|
||||||
|
if (this.profile) {
|
||||||
|
const area = this.profile.printableArea;
|
||||||
|
svg = svg.replace("</svg>", `<rect x="${area.x}" y="${area.y}" width="${area.width}" height="${area.height}" fill="none" stroke="#88949e" stroke-width="0.2" stroke-dasharray="1 1"/></svg>`);
|
||||||
|
}
|
||||||
|
const url = URL.createObjectURL(new Blob([svg], {type:"image/svg+xml"}));
|
||||||
|
const img = new Image();
|
||||||
|
img.src = url;
|
||||||
|
try { await img.decode(); } catch (error) { URL.revokeObjectURL(url); throw error; }
|
||||||
|
if (!this.current(sequence) || preview !== this.previewSequence) { URL.revokeObjectURL(url); return; }
|
||||||
|
if (this.previewURL) URL.revokeObjectURL(this.previewURL);
|
||||||
|
this.previewURL = url;
|
||||||
|
this.el.Preview.replaceChildren(img);
|
||||||
|
this.resize();
|
||||||
|
} catch (error) { if (this.current(sequence) && preview === this.previewSequence) { this.status(error.message); this.layout = null; this.controls(); } }
|
||||||
|
}
|
||||||
|
|
||||||
|
resize() {
|
||||||
|
const img = this.el.Preview.querySelector("img"), side = this.layout?.sides[this.side];
|
||||||
|
if (!img || !side || !this.previewSize) return;
|
||||||
|
const factor = Math.min(this.previewSize.width / side.width, this.previewSize.height / side.height);
|
||||||
|
img.style.width = `${Math.max(1, side.width * factor)}px`;
|
||||||
|
img.style.height = `${Math.max(1, side.height * factor)}px`;
|
||||||
|
}
|
||||||
|
|
||||||
|
status(text = "", busy = false, completed = 0, total = 0) {
|
||||||
|
this.el.Status.textContent = total ? `${text} · ${completed} / ${total}` : text;
|
||||||
|
this.el.Spinner.hidden = !busy;
|
||||||
|
this.el.ProgressTrack.hidden = !busy || !total;
|
||||||
|
this.el.ProgressBar.style.width = `${total ? completed / total * 100 : 0}%`;
|
||||||
|
}
|
||||||
|
|
||||||
|
controls() {
|
||||||
|
const count = this.layout?.sides.length || 0, busy = !!this.running || !!this.loading;
|
||||||
|
this.el.DPIValue.textContent = this.el.DPI.value;
|
||||||
|
this.el.Settings.disabled = busy;
|
||||||
|
this.el.Submit.disabled = !count || !this.job || busy;
|
||||||
|
if (this.el.Printer.value !== "pdf" && this.manual() && this.el.Sides.value === "back" && !this.layout?.backContent) this.el.Submit.disabled = true;
|
||||||
|
this.el.Previous.disabled = busy || !count || this.side === 0;
|
||||||
|
this.el.Next.disabled = busy || !count || this.side + 1 === count;
|
||||||
|
this.el.PreviewNumber.disabled = busy || !count;
|
||||||
|
this.el.PreviewNumber.max = count || 1;
|
||||||
|
this.el.PreviewNumber.value = count ? this.side + 1 : 1;
|
||||||
|
this.el.PageCount.textContent = String(count);
|
||||||
|
this.el.PageControl.style.setProperty("--page-width", `${String(count || 1).length + 0.5}ch`);
|
||||||
|
this.el.Cancel.textContent = busy && !this.waiting ? "取消" : "关闭";
|
||||||
|
this.el.Cancel.disabled = !!this.waiting;
|
||||||
|
}
|
||||||
|
|
||||||
|
restore(saved) {
|
||||||
|
for (const [name, value] of Object.entries(saved?.values || {})) {
|
||||||
|
if (name === "Printer") continue;
|
||||||
|
const node = this.el[name];
|
||||||
|
if (node.type === "checkbox") node.checked = value;
|
||||||
|
else if (!node.options || [...node.options].some(option => option.value === value)) node.value = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
remember() {
|
||||||
|
const context = this.context;
|
||||||
|
if (!context || this.restoring) return;
|
||||||
|
let settings = this.settings.get(context.tab);
|
||||||
|
if (!settings) this.settings.set(context.tab, settings = new Map());
|
||||||
|
const values = {};
|
||||||
|
for (const [name, node] of Object.entries(this.el)) if (node.closest("#printSettings") && name !== "Sides" && node.matches("input, select")) values[name] = node.type === "checkbox" ? node.checked : node.value;
|
||||||
|
settings.set(context.document, {values, orientation:this.orientation, duplex:this.duplexBeforeBooklet, scaling:this.scalingBeforeBooklet});
|
||||||
|
}
|
||||||
|
|
||||||
|
createRoot() {
|
||||||
|
const root = document.createElement("div");
|
||||||
|
root.id = "ofdgoPrintDocument";
|
||||||
|
document.body.append(root);
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
async print() {
|
||||||
|
if (!this.layout || !this.job || this.running) return;
|
||||||
|
this.previewSequence++;
|
||||||
|
if (this.el.Printer.value === "pdf") return this.pdf();
|
||||||
|
const sequence = this.sequence, context = this.context;
|
||||||
|
const job = this.job;
|
||||||
|
this.running = true;
|
||||||
|
this.controls();
|
||||||
|
this.status("正在等待打印", true);
|
||||||
|
const previous = printQueue;
|
||||||
|
let release;
|
||||||
|
printQueue = new Promise(resolve => { release = resolve; });
|
||||||
|
await previous;
|
||||||
|
if (!this.current(sequence)) { release(); return; }
|
||||||
|
this.releasePrint = release;
|
||||||
|
try {
|
||||||
|
this.root = document.querySelector("#ofdgoPrintDocument") || this.createRoot();
|
||||||
|
this.root.replaceChildren();
|
||||||
|
const style = document.createElement("style");
|
||||||
|
style.textContent = this.layout.sides.map((side, i) => `@page ofdgoPrint${i}{size:${side.width}mm ${side.height}mm;margin:0}`).join("");
|
||||||
|
this.root.append(style);
|
||||||
|
this.status("正在准备纸面", true, 0, this.layout.sides.length);
|
||||||
|
for (let i = 0; i < this.layout.sides.length; i++) {
|
||||||
|
if (!this.current(sequence)) throw new DOMException("打印已取消", "AbortError");
|
||||||
|
const {svg} = await context.call("ofdgoPrintSide", i);
|
||||||
|
if (!this.current(sequence)) throw new DOMException("打印已取消", "AbortError");
|
||||||
|
const url = URL.createObjectURL(new Blob([svg], {type:"image/svg+xml"}));
|
||||||
|
this.urls.push(url);
|
||||||
|
const img = new Image(), section = document.createElement("section"), side = this.layout.sides[i];
|
||||||
|
img.src = url;
|
||||||
|
section.append(img);
|
||||||
|
section.style.cssText = `page:ofdgoPrint${i};width:${side.width}mm;height:${side.height}mm`;
|
||||||
|
this.root.append(section);
|
||||||
|
await img.decode();
|
||||||
|
if (this.current(sequence)) this.status("正在准备纸面", true, i + 1, this.layout.sides.length);
|
||||||
|
}
|
||||||
|
await document.fonts.ready;
|
||||||
|
if (!this.current(sequence)) throw new DOMException("打印已取消", "AbortError");
|
||||||
|
if (this.el.Panel.open) {
|
||||||
|
this.previousTitle = document.title;
|
||||||
|
document.title = this.printTitle = context.name;
|
||||||
|
}
|
||||||
|
this.waiting = this.nativeHost ? "native" : "browser";
|
||||||
|
this.controls();
|
||||||
|
this.status(job.deviceOptions ? "正在提交打印" : "正在打开打印", true);
|
||||||
|
if (job.deviceOptions) {
|
||||||
|
const result = await this.nativeHost.call("print", {...job.deviceOptions, fingerprint:job.fingerprint});
|
||||||
|
this.finishPrint(result?.submitted ? "打印已提交" : "打印作业未被接受");
|
||||||
|
if (this.current(sequence) && result?.submitted && job.manual && job.sides === "front") {
|
||||||
|
if (job.backContent) { this.el.Sides.value = "back"; this.schedule(); }
|
||||||
|
else this.status("背面为空白");
|
||||||
|
}
|
||||||
|
} else if (this.nativeHost) {
|
||||||
|
const capabilities = await this.nativeHost.call("print.capabilities", {});
|
||||||
|
if (!this.current(sequence)) throw new DOMException("打印已取消", "AbortError");
|
||||||
|
if (!capabilities.systemDialog) throw new Error("当前运行时不支持系统打印");
|
||||||
|
if (!capabilities.dialogCompletion) this.waiting = "browser";
|
||||||
|
await this.nativeHost.call("print.dialog", {kind:"system"});
|
||||||
|
if (capabilities.dialogCompletion) this.finishPrint("打印窗口已关闭");
|
||||||
|
} else if (typeof window.print === "function") window.print();
|
||||||
|
else throw new Error("当前浏览器不支持打印");
|
||||||
|
} catch (error) {
|
||||||
|
if (this.releasePrint === release) this.finishPrint();
|
||||||
|
if (this.current(sequence)) {
|
||||||
|
this.status(error.name === "AbortError" ? "打印已取消" : error.message);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (this.current(sequence)) {
|
||||||
|
if (!this.waiting) this.running = false;
|
||||||
|
this.controls();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
finishPrint(message = "") {
|
||||||
|
if (this.previousTitle !== undefined) {
|
||||||
|
if (document.title === this.printTitle) document.title = this.previousTitle;
|
||||||
|
delete this.previousTitle;
|
||||||
|
}
|
||||||
|
if (this.releasePrint) this.root?.replaceChildren();
|
||||||
|
for (const url of this.urls) URL.revokeObjectURL(url);
|
||||||
|
this.urls = [];
|
||||||
|
this.releasePrint?.();
|
||||||
|
this.releasePrint = null;
|
||||||
|
this.status(message);
|
||||||
|
this.waiting = this.running = false;
|
||||||
|
this.controls();
|
||||||
|
if (this.destroyed) window.removeEventListener("afterprint", this.afterPrint);
|
||||||
|
}
|
||||||
|
|
||||||
|
async pdf() {
|
||||||
|
if (!this.layout || this.running) return;
|
||||||
|
const sequence = this.sequence, context = this.context;
|
||||||
|
this.running = true;
|
||||||
|
this.controls();
|
||||||
|
this.status("正在生成文件", true);
|
||||||
|
try {
|
||||||
|
const result = await context.call("ofdgoPrintPDF");
|
||||||
|
if (this.current(sequence)) {
|
||||||
|
await this.download(result.bytes, "application/pdf", `${context.name.replace(/\.[^.]+$/, "")}-打印.pdf`);
|
||||||
|
if (this.current(sequence)) this.status("文件已生成");
|
||||||
|
}
|
||||||
|
} catch (error) { if (this.current(sequence)) this.status(error.message); }
|
||||||
|
finally { if (this.current(sequence)) { this.running = false; this.controls(); } }
|
||||||
|
}
|
||||||
|
|
||||||
|
close() {
|
||||||
|
const context = this.context;
|
||||||
|
this.remember();
|
||||||
|
this.sequence++;
|
||||||
|
clearTimeout(this.timer);
|
||||||
|
if (context) this.cancel(context.tab);
|
||||||
|
if (!this.waiting) this.finishPrint();
|
||||||
|
if (this.previewURL) URL.revokeObjectURL(this.previewURL);
|
||||||
|
this.previewURL = null;
|
||||||
|
this.el.Preview.replaceChildren();
|
||||||
|
this.context = null;
|
||||||
|
this.queue = this.queue.catch(() => {}).then(() => context?.call("ofdgoDiscardPrint").catch(() => {}));
|
||||||
|
}
|
||||||
|
|
||||||
|
destroy() {
|
||||||
|
this.destroyed = true;
|
||||||
|
this.close();
|
||||||
|
this.observer.disconnect();
|
||||||
|
window.removeEventListener("beforeprint", this.beforePrint);
|
||||||
|
if (!this.waiting) window.removeEventListener("afterprint", this.afterPrint);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
(() => {
|
||||||
|
const root = document.documentElement;
|
||||||
|
const preference = matchMedia("(prefers-color-scheme: dark)");
|
||||||
|
const key = "ofdgo.theme";
|
||||||
|
let mode = root.dataset.themeMode || "system";
|
||||||
|
let host = null, report = null, pending = Promise.resolve();
|
||||||
|
if (!root.dataset.themeMode) {
|
||||||
|
try { mode = localStorage.getItem(key) || "system"; } catch {}
|
||||||
|
}
|
||||||
|
if (!["system", "light", "dark"].includes(mode)) mode = "system";
|
||||||
|
function apply() {
|
||||||
|
root.dataset.themeMode = mode;
|
||||||
|
root.dataset.theme = mode === "system" ? preference.matches ? "dark" : "light" : mode;
|
||||||
|
document.querySelector('meta[name="theme-color"]').content = root.dataset.theme === "dark" ? "#272e33" : "#fafbfc";
|
||||||
|
for (const button of document.querySelectorAll("[data-theme-choice]")) button.dataset.pressed = String(button.dataset.themeChoice === mode);
|
||||||
|
}
|
||||||
|
function sync() {
|
||||||
|
if (!host) return;
|
||||||
|
const value = {mode, dark: root.dataset.theme === "dark"};
|
||||||
|
pending = pending.then(() => host.call("appearance", value)).catch(error => report(error));
|
||||||
|
}
|
||||||
|
function set(value) {
|
||||||
|
mode = value;
|
||||||
|
apply();
|
||||||
|
if (!host) {
|
||||||
|
try { localStorage.setItem(key, mode); } catch {}
|
||||||
|
}
|
||||||
|
sync();
|
||||||
|
}
|
||||||
|
preference.addEventListener("change", () => {
|
||||||
|
if (mode !== "system") return;
|
||||||
|
apply();
|
||||||
|
sync();
|
||||||
|
});
|
||||||
|
window.addEventListener("storage", event => {
|
||||||
|
if (host || event.key !== key && event.key !== null) return;
|
||||||
|
mode = ["light", "dark"].includes(event.newValue) ? event.newValue : "system";
|
||||||
|
apply();
|
||||||
|
});
|
||||||
|
window.ofdgoTheme = {set, connect(value, onError) { host = value; report = onError; apply(); sync(); }};
|
||||||
|
apply();
|
||||||
|
})();
|
||||||
@@ -0,0 +1,550 @@
|
|||||||
|
export class DocumentDialogs {
|
||||||
|
constructor({ document: root = document, targets = [], titlebar = null } = {}) {
|
||||||
|
Object.assign(this, { document: root, targets, titlebar, owner: null, records: new Map(), tabs: new Map(), released: new WeakSet(), inert: new Map(), styles: new Map() });
|
||||||
|
this.backdrop = root.createElement("div");
|
||||||
|
this.backdrop.className = "document-dialog-backdrop";
|
||||||
|
this.backdrop.hidden = true;
|
||||||
|
Object.assign(this.backdrop.style, { position: "fixed", inset: "0", background: "var(--backdrop)", zIndex: "1000" });
|
||||||
|
root.body.append(this.backdrop);
|
||||||
|
root.addEventListener("keydown", event => {
|
||||||
|
if (event.defaultPrevented || this.applicationOpen()) return;
|
||||||
|
const panel = this.current()?.stack.at(-1);
|
||||||
|
if (!panel) return;
|
||||||
|
if (event.key === "Tab" && !event.ctrlKey && !event.altKey && !event.metaKey) {
|
||||||
|
const selector = "button, input, select, textarea, a[href], [tabindex], [contenteditable=true]";
|
||||||
|
const elements = [this.titlebar, panel].filter(Boolean).flatMap(root => [...root.querySelectorAll(selector)])
|
||||||
|
.filter(node => node.tabIndex >= 0 && !node.disabled && !node.closest("[inert]") && node.getClientRects().length);
|
||||||
|
const index = elements.indexOf(root.activeElement), direction = event.shiftKey ? -1 : 1;
|
||||||
|
const target = index < 0 ? event.shiftKey ? elements.at(-1) : elements[0] : elements[(index + direction + elements.length) % elements.length];
|
||||||
|
event.preventDefault();
|
||||||
|
if (target) target.focus();
|
||||||
|
else panel.focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (event.key !== "Escape") return;
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
this.cancel(panel);
|
||||||
|
}, true);
|
||||||
|
this.backdrop.addEventListener("pointerdown", event => { event.preventDefault(); this.focus(); });
|
||||||
|
root.defaultView.addEventListener("resize", () => this.paint());
|
||||||
|
}
|
||||||
|
|
||||||
|
register(panel, { shared = true, persistent = false } = {}) {
|
||||||
|
if (this.records.has(panel)) return panel;
|
||||||
|
const record = { show: panel.show.bind(panel), showModal: panel.showModal.bind(panel), close: panel.close.bind(panel), owner: null, application: false, shared, clicks: new WeakMap(), initial: shared && !persistent ? this.snapshot(panel) : null };
|
||||||
|
this.records.set(panel, record);
|
||||||
|
panel.showModal = panel.show = () => this.openFor(this.owner, panel);
|
||||||
|
panel.close = value => {
|
||||||
|
if (record.application) record.close(value);
|
||||||
|
else this.closeFor(this.owner, panel, value);
|
||||||
|
};
|
||||||
|
panel.requestClose = value => {
|
||||||
|
if (record.application) {
|
||||||
|
const event = new this.document.defaultView.Event("cancel", { cancelable: true });
|
||||||
|
if (panel.dispatchEvent(event)) record.close(value);
|
||||||
|
} else this.cancel(panel, value);
|
||||||
|
};
|
||||||
|
panel.addEventListener("close", () => {
|
||||||
|
if (record.application) { record.application = false; this.paint(); }
|
||||||
|
});
|
||||||
|
panel.addEventListener("click", event => { record.clicks.set(event, this.owner); }, true);
|
||||||
|
panel.addEventListener("click", event => {
|
||||||
|
if (!record.application && (record.clicks.get(event) !== this.owner || !this.current()?.stack.includes(panel))) event.preventDefault();
|
||||||
|
});
|
||||||
|
panel.addEventListener("submit", event => {
|
||||||
|
if (record.application || event.defaultPrevented) return;
|
||||||
|
const method = event.submitter?.getAttribute("formmethod") || event.target.getAttribute("method");
|
||||||
|
if (method?.toLowerCase() !== "dialog") return;
|
||||||
|
event.preventDefault();
|
||||||
|
this.closeFor(this.owner, panel, event.submitter?.value || "");
|
||||||
|
});
|
||||||
|
return panel;
|
||||||
|
}
|
||||||
|
|
||||||
|
current(tab = this.owner) {
|
||||||
|
return tab ? this.tabs.get(tab) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
entry(tab, panel) {
|
||||||
|
if (!tab || this.released.has(tab)) throw new Error("Document dialog owner is unavailable");
|
||||||
|
this.register(panel);
|
||||||
|
if (!this.tabs.has(tab)) this.tabs.set(tab, { entries: new Map(), stack: [] });
|
||||||
|
const entries = this.tabs.get(tab).entries;
|
||||||
|
if (!entries.has(panel)) entries.set(panel, { snapshot: this.records.get(panel).initial, setup: [], updates: [], resolve: null, promise: null });
|
||||||
|
return entries.get(panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
setOwner(tab) {
|
||||||
|
if (this.owner === tab) return;
|
||||||
|
if (this.owner) this.suspend(this.owner);
|
||||||
|
if (tab) this.restore(tab);
|
||||||
|
}
|
||||||
|
|
||||||
|
openFor(tab, panel, setup) {
|
||||||
|
const entry = this.entry(tab, panel);
|
||||||
|
if (setup) entry.setup.push(setup);
|
||||||
|
const state = this.tabs.get(tab);
|
||||||
|
state.stack = state.stack.filter(value => value !== panel);
|
||||||
|
state.stack.push(panel);
|
||||||
|
if (tab !== this.owner) return panel;
|
||||||
|
this.unpaint();
|
||||||
|
this.records.get(panel).owner = tab;
|
||||||
|
this.prepare(entry, panel);
|
||||||
|
if (!this.records.get(panel).shared) this.document.body.append(panel);
|
||||||
|
if (!panel.open) this.records.get(panel).show();
|
||||||
|
this.paint();
|
||||||
|
this.focus();
|
||||||
|
return panel;
|
||||||
|
}
|
||||||
|
|
||||||
|
request(panel, tab = this.owner, setup) {
|
||||||
|
if (!tab || this.released.has(tab)) return Promise.resolve(null);
|
||||||
|
const entry = this.entry(tab, panel);
|
||||||
|
if (entry.promise) return entry.promise;
|
||||||
|
entry.promise = new Promise(resolve => { entry.resolve = resolve; });
|
||||||
|
const promise = entry.promise;
|
||||||
|
this.openFor(tab, panel, setup);
|
||||||
|
return promise;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateFor(tab, panel, setup) {
|
||||||
|
if (!tab || this.released.has(tab)) return false;
|
||||||
|
const entry = this.current(tab)?.entries.get(panel);
|
||||||
|
if (!entry) return false;
|
||||||
|
if (tab === this.owner && this.records.get(panel).owner === tab) setup(panel);
|
||||||
|
else entry.updates.push(setup);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
closeFor(tab, panel, value) {
|
||||||
|
const state = this.current(tab), entry = state?.entries.get(panel);
|
||||||
|
if (!state?.stack.includes(panel)) return;
|
||||||
|
const visible = tab === this.owner;
|
||||||
|
if (visible) {
|
||||||
|
this.unpaint();
|
||||||
|
if (value !== undefined) panel.returnValue = String(value);
|
||||||
|
panel.removeAttribute("open");
|
||||||
|
if (this.records.get(panel).initial) entry.snapshot = this.snapshot(panel);
|
||||||
|
}
|
||||||
|
const result = value === undefined ? visible ? panel.returnValue : entry.snapshot?.returnValue ?? panel.returnValue : String(value);
|
||||||
|
state.stack = state.stack.filter(value => value !== panel);
|
||||||
|
const resolve = entry.resolve;
|
||||||
|
entry.resolve = entry.promise = null;
|
||||||
|
entry.setup = [];
|
||||||
|
if (visible) {
|
||||||
|
this.paint();
|
||||||
|
panel.dispatchEvent(new this.document.defaultView.Event("close"));
|
||||||
|
this.focus();
|
||||||
|
}
|
||||||
|
resolve?.(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
cancel(panel, value) {
|
||||||
|
const event = new this.document.defaultView.Event("cancel", { cancelable: true });
|
||||||
|
if (panel.dispatchEvent(event)) this.closeFor(this.owner, panel, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend(tab) {
|
||||||
|
if (tab !== this.owner) return;
|
||||||
|
this.unpaint();
|
||||||
|
for (const [panel, entry] of this.current(tab)?.entries || []) {
|
||||||
|
const record = this.records.get(panel);
|
||||||
|
if (record.application || record.owner !== tab) continue;
|
||||||
|
if (record.initial) entry.snapshot = this.snapshot(panel);
|
||||||
|
else if (!record.shared) {
|
||||||
|
entry.focus = panel.contains(this.document.activeElement) ? this.document.activeElement : null;
|
||||||
|
panel.remove();
|
||||||
|
}
|
||||||
|
panel.removeAttribute("open");
|
||||||
|
}
|
||||||
|
this.owner = null;
|
||||||
|
this.paint();
|
||||||
|
}
|
||||||
|
|
||||||
|
restore(tab) {
|
||||||
|
if (!tab || this.released.has(tab)) return false;
|
||||||
|
if (this.owner === tab) return true;
|
||||||
|
if (this.owner) this.suspend(this.owner);
|
||||||
|
if (!this.tabs.has(tab)) this.tabs.set(tab, { entries: new Map(), stack: [] });
|
||||||
|
this.owner = tab;
|
||||||
|
const state = this.current(tab);
|
||||||
|
for (const [panel, entry] of state.entries) {
|
||||||
|
const record = this.records.get(panel);
|
||||||
|
if (record.application) continue;
|
||||||
|
if (record.initial) this.applySnapshot(entry.snapshot, panel);
|
||||||
|
else if (!record.shared) this.document.body.append(panel);
|
||||||
|
record.owner = tab;
|
||||||
|
}
|
||||||
|
for (const [panel, entry] of state.entries) {
|
||||||
|
if (this.records.get(panel).application) continue;
|
||||||
|
for (const update of entry.updates.splice(0)) update(panel);
|
||||||
|
}
|
||||||
|
for (const panel of state.stack) {
|
||||||
|
this.prepare(state.entries.get(panel), panel);
|
||||||
|
if (!panel.open) this.records.get(panel).show();
|
||||||
|
}
|
||||||
|
this.paint();
|
||||||
|
this.focus(true);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
release(tab) {
|
||||||
|
if (!tab || this.released.has(tab)) return;
|
||||||
|
const visible = this.owner === tab;
|
||||||
|
if (visible) this.suspend(tab);
|
||||||
|
const state = this.current(tab);
|
||||||
|
this.tabs.delete(tab);
|
||||||
|
this.released.add(tab);
|
||||||
|
for (const entry of state?.entries.values() || []) entry.resolve?.(null);
|
||||||
|
for (const [panel] of state?.entries || []) {
|
||||||
|
const record = this.records.get(panel);
|
||||||
|
if (!record.shared) {
|
||||||
|
panel.remove();
|
||||||
|
this.records.delete(panel);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (record.application || record.owner !== tab) continue;
|
||||||
|
if (record.initial) this.applySnapshot(record.initial, panel);
|
||||||
|
record.owner = null;
|
||||||
|
}
|
||||||
|
state?.entries.clear();
|
||||||
|
if (state) state.stack.length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
showApplication(panel) {
|
||||||
|
this.register(panel);
|
||||||
|
if ([...this.tabs.values()].some(state => state.stack.includes(panel))) throw new Error("Document dialog is already in use");
|
||||||
|
const record = this.records.get(panel);
|
||||||
|
record.application = true;
|
||||||
|
try { record.showModal(); }
|
||||||
|
catch (error) { record.application = false; throw error; }
|
||||||
|
}
|
||||||
|
|
||||||
|
applicationOpen() {
|
||||||
|
return [...this.records.values()].some(record => record.application);
|
||||||
|
}
|
||||||
|
|
||||||
|
prepare(entry, panel) {
|
||||||
|
for (const setup of entry.setup.splice(0)) setup(panel);
|
||||||
|
}
|
||||||
|
|
||||||
|
snapshot(panel) {
|
||||||
|
const nodes = [panel, ...panel.querySelectorAll("*")].map(node => ({ node,
|
||||||
|
children: [...node.childNodes], attributes: [...node.attributes].filter(attribute => node !== panel || attribute.name !== "open").map(attribute => [attribute.name, attribute.value]),
|
||||||
|
value: "value" in node && node.type !== "file" ? node.value : undefined,
|
||||||
|
checked: node.checked, indeterminate: node.indeterminate, selected: node.selected,
|
||||||
|
files: node.type === "file" ? [...node.files] : undefined, scrollTop: node.scrollTop, scrollLeft: node.scrollLeft,
|
||||||
|
selectionStart: node.selectionStart, selectionEnd: node.selectionEnd, selectionDirection: node.selectionDirection,
|
||||||
|
text: [...node.childNodes].filter(child => child.nodeType === 3).map(child => [child, child.data]) }));
|
||||||
|
const focus = panel.contains(this.document.activeElement) ? this.document.activeElement : null;
|
||||||
|
const range = this.document.getSelection();
|
||||||
|
const selection = !focus?.matches("input, textarea") && range?.anchorNode && panel.contains(range.anchorNode) && panel.contains(range.focusNode)
|
||||||
|
? { anchor: range.anchorNode, start: range.anchorOffset, focus: range.focusNode, end: range.focusOffset } : null;
|
||||||
|
return { nodes, focus, selection, returnValue: panel.returnValue };
|
||||||
|
}
|
||||||
|
|
||||||
|
applySnapshot(snapshot, panel) {
|
||||||
|
panel.removeAttribute("open");
|
||||||
|
for (const item of snapshot.nodes) {
|
||||||
|
const { node, children, attributes } = item;
|
||||||
|
if (node.childNodes.length !== children.length || children.some((child, index) => node.childNodes[index] !== child)) node.replaceChildren(...children);
|
||||||
|
for (const attribute of [...node.attributes]) if (!attributes.some(([name]) => name === attribute.name)) node.removeAttribute(attribute.name);
|
||||||
|
for (const [name, value] of attributes) if (node.getAttribute(name) !== value) node.setAttribute(name, value);
|
||||||
|
for (const [text, value] of item.text) text.data = value;
|
||||||
|
}
|
||||||
|
for (const item of snapshot.nodes) {
|
||||||
|
const { node } = item;
|
||||||
|
if (item.value !== undefined && node.tagName !== "SELECT") node.value = item.value;
|
||||||
|
for (const key of ["checked", "indeterminate", "selected"]) if (item[key] !== undefined) node[key] = item[key];
|
||||||
|
if (item.files !== undefined) {
|
||||||
|
const transfer = new this.document.defaultView.DataTransfer();
|
||||||
|
for (const file of item.files) transfer.items.add(file);
|
||||||
|
node.files = transfer.files;
|
||||||
|
}
|
||||||
|
if (item.selectionStart != null && typeof node.setSelectionRange === "function") node.setSelectionRange(item.selectionStart, item.selectionEnd, item.selectionDirection);
|
||||||
|
node.scrollTop = item.scrollTop;
|
||||||
|
node.scrollLeft = item.scrollLeft;
|
||||||
|
}
|
||||||
|
panel.returnValue = snapshot.returnValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
unpaint() {
|
||||||
|
for (const [node, value] of this.inert) node.inert = value;
|
||||||
|
this.inert.clear();
|
||||||
|
for (const [panel, styles] of this.styles) for (const [name, [value, priority]] of styles) {
|
||||||
|
if (value) panel.style.setProperty(name, value, priority);
|
||||||
|
else panel.style.removeProperty(name);
|
||||||
|
}
|
||||||
|
this.styles.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
paint() {
|
||||||
|
this.unpaint();
|
||||||
|
const stack = this.current()?.stack || [];
|
||||||
|
const top = stack.at(-1);
|
||||||
|
this.backdrop.hidden = !top;
|
||||||
|
if (!top) return;
|
||||||
|
const inset = Math.max(0, this.titlebar?.getBoundingClientRect().bottom || 0);
|
||||||
|
this.backdrop.style.top = `${inset}px`;
|
||||||
|
this.backdrop.style.zIndex = String(1000 + (stack.length - 1) * 2);
|
||||||
|
const disable = node => {
|
||||||
|
if (!node || node === this.titlebar || node === this.backdrop || this.records.has(node)) return;
|
||||||
|
if (node.contains(this.titlebar) || [...this.records.keys()].some(panel => node.contains(panel))) {
|
||||||
|
for (const child of node.children) disable(child);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!this.inert.has(node)) this.inert.set(node, node.inert);
|
||||||
|
node.inert = true;
|
||||||
|
};
|
||||||
|
for (const target of typeof this.targets === "function" ? this.targets() : this.targets) disable(target);
|
||||||
|
for (const [index, panel] of stack.entries()) {
|
||||||
|
if (panel !== top) { this.inert.set(panel, panel.inert); panel.inert = true; }
|
||||||
|
const values = { position: "fixed", inset: `${inset}px 0 0`, zIndex: String(1001 + index * 2), maxHeight: `calc(100dvh - ${inset + 24}px)`, "--dialog-inset": `${inset}px` };
|
||||||
|
const styles = new Map();
|
||||||
|
for (const [key, value] of Object.entries(values)) {
|
||||||
|
const name = key.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`);
|
||||||
|
styles.set(name, [panel.style.getPropertyValue(name), panel.style.getPropertyPriority(name)]);
|
||||||
|
panel.style.setProperty(name, value);
|
||||||
|
}
|
||||||
|
this.styles.set(panel, styles);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
focus(restore = false) {
|
||||||
|
const panel = this.current()?.stack.at(-1);
|
||||||
|
if (!panel || this.applicationOpen()) return;
|
||||||
|
const saved = restore ? this.current().entries.get(panel)?.snapshot?.focus || this.current().entries.get(panel)?.focus : null;
|
||||||
|
const target = saved?.isConnected && panel.contains(saved) ? saved : panel.querySelector("[autofocus], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]") || panel;
|
||||||
|
if (restore || !panel.contains(this.document.activeElement)) target.focus({ preventScroll: true });
|
||||||
|
const selection = restore && this.current().entries.get(panel)?.snapshot?.selection;
|
||||||
|
if (selection?.anchor?.isConnected && selection.focus?.isConnected) this.document.getSelection().setBaseAndExtent(selection.anchor, selection.start, selection.focus, selection.end);
|
||||||
|
if (restore) for (const item of this.current().entries.get(panel)?.snapshot?.nodes || []) { item.node.scrollTop = item.scrollTop; item.node.scrollLeft = item.scrollLeft; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function positionDropdown(list, anchor, fit = false) {
|
||||||
|
const rect = anchor.getBoundingClientRect(), viewport = window.visualViewport;
|
||||||
|
const left = viewport?.offsetLeft || 0, top = viewport?.offsetTop || 0;
|
||||||
|
const width = viewport?.width || window.innerWidth, height = viewport?.height || window.innerHeight;
|
||||||
|
if (rect.right <= left || rect.left >= left + width || rect.bottom <= top || rect.top >= top + height) return false;
|
||||||
|
const below = top + height - rect.bottom - 12, above = rect.top - top - 12;
|
||||||
|
const limit = Math.min(280, Math.max(below, above));
|
||||||
|
if (limit < 20) return false;
|
||||||
|
const minimum = Math.min(rect.width, width - 16);
|
||||||
|
Object.assign(list.style, { width: fit ? "max-content" : `${minimum}px`, minWidth: `${minimum}px`, maxWidth: `${width - 16}px`, maxHeight: `${limit}px` });
|
||||||
|
const size = list.getBoundingClientRect();
|
||||||
|
Object.assign(list.style, { left: `${Math.max(left + 8, Math.min(rect.left, left + width - size.width - 8))}px`,
|
||||||
|
top: `${below >= size.height || below >= above ? rect.bottom + 4 : rect.top - size.height - 4}px` });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function bindDropdownPointer(list, choose) {
|
||||||
|
list.addEventListener("pointerdown", event => {
|
||||||
|
if (event.pointerType !== "touch" && event.target.closest("[data-index]")) event.preventDefault();
|
||||||
|
});
|
||||||
|
list.addEventListener("mousedown", event => { if (event.target.closest("[data-index]")) event.preventDefault(); });
|
||||||
|
list.addEventListener("click", event => {
|
||||||
|
const option = event.target.closest("[data-index]");
|
||||||
|
if (option) choose(Number(option.dataset.index));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SelectPicker {
|
||||||
|
constructor(onOpen) {
|
||||||
|
Object.assign(this, { onOpen, select: null, options: [], active: -1, selected: -1, query: "", queryTime: 0, frame: 0, touchClick: false });
|
||||||
|
this.list = document.createElement("div");
|
||||||
|
this.list.className = "dropdown-list";
|
||||||
|
this.list.setAttribute("popover", "manual");
|
||||||
|
bindDropdownPointer(this.list, index => this.choose(index));
|
||||||
|
window.addEventListener("pointerdown", event => {
|
||||||
|
if (event.button !== 0) return;
|
||||||
|
this.touchClick = false;
|
||||||
|
const select = event.target.closest("select");
|
||||||
|
if (select && !select.matches(":disabled")) event.preventDefault();
|
||||||
|
if (this.select && event.target !== this.select && !this.list.contains(event.target)) this.close();
|
||||||
|
}, true);
|
||||||
|
window.addEventListener("pointerup", event => {
|
||||||
|
const select = event.target.closest("select");
|
||||||
|
if (event.pointerType !== "touch" || !select || select.matches(":disabled")) return;
|
||||||
|
event.preventDefault();
|
||||||
|
if (this.select === select) this.close();
|
||||||
|
else this.show(select);
|
||||||
|
this.touchClick = true;
|
||||||
|
}, true);
|
||||||
|
window.addEventListener("mousedown", event => {
|
||||||
|
if (event.button === 0 && event.target.closest("select")) event.preventDefault();
|
||||||
|
}, true);
|
||||||
|
window.addEventListener("click", event => {
|
||||||
|
const select = event.target.closest("select");
|
||||||
|
if (!select || select.matches(":disabled")) return;
|
||||||
|
event.preventDefault();
|
||||||
|
if (this.touchClick) { this.touchClick = false; return; }
|
||||||
|
if (this.select === select) this.close();
|
||||||
|
else this.show(select);
|
||||||
|
}, true);
|
||||||
|
window.addEventListener("keydown", event => this.keyDown(event), true);
|
||||||
|
window.addEventListener("focusin", event => {
|
||||||
|
if (this.select && event.target !== this.select && !this.list.contains(event.target)) this.close();
|
||||||
|
});
|
||||||
|
window.addEventListener("scroll", event => {
|
||||||
|
if (this.select && !this.list.contains(event.target)) this.position();
|
||||||
|
}, true);
|
||||||
|
window.addEventListener("resize", () => this.close());
|
||||||
|
window.addEventListener("blur", () => this.close());
|
||||||
|
window.addEventListener("pagehide", () => this.close());
|
||||||
|
document.addEventListener("close", event => {
|
||||||
|
if (this.select && event.target.contains(this.select)) this.close();
|
||||||
|
}, true);
|
||||||
|
document.addEventListener("reset", event => {
|
||||||
|
if (this.select?.form === event.target) this.close();
|
||||||
|
}, true);
|
||||||
|
document.addEventListener("change", event => {
|
||||||
|
if (event.target === this.select) this.render();
|
||||||
|
}, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
show(select) {
|
||||||
|
this.close();
|
||||||
|
this.onOpen?.();
|
||||||
|
select.focus({ preventScroll: true });
|
||||||
|
if (!select.isConnected || select.matches(":disabled")) return;
|
||||||
|
this.select = select;
|
||||||
|
(select.closest("dialog") || document.body).append(this.list);
|
||||||
|
this.render();
|
||||||
|
if (!this.select) return;
|
||||||
|
this.list.showPopover();
|
||||||
|
this.position();
|
||||||
|
if (!this.select) return;
|
||||||
|
this.activate(this.active);
|
||||||
|
this.observer = new MutationObserver(() => this.render());
|
||||||
|
this.observer.observe(select, { subtree: true, childList: true, characterData: true, attributes: true });
|
||||||
|
this.watch();
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
const select = this.select;
|
||||||
|
if (!select) return;
|
||||||
|
const previous = this.options[this.active]?.option, changed = this.selected !== select.selectedIndex;
|
||||||
|
this.selected = select.selectedIndex;
|
||||||
|
this.options = [...select.options].filter(option => !option.hidden && !option.parentElement.hidden).map(option => ({
|
||||||
|
option, disabled: option.disabled || option.parentElement.tagName === "OPTGROUP" && option.parentElement.disabled,
|
||||||
|
}));
|
||||||
|
if (!this.options.length) { this.close(); return; }
|
||||||
|
this.list.replaceChildren();
|
||||||
|
let group = null;
|
||||||
|
for (const [index, { option, disabled }] of this.options.entries()) {
|
||||||
|
if (option.parentElement.tagName === "OPTGROUP" && group !== option.parentElement) {
|
||||||
|
group = option.parentElement;
|
||||||
|
const heading = document.createElement("div");
|
||||||
|
heading.className = "dropdown-group";
|
||||||
|
heading.textContent = group.label;
|
||||||
|
this.list.append(heading);
|
||||||
|
}
|
||||||
|
const row = document.createElement("div");
|
||||||
|
row.className = "dropdown-option";
|
||||||
|
row.dataset.index = String(index);
|
||||||
|
row.dataset.disabled = String(disabled);
|
||||||
|
const label = document.createElement("span");
|
||||||
|
label.textContent = option.label;
|
||||||
|
row.append(label);
|
||||||
|
row.title = option.title;
|
||||||
|
this.list.append(row);
|
||||||
|
}
|
||||||
|
const selected = this.options.findIndex(({ option, disabled }) => !disabled && option === (changed ? select.selectedOptions[0] : previous));
|
||||||
|
this.activate(selected < 0 ? this.options.findIndex(({ disabled }) => !disabled) : selected);
|
||||||
|
if (this.list.matches(":popover-open")) this.position();
|
||||||
|
}
|
||||||
|
|
||||||
|
watch() {
|
||||||
|
const select = this.select;
|
||||||
|
if (!select) return;
|
||||||
|
if (!select.isConnected || select.matches(":disabled") || !select.getClientRects().length || select.closest("[hidden], [inert], dialog:not([open])")) {
|
||||||
|
this.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (this.selected !== select.selectedIndex) this.render();
|
||||||
|
if (this.select) this.frame = requestAnimationFrame(() => this.watch());
|
||||||
|
}
|
||||||
|
|
||||||
|
position() {
|
||||||
|
if (this.select && !positionDropdown(this.list, this.select, true)) this.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
activate(index) {
|
||||||
|
this.active = index;
|
||||||
|
for (const row of this.list.querySelectorAll(".dropdown-option")) {
|
||||||
|
row.dataset.selected = String(Number(row.dataset.index) === index);
|
||||||
|
if (row.dataset.selected === "true" && this.list.matches(":popover-open")) row.scrollIntoView({ block: "nearest" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
choose(index) {
|
||||||
|
const select = this.select, item = this.options[index];
|
||||||
|
if (!select || select.matches(":disabled") || !item || item.disabled || !select.contains(item.option)) return;
|
||||||
|
const changed = select.selectedIndex !== item.option.index;
|
||||||
|
select.selectedIndex = item.option.index;
|
||||||
|
this.close();
|
||||||
|
if (changed) {
|
||||||
|
select.dispatchEvent(new Event("input", { bubbles: true }));
|
||||||
|
select.dispatchEvent(new Event("change", { bubbles: true }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
close() {
|
||||||
|
if (!this.select) return;
|
||||||
|
this.observer?.disconnect();
|
||||||
|
this.observer = null;
|
||||||
|
cancelAnimationFrame(this.frame);
|
||||||
|
this.frame = 0;
|
||||||
|
this.list.hidePopover();
|
||||||
|
this.list.remove();
|
||||||
|
this.list.replaceChildren();
|
||||||
|
this.select = null;
|
||||||
|
this.options = [];
|
||||||
|
this.active = this.selected = -1;
|
||||||
|
this.query = "";
|
||||||
|
this.queryTime = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
keyDown(event) {
|
||||||
|
if (event.defaultPrevented || event.isComposing) return;
|
||||||
|
this.touchClick = false;
|
||||||
|
if (event.ctrlKey || event.metaKey || event.key === "Tab") { this.close(); return; }
|
||||||
|
const select = event.target.closest("select");
|
||||||
|
if (!select || select.matches(":disabled") || event.altKey && !["ArrowDown", "ArrowUp"].includes(event.key)) return;
|
||||||
|
const key = event.key, open = this.select === select;
|
||||||
|
if (key === "Escape") {
|
||||||
|
if (!open) return;
|
||||||
|
this.close();
|
||||||
|
} else if (key === "F4" || event.altKey) {
|
||||||
|
if (open) this.close();
|
||||||
|
else this.show(select);
|
||||||
|
} else if (["Enter", " "].includes(key)) {
|
||||||
|
if (open) this.choose(this.active);
|
||||||
|
else this.show(select);
|
||||||
|
} else if (["ArrowDown", "ArrowUp", "Home", "End", "PageDown", "PageUp"].includes(key)) {
|
||||||
|
if (!open) this.show(select);
|
||||||
|
if (this.select && (open || !["ArrowDown", "ArrowUp"].includes(key))) {
|
||||||
|
const available = this.options.flatMap(({ disabled }, index) => disabled ? [] : [index]);
|
||||||
|
const at = available.indexOf(this.active), direction = ["ArrowUp", "PageUp"].includes(key) ? -1 : 1;
|
||||||
|
const step = key.startsWith("Page") ? Math.max(1, Math.floor(this.list.clientHeight / (this.list.querySelector(".dropdown-option")?.offsetHeight || 32)) - 1) : 1;
|
||||||
|
const next = key === "Home" ? 0 : key === "End" ? available.length - 1 : Math.max(0, Math.min(available.length - 1, at + direction * step));
|
||||||
|
this.activate(available[next] ?? -1);
|
||||||
|
}
|
||||||
|
} else if (key.length === 1) {
|
||||||
|
if (!open) this.show(select);
|
||||||
|
const now = performance.now();
|
||||||
|
this.query = (now - this.queryTime < 700 ? this.query : "") + key.toLocaleLowerCase();
|
||||||
|
this.queryTime = now;
|
||||||
|
const repeated = [...this.query].every(value => value === this.query[0]), query = repeated ? this.query[0] : this.query;
|
||||||
|
const start = repeated ? this.active + 1 : Math.max(0, this.active);
|
||||||
|
for (let offset = 0; offset < this.options.length; offset++) {
|
||||||
|
const index = (start + offset) % this.options.length, item = this.options[index];
|
||||||
|
if (!item.disabled && item.option.label.trim().toLocaleLowerCase().startsWith(query)) { this.activate(index); break; }
|
||||||
|
}
|
||||||
|
} else return;
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopImmediatePropagation();
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
+141
-48
@@ -1,12 +1,15 @@
|
|||||||
importScripts("./wasm_exec.js");
|
importScripts("./wasm_exec.js");
|
||||||
|
|
||||||
let pending = Promise.resolve();
|
const engines = new Map();
|
||||||
const operations = new Map();
|
let resolveRuntime;
|
||||||
const fontRequests = new Map();
|
let rejectRuntime;
|
||||||
|
const runtimeReady = new Promise((resolve, reject) => { resolveRuntime = resolve; rejectRuntime = reject; });
|
||||||
|
runtimeReady.catch(() => {});
|
||||||
let fontSequence = 0;
|
let fontSequence = 0;
|
||||||
let engineMemory = null;
|
let engineMemory = null;
|
||||||
|
|
||||||
function requestFont(id, signal, name, done) {
|
function requestFont(engine, id, signal, name, done) {
|
||||||
|
const fontRequests = engine.fontRequests;
|
||||||
if (signal.aborted) { done(null, "", true); return; }
|
if (signal.aborted) { done(null, "", true); return; }
|
||||||
const request = ++fontSequence;
|
const request = ++fontSequence;
|
||||||
const cancel = () => {
|
const cancel = () => {
|
||||||
@@ -18,7 +21,7 @@ function requestFont(id, signal, name, done) {
|
|||||||
signal.removeEventListener("abort", cancel);
|
signal.removeEventListener("abort", cancel);
|
||||||
done(result.bytes, result.error || "", signal.aborted);
|
done(result.bytes, result.error || "", signal.aborted);
|
||||||
});
|
});
|
||||||
self.postMessage({ id, type: "font", request, name });
|
self.postMessage({ engineID: engine.id, id, type: "font", request, name });
|
||||||
}
|
}
|
||||||
self.onmessage = ({ data }) => {
|
self.onmessage = ({ data }) => {
|
||||||
if (data.type === "module") {
|
if (data.type === "module") {
|
||||||
@@ -26,20 +29,71 @@ self.onmessage = ({ data }) => {
|
|||||||
else loadWASM(data.module).catch(exitWASM);
|
else loadWASM(data.module).catch(exitWASM);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const engineID = data.engineID;
|
||||||
|
if (typeof engineID !== "string" || !engineID) {
|
||||||
|
self.postMessage({ engineID, id: data.id, ok: false, error: "missing engine ID" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (data.type === "open") {
|
||||||
|
if (engines.has(engineID)) {
|
||||||
|
self.postMessage({ engineID, type: "exit", error: "engine already exists" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const engine = { id: engineID, operations: new Map(), fontRequests: new Map(), active: new Set(), closed: false };
|
||||||
|
engines.set(engineID, engine);
|
||||||
|
engine.pending = runtimeReady.then(async () => {
|
||||||
|
if (engine.closed) return;
|
||||||
|
const opened = JSON.parse(globalThis.ofdgoEngineOpen(engineID));
|
||||||
|
if (!opened.ok) throw new Error(opened.error);
|
||||||
|
const backends = JSON.parse(await globalThis.ofdgoEngineCall(engineID, "ofdgoRenderBackends", null));
|
||||||
|
if (!backends.ok) throw new Error(backends.error);
|
||||||
|
if (!engine.closed) self.postMessage({ engineID, type: "ready", backends: backends.data, memory: engineMemory.buffer.byteLength });
|
||||||
|
}).catch(error => {
|
||||||
|
engine.closed = true;
|
||||||
|
self.postMessage({ engineID, type: "exit", error: error.message });
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const engine = engines.get(engineID);
|
||||||
|
if (!engine && data.type === "close") {
|
||||||
|
self.postMessage({ engineID, type: "closed" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!engine || engine.closed && data.type !== "close") {
|
||||||
|
self.postMessage({ engineID, id: data.id, ok: false, error: "unknown or closed engine" });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (data.type === "close") {
|
||||||
|
engine.closed = true;
|
||||||
|
for (const operation of engine.operations.values()) operation.abort();
|
||||||
|
engine.pending.then(async () => {
|
||||||
|
await Promise.all([...engine.active]);
|
||||||
|
await runtimeReady;
|
||||||
|
globalThis.ofdgoEngineClose(engineID);
|
||||||
|
engines.delete(engineID);
|
||||||
|
self.postMessage({ engineID, type: "closed" });
|
||||||
|
}).catch(() => engines.delete(engineID));
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (data.type === "font") {
|
if (data.type === "font") {
|
||||||
fontRequests.get(data.request)?.(data);
|
engine.fontRequests.get(data.request)?.(data);
|
||||||
fontRequests.delete(data.request);
|
engine.fontRequests.delete(data.request);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (data.type === "cancel") {
|
if (data.type === "cancel") {
|
||||||
operations.get(data.id)?.abort();
|
engine.operations.get(data.id)?.abort();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (data.name === "ofdgoResources") operations.set(data.id, new AbortController());
|
engine.operations.set(data.id, new AbortController());
|
||||||
if (data.name === "ofdgoImportDocuments" || data.name === "ofdgoImportImages" || data.name === "ofdgoExportImages" || data.name === "ofdgoConvertFile" || data.name === "ofdgoPackFiles" || data.name === "ofdgoConvertPDF" || data.name === "ofdgoExportPage" || data.name === "ofdgoExportDocument" || data.name === "ofdgoExportAttachment" || data.name === "ofdgoExportResource" || data.name === "ofdgoExportMedia" || data.name === "ofdgoExportVersion" || data.name === "ofdgoSaveDocument" || data.name === "ofdgoSaveSigned" || data.name === "ofdgoImportPages") {
|
engine.pending = engine.pending.then(() => {
|
||||||
operations.set(data.id, new AbortController());
|
const operation = (data.name === "ofdgoConvertFile" || data.name === "ofdgoPackFiles" ? handleBatchMessage(engine, data) : handleMessage(engine, data)).catch(error => {
|
||||||
}
|
engine.operations.delete(data.id);
|
||||||
pending = pending.then(() => data.name === "ofdgoConvertFile" || data.name === "ofdgoPackFiles" ? handleBatchMessage(data) : handleMessage(data));
|
self.postMessage({ engineID, id: data.id, ok: false, error: error.message });
|
||||||
|
});
|
||||||
|
engine.active.add(operation);
|
||||||
|
operation.finally(() => engine.active.delete(operation));
|
||||||
|
if (data.name !== "ofdgoSaveSnapshot") return operation;
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
async function availableOutput(directory, base, format) {
|
async function availableOutput(directory, base, format) {
|
||||||
@@ -55,7 +109,9 @@ async function availableOutput(directory, base, format) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleBatchMessage({ id, name, args }) {
|
async function handleBatchMessage(engine, { id, name, args }) {
|
||||||
|
const operations = engine.operations;
|
||||||
|
const postMessage = (data, transfer) => self.postMessage({ ...data, engineID: engine.id }, transfer);
|
||||||
const signal = operations.get(id).signal;
|
const signal = operations.get(id).signal;
|
||||||
const channel = new MessageChannel();
|
const channel = new MessageChannel();
|
||||||
const finish = (done, err) => {
|
const finish = (done, err) => {
|
||||||
@@ -85,7 +141,7 @@ async function handleBatchMessage({ id, name, args }) {
|
|||||||
if (name === "ofdgoConvertFile") {
|
if (name === "ofdgoConvertFile") {
|
||||||
const [file, options, fonts, destination] = args;
|
const [file, options, fonts, destination] = args;
|
||||||
credentials = options.credentials;
|
credentials = options.credentials;
|
||||||
const formats = JSON.parse(globalThis.ofdgoOutputFormats()).data;
|
const formats = JSON.parse(await globalThis.ofdgoEngineCall(engine.id, "ofdgoOutputFormats", null)).data;
|
||||||
const format = formats.find(item => item.value === options.format);
|
const format = formats.find(item => item.value === options.format);
|
||||||
if (!format) throw new Error("不支持此格式");
|
if (!format) throw new Error("不支持此格式");
|
||||||
root = destination;
|
root = destination;
|
||||||
@@ -96,7 +152,7 @@ async function handleBatchMessage({ id, name, args }) {
|
|||||||
if (format.paged) directory = await root.getDirectoryHandle(target.name, { create: true });
|
if (format.paged) directory = await root.getDirectoryHandle(target.name, { create: true });
|
||||||
else { await root.getFileHandle(target.name, { create: true }); directory = root; }
|
else { await root.getFileHandle(target.name, { create: true }); directory = root; }
|
||||||
created = target.name;
|
created = target.name;
|
||||||
self.postMessage({ id, type: "output", name: created });
|
postMessage({ id, type: "output", name: created });
|
||||||
return target;
|
return target;
|
||||||
}) : { stem: base, name: format.paged ? base : `${base}.${format.extension}` };
|
}) : { stem: base, name: format.paged ? base : `${base}.${format.extension}` };
|
||||||
const boundary = async (action, pageName) => {
|
const boundary = async (action, pageName) => {
|
||||||
@@ -109,7 +165,7 @@ async function handleBatchMessage({ id, name, args }) {
|
|||||||
const handle = await directory.getFileHandle(fileName, { create: true });
|
const handle = await directory.getFileHandle(fileName, { create: true });
|
||||||
if (!format.paged) {
|
if (!format.paged) {
|
||||||
created = fileName;
|
created = fileName;
|
||||||
self.postMessage({ id, type: "output", name: created });
|
postMessage({ id, type: "output", name: created });
|
||||||
}
|
}
|
||||||
current.handle = handle;
|
current.handle = handle;
|
||||||
output = await handle.createWritable();
|
output = await handle.createWritable();
|
||||||
@@ -122,19 +178,19 @@ async function handleBatchMessage({ id, name, args }) {
|
|||||||
chunks = [];
|
chunks = [];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
payload = await globalThis.ofdgoConvertFile(read(file), file.size, options, write,
|
payload = await globalThis.ofdgoEngineCall(engine.id, "ofdgoConvertFile", done => finish(done), read(file), file.size, options, write,
|
||||||
(phase, completed, total, done) => {
|
(phase, completed, total, done) => {
|
||||||
self.postMessage({ id, type: "conversion", phase, completed, total });
|
postMessage({ id, type: "conversion", phase, completed, total, memory: engineMemory.buffer.byteLength });
|
||||||
finish(done);
|
finish(done);
|
||||||
},
|
},
|
||||||
(action, pageName, done) => boundary(action, pageName).then(() => finish(done), err => finish(done, err)),
|
(action, pageName, done) => boundary(action, pageName).then(() => finish(done), err => finish(done, err)),
|
||||||
done => finish(done), fonts, (name, done) => requestFont(id, signal, name, done));
|
done => finish(done), fonts, (name, done) => requestFont(engine, id, signal, name, done));
|
||||||
} else {
|
} else {
|
||||||
const [entries, handle, compression] = args;
|
const [entries, handle, compression] = args;
|
||||||
if (handle) output = await handle.createWritable();
|
if (handle) output = await handle.createWritable();
|
||||||
payload = await globalThis.ofdgoPackFiles(entries.map(entry => ({ name: entry.name, size: entry.file.size })),
|
payload = await globalThis.ofdgoEngineCall(engine.id, "ofdgoPackFiles", done => finish(done), entries.map(entry => ({ name: entry.name, size: entry.file.size })),
|
||||||
index => read(entries[index].file), write,
|
index => read(entries[index].file), write,
|
||||||
(completed, total, done) => { self.postMessage({ id, type: "conversion", phase: "pack", completed, total }); finish(done); },
|
(completed, total, done) => { postMessage({ id, type: "conversion", phase: "pack", completed, total, memory: engineMemory.buffer.byteLength }); finish(done); },
|
||||||
done => finish(done), compression);
|
done => finish(done), compression);
|
||||||
}
|
}
|
||||||
signal.throwIfAborted();
|
signal.throwIfAborted();
|
||||||
@@ -153,7 +209,7 @@ async function handleBatchMessage({ id, name, args }) {
|
|||||||
}
|
}
|
||||||
result.data.size = size;
|
result.data.size = size;
|
||||||
operations.delete(id);
|
operations.delete(id);
|
||||||
self.postMessage({ id, ...result, memory: engineMemory.buffer.byteLength });
|
postMessage({ id, ...result, memory: engineMemory.buffer.byteLength });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await output?.abort().catch(() => {});
|
await output?.abort().catch(() => {});
|
||||||
let message = signal.aborted ? "转换已取消" : err.message;
|
let message = signal.aborted ? "转换已取消" : err.message;
|
||||||
@@ -161,7 +217,7 @@ async function handleBatchMessage({ id, name, args }) {
|
|||||||
try { await root.removeEntry(created, { recursive: true }); }
|
try { await root.removeEntry(created, { recursive: true }); }
|
||||||
catch (cleanupError) { message += `;清理失败:${cleanupError.message}`; }
|
catch (cleanupError) { message += `;清理失败:${cleanupError.message}`; }
|
||||||
}
|
}
|
||||||
self.postMessage({ id, ok: false, error: message, code: err.code, canceled: signal.aborted, memory: engineMemory.buffer.byteLength });
|
postMessage({ id, ok: false, error: message, code: err.code, canceled: signal.aborted, memory: engineMemory.buffer.byteLength });
|
||||||
} finally {
|
} finally {
|
||||||
credentials?.password?.fill(0);
|
credentials?.password?.fill(0);
|
||||||
credentials?.key?.fill(0);
|
credentials?.key?.fill(0);
|
||||||
@@ -171,19 +227,32 @@ async function handleBatchMessage({ id, name, args }) {
|
|||||||
operations.delete(id);
|
operations.delete(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async function handleMessage({ id, name, args }) {
|
async function handleMessage(engine, { id, name, args }) {
|
||||||
|
const operations = engine.operations;
|
||||||
|
const postMessage = (data, transfer) => self.postMessage({ ...data, engineID: engine.id }, transfer);
|
||||||
let output;
|
let output;
|
||||||
|
let saveFile;
|
||||||
|
let saveStamp;
|
||||||
let channel;
|
let channel;
|
||||||
const signal = operations.get(id)?.signal;
|
const signal = operations.get(id)?.signal;
|
||||||
|
const cancellable = ["ofdgoPreparePrint", "ofdgoLayoutPrint", "ofdgoPrintSide", "ofdgoPrintPDF", "ofdgoResources", "ofdgoPrepareSave", "ofdgoSaveSnapshot", "ofdgoImportDocuments", "ofdgoImportImages", "ofdgoExportImages", "ofdgoOpenPDF", "ofdgoExportPage", "ofdgoExportDocument", "ofdgoExportAttachment", "ofdgoExportResource", "ofdgoExportMedia", "ofdgoExportVersion", "ofdgoSaveDocument", "ofdgoSaveSigned", "ofdgoImportPages"].includes(name);
|
||||||
const importing = name === "ofdgoImportPages" || name === "ofdgoImportImages" || name === "ofdgoImportDocuments";
|
const importing = name === "ofdgoImportPages" || name === "ofdgoImportImages" || name === "ofdgoImportDocuments";
|
||||||
const converting = name === "ofdgoConvertPDF";
|
const converting = name === "ofdgoOpenPDF";
|
||||||
const saving = name === "ofdgoSaveDocument" || name === "ofdgoSaveSigned";
|
const saving = name === "ofdgoSaveDocument" || name === "ofdgoSaveSnapshot" || name === "ofdgoSaveSigned";
|
||||||
const resources = name === "ofdgoResources";
|
const resources = ["ofdgoPreparePrint", "ofdgoLayoutPrint", "ofdgoPrintSide", "ofdgoPrintPDF", "ofdgoResources", "ofdgoPrepareSave"].includes(name);
|
||||||
|
if (engine.pdf) {
|
||||||
|
const checked = JSON.parse(await globalThis.ofdgoEngineCall(engine.id, "ofdgoCheckDocument", null, name));
|
||||||
|
if (!checked.ok) { postMessage({id, ...checked}); operations.delete(id); return; }
|
||||||
|
}
|
||||||
const key = name === "ofdgoOpen" ? args[3]?.key : name === "ofdgoSaveSigned" || name === "ofdgoLoadImport" ? args[1]?.key : null;
|
const key = name === "ofdgoOpen" ? args[3]?.key : name === "ofdgoSaveSigned" || name === "ofdgoLoadImport" ? args[1]?.key : null;
|
||||||
const keyPassword = name === "ofdgoOpen" ? args[3]?.keyPassword : name === "ofdgoSaveSigned" || name === "ofdgoLoadImport" ? args[1]?.keyPassword : null;
|
const keyPassword = name === "ofdgoOpen" ? args[3]?.keyPassword : name === "ofdgoSaveSigned" || name === "ofdgoLoadImport" ? args[1]?.keyPassword : null;
|
||||||
const password = converting ? args[2] : name === "ofdgoSetEncryption" ? args[0]?.password : name === "ofdgoOpen" ? args[3]?.password : name === "ofdgoLoadImport" ? args[1]?.password : null;
|
const password = converting ? args[2] : name === "ofdgoSetEncryption" ? args[0]?.password : name === "ofdgoOpen" ? args[3]?.password : name === "ofdgoLoadImport" ? args[1]?.password : null;
|
||||||
try {
|
try {
|
||||||
signal?.throwIfAborted();
|
signal?.throwIfAborted();
|
||||||
|
if (["ofdgoOpen", "ofdgoOpenPDF", "ofdgoLoadImport"].includes(name) && args[0] instanceof Blob) {
|
||||||
|
const file = args[0], reader = new FileReaderSync();
|
||||||
|
args[0] = {size: file.size, read: (offset, size) => new Uint8Array(reader.readAsArrayBuffer(file.slice(offset, offset + size)))};
|
||||||
|
}
|
||||||
if (name === "ofdgoDetectFormat") {
|
if (name === "ofdgoDetectFormat") {
|
||||||
const file = args[0], reader = new FileReaderSync();
|
const file = args[0], reader = new FileReaderSync();
|
||||||
channel = new MessageChannel();
|
channel = new MessageChannel();
|
||||||
@@ -212,7 +281,7 @@ async function handleMessage({ id, name, args }) {
|
|||||||
}
|
}
|
||||||
const chunks = [];
|
const chunks = [];
|
||||||
let size = 0;
|
let size = 0;
|
||||||
if (signal) {
|
if (cancellable) {
|
||||||
channel = new MessageChannel();
|
channel = new MessageChannel();
|
||||||
const finish = (done, err, commit = false) => {
|
const finish = (done, err, commit = false) => {
|
||||||
channel.port1.onmessage = () => {
|
channel.port1.onmessage = () => {
|
||||||
@@ -225,12 +294,15 @@ async function handleMessage({ id, name, args }) {
|
|||||||
args.push(done => finish(done));
|
args.push(done => finish(done));
|
||||||
} else if (importing || converting) {
|
} else if (importing || converting) {
|
||||||
args.push((phase, completed, total, done) => {
|
args.push((phase, completed, total, done) => {
|
||||||
self.postMessage({ id, type: importing ? "import" : "conversion", phase, completed, total });
|
postMessage({ id, type: importing ? "import" : "conversion", phase, completed, total });
|
||||||
finish(done, null, importing && phase === "commit");
|
finish(done, null, importing && phase === "commit");
|
||||||
});
|
});
|
||||||
if (converting) args.push((name, done) => requestFont(id, signal, name, done));
|
if (converting) args.push((name, done) => requestFont(engine, id, signal, name, done));
|
||||||
} else {
|
} else {
|
||||||
const file = args.pop();
|
const destination = args.pop();
|
||||||
|
const file = destination?.fileHandle || destination;
|
||||||
|
saveFile = file;
|
||||||
|
saveStamp = destination?.saveStamp;
|
||||||
const compression = saving && name !== "ofdgoSaveSigned" && args.at(-1)?.mode !== undefined ? args.pop() : null;
|
const compression = saving && name !== "ofdgoSaveSigned" && args.at(-1)?.mode !== undefined ? args.pop() : null;
|
||||||
const indices = saving ? args.shift() : null;
|
const indices = saving ? args.shift() : null;
|
||||||
if (file) output = await file.createWritable();
|
if (file) output = await file.createWritable();
|
||||||
@@ -250,33 +322,55 @@ async function handleMessage({ id, name, args }) {
|
|||||||
});
|
});
|
||||||
if (name === "ofdgoExportDocument") {
|
if (name === "ofdgoExportDocument") {
|
||||||
args.push((completed, total, done) => {
|
args.push((completed, total, done) => {
|
||||||
self.postMessage({ id, type: "export", stage: "pages", completed, total });
|
postMessage({ id, type: "export", stage: "pages", completed, total });
|
||||||
finish(done);
|
finish(done);
|
||||||
});
|
});
|
||||||
} else if (name === "ofdgoExportVersion") {
|
} else if (name === "ofdgoExportVersion") {
|
||||||
args.push((phase, completed, total, done) => {
|
args.push((phase, completed, total, done) => {
|
||||||
self.postMessage({ id, type: "export", stage: "prepare", phase, completed, total });
|
postMessage({ id, type: "export", stage: "prepare", phase, completed, total });
|
||||||
finish(done);
|
finish(done);
|
||||||
}, done => finish(done));
|
}, done => finish(done));
|
||||||
} else if (saving) {
|
} else if (saving) {
|
||||||
args.push((phase, completed, total, done) => {
|
args.push((phase, completed, total, done) => {
|
||||||
self.postMessage({ id, type: "export", stage: "prepare", phase, completed, total });
|
postMessage({ id, type: "export", stage: "prepare", phase, completed, total });
|
||||||
finish(done);
|
finish(done);
|
||||||
});
|
});
|
||||||
if (compression) args.push(indices, compression, done => finish(done));
|
if (compression || name === "ofdgoSaveSnapshot") args.push(indices, compression || {mode: 0}, done => finish(done));
|
||||||
else if (indices != null) args.push(indices);
|
else if (indices != null) args.push(indices);
|
||||||
}
|
}
|
||||||
if (!saving && args.some(value => value?.mode !== undefined)) args.push(done => finish(done));
|
if (!saving && args.some(value => value?.mode !== undefined)) args.push(done => finish(done));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const payload = await globalThis[name](...args);
|
if (engine.pdf && name !== "ofdgoOpenPDF") {
|
||||||
|
channel ||= new MessageChannel();
|
||||||
|
const context = await globalThis.ofdgoEngineCall(engine.id, "ofdgoPDFContext", null, (phase, completed, total, done) => {
|
||||||
|
postMessage({id, type: "conversion", phase, completed, total});
|
||||||
|
channel.port1.onmessage = () => done("", signal.aborted);
|
||||||
|
channel.port2.postMessage(null);
|
||||||
|
}, (name, done) => requestFont(engine, id, signal, name, done));
|
||||||
|
engine.pdf = JSON.parse(context).data === true;
|
||||||
|
}
|
||||||
|
const started = name === "ofdgoOpen" || name === "ofdgoRenderPage" ? performance.now() : null;
|
||||||
|
const payload = await globalThis.ofdgoEngineCall(engine.id, name, done => {
|
||||||
|
channel ||= new MessageChannel();
|
||||||
|
channel.port1.onmessage = () => done("", signal.aborted);
|
||||||
|
channel.port2.postMessage(null);
|
||||||
|
}, ...args);
|
||||||
signal?.throwIfAborted();
|
signal?.throwIfAborted();
|
||||||
const result = typeof payload === "string" ? JSON.parse(payload) : payload;
|
const result = typeof payload === "string" ? JSON.parse(payload) : payload;
|
||||||
if (signal && !importing && !converting && !resources && result.ok) {
|
if (result.ok && name === "ofdgoOpenPDF") engine.pdf = true;
|
||||||
operations.delete(id);
|
if (result.ok && (name === "ofdgoOpen" || name === "ofdgoLoadPDF" && result.data.done)) engine.pdf = false;
|
||||||
|
if (started !== null && result.ok) result.elapsed = performance.now() - started;
|
||||||
|
if (cancellable && !importing && !converting && !resources && result.ok) {
|
||||||
result.data.size = size;
|
result.data.size = size;
|
||||||
if (name !== "ofdgoExportMedia") self.postMessage({ id, type: "export", stage: "save" });
|
if (name !== "ofdgoExportMedia") postMessage({ id, type: "export", stage: "save" });
|
||||||
if (output) {
|
if (output) {
|
||||||
|
if (saveStamp) {
|
||||||
|
const current = await saveFile.getFile();
|
||||||
|
if (current.size !== saveStamp.size || current.lastModified !== saveStamp.modified) throw new Error("文件已被修改,请另存");
|
||||||
|
}
|
||||||
|
signal.throwIfAborted();
|
||||||
|
operations.delete(id);
|
||||||
await output.close();
|
await output.close();
|
||||||
} else {
|
} else {
|
||||||
result.data.blob = new Blob(chunks, { type: result.data.mime });
|
result.data.blob = new Blob(chunks, { type: result.data.mime });
|
||||||
@@ -285,16 +379,16 @@ async function handleMessage({ id, name, args }) {
|
|||||||
await output.abort();
|
await output.abort();
|
||||||
}
|
}
|
||||||
output = null;
|
output = null;
|
||||||
const transfer = result.data?.bytes ? [result.data.bytes.buffer] : (result.data?.images || []).map((image) => image.bytes.buffer);
|
const transfer = [...new Set([result.data?.bytes, ...(result.data?.images || []).map(image => image.bytes), ...(result.data?.fonts || []).map(font => font.data)].filter(bytes => bytes?.byteLength).map(bytes => bytes.buffer))];
|
||||||
self.postMessage({ id, ...result }, transfer);
|
postMessage({ id, ...result, memory: engineMemory.buffer.byteLength }, transfer);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await output?.abort().catch(() => {});
|
await output?.abort().catch(() => {});
|
||||||
const result = { id, ok: false, error: err.message };
|
const result = { id, ok: false, error: err.message, errorName: err.name };
|
||||||
if (signal?.aborted) {
|
if (signal?.aborted) {
|
||||||
result.error = resources ? "查询已取消" : importing ? "导入已取消" : converting ? "转换已取消" : "导出已取消";
|
result.error = resources ? "查询已取消" : importing ? "导入已取消" : converting ? "转换已取消" : cancellable ? "导出已取消" : "操作已取消";
|
||||||
result.canceled = true;
|
result.canceled = true;
|
||||||
}
|
}
|
||||||
self.postMessage(result);
|
postMessage(result);
|
||||||
} finally {
|
} finally {
|
||||||
password?.fill(0);
|
password?.fill(0);
|
||||||
key?.fill(0);
|
key?.fill(0);
|
||||||
@@ -306,6 +400,7 @@ async function handleMessage({ id, name, args }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function exitWASM(err) {
|
function exitWASM(err) {
|
||||||
|
rejectRuntime(err || new Error("引擎运行中断"));
|
||||||
self.postMessage({ type: "exit", error: err?.message || "引擎运行中断" });
|
self.postMessage({ type: "exit", error: err?.message || "引擎运行中断" });
|
||||||
self.close();
|
self.close();
|
||||||
}
|
}
|
||||||
@@ -317,9 +412,7 @@ async function loadWASM(module) {
|
|||||||
self.postMessage({ type: "progress", phase: "start", text: "正在启动引擎", percent: 58 });
|
self.postMessage({ type: "progress", phase: "start", text: "正在启动引擎", percent: 58 });
|
||||||
go.run(instance).then(exitWASM, exitWASM);
|
go.run(instance).then(exitWASM, exitWASM);
|
||||||
if (!go.exited) {
|
if (!go.exited) {
|
||||||
const backends = JSON.parse(globalThis.ofdgoRenderBackends());
|
resolveRuntime();
|
||||||
if (!backends.ok) throw new Error(backends.error);
|
|
||||||
self.postMessage({ type: "ready", backends: backends.data });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
const CACHE_PREFIX = `ofdgo:${self.registration.scope}:app:`;
|
const CACHE_PREFIX = `ofdgo:${self.registration.scope}:app:`;
|
||||||
const META_CACHE = `${CACHE_PREFIX}meta`;
|
const META_CACHE = `${CACHE_PREFIX}meta`;
|
||||||
const ASSETS = ["./", "ofdgo.css", "ofdgo.ico", "ofdgo.js", "ofdgo.json", "ofdgo.png", "ofdgo.svg", "ofdgo.wasm", "ofdgo_edit.js", "ofdgo_font.js", "ofdgo_host.js", "ofdgo_wasm.js", "ofdgo_work.js", "wasm_exec.js"]
|
const ASSETS = ["./", "ofdgo.css", "ofdgo.ico", "ofdgo.js", "ofdgo.json", "ofdgo.png", "ofdgo.svg", "ofdgo.wasm", "ofdgo_edit.js", "ofdgo_font.js", "ofdgo_host.js", "ofdgo_print.js", "ofdgo_theme.js", "ofdgo_util.js", "ofdgo_view.js", "ofdgo_wasm.js", "ofdgo_work.js", "wasm_exec.js"]
|
||||||
.map((path) => new URL(path, self.registration.scope).href);
|
.map((path) => new URL(path, self.registration.scope).href);
|
||||||
const CLIENT_PREFIX = new URL("__client/", self.registration.scope).href;
|
const CLIENT_PREFIX = new URL("__client/", self.registration.scope).href;
|
||||||
|
|
||||||
@@ -92,6 +92,8 @@ async function readResource(event, navigation) {
|
|||||||
bundle = await readBundle(meta, CLIENT_PREFIX + event.clientId);
|
bundle = await readBundle(meta, CLIENT_PREFIX + event.clientId);
|
||||||
}
|
}
|
||||||
if (!bundle || !await caches.has(bundle.name)) {
|
if (!bundle || !await caches.has(bundle.name)) {
|
||||||
|
const client = await self.clients.get(event.clientId);
|
||||||
|
if (client && resourceURL(client.url) !== self.registration.scope) return fetch(event.request);
|
||||||
return Response.error();
|
return Response.error();
|
||||||
}
|
}
|
||||||
if (event.resultingClientId) {
|
if (event.resultingClientId) {
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
setlocal
|
||||||
|
set Version=
|
||||||
|
for /f %%V in ('git show -s --format^=%%ct-%%H HEAD') do set Version=%%V
|
||||||
|
|
||||||
|
set GOOS=linux
|
||||||
|
set GOARCH=arm64
|
||||||
|
set CGO_ENABLED=0
|
||||||
|
go build -o releases/ofdgo_linux_arm64 -trimpath -ldflags "-s -w -buildid= -X github.com/xiaoqidun/ofdgo/internal/build.Version=%Version%" ./cmd/webview
|
||||||
|
|
||||||
|
set GOOS=linux
|
||||||
|
set GOARCH=amd64
|
||||||
|
set CGO_ENABLED=0
|
||||||
|
go build -o releases/ofdgo_linux_amd64 -trimpath -ldflags "-s -w -buildid= -X github.com/xiaoqidun/ofdgo/internal/build.Version=%Version%" ./cmd/webview
|
||||||
|
|
||||||
|
set GOOS=windows
|
||||||
|
set GOARCH=amd64
|
||||||
|
set CGO_ENABLED=0
|
||||||
|
go build -o releases/ofdgo_windows_amd64.exe -trimpath -ldflags "-H windowsgui -s -w -buildid= -X github.com/xiaoqidun/ofdgo/internal/build.Version=%Version%" ./cmd/webview
|
||||||
@@ -29,6 +29,7 @@ import (
|
|||||||
|
|
||||||
"github.com/xiaoqidun/ofdgo/assets/webui"
|
"github.com/xiaoqidun/ofdgo/assets/webui"
|
||||||
"github.com/xiaoqidun/ofdgo/assets/webui/wasm"
|
"github.com/xiaoqidun/ofdgo/assets/webui/wasm"
|
||||||
|
"github.com/xiaoqidun/ofdgo/internal/build"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -50,6 +51,7 @@ func serveWebUI() http.Handler {
|
|||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Cache-Control", "no-store")
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
w.Header().Set("X-OFDGo-Checksum", checksum)
|
w.Header().Set("X-OFDGo-Checksum", checksum)
|
||||||
|
w.Header().Set("X-OFDGo-Build-Version", build.Version)
|
||||||
if r.URL.Path == "/ofdgo.wasm" {
|
if r.URL.Path == "/ofdgo.wasm" {
|
||||||
wasm.ServeHTTP(w, r)
|
wasm.ServeHTTP(w, r)
|
||||||
return
|
return
|
||||||
|
|||||||
+36
-17
@@ -12,29 +12,48 @@
|
|||||||
// See the License for the specific language governing permissions and
|
// See the License for the specific language governing permissions and
|
||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
|
|
||||||
//go:build windows && amd64
|
//go:build (windows && amd64) || (linux && (amd64 || arm64))
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"flag"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
"os"
|
||||||
"syscall"
|
"strings"
|
||||||
"unsafe"
|
|
||||||
|
|
||||||
"github.com/xiaoqidun/ofdgo/internal/webview"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
// commandLine 读取桌面参数并处理参数错误
|
||||||
dataDir := flag.String("data-dir", "", "browser data directory")
|
// 返回: []string 文件路径, string 浏览器数据目录
|
||||||
flag.Parse()
|
func commandLine() ([]string, string) {
|
||||||
if err := webview.Run(context.Background(), flag.Args(), *dataDir); err != nil {
|
paths, dataDir, ok := parseArguments(os.Args[1:])
|
||||||
fmt.Fprintln(os.Stderr, err)
|
if !ok {
|
||||||
message, _ := syscall.UTF16PtrFromString(err.Error())
|
os.Exit(2)
|
||||||
title, _ := syscall.UTF16PtrFromString("OFDGo")
|
|
||||||
syscall.NewLazyDLL("user32.dll").NewProc("MessageBoxW").Call(0, uintptr(unsafe.Pointer(message)), uintptr(unsafe.Pointer(title)), 0x10)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
}
|
||||||
|
return paths, dataDir
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseArguments 解析双横线选项及后续文件路径
|
||||||
|
// 入参: args 启动参数
|
||||||
|
// 返回: []string 文件路径, string 浏览器数据目录, bool 参数是否有效
|
||||||
|
func parseArguments(args []string) ([]string, string, bool) {
|
||||||
|
var dataDir string
|
||||||
|
for len(args) > 0 {
|
||||||
|
arg := args[0]
|
||||||
|
switch {
|
||||||
|
case arg == "--":
|
||||||
|
return args[1:], dataDir, true
|
||||||
|
case arg == "--data-dir":
|
||||||
|
if len(args) < 2 || strings.HasPrefix(args[1], "-") {
|
||||||
|
return nil, dataDir, false
|
||||||
|
}
|
||||||
|
dataDir, args = args[1], args[1:]
|
||||||
|
case strings.HasPrefix(arg, "--data-dir="):
|
||||||
|
dataDir = strings.TrimPrefix(arg, "--data-dir=")
|
||||||
|
case strings.HasPrefix(arg, "-"):
|
||||||
|
return nil, dataDir, false
|
||||||
|
default:
|
||||||
|
return args, dataDir, true
|
||||||
|
}
|
||||||
|
args = args[1:]
|
||||||
|
}
|
||||||
|
return nil, dataDir, true
|
||||||
}
|
}
|
||||||
@@ -12,18 +12,22 @@
|
|||||||
// See the License for the specific language governing permissions and
|
// See the License for the specific language governing permissions and
|
||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
|
|
||||||
//go:build !windows
|
//go:build linux && (amd64 || arm64)
|
||||||
|
|
||||||
package webview
|
package main
|
||||||
|
|
||||||
import "os"
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
// openReadFile 打开独立读取句柄
|
"github.com/xiaoqidun/ofdgo/internal/webview"
|
||||||
func openReadFile(name string) (*os.File, error) {
|
)
|
||||||
return os.Open(name)
|
|
||||||
|
func main() {
|
||||||
|
paths, dataDir := commandLine()
|
||||||
|
if err := webview.Run(context.Background(), paths, dataDir); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// replaceFile 替换目标文件并保留已有读取句柄
|
|
||||||
func replaceFile(source, target string) error {
|
|
||||||
return os.Rename(source, target)
|
|
||||||
}
|
}
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
// See the License for the specific language governing permissions and
|
// See the License for the specific language governing permissions and
|
||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
|
|
||||||
//go:build !windows || !amd64
|
//go:build !(windows && amd64) && !(linux && (amd64 || arm64))
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
//go:build windows && amd64
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"github.com/xiaoqidun/ofdgo/internal/webview"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
paths, dataDir := commandLine()
|
||||||
|
if err := webview.Run(context.Background(), paths, dataDir); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
message, _ := syscall.UTF16PtrFromString(err.Error())
|
||||||
|
title, _ := syscall.UTF16PtrFromString("OFDGo")
|
||||||
|
syscall.NewLazyDLL("user32.dll").NewProc("MessageBoxW").Call(0, uintptr(unsafe.Pointer(message)), uintptr(unsafe.Pointer(title)), 0x10)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,17 +3,18 @@ module github.com/xiaoqidun/ofdgo
|
|||||||
go 1.26.0
|
go 1.26.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/andybalholm/brotli v1.2.6
|
github.com/andybalholm/brotli v1.2.7
|
||||||
github.com/emmansun/gmsm v0.45.0
|
github.com/emmansun/gmsm v0.45.1
|
||||||
github.com/go-text/typesetting v0.3.5
|
github.com/go-text/typesetting v0.3.5
|
||||||
github.com/tdewolff/canvas v0.0.0-20260923214215-09804640d00c
|
github.com/tdewolff/canvas v0.0.0-20260923214215-09804640d00c
|
||||||
github.com/tdewolff/font v0.0.0-20261010204837-88a7f6b56918
|
github.com/tdewolff/font v0.0.0-20261010204837-88a7f6b56918
|
||||||
github.com/xiaoqidun/guigo v0.0.0-20261017165144-57ca5ff5f547
|
github.com/xiaoqidun/guigo v0.0.0-20261030045545-8b12eb7ed706
|
||||||
github.com/xiaoqidun/j2kgo v1.0.2
|
github.com/xiaoqidun/j2kgo v1.0.2
|
||||||
github.com/xiaoqidun/jbig2 v1.1.8
|
github.com/xiaoqidun/jbig2 v1.1.8
|
||||||
github.com/xiaoqidun/pdfgo v0.0.0-20261017161421-0b88b77eefc9
|
github.com/xiaoqidun/pdfgo v0.0.0-20261026125713-90454771d5d0
|
||||||
golang.org/x/crypto v0.58.0
|
golang.org/x/crypto v0.58.0
|
||||||
golang.org/x/image v0.47.0
|
golang.org/x/image v0.47.0
|
||||||
|
golang.org/x/sys v0.49.0
|
||||||
golang.org/x/text v0.43.0
|
golang.org/x/text v0.43.0
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -26,6 +27,7 @@ require (
|
|||||||
github.com/ByteArena/poly2tri-go v0.0.0-20170716161910-d102ad91854f // indirect
|
github.com/ByteArena/poly2tri-go v0.0.0-20170716161910-d102ad91854f // indirect
|
||||||
github.com/benoitkugler/textlayout v0.3.2 // indirect
|
github.com/benoitkugler/textlayout v0.3.2 // indirect
|
||||||
github.com/benoitkugler/textprocessing v0.0.6 // indirect
|
github.com/benoitkugler/textprocessing v0.0.6 // indirect
|
||||||
|
github.com/ebitengine/purego v0.11.2 // indirect
|
||||||
github.com/go-fonts/latin-modern v0.3.3 // indirect
|
github.com/go-fonts/latin-modern v0.3.3 // indirect
|
||||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
|
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
|
||||||
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef // indirect
|
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef // indirect
|
||||||
@@ -34,7 +36,6 @@ require (
|
|||||||
github.com/tdewolff/parse/v2 v2.8.16 // indirect
|
github.com/tdewolff/parse/v2 v2.8.16 // indirect
|
||||||
github.com/yuin/goldmark v1.8.5 // indirect
|
github.com/yuin/goldmark v1.8.5 // indirect
|
||||||
golang.org/x/net v0.60.0 // indirect
|
golang.org/x/net v0.60.0 // indirect
|
||||||
golang.org/x/sys v0.49.0 // indirect
|
|
||||||
modernc.org/knuth v0.6.0 // indirect
|
modernc.org/knuth v0.6.0 // indirect
|
||||||
modernc.org/token v1.1.0 // indirect
|
modernc.org/token v1.1.0 // indirect
|
||||||
star-tex.org/x/tex v0.7.1 // indirect
|
star-tex.org/x/tex v0.7.1 // indirect
|
||||||
|
|||||||
@@ -20,16 +20,18 @@ github.com/ByteArena/poly2tri-go v0.0.0-20170716161910-d102ad91854f h1:l7moT9o/v
|
|||||||
github.com/ByteArena/poly2tri-go v0.0.0-20170716161910-d102ad91854f/go.mod h1:vIOkSdX3NDCPwgu8FIuTat2zDF0FPXXQ0RYFRy+oQic=
|
github.com/ByteArena/poly2tri-go v0.0.0-20170716161910-d102ad91854f/go.mod h1:vIOkSdX3NDCPwgu8FIuTat2zDF0FPXXQ0RYFRy+oQic=
|
||||||
github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b h1:slYM766cy2nI3BwyRiyQj/Ud48djTMtMebDqepE95rw=
|
github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b h1:slYM766cy2nI3BwyRiyQj/Ud48djTMtMebDqepE95rw=
|
||||||
github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b/go.mod h1:1KcenG0jGWcpt8ov532z81sp/kMMUG485J2InIOyADM=
|
github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b/go.mod h1:1KcenG0jGWcpt8ov532z81sp/kMMUG485J2InIOyADM=
|
||||||
github.com/andybalholm/brotli v1.2.6 h1:ftYnfj6usCp+UGV5kSJ3+chpMQgU+gJf/AxsUQ52REI=
|
github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A=
|
||||||
github.com/andybalholm/brotli v1.2.6/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||||
github.com/benoitkugler/pstokenizer v1.0.0/go.mod h1:l1G2Voirz0q/jj0TQfabNxVsa8HZXh/VMxFSRALWTiE=
|
github.com/benoitkugler/pstokenizer v1.0.0/go.mod h1:l1G2Voirz0q/jj0TQfabNxVsa8HZXh/VMxFSRALWTiE=
|
||||||
github.com/benoitkugler/textlayout v0.3.2 h1:Y/LTkwpQ9G0Fia9yhPmZA9IR5AnE8Cq30j3C+Gx5/IE=
|
github.com/benoitkugler/textlayout v0.3.2 h1:Y/LTkwpQ9G0Fia9yhPmZA9IR5AnE8Cq30j3C+Gx5/IE=
|
||||||
github.com/benoitkugler/textlayout v0.3.2/go.mod h1:o+1hFV+JSHBC9qNLIuwVoLedERU7sBPgEFcuSgfvi/w=
|
github.com/benoitkugler/textlayout v0.3.2/go.mod h1:o+1hFV+JSHBC9qNLIuwVoLedERU7sBPgEFcuSgfvi/w=
|
||||||
github.com/benoitkugler/textlayout-testdata v0.1.1/go.mod h1:i/qZl09BbUOtd7Bu/W1CAubRwTWrEXWq6JwMkw8wYxo=
|
github.com/benoitkugler/textlayout-testdata v0.1.1/go.mod h1:i/qZl09BbUOtd7Bu/W1CAubRwTWrEXWq6JwMkw8wYxo=
|
||||||
github.com/benoitkugler/textprocessing v0.0.6 h1:obkMyj62GEPg3xUVYqROlCN22z1OleuZm6ULqX9Om1g=
|
github.com/benoitkugler/textprocessing v0.0.6 h1:obkMyj62GEPg3xUVYqROlCN22z1OleuZm6ULqX9Om1g=
|
||||||
github.com/benoitkugler/textprocessing v0.0.6/go.mod h1:Io0gN08/PXEzrSOWFa88xHx2Xv3VjvLMY7H76YoI23A=
|
github.com/benoitkugler/textprocessing v0.0.6/go.mod h1:Io0gN08/PXEzrSOWFa88xHx2Xv3VjvLMY7H76YoI23A=
|
||||||
github.com/emmansun/gmsm v0.45.0 h1:PU/6ObyR3g05YN3jn1L5GZDowzyAi8Xhkq4svzYNyiA=
|
github.com/ebitengine/purego v0.11.2 h1:WWiTx8rD8zYdOwSj8O/NiNbsOvSAgJMTlyV1XlbUSeU=
|
||||||
github.com/emmansun/gmsm v0.45.0/go.mod h1:HgLSvmdePGLo+Fo2PNgdTQU6lqAepSyriSQJRpECY6w=
|
github.com/ebitengine/purego v0.11.2/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
|
||||||
|
github.com/emmansun/gmsm v0.45.1 h1:S77WOluBZ9JH2wh701H2QR03eQYNGLeN8IUkdhgGpRA=
|
||||||
|
github.com/emmansun/gmsm v0.45.1/go.mod h1:RfnfrzyB9XbDi73nF1NHbJeqJj+a6pg/pXr5lrZKMok=
|
||||||
github.com/go-fonts/latin-modern v0.3.3 h1:g2xNgI8yzdNzIVm+qvbMryB6yGPe0pSMss8QT3QwlJ0=
|
github.com/go-fonts/latin-modern v0.3.3 h1:g2xNgI8yzdNzIVm+qvbMryB6yGPe0pSMss8QT3QwlJ0=
|
||||||
github.com/go-fonts/latin-modern v0.3.3/go.mod h1:tHaiWDGze4EPB0Go4cLT5M3QzRY3peya09Z/8KSCrpY=
|
github.com/go-fonts/latin-modern v0.3.3/go.mod h1:tHaiWDGze4EPB0Go4cLT5M3QzRY3peya09Z/8KSCrpY=
|
||||||
github.com/go-text/typesetting v0.3.5 h1:XZPUooClHY0Vf/rFyUyuPRNEkawARaFzLMQcXLSEyPk=
|
github.com/go-text/typesetting v0.3.5 h1:XZPUooClHY0Vf/rFyUyuPRNEkawARaFzLMQcXLSEyPk=
|
||||||
@@ -58,14 +60,14 @@ github.com/tdewolff/parse/v2 v2.8.16 h1:bLk5svUOQRkW/Y2SJ+DeENSIkZBcTIkq+Atyv5D8
|
|||||||
github.com/tdewolff/parse/v2 v2.8.16/go.mod h1:XdsoSFThlVIRIajAuqz1evNY7bagZS8LBOPA3aVopwQ=
|
github.com/tdewolff/parse/v2 v2.8.16/go.mod h1:XdsoSFThlVIRIajAuqz1evNY7bagZS8LBOPA3aVopwQ=
|
||||||
github.com/tdewolff/test v1.0.12 h1:7F21DqIajswxuche0geHdrUZRCWE4oko4b7bcmkkrxk=
|
github.com/tdewolff/test v1.0.12 h1:7F21DqIajswxuche0geHdrUZRCWE4oko4b7bcmkkrxk=
|
||||||
github.com/tdewolff/test v1.0.12/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8=
|
github.com/tdewolff/test v1.0.12/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8=
|
||||||
github.com/xiaoqidun/guigo v0.0.0-20261017165144-57ca5ff5f547 h1:BEybx66cn0nugBoWwUNOnAWgpcRhPUWPxO3fyizebO0=
|
github.com/xiaoqidun/guigo v0.0.0-20261030045545-8b12eb7ed706 h1:0QmFYCnRMw9mQ2MZLuFV1NMItMRcYJJQgGrxvPv0fg4=
|
||||||
github.com/xiaoqidun/guigo v0.0.0-20261017165144-57ca5ff5f547/go.mod h1:QAHK2Sa/KvY6dO+6dtvVUeOXVQO4Zh8R5oSSU+av7kE=
|
github.com/xiaoqidun/guigo v0.0.0-20261030045545-8b12eb7ed706/go.mod h1:bXz+dPMVntPIVwePTTuMXt8Q0z1YoUGuROQSsXyUEfY=
|
||||||
github.com/xiaoqidun/j2kgo v1.0.2 h1:OAjjEOfaBaQzBNcj9wx+eM68UI5pewR6SzNZa1R1DIw=
|
github.com/xiaoqidun/j2kgo v1.0.2 h1:OAjjEOfaBaQzBNcj9wx+eM68UI5pewR6SzNZa1R1DIw=
|
||||||
github.com/xiaoqidun/j2kgo v1.0.2/go.mod h1:DCwAfuDzCDYqUiAlZ7BDwigTjaXw7o9L1FtEma/D1aA=
|
github.com/xiaoqidun/j2kgo v1.0.2/go.mod h1:DCwAfuDzCDYqUiAlZ7BDwigTjaXw7o9L1FtEma/D1aA=
|
||||||
github.com/xiaoqidun/jbig2 v1.1.8 h1:dERPW7F8gs18a/DOD9gXHR3fP1Vl6KhCNsLnq5l3BIo=
|
github.com/xiaoqidun/jbig2 v1.1.8 h1:dERPW7F8gs18a/DOD9gXHR3fP1Vl6KhCNsLnq5l3BIo=
|
||||||
github.com/xiaoqidun/jbig2 v1.1.8/go.mod h1:9jromqVwMqlptUDEt6Yip8vqYA5I1YjhG7FgMl/Z2dA=
|
github.com/xiaoqidun/jbig2 v1.1.8/go.mod h1:9jromqVwMqlptUDEt6Yip8vqYA5I1YjhG7FgMl/Z2dA=
|
||||||
github.com/xiaoqidun/pdfgo v0.0.0-20261017161421-0b88b77eefc9 h1:DsWSdFwsDpI8k0jadqcnGbpJuOpT+tIVIX5JfDFS2GQ=
|
github.com/xiaoqidun/pdfgo v0.0.0-20261026125713-90454771d5d0 h1:fBOCrYQedZ3ZxAlpI5bXeVs+/kWxWbVrt0iFlmTYMpU=
|
||||||
github.com/xiaoqidun/pdfgo v0.0.0-20261017161421-0b88b77eefc9/go.mod h1:AaabzsObZ8Z76AcaWbo6swRROrJsblyIGB7HbieeJA4=
|
github.com/xiaoqidun/pdfgo v0.0.0-20261026125713-90454771d5d0/go.mod h1:AaabzsObZ8Z76AcaWbo6swRROrJsblyIGB7HbieeJA4=
|
||||||
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
|
||||||
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
|
||||||
github.com/yuin/goldmark v1.8.5 h1:r6N5afV5qj/5S4UTch8agZHJ8UxNCMwX7WjkkJam2NA=
|
github.com/yuin/goldmark v1.8.5 h1:r6N5afV5qj/5S4UTch8agZHJ8UxNCMwX7WjkkJam2NA=
|
||||||
|
|||||||
@@ -0,0 +1,232 @@
|
|||||||
|
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package file
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math/big"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrChanged 表示目标文件已被其他操作修改
|
||||||
|
var ErrChanged = errors.New("file changed since opening")
|
||||||
|
|
||||||
|
// ErrBusy 表示目标文件正在写入
|
||||||
|
var ErrBusy = errors.New("file save is in progress")
|
||||||
|
|
||||||
|
// activeFiles 协调当前进程内的目标写入
|
||||||
|
var activeFiles sync.Map
|
||||||
|
|
||||||
|
// Target 保存文件路径及最近确认的文件状态,可跨次写入复用
|
||||||
|
type Target struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
name string
|
||||||
|
info os.FileInfo
|
||||||
|
}
|
||||||
|
|
||||||
|
// Writer 写入同目录临时文件,提交前检查取消及目标冲突
|
||||||
|
type Writer struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
target *Target
|
||||||
|
file *os.File
|
||||||
|
ctx context.Context
|
||||||
|
err error
|
||||||
|
closed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTemp 创建私有输入缓存文件,调用方负责关闭和删除
|
||||||
|
// 入参: directory 缓存目录,空值使用系统临时目录
|
||||||
|
// 返回: *os.File 缓存文件, error 创建错误
|
||||||
|
func NewTemp(directory string) (*os.File, error) {
|
||||||
|
if directory == "" {
|
||||||
|
directory = os.TempDir()
|
||||||
|
}
|
||||||
|
for range 100 {
|
||||||
|
n, err := rand.Int(rand.Reader, big.NewInt(10000000))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
name := filepath.Join(directory, fmt.Sprintf("ofdgo-%07d.tmp", n.Int64()))
|
||||||
|
file, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
|
||||||
|
if errors.Is(err, os.ErrExist) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return file, err
|
||||||
|
}
|
||||||
|
return nil, os.ErrExist
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTarget 记录目标当前状态,允许目标尚不存在
|
||||||
|
// 入参: name 目标路径
|
||||||
|
// 返回: *Target 保存目标, error 路径或文件错误
|
||||||
|
func NewTarget(name string) (*Target, error) {
|
||||||
|
if name == "" {
|
||||||
|
return nil, os.ErrInvalid
|
||||||
|
}
|
||||||
|
name, err := filepath.Abs(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
info, err := os.Lstat(name)
|
||||||
|
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if info != nil && !info.Mode().IsRegular() {
|
||||||
|
return nil, fmt.Errorf("save target is not a regular file")
|
||||||
|
}
|
||||||
|
return &Target{name: name, info: info}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// check 检查目标是否保持最近确认的状态
|
||||||
|
// 返回: error 文件状态错误
|
||||||
|
func (t *Target) check() error {
|
||||||
|
info, err := os.Lstat(t.name)
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
if t.info == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return ErrChanged
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if t.info == nil || !os.SameFile(t.info, info) || t.info.Size() != info.Size() || !t.info.ModTime().Equal(info.ModTime()) {
|
||||||
|
return ErrChanged
|
||||||
|
}
|
||||||
|
if info.Mode().Perm()&0222 == 0 {
|
||||||
|
return os.ErrPermission
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Begin 创建独占写入事务,调用方必须提交或终止
|
||||||
|
// 入参: ctx 取消上下文
|
||||||
|
// 返回: *Writer 事务, error 创建错误
|
||||||
|
func (t *Target) Begin(ctx context.Context) (*Writer, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
t.mu.Lock()
|
||||||
|
defer t.mu.Unlock()
|
||||||
|
if _, loaded := activeFiles.LoadOrStore(t.name, true); loaded {
|
||||||
|
return nil, ErrBusy
|
||||||
|
}
|
||||||
|
if err := t.check(); err != nil {
|
||||||
|
activeFiles.Delete(t.name)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for range 100 {
|
||||||
|
n, err := rand.Int(rand.Reader, big.NewInt(10000000))
|
||||||
|
if err != nil {
|
||||||
|
activeFiles.Delete(t.name)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
name := fmt.Sprintf("%s.%07d.tmp", t.name, n.Int64())
|
||||||
|
f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
|
||||||
|
if errors.Is(err, os.ErrExist) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
activeFiles.Delete(t.name)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Writer{target: t, file: f, ctx: ctx}, nil
|
||||||
|
}
|
||||||
|
activeFiles.Delete(t.name)
|
||||||
|
return nil, os.ErrExist
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write 追加数据并记录写入错误
|
||||||
|
// 入参: data 数据
|
||||||
|
// 返回: int 写入长度, error 写入错误
|
||||||
|
func (w *Writer) Write(data []byte) (int, error) {
|
||||||
|
w.mu.Lock()
|
||||||
|
defer w.mu.Unlock()
|
||||||
|
if w.closed {
|
||||||
|
return 0, os.ErrClosed
|
||||||
|
}
|
||||||
|
if w.err == nil {
|
||||||
|
w.err = w.ctx.Err()
|
||||||
|
}
|
||||||
|
if w.err != nil {
|
||||||
|
return 0, w.err
|
||||||
|
}
|
||||||
|
n, err := w.file.Write(data)
|
||||||
|
if err == nil && n != len(data) {
|
||||||
|
err = io.ErrShortWrite
|
||||||
|
}
|
||||||
|
w.err = err
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Commit 完成写入并替换目标,成功后刷新目标状态
|
||||||
|
// 返回: error 提交错误
|
||||||
|
func (w *Writer) Commit() error {
|
||||||
|
w.mu.Lock()
|
||||||
|
defer w.mu.Unlock()
|
||||||
|
if w.closed {
|
||||||
|
return os.ErrClosed
|
||||||
|
}
|
||||||
|
w.closed = true
|
||||||
|
defer activeFiles.Delete(w.target.name)
|
||||||
|
defer os.Remove(w.file.Name())
|
||||||
|
w.target.mu.Lock()
|
||||||
|
defer w.target.mu.Unlock()
|
||||||
|
if err := errors.Join(w.err, w.ctx.Err(), w.target.check()); err != nil {
|
||||||
|
return errors.Join(err, w.file.Close())
|
||||||
|
}
|
||||||
|
if w.target.info != nil {
|
||||||
|
if err := w.file.Chmod(w.target.info.Mode().Perm()); err != nil {
|
||||||
|
return errors.Join(err, w.file.Close())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := w.file.Sync(); err != nil {
|
||||||
|
return errors.Join(err, w.file.Close())
|
||||||
|
}
|
||||||
|
info, err := w.file.Stat()
|
||||||
|
if err = errors.Join(err, w.file.Close(), w.ctx.Err()); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := w.target.check(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := Replace(w.file.Name(), w.target.name); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
w.target.info = info
|
||||||
|
if current, err := os.Stat(w.target.name); err == nil {
|
||||||
|
w.target.info = current
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Abort 丢弃临时输出,不改变目标
|
||||||
|
// 返回: error 清理错误
|
||||||
|
func (w *Writer) Abort() error {
|
||||||
|
w.mu.Lock()
|
||||||
|
defer w.mu.Unlock()
|
||||||
|
if w.closed {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
w.closed = true
|
||||||
|
defer activeFiles.Delete(w.target.name)
|
||||||
|
return errors.Join(w.file.Close(), os.Remove(w.file.Name()))
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package file
|
||||||
|
|
||||||
|
import "os"
|
||||||
|
|
||||||
|
// Open 打开文件,路径替换后已有读取句柄仍有效
|
||||||
|
// 入参: name 文件路径
|
||||||
|
// 返回: *os.File 文件, error 打开错误
|
||||||
|
func Open(name string) (*os.File, error) {
|
||||||
|
return os.Open(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Replace 替换目标路径
|
||||||
|
// 入参: source 临时路径, target 目标路径
|
||||||
|
// 返回: error 替换错误
|
||||||
|
func Replace(source, target string) error {
|
||||||
|
return os.Rename(source, target)
|
||||||
|
}
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
// See the License for the specific language governing permissions and
|
// See the License for the specific language governing permissions and
|
||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
|
|
||||||
package webview
|
package file
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"os"
|
"os"
|
||||||
@@ -25,11 +25,13 @@ import (
|
|||||||
// replaceFileProc 保留目标文件属性并替换文件内容
|
// replaceFileProc 保留目标文件属性并替换文件内容
|
||||||
var replaceFileProc = syscall.NewLazyDLL("kernel32.dll").NewProc("ReplaceFileW")
|
var replaceFileProc = syscall.NewLazyDLL("kernel32.dll").NewProc("ReplaceFileW")
|
||||||
|
|
||||||
// openReadFile 允许原子替换路径,同时保持已有读取句柄有效
|
// Open 保留替换共享权限,路径替换后已有读取句柄仍有效
|
||||||
func openReadFile(name string) (*os.File, error) {
|
// 入参: name 文件路径
|
||||||
path, err := nativeFilePath(name)
|
// 返回: *os.File 文件, error 打开错误
|
||||||
|
func Open(name string) (*os.File, error) {
|
||||||
|
path, err := nativePath(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, &os.PathError{Op: "open", Path: name, Err: err}
|
return nil, err
|
||||||
}
|
}
|
||||||
handle, err := syscall.CreateFile(path, syscall.GENERIC_READ, syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0)
|
handle, err := syscall.CreateFile(path, syscall.GENERIC_READ, syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, nil, syscall.OPEN_EXISTING, syscall.FILE_ATTRIBUTE_NORMAL, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -38,13 +40,15 @@ func openReadFile(name string) (*os.File, error) {
|
|||||||
return os.NewFile(uintptr(handle), name), nil
|
return os.NewFile(uintptr(handle), name), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// replaceFile 替换已有文件,目标不存在时直接重命名
|
// Replace 替换目标,目标不存在时重命名
|
||||||
func replaceFile(source, target string) error {
|
// 入参: source 临时路径, target 目标路径
|
||||||
from, err := nativeFilePath(source)
|
// 返回: error 替换错误
|
||||||
|
func Replace(source, target string) error {
|
||||||
|
from, err := nativePath(source)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
to, err := nativeFilePath(target)
|
to, err := nativePath(target)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -58,8 +62,10 @@ func replaceFile(source, target string) error {
|
|||||||
return &os.LinkError{Op: "replace", Old: source, New: target, Err: err}
|
return &os.LinkError{Op: "replace", Old: source, New: target, Err: err}
|
||||||
}
|
}
|
||||||
|
|
||||||
// nativeFilePath 转换绝对路径并支持长路径与网络共享
|
// nativePath 转换绝对长路径
|
||||||
func nativeFilePath(name string) (*uint16, error) {
|
// 入参: name 路径
|
||||||
|
// 返回: *uint16 原生路径, error 转换错误
|
||||||
|
func nativePath(name string) (*uint16, error) {
|
||||||
path, err := filepath.Abs(name)
|
path, err := filepath.Abs(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
+39
-14
@@ -131,6 +131,14 @@ func NormalizeCFFCharstringsAt(data []byte, unitsPerEm uint16) ([]byte, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if _, cid := dict[1230]; !cid {
|
||||||
|
for op := 1231; op <= 1238; op++ {
|
||||||
|
if _, exists := dict[op]; exists {
|
||||||
|
delete(dict, op)
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if transform != nil {
|
if transform != nil {
|
||||||
scale := 1 / float64(unitsPerEm)
|
scale := 1 / float64(unitsPerEm)
|
||||||
dict[1207] = []float64{scale, 0, 0, scale, 0, 0}
|
dict[1207] = []float64{scale, 0, 0, scale, 0, 0}
|
||||||
@@ -260,6 +268,21 @@ func SanitizeCFF(data []byte) ([]byte, error) {
|
|||||||
if kind == 1 {
|
if kind == 1 {
|
||||||
return normalizeCFFType1(data, topDict)
|
return normalizeCFFType1(data, topDict)
|
||||||
}
|
}
|
||||||
|
private, err := readType2Private(data, topDict[18], &type2Font{})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
count := len(private)
|
||||||
|
if err := normalizeCFFPrivate(private); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(private) != count {
|
||||||
|
font, err := readType2Font(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return rebuildNamedCFF(data, font, font.chars, nil)
|
||||||
|
}
|
||||||
return data, nil
|
return data, nil
|
||||||
}
|
}
|
||||||
fdArrOff, err := cffDictOffset(data, topDict, 1236)
|
fdArrOff, err := cffDictOffset(data, topDict, 1236)
|
||||||
@@ -316,10 +339,9 @@ func SanitizeCFF(data []byte) ([]byte, error) {
|
|||||||
localSubrData = data[start:end]
|
localSubrData = data[start:end]
|
||||||
}
|
}
|
||||||
charStringsData := data[charStringsOff:charEnd]
|
charStringsData := data[charStringsOff:charEnd]
|
||||||
delete(topDict, 1230)
|
for op := 1230; op <= 1238; op++ {
|
||||||
delete(topDict, 1236)
|
delete(topDict, op)
|
||||||
delete(topDict, 1237)
|
}
|
||||||
delete(topDict, 1234)
|
|
||||||
delete(topDict, 15)
|
delete(topDict, 15)
|
||||||
delete(topDict, 16)
|
delete(topDict, 16)
|
||||||
var finalPrivData []byte
|
var finalPrivData []byte
|
||||||
@@ -342,17 +364,21 @@ func SanitizeCFF(data []byte) ([]byte, error) {
|
|||||||
return encodeSanitizedCFF(data[:hdrSize], nameIndexData, topDict, stringIndexData, globalSubrIndexData, charStringsData, finalPrivData, localSubrData), nil
|
return encodeSanitizedCFF(data[:hdrSize], nameIndexData, topDict, stringIndexData, globalSubrIndexData, charStringsData, finalPrivData, localSubrData), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// normalizeCFFPrivate 移除旧版CFF中不生效的缺省字段,拒绝需要额外解释的取值
|
// normalizeCFFPrivate 移除废弃的加粗阈值及未加密标记,拒绝加密字形程序
|
||||||
// 入参: dict 私有字典
|
// 入参: dict 私有字典
|
||||||
// 返回: error 不支持的旧版行为
|
// 返回: error 不支持的旧版行为
|
||||||
func normalizeCFFPrivate(dict cffDict) error {
|
func normalizeCFFPrivate(dict cffDict) error {
|
||||||
for op, value := range map[int]float64{1215: 0, 1216: -1} {
|
if values, ok := dict[1215]; ok {
|
||||||
if values, ok := dict[op]; ok {
|
if len(values) != 1 || !finite(values[0]) {
|
||||||
if len(values) != 1 || values[0] != value {
|
return fmt.Errorf("invalid legacy CFF bold threshold")
|
||||||
return fmt.Errorf("unsupported legacy CFF private operator %d", op)
|
|
||||||
}
|
}
|
||||||
delete(dict, op)
|
delete(dict, 1215)
|
||||||
}
|
}
|
||||||
|
if values, ok := dict[1216]; ok {
|
||||||
|
if len(values) != 1 || values[0] != -1 {
|
||||||
|
return fmt.Errorf("unsupported legacy CFF private operator 1216")
|
||||||
|
}
|
||||||
|
delete(dict, 1216)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -475,10 +501,9 @@ func sanitizeMultiFDCFF(data []byte, hdrSize int, nameIndexData []byte, topDict
|
|||||||
}
|
}
|
||||||
inlined[gid] = output.Bytes()
|
inlined[gid] = output.Bytes()
|
||||||
}
|
}
|
||||||
delete(topDict, 1230)
|
for op := 1230; op <= 1238; op++ {
|
||||||
delete(topDict, 1236)
|
delete(topDict, op)
|
||||||
delete(topDict, 1237)
|
}
|
||||||
delete(topDict, 1234)
|
|
||||||
delete(topDict, 15)
|
delete(topDict, 15)
|
||||||
delete(topDict, 16)
|
delete(topDict, 16)
|
||||||
delete(topDict, 1206)
|
delete(topDict, 1206)
|
||||||
|
|||||||
@@ -231,6 +231,9 @@ func rebuildNamedCFF(data []byte, font *type2Font, chars [][]byte, ids []uint16)
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if err := normalizeCFFPrivate(private); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
privateData, err := encodeCFFSubsetPrivate(private)
|
privateData, err := encodeCFFSubsetPrivate(private)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ package font
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"crypto/sha256"
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -23,6 +24,8 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Face 字体文件中的字体名称与零起始索引,不依赖文件名
|
// Face 字体文件中的字体名称与零起始索引,不依赖文件名
|
||||||
|
// Family和Style为排版族,MenuFamily和MenuStyle为兼容四款式的菜单名称
|
||||||
|
// FamilyKey区分兼容族、厂商和版本,未知时为空;Bold和Italic表示字体固有样式
|
||||||
type Face struct {
|
type Face struct {
|
||||||
Index int `json:"index"`
|
Index int `json:"index"`
|
||||||
FullName string `json:"fullName"`
|
FullName string `json:"fullName"`
|
||||||
@@ -30,12 +33,24 @@ type Face struct {
|
|||||||
Style string `json:"style"`
|
Style string `json:"style"`
|
||||||
PostScriptName string `json:"postscriptName"`
|
PostScriptName string `json:"postscriptName"`
|
||||||
Names []string `json:"names"`
|
Names []string `json:"names"`
|
||||||
|
MenuFamily string `json:"menuFamily"`
|
||||||
|
MenuStyle string `json:"menuStyle"`
|
||||||
|
FamilyKey string `json:"familyKey"`
|
||||||
|
Bold bool `json:"bold"`
|
||||||
|
Italic bool `json:"italic"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// FaceInfo 从名称表读取字体信息
|
// FaceInfo 从名称表读取字体信息
|
||||||
// 入参: data 名称表数据, index 零起始字体索引
|
// 入参: data 名称表数据, index 零起始字体索引
|
||||||
// 返回: Face 字体信息
|
// 返回: Face 字体信息
|
||||||
func FaceInfo(data []byte, index int) Face {
|
func FaceInfo(data []byte, index int) Face {
|
||||||
|
return faceInfoLanguage(data, index, 0xffff, 0xffff)
|
||||||
|
}
|
||||||
|
|
||||||
|
// faceInfoLanguage 优先读取指定平台和语言的显示名称,保留标识及全部别名
|
||||||
|
// 入参: data 名称表数据, index 字体索引, platform 平台标识, language 语言标识
|
||||||
|
// 返回: Face 字体信息
|
||||||
|
func faceInfoLanguage(data []byte, index int, platform, language uint16) Face {
|
||||||
records, values := fontNameValues(data)
|
records, values := fontNameValues(data)
|
||||||
name := func(ids ...uint16) string {
|
name := func(ids ...uint16) string {
|
||||||
for _, id := range ids {
|
for _, id := range ids {
|
||||||
@@ -49,7 +64,52 @@ func FaceInfo(data []byte, index int) Face {
|
|||||||
}
|
}
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
return Face{Index: index, FullName: name(4, 6, 16, 1), Family: name(16, 1), Style: name(17, 2), PostScriptName: name(6), Names: fontNamesFromValues(records, values)}
|
localized := func(ids ...uint16) string {
|
||||||
|
for _, id := range ids {
|
||||||
|
for _, record := range records {
|
||||||
|
if record.Platform == platform && record.Language == language && record.Name == id {
|
||||||
|
if value := strings.TrimSpace(values[[4]uint16{record.Platform, record.Encoding, record.Language, id}]); value != "" {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return name(ids...)
|
||||||
|
}
|
||||||
|
key := ""
|
||||||
|
if family, version := name(1), name(5); family != "" && version != "" {
|
||||||
|
key = fmt.Sprintf("%x", sha256.Sum256([]byte(strings.Join([]string{family, version, name(8)}, "\x00"))))
|
||||||
|
}
|
||||||
|
family, style := localized(1), localized(2)
|
||||||
|
if family == "" {
|
||||||
|
family = localized(16, 4, 6)
|
||||||
|
}
|
||||||
|
if style == "" {
|
||||||
|
style = localized(17)
|
||||||
|
}
|
||||||
|
return Face{Index: index, FullName: localized(4, 6, 16, 1), Family: localized(16, 1), Style: localized(17, 2), PostScriptName: name(6), Names: fontNamesFromValues(records, values), MenuFamily: family, MenuStyle: style, FamilyKey: key}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TableFaceInfo 读取名称及字体固有款式,名称键不随显示语言变化
|
||||||
|
// 入参: tables 字体表, index 集合索引, platform 平台标识, language 语言标识
|
||||||
|
// 返回: Face 字体信息
|
||||||
|
func TableFaceInfo(tables map[string][]byte, index int, platform, language uint16) Face {
|
||||||
|
face := faceInfoLanguage(tables["name"], index, platform, language)
|
||||||
|
key := face.FamilyKey
|
||||||
|
if head := tables["head"]; len(head) >= 46 {
|
||||||
|
key += string(head[4:8])
|
||||||
|
style := binary.BigEndian.Uint16(head[44:])
|
||||||
|
face.Bold, face.Italic = style&1 != 0, style&2 != 0
|
||||||
|
}
|
||||||
|
if os2 := tables["OS/2"]; len(os2) >= 64 {
|
||||||
|
key += string(os2[58:62])
|
||||||
|
style := binary.BigEndian.Uint16(os2[62:])
|
||||||
|
face.Bold, face.Italic = style&32 != 0, style&1 != 0 || style&512 != 0
|
||||||
|
}
|
||||||
|
if face.FamilyKey != "" {
|
||||||
|
face.FamilyKey = fmt.Sprintf("%x", sha256.Sum256([]byte(key)))
|
||||||
|
}
|
||||||
|
return face
|
||||||
}
|
}
|
||||||
|
|
||||||
// FileCount 校验字体或集合头并读取字体数量
|
// FileCount 校验字体或集合头并读取字体数量
|
||||||
@@ -78,6 +138,13 @@ func FileCount(data []byte) (int, error) {
|
|||||||
// 入参: data OpenType数据
|
// 入参: data OpenType数据
|
||||||
// 返回: []Face 字体列表, error 格式或名称表错误
|
// 返回: []Face 字体列表, error 格式或名称表错误
|
||||||
func ReadFaces(data []byte) ([]Face, error) {
|
func ReadFaces(data []byte) ([]Face, error) {
|
||||||
|
return ReadLocalizedFaces(data, 0xffff, 0xffff)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadLocalizedFaces 读取指定平台和语言的字体名称,缺失时沿用名称表顺序
|
||||||
|
// 入参: data OpenType数据, platform 名称表平台标识, language 名称表语言标识
|
||||||
|
// 返回: []Face 字体列表, error 格式或名称表错误
|
||||||
|
func ReadLocalizedFaces(data []byte, platform, language uint16) ([]Face, error) {
|
||||||
count, err := FileCount(data)
|
count, err := FileCount(data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -88,7 +155,7 @@ func ReadFaces(data []byte) ([]Face, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
face := FaceInfo(tables["name"], index)
|
face := TableFaceInfo(tables, index, platform, language)
|
||||||
if face.FullName == "" {
|
if face.FullName == "" {
|
||||||
return nil, fmt.Errorf("font %d has no usable name", index)
|
return nil, fmt.Errorf("font %d has no usable name", index)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -235,7 +235,7 @@ func (f *Outliner) phantomPoints(id uint16, data []byte) [4]ttPoint {
|
|||||||
return [4]ttPoint{{x: left * 64, ox: left * 64}, {x: (left + int32(f.Font.GlyphAdvance(id))) * 64, ox: (left + int32(f.Font.GlyphAdvance(id))) * 64}, {y: top * 64, oy: top * 64}, {y: (top - int32(f.Font.GlyphVerticalAdvance(id))) * 64, oy: (top - int32(f.Font.GlyphVerticalAdvance(id))) * 64}}
|
return [4]ttPoint{{x: left * 64, ox: left * 64}, {x: (left + int32(f.Font.GlyphAdvance(id))) * 64, ox: (left + int32(f.Font.GlyphAdvance(id))) * 64}, {y: top * 64, oy: top * 64}, {y: (top - int32(f.Font.GlyphVerticalAdvance(id))) * 64, oy: (top - int32(f.Font.GlyphVerticalAdvance(id))) * 64}}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ttRecoverableHint 判断栈参数、指令引用或控制流错误是否允许保留执行前轮廓
|
// ttRecoverableHint 判断栈参数、区点轮廓及函数引用或控制流错误是否允许保留执行前轮廓
|
||||||
// 入参: err 指令错误
|
// 入参: err 指令错误
|
||||||
// 返回: bool 是否可恢复
|
// 返回: bool 是否可恢复
|
||||||
func ttRecoverableHint(err error) bool {
|
func ttRecoverableHint(err error) bool {
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ import (
|
|||||||
// errTTStackUnderflow 表示字形程序缺少必需的栈参数
|
// errTTStackUnderflow 表示字形程序缺少必需的栈参数
|
||||||
var errTTStackUnderflow = errors.New("TrueType instruction stack underflow")
|
var errTTStackUnderflow = errors.New("TrueType instruction stack underflow")
|
||||||
|
|
||||||
// errTTInvalidReference 表示字形指令引用不存在的点或函数
|
// errTTInvalidReference 表示字形指令引用不存在的区、点、轮廓或函数
|
||||||
var errTTInvalidReference = errors.New("invalid TrueType instruction reference")
|
var errTTInvalidReference = errors.New("invalid TrueType instruction reference")
|
||||||
|
|
||||||
// errTTInvalidControlFlow 表示条件分支未闭合或跳转超出字节码范围
|
// errTTInvalidControlFlow 表示条件分支未闭合或跳转超出字节码范围
|
||||||
@@ -380,7 +380,8 @@ func (v *ttInterpreter) execute(code []byte, depth int) error {
|
|||||||
case op >= 0x13 && op <= 0x16:
|
case op >= 0x13 && op <= 0x16:
|
||||||
z := v.pop()
|
z := v.pop()
|
||||||
if z < 0 || z > 1 {
|
if z < 0 || z > 1 {
|
||||||
return fmt.Errorf("invalid TrueType zone")
|
v.err = fmt.Errorf("%w: zone %d", errTTInvalidReference, z)
|
||||||
|
break
|
||||||
}
|
}
|
||||||
if op == 0x16 {
|
if op == 0x16 {
|
||||||
g.zone = [3]int32{z, z, z}
|
g.zone = [3]int32{z, z, z}
|
||||||
@@ -854,7 +855,7 @@ func (v *ttInterpreter) shift(op byte) {
|
|||||||
if op <= 0x35 {
|
if op <= 0x35 {
|
||||||
contour := v.pop()
|
contour := v.pop()
|
||||||
if contour < 0 || int64(contour) >= int64(len(v.ends)) {
|
if contour < 0 || int64(contour) >= int64(len(v.ends)) {
|
||||||
v.err = fmt.Errorf("invalid TrueType contour reference")
|
v.err = fmt.Errorf("%w: contour %d", errTTInvalidReference, contour)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if contour > 0 {
|
if contour > 0 {
|
||||||
@@ -864,7 +865,7 @@ func (v *ttInterpreter) shift(op byte) {
|
|||||||
} else {
|
} else {
|
||||||
target = v.pop()
|
target = v.pop()
|
||||||
if target < 0 || target > 1 {
|
if target < 0 || target > 1 {
|
||||||
v.err = fmt.Errorf("invalid TrueType zone")
|
v.err = fmt.Errorf("%w: zone %d", errTTInvalidReference, target)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
to = len(v.zones[target])
|
to = len(v.zones[target])
|
||||||
|
|||||||
@@ -142,7 +142,7 @@ func fontNameValues(data []byte) ([]fontNameRecord, map[[4]uint16]string) {
|
|||||||
values := make(map[[4]uint16]string)
|
values := make(map[[4]uint16]string)
|
||||||
for _, record := range records {
|
for _, record := range records {
|
||||||
switch record.Name {
|
switch record.Name {
|
||||||
case 1, 2, 4, 6, 16, 17:
|
case 1, 2, 4, 5, 6, 8, 16, 17:
|
||||||
default:
|
default:
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|||||||
+118
-18
@@ -17,9 +17,11 @@ package font
|
|||||||
import (
|
import (
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"iter"
|
||||||
"maps"
|
"maps"
|
||||||
"slices"
|
"slices"
|
||||||
"sync"
|
"sync"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"github.com/go-text/typesetting/font/opentype/tables"
|
"github.com/go-text/typesetting/font/opentype/tables"
|
||||||
)
|
)
|
||||||
@@ -34,10 +36,12 @@ type SFNT struct {
|
|||||||
reverse map[uint16][]rune
|
reverse map[uint16][]rune
|
||||||
}
|
}
|
||||||
|
|
||||||
// sfntCmap 保存编码记录及对应字符映射,标记已解析的共享子表
|
// sfntCmap 保存编码记录及字符映射,连续区间与共享子表不重复展开
|
||||||
type sfntCmap struct {
|
type sfntCmap struct {
|
||||||
platform, encoding, format uint16
|
platform, encoding, format uint16
|
||||||
mapping map[rune]uint16
|
mapping map[rune]uint16
|
||||||
|
groups []byte
|
||||||
|
entries uint64
|
||||||
duplicate bool
|
duplicate bool
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,7 +94,7 @@ func ParseSFNTTables(table map[string][]byte) (*SFNT, error) {
|
|||||||
if cmap.duplicate {
|
if cmap.duplicate {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for _, glyph := range cmap.mapping {
|
for _, glyph := range cmap.pairs() {
|
||||||
if glyph >= f.count {
|
if glyph >= f.count {
|
||||||
return nil, fmt.Errorf("cmap glyph index out of range")
|
return nil, fmt.Errorf("cmap glyph index out of range")
|
||||||
}
|
}
|
||||||
@@ -119,7 +123,7 @@ func readSFNTCmaps(data []byte) ([]sfntCmap, error) {
|
|||||||
}
|
}
|
||||||
count := int(binary.BigEndian.Uint16(data[2:]))
|
count := int(binary.BigEndian.Uint16(data[2:]))
|
||||||
result := make([]sfntCmap, 0, count)
|
result := make([]sfntCmap, 0, count)
|
||||||
parsed := make(map[uint32]map[rune]uint16)
|
parsed := make(map[uint32]sfntCmap)
|
||||||
for i := range count {
|
for i := range count {
|
||||||
record := data[4+8*i:]
|
record := data[4+8*i:]
|
||||||
offset := binary.BigEndian.Uint32(record[4:])
|
offset := binary.BigEndian.Uint32(record[4:])
|
||||||
@@ -128,23 +132,44 @@ func readSFNTCmaps(data []byte) ([]sfntCmap, error) {
|
|||||||
}
|
}
|
||||||
sub := data[offset:]
|
sub := data[offset:]
|
||||||
format := binary.BigEndian.Uint16(sub)
|
format := binary.BigEndian.Uint16(sub)
|
||||||
mapping, found := parsed[offset]
|
cmap, found := parsed[offset]
|
||||||
if !found {
|
if !found {
|
||||||
mapping = make(map[rune]uint16)
|
cmap.mapping = make(map[rune]uint16)
|
||||||
var err error
|
var err error
|
||||||
switch format {
|
switch format {
|
||||||
case 0:
|
case 0:
|
||||||
parseCmapFormat0(sub, mapping)
|
parseCmapFormat0(sub, cmap.mapping)
|
||||||
case 4:
|
case 4:
|
||||||
parseCmapFormat4(sub, mapping)
|
parseCmapFormat4(sub, cmap.mapping)
|
||||||
case 6:
|
case 6:
|
||||||
parseCmapFormat6(sub, mapping)
|
parseCmapFormat6(sub, cmap.mapping)
|
||||||
case 12:
|
case 12:
|
||||||
parseCmapFormat12(sub, mapping)
|
if len(sub) >= 16 {
|
||||||
|
length := uint64(binary.BigEndian.Uint32(sub[4:]))
|
||||||
|
count := uint64(binary.BigEndian.Uint32(sub[12:]))
|
||||||
|
if length >= 16 && length <= uint64(len(sub)) && count <= (length-16)/12 {
|
||||||
|
cmap.groups = sub[16 : 16+12*count]
|
||||||
|
for offset := 0; offset < len(cmap.groups); offset += 12 {
|
||||||
|
first := binary.BigEndian.Uint32(cmap.groups[offset:])
|
||||||
|
last := binary.BigEndian.Uint32(cmap.groups[offset+4:])
|
||||||
|
if first > last || offset != 0 && first <= binary.BigEndian.Uint32(cmap.groups[offset-8:]) {
|
||||||
|
cmap.groups = nil
|
||||||
|
parseCmapFormat12(sub, cmap.mapping)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if cmap.groups != nil {
|
||||||
|
cmap.mapping = nil
|
||||||
|
for range cmap.pairs() {
|
||||||
|
cmap.entries++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
case 2:
|
case 2:
|
||||||
mapping, err = parseCmapFormat2(sub)
|
cmap.mapping, err = parseCmapFormat2(sub)
|
||||||
case 8, 10, 13:
|
case 8, 10, 13:
|
||||||
mapping, err = parseCmapExtended(sub)
|
cmap.mapping, err = parseCmapExtended(sub)
|
||||||
case 14:
|
case 14:
|
||||||
default:
|
default:
|
||||||
return nil, fmt.Errorf("unsupported cmap format %d", format)
|
return nil, fmt.Errorf("unsupported cmap format %d", format)
|
||||||
@@ -152,13 +177,67 @@ func readSFNTCmaps(data []byte) ([]sfntCmap, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
parsed[offset] = mapping
|
parsed[offset] = cmap
|
||||||
}
|
}
|
||||||
result = append(result, sfntCmap{platform: binary.BigEndian.Uint16(record), encoding: binary.BigEndian.Uint16(record[2:]), format: format, mapping: mapping, duplicate: found})
|
cmap.platform, cmap.encoding, cmap.format, cmap.duplicate = binary.BigEndian.Uint16(record), binary.BigEndian.Uint16(record[2:]), format, found
|
||||||
|
result = append(result, cmap)
|
||||||
}
|
}
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// pairs 按原映射返回字符与字形,连续编码段不展开存储
|
||||||
|
// 返回: iter.Seq2[rune, uint16] 非零有效字符映射
|
||||||
|
func (c sfntCmap) pairs() iter.Seq2[rune, uint16] {
|
||||||
|
return func(yield func(rune, uint16) bool) {
|
||||||
|
for char, glyph := range c.mapping {
|
||||||
|
if !yield(char, glyph) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for offset := 0; offset+12 <= len(c.groups); offset += 12 {
|
||||||
|
group := c.groups[offset:]
|
||||||
|
first, last, glyph := binary.BigEndian.Uint32(group), binary.BigEndian.Uint32(group[4:]), binary.BigEndian.Uint32(group[8:])
|
||||||
|
if first > last || first > utf8.MaxRune || glyph > 65535 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
end := min(uint64(last), uint64(first)+65535-uint64(glyph), uint64(utf8.MaxRune))
|
||||||
|
for char := uint64(first); char <= end; char++ {
|
||||||
|
id := uint16(uint64(glyph) + char - uint64(first))
|
||||||
|
if id != 0 && utf8.ValidRune(rune(char)) && !yield(rune(char), id) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// lookup 查找原字符映射,连续编码段使用有序区间查询
|
||||||
|
// 入参: char 字符
|
||||||
|
// 返回: uint16 字形编号, bool 是否存在映射
|
||||||
|
func (c sfntCmap) lookup(char rune) (uint16, bool) {
|
||||||
|
if glyph, ok := c.mapping[char]; ok {
|
||||||
|
return glyph, true
|
||||||
|
}
|
||||||
|
if !utf8.ValidRune(char) {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
low, high := 0, len(c.groups)/12
|
||||||
|
for low < high {
|
||||||
|
middle := low + (high-low)/2
|
||||||
|
group := c.groups[middle*12:]
|
||||||
|
first, last := binary.BigEndian.Uint32(group), binary.BigEndian.Uint32(group[4:])
|
||||||
|
if uint32(char) < first {
|
||||||
|
high = middle
|
||||||
|
} else if uint32(char) > last {
|
||||||
|
low = middle + 1
|
||||||
|
} else {
|
||||||
|
glyph := uint64(binary.BigEndian.Uint32(group[8:])) + uint64(uint32(char)-first)
|
||||||
|
return uint16(glyph), glyph > 0 && glyph <= 65535
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
// UnitsPerEm 返回字体设计单位
|
// UnitsPerEm 返回字体设计单位
|
||||||
// 返回: uint16 每em单位数
|
// 返回: uint16 每em单位数
|
||||||
func (f *SFNT) UnitsPerEm() uint16 { return f.units }
|
func (f *SFNT) UnitsPerEm() uint16 { return f.units }
|
||||||
@@ -172,7 +251,7 @@ func (f *SFNT) NumGlyphs() uint16 { return f.count }
|
|||||||
func (f *SFNT) CmapEntries() uint64 {
|
func (f *SFNT) CmapEntries() uint64 {
|
||||||
var count uint64
|
var count uint64
|
||||||
for _, cmap := range f.cmaps {
|
for _, cmap := range f.cmaps {
|
||||||
count += uint64(len(cmap.mapping))
|
count += uint64(len(cmap.mapping)) + cmap.entries
|
||||||
}
|
}
|
||||||
return count
|
return count
|
||||||
}
|
}
|
||||||
@@ -185,14 +264,14 @@ func (f *SFNT) GlyphIndex(char rune) uint16 {
|
|||||||
if cmap.duplicate {
|
if cmap.duplicate {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if gid := cmap.mapping[char]; gid != 0 {
|
if gid, ok := cmap.lookup(char); ok && gid != 0 {
|
||||||
return gid
|
return gid
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// glyphCharacters 返回指向指定字形的全部字符
|
// glyphCharacters 返回指向指定字形的全部字符,连续区间按需反查
|
||||||
// 入参: gid 字形编号
|
// 入参: gid 字形编号
|
||||||
// 返回: []rune 排序后的字符
|
// 返回: []rune 排序后的字符
|
||||||
func (f *SFNT) glyphCharacters(gid uint16) []rune {
|
func (f *SFNT) glyphCharacters(gid uint16) []rune {
|
||||||
@@ -204,7 +283,7 @@ func (f *SFNT) glyphCharacters(gid uint16) []rune {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for char, glyph := range cmap.mapping {
|
for char, glyph := range cmap.mapping {
|
||||||
if glyph != 0 && !seen[char] {
|
if glyph != 0 && !seen[char] && f.GlyphIndex(char) == glyph {
|
||||||
f.reverse[glyph] = append(f.reverse[glyph], char)
|
f.reverse[glyph] = append(f.reverse[glyph], char)
|
||||||
seen[char] = true
|
seen[char] = true
|
||||||
}
|
}
|
||||||
@@ -214,7 +293,28 @@ func (f *SFNT) glyphCharacters(gid uint16) []rune {
|
|||||||
slices.Sort(chars)
|
slices.Sort(chars)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
return f.reverse[gid]
|
if gid == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
chars := slices.Clone(f.reverse[gid])
|
||||||
|
for _, cmap := range f.cmaps {
|
||||||
|
if cmap.duplicate {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for offset := 0; offset+12 <= len(cmap.groups); offset += 12 {
|
||||||
|
group := cmap.groups[offset:]
|
||||||
|
first, last, glyph := binary.BigEndian.Uint32(group), binary.BigEndian.Uint32(group[4:]), binary.BigEndian.Uint32(group[8:])
|
||||||
|
if first > last || uint32(gid) < glyph {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
char := uint64(first) + uint64(uint32(gid)-glyph)
|
||||||
|
if char <= uint64(last) && char <= utf8.MaxRune && utf8.ValidRune(rune(char)) && f.GlyphIndex(rune(char)) == gid {
|
||||||
|
chars = append(chars, rune(char))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
slices.Sort(chars)
|
||||||
|
return slices.Compact(chars)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GlyphAdvance 返回水平字宽
|
// GlyphAdvance 返回水平字宽
|
||||||
|
|||||||
@@ -197,7 +197,7 @@ func subsetSourceSFNT(sfnt *SFNT, usage *Usage, size int) []byte {
|
|||||||
for char := range usage.Characters {
|
for char := range usage.Characters {
|
||||||
id := sfnt.GlyphIndex(char)
|
id := sfnt.GlyphIndex(char)
|
||||||
for _, cmap := range unicodeTables {
|
for _, cmap := range unicodeTables {
|
||||||
if alternate, ok := cmap.mapping[char]; ok && alternate != id {
|
if alternate, ok := cmap.lookup(char); ok && alternate != id {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,7 +29,6 @@ func NormalizeOS2(data []byte) []byte {
|
|||||||
var size int
|
var size int
|
||||||
switch binary.BigEndian.Uint16(data) {
|
switch binary.BigEndian.Uint16(data) {
|
||||||
case 0:
|
case 0:
|
||||||
// 旧式68字节表保持原样,不将截断的78字节表推断为旧式表
|
|
||||||
size = 78
|
size = 78
|
||||||
case 1:
|
case 1:
|
||||||
size = 86
|
size = 86
|
||||||
|
|||||||
@@ -198,6 +198,9 @@ func ParseType1Program(data []byte) (Type1Program, error) {
|
|||||||
return Type1Program{}, fmt.Errorf("Type1 font has no glyphs")
|
return Type1Program{}, fmt.Errorf("Type1 font has no glyphs")
|
||||||
}
|
}
|
||||||
for index := range program.subrs {
|
for index := range program.subrs {
|
||||||
|
if program.subrs[index] == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
program.subrs[index], err = type1CharString(program.subrs[index], program.lenIV)
|
program.subrs[index], err = type1CharString(program.subrs[index], program.lenIV)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Type1Program{}, err
|
return Type1Program{}, err
|
||||||
@@ -212,6 +215,61 @@ func ParseType1Program(data []byte) (Type1Program, error) {
|
|||||||
return program, nil
|
return program, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NormalizePDFType1 修复完整加密分段之后的PFB明文尾部,不补齐加密或字形数据
|
||||||
|
// 入参: data 原始PFB程序
|
||||||
|
// 返回: []byte 原程序或独立修复容器, bool 是否修复, error 容器或程序错误
|
||||||
|
func NormalizePDFType1(data []byte) ([]byte, bool, error) {
|
||||||
|
if len(data) < 6 || data[0] != 0x80 {
|
||||||
|
return data, false, nil
|
||||||
|
}
|
||||||
|
binarySeen := false
|
||||||
|
for offset := 0; offset+2 <= len(data) && data[offset] == 0x80; {
|
||||||
|
kind := data[offset+1]
|
||||||
|
if kind == 3 {
|
||||||
|
return data, false, nil
|
||||||
|
}
|
||||||
|
if offset+6 > len(data) || kind != 1 && kind != 2 {
|
||||||
|
return data, false, fmt.Errorf("incomplete PFB segment header")
|
||||||
|
}
|
||||||
|
length := uint64(binary.LittleEndian.Uint32(data[offset+2:]))
|
||||||
|
remaining := len(data) - offset - 6
|
||||||
|
if binarySeen && kind == 1 && remaining == 0 {
|
||||||
|
result := append(bytes.Clone(data[:offset]), 0x80, 3)
|
||||||
|
if _, err := ParseType1Program(result); err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
return result, true, nil
|
||||||
|
}
|
||||||
|
if length > uint64(remaining) {
|
||||||
|
return nil, false, fmt.Errorf("incomplete PFB encrypted or text segment")
|
||||||
|
}
|
||||||
|
if binarySeen && kind == 1 && length == 0 {
|
||||||
|
tail := data[offset+6:]
|
||||||
|
if len(tail) < 2 || !bytes.Equal(tail[len(tail)-2:], []byte{0x80, 3}) {
|
||||||
|
return data, false, fmt.Errorf("unbounded PFB text trailer")
|
||||||
|
}
|
||||||
|
text := bytes.TrimSpace(tail[:len(tail)-2])
|
||||||
|
if !bytes.HasSuffix(text, []byte("cleartomark")) {
|
||||||
|
return data, false, fmt.Errorf("PFB trailer lacks cleartomark")
|
||||||
|
}
|
||||||
|
for _, b := range bytes.TrimSuffix(text, []byte("cleartomark")) {
|
||||||
|
if b != '0' && !type1Space(b) {
|
||||||
|
return data, false, fmt.Errorf("unexpected PFB text trailer")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result := bytes.Clone(data)
|
||||||
|
binary.LittleEndian.PutUint32(result[offset+2:], uint32(len(tail)-2))
|
||||||
|
if _, err := ParseType1Program(result); err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
return result, true, nil
|
||||||
|
}
|
||||||
|
binarySeen = binarySeen || kind == 2
|
||||||
|
offset += 6 + int(length)
|
||||||
|
}
|
||||||
|
return data, false, nil
|
||||||
|
}
|
||||||
|
|
||||||
// readType1Header 读取明文字体矩阵及加密数据起点
|
// readType1Header 读取明文字体矩阵及加密数据起点
|
||||||
// 入参: data Type1程序
|
// 入参: data Type1程序
|
||||||
// 返回: []float64 字体矩阵, int 加密起点, error 头部错误
|
// 返回: []float64 字体矩阵, int 加密起点, error 头部错误
|
||||||
|
|||||||
@@ -87,6 +87,108 @@ func FileTables(data []byte, index int) (map[string][]byte, error) {
|
|||||||
return tables, nil
|
return tables, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NormalizePDFProgram 修复可确定的PDF内嵌SFNT封装,不补造TrueType轮廓或字形编号
|
||||||
|
// 入参: data 原始字体程序
|
||||||
|
// 返回: []byte 原程序或独立修复程序, bool 是否修复, error 无法确认的目录或度量错误
|
||||||
|
func NormalizePDFProgram(data []byte) ([]byte, bool, error) {
|
||||||
|
if len(data) < 12 || string(data[:4]) != "OTTO" && string(data[:4]) != "\x00\x01\x00\x00" && string(data[:4]) != "true" {
|
||||||
|
return data, false, nil
|
||||||
|
}
|
||||||
|
count := int(binary.BigEndian.Uint16(data[4:6]))
|
||||||
|
if count == 0 || count > (len(data)-12)/16 {
|
||||||
|
return nil, false, fmt.Errorf("unrecoverable PDF font directory size")
|
||||||
|
}
|
||||||
|
first := len(data)
|
||||||
|
for n := 0; n < count; n++ {
|
||||||
|
record := data[12+n*16:]
|
||||||
|
start, size := uint64(binary.BigEndian.Uint32(record[8:])), uint64(binary.BigEndian.Uint32(record[12:]))
|
||||||
|
if size != 0 && start >= 12 && start+size <= uint64(len(data)) {
|
||||||
|
first = min(first, int(start))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
changed := false
|
||||||
|
if first < 12+count*16 {
|
||||||
|
if (first-12)%16 != 0 {
|
||||||
|
return nil, false, fmt.Errorf("ambiguous PDF font directory overlap")
|
||||||
|
}
|
||||||
|
actual := (first - 12) / 16
|
||||||
|
for n := 0; n < count; n++ {
|
||||||
|
record := data[12+n*16:]
|
||||||
|
printable := true
|
||||||
|
for _, b := range record[:4] {
|
||||||
|
printable = printable && b >= 32 && b <= 126
|
||||||
|
}
|
||||||
|
if printable != (n < actual) {
|
||||||
|
return nil, false, fmt.Errorf("ambiguous PDF font table count")
|
||||||
|
}
|
||||||
|
if n < actual {
|
||||||
|
start, size := uint64(binary.BigEndian.Uint32(record[8:])), uint64(binary.BigEndian.Uint32(record[12:]))
|
||||||
|
if size != 0 && (start < uint64(first) || start+size > uint64(len(data))) {
|
||||||
|
return nil, false, fmt.Errorf("incomplete PDF font table")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data = bytes.Clone(data)
|
||||||
|
binary.BigEndian.PutUint16(data[4:6], uint16(actual))
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
tables, err := FileTables(data, 0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
if head := tables["head"]; len(head) > 54 && len(head) <= 57 {
|
||||||
|
tables["head"] = head[:54]
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if hhea := tables["hhea"]; len(hhea) > 36 && len(hhea) <= 39 && binary.BigEndian.Uint32(hhea) == 0x00010000 {
|
||||||
|
tables["hhea"] = hhea[:36]
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if maxp := tables["maxp"]; tables["glyf"] != nil && len(maxp) > 32 && len(maxp) <= 35 && binary.BigEndian.Uint32(maxp) == 0x00010000 {
|
||||||
|
tables["maxp"] = maxp[:32]
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if post := tables["post"]; len(post) > 32 && binary.BigEndian.Uint32(post) == 0x00030000 {
|
||||||
|
tables["post"] = post[:32]
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if cvt := tables["cvt "]; len(cvt)%2 != 0 && cvt[len(cvt)-1] == 0 {
|
||||||
|
tables["cvt "] = cvt[:len(cvt)-1]
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if len(tables["CFF "]) != 0 && len(tables["head"]) == 0 && len(tables["maxp"]) == 0 && len(tables["hhea"]) == 0 && len(tables["hmtx"]) == 0 {
|
||||||
|
program, _, err := WrapCFFToOTF(tables["CFF "])
|
||||||
|
return program, true, err
|
||||||
|
}
|
||||||
|
if maxp := tables["maxp"]; len(tables["CFF "]) != 0 && tables["glyf"] == nil && len(maxp) >= 6 && (binary.BigEndian.Uint32(maxp) == 0x00010000 || binary.BigEndian.Uint32(maxp) == 0x00005000 && len(maxp) != 6) {
|
||||||
|
count, err := parseCFFAndCountGlyphs(tables["CFF "])
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
if count != int(binary.BigEndian.Uint16(maxp[4:6])) {
|
||||||
|
program, _, err := WrapCFFToOTF(tables["CFF "])
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
rebuilt, err := FileTables(program, 0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
if len(tables["head"]) < 20 || !bytes.Equal(tables["head"][18:20], rebuilt["head"][18:20]) {
|
||||||
|
return nil, false, fmt.Errorf("CFF and SFNT design units differ")
|
||||||
|
}
|
||||||
|
return program, true, nil
|
||||||
|
}
|
||||||
|
tables["maxp"] = buildCFFMaxpTable(uint16(count))
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
if !changed {
|
||||||
|
return data, false, nil
|
||||||
|
}
|
||||||
|
program, err := SerializeOTF(tables)
|
||||||
|
return program, true, err
|
||||||
|
}
|
||||||
|
|
||||||
// calcTableChecksum 计算字体表校验和
|
// calcTableChecksum 计算字体表校验和
|
||||||
// 入参: data 表数据
|
// 入参: data 表数据
|
||||||
// 返回: uint32 校验和
|
// 返回: uint32 校验和
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ package geom
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
|
"slices"
|
||||||
)
|
)
|
||||||
|
|
||||||
// UnsupportedError 表示当前几何实现无法展开的描边形态
|
// UnsupportedError 表示当前几何实现无法展开的描边形态
|
||||||
@@ -347,7 +348,22 @@ func (line geometryPolyline) stroke(result Path, options StrokeOptions) (Path, e
|
|||||||
}
|
}
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
directions := make([]Point, len(points)-1)
|
segments := len(points) - 1
|
||||||
|
joins := segments - 1
|
||||||
|
caps := 0
|
||||||
|
if line.closed {
|
||||||
|
joins++
|
||||||
|
} else if options.Cap == "Round" {
|
||||||
|
caps = 8
|
||||||
|
} else if options.Cap == "Square" {
|
||||||
|
caps = 10
|
||||||
|
}
|
||||||
|
joinSize := 4
|
||||||
|
if options.Join == "" || options.Join == "Miter" {
|
||||||
|
joinSize = 5
|
||||||
|
}
|
||||||
|
result = slices.Grow(result, min(segments*5+joins*joinSize+caps, 1<<20-len(result)))
|
||||||
|
directions := make([]Point, segments)
|
||||||
for i := range directions {
|
for i := range directions {
|
||||||
a, b := points[i], points[i+1]
|
a, b := points[i], points[i+1]
|
||||||
length := math.Hypot(b.X-a.X, b.Y-a.Y)
|
length := math.Hypot(b.X-a.X, b.Y-a.Y)
|
||||||
|
|||||||
@@ -96,7 +96,7 @@ func pngColorProfile(ctx context.Context, data []byte) ([]byte, *pngColor, error
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
profile, err := io.ReadAll(io.LimitReader(contextInput{ReadCloser: reader, context: ctx}, profileLimit+1))
|
profile, err := io.ReadAll(io.LimitReader(contextInput{ReadCloser: reader, ctx: ctx}, profileLimit+1))
|
||||||
closeErr := reader.Close()
|
closeErr := reader.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
|
|||||||
@@ -139,7 +139,7 @@ func (img *EncodedImage) decodeContext(ctx context.Context, pending chan struct{
|
|||||||
close(pending)
|
close(pending)
|
||||||
img.mu.Unlock()
|
img.mu.Unlock()
|
||||||
}()
|
}()
|
||||||
pixels, _, err := image.Decode(contextInput{ReadCloser: io.NopCloser(bytes.NewReader(img.data)), context: ctx})
|
pixels, _, err := image.Decode(contextInput{ReadCloser: io.NopCloser(bytes.NewReader(img.data)), ctx: ctx})
|
||||||
if err == nil && (img.format == "jpeg" || img.profile != nil) {
|
if err == nil && (img.format == "jpeg" || img.profile != nil) {
|
||||||
var profile *pdfgo.ColorSpace
|
var profile *pdfgo.ColorSpace
|
||||||
if img.profile != nil {
|
if img.profile != nil {
|
||||||
@@ -184,7 +184,7 @@ func newEncodedImage(data []byte) (*EncodedImage, error) {
|
|||||||
// 入参: ctx 取消上下文, data 只读图片编码
|
// 入参: ctx 取消上下文, data 只读图片编码
|
||||||
// 返回: *EncodedImage 惰性图片, error 头信息、格式或取消错误
|
// 返回: *EncodedImage 惰性图片, error 头信息、格式或取消错误
|
||||||
func newEncodedImageContext(ctx context.Context, data []byte) (*EncodedImage, error) {
|
func newEncodedImageContext(ctx context.Context, data []byte) (*EncodedImage, error) {
|
||||||
config, format, err := image.DecodeConfig(contextInput{ReadCloser: io.NopCloser(bytes.NewReader(data)), context: ctx})
|
config, format, err := image.DecodeConfig(contextInput{ReadCloser: io.NopCloser(bytes.NewReader(data)), ctx: ctx})
|
||||||
if cancelErr := ctx.Err(); cancelErr != nil {
|
if cancelErr := ctx.Err(); cancelErr != nil {
|
||||||
return nil, cancelErr
|
return nil, cancelErr
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -170,7 +170,7 @@ func DecodeContext(ctx context.Context, data []byte) (img image.Image, format st
|
|||||||
img, err := DecodeTIFF(ctx, data, layout)
|
img, err := DecodeTIFF(ctx, data, layout)
|
||||||
return img, "tiff", err
|
return img, "tiff", err
|
||||||
}
|
}
|
||||||
img, format, err = image.Decode(contextInput{ReadCloser: io.NopCloser(bytes.NewReader(data)), context: ctx})
|
img, format, err = image.Decode(contextInput{ReadCloser: io.NopCloser(bytes.NewReader(data)), ctx: ctx})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return img, NormalizeFormat(format), nil
|
return img, NormalizeFormat(format), nil
|
||||||
}
|
}
|
||||||
@@ -267,7 +267,7 @@ func DecodeConfigDataContext(ctx context.Context, data []byte) (config image.Con
|
|||||||
cfg.Width, cfg.Height = size.X, size.Y
|
cfg.Width, cfg.Height = size.X, size.Y
|
||||||
return cfg, "tiff", nil
|
return cfg, "tiff", nil
|
||||||
}
|
}
|
||||||
cfg, format, err := image.DecodeConfig(contextInput{ReadCloser: io.NopCloser(bytes.NewReader(data)), context: ctx})
|
cfg, format, err := image.DecodeConfig(contextInput{ReadCloser: io.NopCloser(bytes.NewReader(data)), ctx: ctx})
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return cfg, NormalizeFormat(format), nil
|
return cfg, NormalizeFormat(format), nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,14 +22,14 @@ import (
|
|||||||
// contextInput 在读取图像编码时检查调用方取消状态
|
// contextInput 在读取图像编码时检查调用方取消状态
|
||||||
type contextInput struct {
|
type contextInput struct {
|
||||||
io.ReadCloser
|
io.ReadCloser
|
||||||
context context.Context
|
ctx context.Context
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read 检查取消状态后读取原始数据
|
// Read 检查取消状态后读取原始数据
|
||||||
// 入参: data 数据缓冲区
|
// 入参: data 数据缓冲区
|
||||||
// 返回: int 读取字节数, error 读取或取消错误
|
// 返回: int 读取字节数, error 读取或取消错误
|
||||||
func (r contextInput) Read(data []byte) (int, error) {
|
func (r contextInput) Read(data []byte) (int, error) {
|
||||||
if err := r.context.Err(); err != nil {
|
if err := r.ctx.Err(); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
return r.ReadCloser.Read(data)
|
return r.ReadCloser.Read(data)
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ func (s rasterImageSource) RGBA64At(x, y int) color.RGBA64 {
|
|||||||
return color.RGBA64{R: uint16(r), G: uint16(g), B: uint16(b), A: uint16(a)}
|
return color.RGBA64{R: uint16(r), G: uint16(g), B: uint16(b), A: uint16(a)}
|
||||||
}
|
}
|
||||||
|
|
||||||
// drawRasterAxisImage 按像素中心进行轴向缩放,逐行复用横向采样并保留镜像与小数坐标
|
// drawRasterAxisImage 轴向缩放复用逐行采样,细轴按面积覆盖并保留镜像与小数坐标
|
||||||
// 入参: dst 目标图像, src 源图像, m 像素变换, op 合成操作
|
// 入参: dst 目标图像, src 源图像, m 像素变换, op 合成操作
|
||||||
// 返回: bool 是否使用轴向采样
|
// 返回: bool 是否使用轴向采样
|
||||||
func drawRasterAxisImage(dst draw.Image, src image.Image, m [6]float64, op draw.Op) bool {
|
func drawRasterAxisImage(dst draw.Image, src image.Image, m [6]float64, op draw.Op) bool {
|
||||||
@@ -78,8 +78,14 @@ func drawRasterAxisImage(dst draw.Image, src image.Image, m [6]float64, op draw.
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if float64(r.Dx())*math.Min(float64(r.Dy()), math.Ceil(4*math.Max(1, sy))+2) > rasterScaleBufferLimit/32 {
|
if float64(r.Dx())*math.Min(float64(r.Dy()), math.Ceil(4*math.Max(1, sy))+2) > rasterScaleBufferLimit/32 {
|
||||||
|
if sx*float64(b.Dx()) < 1 || sy*float64(b.Dy()) < 1 {
|
||||||
|
return drawRasterFootprintImage(dst, src, m, op, r)
|
||||||
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
if !rasterFootprintWeightsFit(b, r, m) {
|
||||||
|
return drawRasterFootprintImage(dst, src, m, op, r)
|
||||||
|
}
|
||||||
xs := rasterImageAxis(r.Min.X, r.Max.X, b.Min.X, b.Max.X, m[0], m[4])
|
xs := rasterImageAxis(r.Min.X, r.Max.X, b.Min.X, b.Max.X, m[0], m[4])
|
||||||
ys := rasterImageAxis(r.Min.Y, r.Max.Y, b.Min.Y, b.Max.Y, m[3], m[5])
|
ys := rasterImageAxis(r.Min.Y, r.Max.Y, b.Min.Y, b.Max.Y, m[3], m[5])
|
||||||
if len(xs) == 0 || len(ys) == 0 {
|
if len(xs) == 0 || len(ys) == 0 {
|
||||||
@@ -139,10 +145,13 @@ func drawRasterAxisImage(dst draw.Image, src image.Image, m [6]float64, op draw.
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// rasterImageAxis 按连续源坐标生成CatmullRom权重,不对图像几何边界取整
|
// rasterImageAxis 按连续源坐标生成CatmullRom权重,亚像素细轴使用面积覆盖权重
|
||||||
// 入参: first 目标起点, end 目标终点, source 源起点, limit 源终点, scale 缩放比例, offset 平移距离
|
// 入参: first 目标起点, end 目标终点, source 源起点, limit 源终点, scale 缩放比例, offset 平移距离
|
||||||
// 返回: []rasterAxisSample 轴向采样表
|
// 返回: []rasterAxisSample 轴向采样表
|
||||||
func rasterImageAxis(first, end, source, limit int, scale, offset float64) []rasterAxisSample {
|
func rasterImageAxis(first, end, source, limit int, scale, offset float64) []rasterAxisSample {
|
||||||
|
if math.Abs(scale)*float64(limit-source) < 1 {
|
||||||
|
return rasterImageFootprintAxis(first, end, source, limit, scale, offset)
|
||||||
|
}
|
||||||
result := make([]rasterAxisSample, 0, end-first)
|
result := make([]rasterAxisSample, 0, end-first)
|
||||||
argument := math.Min(1, math.Abs(scale))
|
argument := math.Min(1, math.Abs(scale))
|
||||||
support := draw.CatmullRom.Support / argument
|
support := draw.CatmullRom.Support / argument
|
||||||
@@ -183,6 +192,142 @@ func rasterImageAxis(first, end, source, limit int, scale, offset float64) []ras
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// rasterFootprintWeightsFit 检查细轴权重表的合计预算,乘法前排除溢出
|
||||||
|
// 入参: source 源边界, target 目标范围, m 像素变换
|
||||||
|
// 返回: bool 权重表是否符合预算
|
||||||
|
func rasterFootprintWeightsFit(source, target image.Rectangle, m [6]float64) bool {
|
||||||
|
budget := rasterScaleBufferLimit / 8
|
||||||
|
for _, axis := range [...]struct {
|
||||||
|
source, target int
|
||||||
|
scale float64
|
||||||
|
}{{source.Dx(), target.Dx(), m[0]}, {source.Dy(), target.Dy(), m[3]}} {
|
||||||
|
if math.Abs(axis.scale)*float64(axis.source) < 1 && axis.target > 0 {
|
||||||
|
n, samples := axis.source, min(2, axis.target)
|
||||||
|
if n > budget/samples {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
budget -= n * samples
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// rasterImageWeightSpan 提供单个目标像素的源范围和权重,不分配整轴权重表
|
||||||
|
// 入参: pixel 目标像素, source 源起点, limit 源终点, scale 缩放比例, offset 平移距离
|
||||||
|
// 返回: int 源起点, int 源终点, func(int)float64 源权重
|
||||||
|
func rasterImageWeightSpan(pixel, source, limit int, scale, offset float64) (int, int, func(int) float64) {
|
||||||
|
if math.Abs(scale)*float64(limit-source) < 1 {
|
||||||
|
left, right := (float64(pixel)-offset)/scale, (float64(pixel+1)-offset)/scale
|
||||||
|
if right < left {
|
||||||
|
left, right = right, left
|
||||||
|
}
|
||||||
|
if right <= float64(source) || left >= float64(limit) {
|
||||||
|
return 0, 0, nil
|
||||||
|
}
|
||||||
|
return source, limit, func(x int) float64 {
|
||||||
|
return math.Max(0, math.Min(float64(x)+1, right)-math.Max(float64(x), left)) * math.Abs(scale)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
center := (float64(pixel) + .5 - offset) / scale
|
||||||
|
if center < float64(source) || center >= float64(limit) {
|
||||||
|
return 0, 0, nil
|
||||||
|
}
|
||||||
|
center -= .5
|
||||||
|
argument := math.Min(1, math.Abs(scale))
|
||||||
|
support := draw.CatmullRom.Support / argument
|
||||||
|
start := int(max(float64(source), math.Floor(center-support)))
|
||||||
|
stop := int(min(float64(limit), math.Ceil(center+support)))
|
||||||
|
weight := func(x int) float64 {
|
||||||
|
distance := math.Abs((float64(x) - center) * argument)
|
||||||
|
if distance < draw.CatmullRom.Support {
|
||||||
|
return draw.CatmullRom.At(distance)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
var total float64
|
||||||
|
for x := start; x < stop; x++ {
|
||||||
|
total += weight(x)
|
||||||
|
}
|
||||||
|
return start, stop, func(x int) float64 { return weight(x) / total }
|
||||||
|
}
|
||||||
|
|
||||||
|
// drawRasterFootprintImage 在细轴权重超预算时按原累加顺序逐点绘制
|
||||||
|
// 入参: dst 目标图像, src 源图像, m 像素变换, op 合成操作, target 目标范围
|
||||||
|
// 返回: bool 是否完成绘制
|
||||||
|
func drawRasterFootprintImage(dst draw.Image, src image.Image, m [6]float64, op draw.Op, target image.Rectangle) bool {
|
||||||
|
pixels, ok := src.(image.RGBA64Image)
|
||||||
|
if !ok {
|
||||||
|
pixels = rasterImageSource{src}
|
||||||
|
}
|
||||||
|
b := src.Bounds()
|
||||||
|
output := image.NewRGBA64(image.Rect(0, 0, 1, 1))
|
||||||
|
var value [1]rasterImagePixel
|
||||||
|
for y := target.Min.Y; y < target.Max.Y; y++ {
|
||||||
|
firstY, endY, wy := rasterImageWeightSpan(y, b.Min.Y, b.Max.Y, m[3], m[5])
|
||||||
|
if firstY == endY {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for x := target.Min.X; x < target.Max.X; x++ {
|
||||||
|
firstX, endX, wx := rasterImageWeightSpan(x, b.Min.X, b.Max.X, m[0], m[4])
|
||||||
|
if firstX == endX {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
value[0] = rasterImagePixel{}
|
||||||
|
for sy := firstY; sy < endY; sy++ {
|
||||||
|
var row rasterImagePixel
|
||||||
|
for sx := firstX; sx < endX; sx++ {
|
||||||
|
p, weight := pixels.RGBA64At(sx, sy), wx(sx)
|
||||||
|
if weight != 0 {
|
||||||
|
row.r += float64(p.R) * weight
|
||||||
|
row.g += float64(p.G) * weight
|
||||||
|
row.b += float64(p.B) * weight
|
||||||
|
row.a += float64(p.A) * weight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if weight := wy(sy); weight != 0 {
|
||||||
|
value[0].r += row.r * weight
|
||||||
|
value[0].g += row.g * weight
|
||||||
|
value[0].b += row.b * weight
|
||||||
|
value[0].a += row.a * weight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rasterImageWriteRow(dst, output, value[:], x, y, op)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// rasterImageFootprintAxis 对不足一个目标像素的整轴保留真实交叠面积及预乘透明度
|
||||||
|
// 入参: first 目标起点, end 目标终点, source 源起点, limit 源终点, scale 缩放比例, offset 平移距离
|
||||||
|
// 返回: []rasterAxisSample 轴向覆盖权重
|
||||||
|
func rasterImageFootprintAxis(first, end, source, limit int, scale, offset float64) []rasterAxisSample {
|
||||||
|
lo, hi := float64(source)*scale+offset, float64(limit)*scale+offset
|
||||||
|
if hi < lo {
|
||||||
|
lo, hi = hi, lo
|
||||||
|
}
|
||||||
|
result := make([]rasterAxisSample, 0, min(2, end-first))
|
||||||
|
for pixel := first; pixel < end; pixel++ {
|
||||||
|
if math.Min(float64(pixel+1), hi) > math.Max(float64(pixel), lo) {
|
||||||
|
result = append(result, rasterAxisSample{pixel: pixel, first: source})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buffer := make([]float64, len(result)*(limit-source))
|
||||||
|
for index := range result {
|
||||||
|
sample := &result[index]
|
||||||
|
left, right := (float64(sample.pixel)-offset)/scale, (float64(sample.pixel+1)-offset)/scale
|
||||||
|
if right < left {
|
||||||
|
left, right = right, left
|
||||||
|
}
|
||||||
|
n := limit - source
|
||||||
|
sample.weights, buffer = buffer[:n:n], buffer[n:]
|
||||||
|
for i := range sample.weights {
|
||||||
|
x := float64(source + i)
|
||||||
|
sample.weights[i] = math.Max(0, math.Min(x+1, right)-math.Max(x, left)) * math.Abs(scale)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
// rasterImageHorizontal 按源列复用像素,保留各目标像素的权重累加顺序与中间精度
|
// rasterImageHorizontal 按源列复用像素,保留各目标像素的权重累加顺序与中间精度
|
||||||
// 入参: row 横向缓冲, src 源像素, samples 采样表, y 源行坐标
|
// 入参: row 横向缓冲, src 源像素, samples 采样表, y 源行坐标
|
||||||
func rasterImageHorizontal(row []rasterImagePixel, src image.RGBA64Image, samples []rasterAxisSample, y int) {
|
func rasterImageHorizontal(row []rasterImagePixel, src image.RGBA64Image, samples []rasterAxisSample, y int) {
|
||||||
|
|||||||
@@ -165,7 +165,7 @@ func readTIFFDirectory(ctx context.Context, input io.Reader, order binary.ByteOr
|
|||||||
if offset < position {
|
if offset < position {
|
||||||
return result, position, ErrTIFFRandomAccess
|
return result, position, ErrTIFFRandomAccess
|
||||||
}
|
}
|
||||||
reader := contextInput{ReadCloser: io.NopCloser(input), context: ctx}
|
reader := contextInput{ReadCloser: io.NopCloser(input), ctx: ctx}
|
||||||
if _, err := io.CopyN(io.Discard, reader, offset-position); err != nil {
|
if _, err := io.CopyN(io.Discard, reader, offset-position); err != nil {
|
||||||
return result, position, err
|
return result, position, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -211,11 +211,11 @@ func (s *u3dLineState) accumulateCorners(mesh *U3DMesh, shadingIndex uint32, cor
|
|||||||
}
|
}
|
||||||
|
|
||||||
// value 按指定上下文和位宽读取点集或线集字段
|
// value 按指定上下文和位宽读取点集或线集字段
|
||||||
// 入参: context 压缩上下文, small 是否为8位字段
|
// 入参: ctx 压缩上下文, small 是否为8位字段
|
||||||
// 返回: uint32 字段值
|
// 返回: uint32 字段值
|
||||||
func (r *u3dLineReader) value(context int, small bool) uint32 {
|
func (r *u3dLineReader) value(ctx int, small bool) uint32 {
|
||||||
if r.bits != nil {
|
if r.bits != nil {
|
||||||
return r.bits.dynamicValue(&r.hist[context], small)
|
return r.bits.dynamicValue(&r.hist[ctx], small)
|
||||||
}
|
}
|
||||||
if small {
|
if small {
|
||||||
return uint32(r.values.u8())
|
return uint32(r.values.u8())
|
||||||
|
|||||||
@@ -167,15 +167,15 @@ func (r *u3dResourceReader) motionFrame(frame *U3DKeyFrame, previous U3DKeyFrame
|
|||||||
}
|
}
|
||||||
|
|
||||||
// motionDifference 用共享幅值上下文恢复一至三个差分分量
|
// motionDifference 用共享幅值上下文恢复一至三个差分分量
|
||||||
// 入参: previous 前一帧分量, scale 逆量化系数, context 符号上下文,下一项为幅值上下文
|
// 入参: previous 前一帧分量, scale 逆量化系数, ctx 符号上下文,下一项为幅值上下文
|
||||||
// 返回: [3]float32 重建分量, error 符号、数值或读取错误
|
// 返回: [3]float32 重建分量, error 符号、数值或读取错误
|
||||||
func (r *u3dResourceReader) motionDifference(previous []float32, scale float32, context int) (values [3]float32, err error) {
|
func (r *u3dResourceReader) motionDifference(previous []float32, scale float32, ctx int) (values [3]float32, err error) {
|
||||||
signs := r.value(context, true)
|
signs := r.value(ctx, true)
|
||||||
if signs >= 1<<len(previous) {
|
if signs >= 1<<len(previous) {
|
||||||
return values, fmt.Errorf("invalid U3D motion difference signs")
|
return values, fmt.Errorf("invalid U3D motion difference signs")
|
||||||
}
|
}
|
||||||
for index, prior := range previous {
|
for index, prior := range previous {
|
||||||
difference := float64(r.value(context+1, false)) * float64(scale)
|
difference := float64(r.value(ctx+1, false)) * float64(scale)
|
||||||
if signs&(1<<index) != 0 {
|
if signs&(1<<index) != 0 {
|
||||||
difference = -difference
|
difference = -difference
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,9 +30,9 @@ type u3dResourceReader struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// value 读取指定上下文的压缩字段,首次使用时初始化算术区间
|
// value 读取指定上下文的压缩字段,首次使用时初始化算术区间
|
||||||
// 入参: context 压缩上下文, small 是否为8位字段
|
// 入参: ctx 压缩上下文, small 是否为8位字段
|
||||||
// 返回: uint32 字段值
|
// 返回: uint32 字段值
|
||||||
func (r *u3dResourceReader) value(context int, small bool) uint32 {
|
func (r *u3dResourceReader) value(ctx int, small bool) uint32 {
|
||||||
if r.err() != nil {
|
if r.err() != nil {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
@@ -52,7 +52,7 @@ func (r *u3dResourceReader) value(context int, small bool) uint32 {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return r.bits.dynamicValue(&r.hist[context], small)
|
return r.bits.dynamicValue(&r.hist[ctx], small)
|
||||||
}
|
}
|
||||||
|
|
||||||
// u32 读取普通32位字段,压缩开始后沿用当前算术区间
|
// u32 读取普通32位字段,压缩开始后沿用当前算术区间
|
||||||
|
|||||||
@@ -12,9 +12,6 @@
|
|||||||
// See the License for the specific language governing permissions and
|
// See the License for the specific language governing permissions and
|
||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
|
|
||||||
//go:build !windows
|
package build
|
||||||
|
|
||||||
package webview
|
var Version string
|
||||||
|
|
||||||
// conversionMemory 未提供系统内存探测时仅按并行数调度
|
|
||||||
var conversionMemory func() int64
|
|
||||||
@@ -340,3 +340,18 @@ func PaintChannels(values [4]float64, compatible bool, marked *[4]bool) [4]bool
|
|||||||
}
|
}
|
||||||
return channels
|
return channels
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// OpaqueBlack 判断不受底层分色影响的全黑设备色
|
||||||
|
// 入参: paint PDF颜色与不透明度
|
||||||
|
// 返回: bool 是否为不透明全黑CMYK颜色
|
||||||
|
func OpaqueBlack(paint pdfgo.Paint) bool {
|
||||||
|
return paint.Alpha == 1 && paint.CMYK != nil && paint.CMYK[3] == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// OverprintNeedsSeparation 判断彩色CMYK套印是否依赖分色输出
|
||||||
|
// 入参: paint PDF颜色与不透明度
|
||||||
|
// 返回: bool 是否需要保留分色语义
|
||||||
|
func OverprintNeedsSeparation(paint pdfgo.Paint) bool {
|
||||||
|
_, process := paint.Process.CMYKMask()
|
||||||
|
return (paint.CMYK != nil || process) && !OpaqueBlack(paint)
|
||||||
|
}
|
||||||
@@ -31,10 +31,11 @@ type TextPage struct {
|
|||||||
Replacements []pdfgo.TextReplacement
|
Replacements []pdfgo.TextReplacement
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteOptions 保存PDF最终写出所需的像素、文字和导航修正
|
// WriteOptions 保存PDF最终写出所需的元数据、像素、文字和导航修正
|
||||||
// Images逐页记录绘制图像,nil图像表示不替换;Links保留全部链接位置,包括矩形区域的nil项
|
// Images逐页记录绘制图像,nil图像表示不替换;Links保留全部链接位置,包括矩形区域的nil项
|
||||||
// PrepareRewrite在页面引用确定后填充导航动作,不得提前写出PDF
|
// PrepareRewrite在页面引用确定后填充导航动作,不得提前写出PDF
|
||||||
type WriteOptions struct {
|
type WriteOptions struct {
|
||||||
|
Information pdfgo.Dictionary
|
||||||
Images [][]image.Image
|
Images [][]image.Image
|
||||||
Text []TextPage
|
Text []TextPage
|
||||||
Links map[int][]*pdfgo.LinkRegion
|
Links map[int][]*pdfgo.LinkRegion
|
||||||
@@ -49,7 +50,7 @@ type WriteOptions struct {
|
|||||||
// 返回: error 资源、压缩或写入错误
|
// 返回: error 资源、压缩或写入错误
|
||||||
func Write(ctx context.Context, data []byte, writer io.Writer, settings WriteOptions) error {
|
func Write(ctx context.Context, data []byte, writer io.Writer, settings WriteOptions) error {
|
||||||
nativeWrite := settings.PrepareRewrite != nil
|
nativeWrite := settings.PrepareRewrite != nil
|
||||||
if !settings.ExactImages && !settings.ExactText && !nativeWrite && settings.Optimization.Compression.Mode == pdfgo.CompressionUnchanged {
|
if !settings.ExactImages && !settings.ExactText && !nativeWrite && len(settings.Information) == 0 && settings.Optimization.Compression.Mode == pdfgo.CompressionUnchanged {
|
||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -65,6 +66,10 @@ func Write(ctx context.Context, data []byte, writer io.Writer, settings WriteOpt
|
|||||||
}
|
}
|
||||||
defer reader.Close()
|
defer reader.Close()
|
||||||
if !settings.ExactImages && !settings.ExactText && !nativeWrite {
|
if !settings.ExactImages && !settings.ExactText && !nativeWrite {
|
||||||
|
if len(settings.Information) != 0 {
|
||||||
|
_, err := reader.RewriteTo(ctx, writer, pdfgo.RewriteOptions{Information: settings.Information, Optimization: settings.Optimization})
|
||||||
|
return err
|
||||||
|
}
|
||||||
_, err := reader.OptimizeTo(ctx, writer, settings.Optimization)
|
_, err := reader.OptimizeTo(ctx, writer, settings.Optimization)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -171,7 +176,7 @@ func Write(ctx context.Context, data []byte, writer io.Writer, settings WriteOpt
|
|||||||
if pages != len(settings.Images) {
|
if pages != len(settings.Images) {
|
||||||
return fmt.Errorf("PDF output page missing")
|
return fmt.Errorf("PDF output page missing")
|
||||||
}
|
}
|
||||||
options := pdfgo.RewriteOptions{Images: images, ImageOptions: pdfgo.ImageWriteOptions{PreblendBinary: true}, LinkRegions: links, TextReplacements: texts, Optimization: settings.Optimization}
|
options := pdfgo.RewriteOptions{Information: settings.Information, Images: images, ImageOptions: pdfgo.ImageWriteOptions{PreblendBinary: true}, LinkRegions: links, TextReplacements: texts, Optimization: settings.Optimization}
|
||||||
if nativeWrite {
|
if nativeWrite {
|
||||||
if err := settings.PrepareRewrite(ctx, reader, references, &options); err != nil {
|
if err := settings.PrepareRewrite(ctx, reader, references, &options); err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ package pdf
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
basegeom "github.com/xiaoqidun/ofdgo/internal/base/geom"
|
basegeom "github.com/xiaoqidun/ofdgo/internal/base/geom"
|
||||||
"github.com/xiaoqidun/pdfgo"
|
"github.com/xiaoqidun/pdfgo"
|
||||||
@@ -99,3 +101,67 @@ func GlyphPath(outline basegeom.Path, matrix pdfgo.Matrix) (pdfgo.Path, error) {
|
|||||||
}
|
}
|
||||||
return path, nil
|
return path, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PathBounds 逐段计算变换后的控制点边界,不创建临时点集合
|
||||||
|
// 入参: ctx 取消上下文, path PDF路径, matrix 坐标变换
|
||||||
|
// 返回: basegeom.Box 控制点边界,空路径返回零值, error 取消错误
|
||||||
|
func PathBounds(ctx context.Context, path pdfgo.Path, matrix pdfgo.Matrix) (basegeom.Box, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return basegeom.Box{}, err
|
||||||
|
}
|
||||||
|
minX, minY, maxX, maxY := math.Inf(1), math.Inf(1), math.Inf(-1), math.Inf(-1)
|
||||||
|
found := false
|
||||||
|
for _, segment := range path.Segments {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return basegeom.Box{}, err
|
||||||
|
}
|
||||||
|
for index, point := range segment.Points {
|
||||||
|
if index&255 == 0 {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return basegeom.Box{}, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
point = matrix.Apply(point)
|
||||||
|
minX, minY = math.Min(minX, point.X), math.Min(minY, point.Y)
|
||||||
|
maxX, maxY = math.Max(maxX, point.X), math.Max(maxY, point.Y)
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return basegeom.Box{}, err
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
return basegeom.Box{}, nil
|
||||||
|
}
|
||||||
|
return basegeom.Box{X: minX, Y: minY, W: math.Max(maxX-minX, 1e-6), H: math.Max(maxY-minY, 1e-6)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PathData 转换路径并在分段处理时检查取消
|
||||||
|
// 入参: ctx 取消上下文, path PDF路径, matrix 坐标变换, origin 对象边界
|
||||||
|
// 返回: string OFD路径数据, error 取消错误
|
||||||
|
func PathData(ctx context.Context, path pdfgo.Path, matrix pdfgo.Matrix, origin basegeom.Box) (string, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
data := make([]byte, 0, len(path.Segments)*48)
|
||||||
|
for index, segment := range path.Segments {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if index != 0 {
|
||||||
|
data = append(data, ' ')
|
||||||
|
}
|
||||||
|
data = append(data, segment.Operator...)
|
||||||
|
for _, point := range segment.Points {
|
||||||
|
point = matrix.Apply(point)
|
||||||
|
data = append(data, ' ')
|
||||||
|
data = strconv.AppendFloat(data, point.X-origin.X, 'g', -1, 64)
|
||||||
|
data = append(data, ' ')
|
||||||
|
data = strconv.AppendFloat(data, point.Y-origin.Y, 'g', -1, 64)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return string(data), nil
|
||||||
|
}
|
||||||
+12
-12
@@ -28,6 +28,18 @@ import (
|
|||||||
"github.com/xiaoqidun/pdfgo"
|
"github.com/xiaoqidun/pdfgo"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// StencilImage 按当前填充色读取模板图像,不分配整幅彩色样本
|
||||||
|
type StencilImage struct {
|
||||||
|
Source image.Image
|
||||||
|
Fill color.NRGBA64
|
||||||
|
}
|
||||||
|
|
||||||
|
// NativeImage 按源像素输出原生过程色,不分配完整显示颜色缓冲
|
||||||
|
type NativeImage struct {
|
||||||
|
Source *pdfgo.ImageProcess
|
||||||
|
Space *pdfgo.ColorSpace
|
||||||
|
}
|
||||||
|
|
||||||
// EncodeCMYKTIFF 将直接四色图像保存为十六位无损TIFF,不经过显示颜色转换
|
// EncodeCMYKTIFF 将直接四色图像保存为十六位无损TIFF,不经过显示颜色转换
|
||||||
// 入参: ctx 取消上下文, source PDF源图像
|
// 入参: ctx 取消上下文, source PDF源图像
|
||||||
// 返回: []byte 含ICC和非预乘透明度的TIFF,非四色图像为nil, error 解码或编码错误
|
// 返回: []byte 含ICC和非预乘透明度的TIFF,非四色图像为nil, error 解码或编码错误
|
||||||
@@ -143,18 +155,6 @@ func EncodeCMYKTIFF(ctx context.Context, source *pdfgo.Image) ([]byte, error) {
|
|||||||
return data, nil
|
return data, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// StencilImage 按当前填充色读取模板图像,不分配整幅彩色样本
|
|
||||||
type StencilImage struct {
|
|
||||||
Source image.Image
|
|
||||||
Fill color.NRGBA64
|
|
||||||
}
|
|
||||||
|
|
||||||
// NativeImage 按源像素输出原生过程色,不分配完整显示颜色缓冲
|
|
||||||
type NativeImage struct {
|
|
||||||
Source *pdfgo.ImageProcess
|
|
||||||
Space *pdfgo.ColorSpace
|
|
||||||
}
|
|
||||||
|
|
||||||
// ColorModel 保留填充色和模板的有效采样精度
|
// ColorModel 保留填充色和模板的有效采样精度
|
||||||
// 返回: color.Model 非预乘颜色模型
|
// 返回: color.Model 非预乘颜色模型
|
||||||
func (s *StencilImage) ColorModel() color.Model {
|
func (s *StencilImage) ColorModel() color.Model {
|
||||||
|
|||||||
@@ -0,0 +1,306 @@
|
|||||||
|
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package pdf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"slices"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/xiaoqidun/pdfgo"
|
||||||
|
)
|
||||||
|
|
||||||
|
// meshVertex 保存局部毫米坐标及原曲面参数
|
||||||
|
type meshVertex struct {
|
||||||
|
point pdfgo.Point
|
||||||
|
u, v float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// MeshTriangle 保存按输出精度细分的曲面网格
|
||||||
|
type MeshTriangle struct {
|
||||||
|
vertices [3]meshVertex
|
||||||
|
patch int
|
||||||
|
}
|
||||||
|
|
||||||
|
// meshSample 保存采样点参数,patch为一基编号,零表示未覆盖
|
||||||
|
type meshSample struct {
|
||||||
|
u, v float64
|
||||||
|
patch int
|
||||||
|
}
|
||||||
|
|
||||||
|
// MeshRasterOptions 保存网格采样的坐标、精度及并行配置
|
||||||
|
// Matrix将PDF页面坐标转换为毫米,Origin为输出块的毫米原点
|
||||||
|
type MeshRasterOptions struct {
|
||||||
|
Matrix pdfgo.Matrix
|
||||||
|
Origin pdfgo.Point
|
||||||
|
DPI float64
|
||||||
|
Width, Height int
|
||||||
|
Workers int
|
||||||
|
SoftMask bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// MeshEdge 按坐标及颜色分量匹配相邻三角形的共享边,不改变顶点顺序
|
||||||
|
// 入参: previous 前一三角形, current 当前三角形
|
||||||
|
// 返回: int OFD共享边标志,零表示独立三角形
|
||||||
|
func MeshEdge(previous, current pdfgo.MeshTriangle) int {
|
||||||
|
if previous.Points[2] != current.Points[1] || !slices.Equal(previous.Colors[2], current.Colors[1]) {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
for _, index := range [2]int{1, 0} {
|
||||||
|
if previous.Points[index] == current.Points[0] && slices.Equal(previous.Colors[index], current.Colors[0]) {
|
||||||
|
return 2 - index
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// MeshTriangles 按曲面二阶导数界细分,将几何误差控制在输出像素的十六分之一内
|
||||||
|
// 入参: ctx 取消上下文, mesh 原始曲面, matrix 页面变换, dpi 输出精度
|
||||||
|
// 返回: []MeshTriangle 细分结果, error 取消或坐标错误
|
||||||
|
func MeshTriangles(ctx context.Context, mesh *pdfgo.MeshGradient, matrix pdfgo.Matrix, dpi float64) ([]MeshTriangle, error) {
|
||||||
|
matrix = matrix.Mul(mesh.Matrix)
|
||||||
|
var triangles []MeshTriangle
|
||||||
|
for index, patch := range mesh.Patches {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for i := range patch.Points {
|
||||||
|
for j := range patch.Points[i] {
|
||||||
|
patch.Points[i][j] = matrix.Apply(patch.Points[i][j])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var duu, dvv, duv float64
|
||||||
|
for i := 0; i < 4; i++ {
|
||||||
|
for j := 0; j < 4; j++ {
|
||||||
|
a := patch.Points[i][j]
|
||||||
|
if i < 2 {
|
||||||
|
b, c := patch.Points[i+1][j], patch.Points[i+2][j]
|
||||||
|
duu = math.Max(duu, 6*math.Hypot(c.X-2*b.X+a.X, c.Y-2*b.Y+a.Y))
|
||||||
|
}
|
||||||
|
if j < 2 {
|
||||||
|
b, c := patch.Points[i][j+1], patch.Points[i][j+2]
|
||||||
|
dvv = math.Max(dvv, 6*math.Hypot(c.X-2*b.X+a.X, c.Y-2*b.Y+a.Y))
|
||||||
|
}
|
||||||
|
if i < 3 && j < 3 {
|
||||||
|
b, c, d := patch.Points[i+1][j], patch.Points[i][j+1], patch.Points[i+1][j+1]
|
||||||
|
duv = math.Max(duv, 9*math.Hypot(d.X-b.X-c.X+a.X, d.Y-b.Y-c.Y+a.Y))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
steps := math.Max(1, math.Ceil(math.Sqrt(8*(duu+dvv+2*duv)*dpi/25.4)))
|
||||||
|
if !finite(steps) || steps >= math.Sqrt(float64(int(^uint(0)>>1)/2)) {
|
||||||
|
return nil, fmt.Errorf("mesh subdivision exceeds platform integer range")
|
||||||
|
}
|
||||||
|
n := int(steps)
|
||||||
|
row := make([]meshVertex, n+1)
|
||||||
|
for i := range row {
|
||||||
|
if i%CompositeTileSize == 0 {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
u := float64(i) / steps
|
||||||
|
row[i] = meshVertex{patch.PointAt(u, 0), u, 0}
|
||||||
|
}
|
||||||
|
for j := 1; j <= n; j++ {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
v := float64(j) / steps
|
||||||
|
left := meshVertex{patch.PointAt(0, v), 0, v}
|
||||||
|
for i := 1; i <= n; i++ {
|
||||||
|
u := float64(i) / steps
|
||||||
|
right := meshVertex{patch.PointAt(u, v), u, v}
|
||||||
|
a, b := row[i-1], row[i]
|
||||||
|
triangles = append(triangles, MeshTriangle{[3]meshVertex{a, b, left}, index}, MeshTriangle{[3]meshVertex{b, right, left}, index})
|
||||||
|
row[i-1], left = left, right
|
||||||
|
}
|
||||||
|
row[n] = left
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for index, triangle := range mesh.Triangles {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
vertices := [3]meshVertex{
|
||||||
|
{matrix.Apply(triangle.Points[0]), 0, 0},
|
||||||
|
{matrix.Apply(triangle.Points[1]), 1, 0},
|
||||||
|
{matrix.Apply(triangle.Points[2]), 0, 1},
|
||||||
|
}
|
||||||
|
triangles = append(triangles, MeshTriangle{vertices, len(mesh.Patches) + index})
|
||||||
|
}
|
||||||
|
return triangles, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MeshPixels 对输出块执行四倍超采样,曲面重叠按后补片及较大v、u取值
|
||||||
|
// 入参: ctx 取消上下文, mesh 原曲面, triangles 已细分网格, space 混合空间, converter 已准备的颜色转换, options 采样配置
|
||||||
|
// 返回: []ShadingPixel 颜色及覆盖, error 几何、颜色或取消错误
|
||||||
|
func MeshPixels(ctx context.Context, mesh *pdfgo.MeshGradient, triangles []MeshTriangle, space *pdfgo.ColorSpace, converter pdfgo.ColorConverter, options MeshRasterOptions) ([]ShadingPixel, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
const samples = 4
|
||||||
|
w, h := options.Width*samples, options.Height*samples
|
||||||
|
grid := make([]meshSample, w*h)
|
||||||
|
scale := options.DPI / 25.4 * samples
|
||||||
|
for _, triangle := range triangles {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
vertices := triangle.vertices
|
||||||
|
for i := range vertices {
|
||||||
|
vertices[i].point.X = (vertices[i].point.X - options.Origin.X) * scale
|
||||||
|
vertices[i].point.Y = (vertices[i].point.Y - options.Origin.Y) * scale
|
||||||
|
}
|
||||||
|
a, b, d := vertices[0].point, vertices[1].point, vertices[2].point
|
||||||
|
denominator := (b.Y-d.Y)*(a.X-d.X) + (d.X-b.X)*(a.Y-d.Y)
|
||||||
|
if denominator == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
minX, maxX := math.Min(a.X, math.Min(b.X, d.X)), math.Max(a.X, math.Max(b.X, d.X))
|
||||||
|
minY, maxY := math.Min(a.Y, math.Min(b.Y, d.Y)), math.Max(a.Y, math.Max(b.Y, d.Y))
|
||||||
|
if maxX < 0 || maxY < 0 || minX >= float64(w) || minY >= float64(h) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
endX := int(math.Min(float64(w), math.Ceil(maxX)))
|
||||||
|
endY := int(math.Min(float64(h), math.Ceil(maxY)))
|
||||||
|
for y := int(math.Max(0, math.Floor(minY))); y < endY; y++ {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for x := int(math.Max(0, math.Floor(minX))); x < endX; x++ {
|
||||||
|
px, py := float64(x)+.5, float64(y)+.5
|
||||||
|
l0 := ((b.Y-d.Y)*(px-d.X) + (d.X-b.X)*(py-d.Y)) / denominator
|
||||||
|
l1 := ((d.Y-a.Y)*(px-d.X) + (a.X-d.X)*(py-d.Y)) / denominator
|
||||||
|
l2 := 1 - l0 - l1
|
||||||
|
if l0 < -1e-10 || l1 < -1e-10 || l2 < -1e-10 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
u := math.Max(0, math.Min(1, l0*vertices[0].u+l1*vertices[1].u+l2*vertices[2].u))
|
||||||
|
v := math.Max(0, math.Min(1, l0*vertices[0].v+l1*vertices[1].v+l2*vertices[2].v))
|
||||||
|
current := &grid[y*w+x]
|
||||||
|
if triangle.patch+1 > current.patch || triangle.patch+1 == current.patch && (v > current.v || v == current.v && u > current.u) {
|
||||||
|
*current = meshSample{u, v, triangle.patch + 1}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pixels := make([]ShadingPixel, options.Width*options.Height)
|
||||||
|
var background [4]float64
|
||||||
|
if mesh.Background != nil {
|
||||||
|
var err error
|
||||||
|
background, err = converter.Convert(mesh.Background[:mesh.Space.Components()])
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var inverse pdfgo.Matrix
|
||||||
|
if mesh.Bounds != nil {
|
||||||
|
var ok bool
|
||||||
|
inverse, ok = options.Matrix.Mul(mesh.Matrix).Inverse()
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("singular mesh bounds transform")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sampleRows := func(start, end int) error {
|
||||||
|
colors := make(map[[4]float64][4]float64)
|
||||||
|
colorants := PrepareShadingColorants(pdfgo.Paint{Mesh: mesh}, space, options.SoftMask)
|
||||||
|
var sampler *pdfgo.MeshSampler
|
||||||
|
if colorants == nil {
|
||||||
|
sampler = mesh.NewSampler()
|
||||||
|
}
|
||||||
|
for y := start * samples; y < end*samples; y++ {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for x := 0; x < w; x++ {
|
||||||
|
if box := mesh.Bounds; box != nil {
|
||||||
|
point := inverse.Apply(pdfgo.Point{X: options.Origin.X + (float64(x)+.5)/scale, Y: options.Origin.Y + (float64(y)+.5)/scale})
|
||||||
|
if point.X < box.XMin || point.X > box.XMax || point.Y < box.YMin || point.Y > box.YMax {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sample := grid[y*w+x]
|
||||||
|
if sample.patch == 0 && mesh.Background == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
values := background
|
||||||
|
if sample.patch != 0 {
|
||||||
|
var err error
|
||||||
|
if colorants != nil {
|
||||||
|
values, err = colorants.MeshAt(sample.patch-1, sample.u, sample.v)
|
||||||
|
} else {
|
||||||
|
values, err = sampler.ValuesAt(sample.patch-1, sample.u, sample.v)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if cached, ok := colors[values]; ok {
|
||||||
|
values = cached
|
||||||
|
} else if colorants == nil {
|
||||||
|
source := values
|
||||||
|
values, err = converter.Convert(values[:mesh.Space.Components()])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(colors) == 2*CompositeTileSize {
|
||||||
|
clear(colors)
|
||||||
|
}
|
||||||
|
colors[source] = values
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pixel := &pixels[(y/samples)*options.Width+x/samples]
|
||||||
|
for i, value := range values {
|
||||||
|
pixel.Values[i] += value
|
||||||
|
}
|
||||||
|
pixel.Shape++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
workers := min(max(1, options.Workers), max(1, options.Height/32))
|
||||||
|
if workers == 1 {
|
||||||
|
if err := sampleRows(0, options.Height); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var group sync.WaitGroup
|
||||||
|
errors := make([]error, workers)
|
||||||
|
for worker := range workers {
|
||||||
|
group.Go(func() {
|
||||||
|
errors[worker] = sampleRows(worker*options.Height/workers, (worker+1)*options.Height/workers)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
group.Wait()
|
||||||
|
for _, err := range errors {
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := range pixels {
|
||||||
|
pixel := &pixels[i]
|
||||||
|
if pixel.Shape == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for j := range pixel.Values {
|
||||||
|
pixel.Values[j] /= pixel.Shape
|
||||||
|
}
|
||||||
|
pixel.Shape /= samples * samples
|
||||||
|
}
|
||||||
|
return pixels, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package pdf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/xiaoqidun/pdfgo"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NormalizeDate 校验PDF日期,非严格模式修正单层外括号及完整时区偏移的分隔符
|
||||||
|
// 入参: text PDF日期字符串, strict 是否严格校验
|
||||||
|
// 返回: string 标准日期字符串, error 日期错误
|
||||||
|
func NormalizeDate(text string, strict bool) (string, error) {
|
||||||
|
if text == "" {
|
||||||
|
return text, nil
|
||||||
|
}
|
||||||
|
_, err := pdfgo.ParseDate(text)
|
||||||
|
if err == nil || strict {
|
||||||
|
return text, err
|
||||||
|
}
|
||||||
|
normalized := text
|
||||||
|
if strings.HasPrefix(normalized, "(") && strings.HasSuffix(normalized, ")") {
|
||||||
|
normalized = normalized[1 : len(normalized)-1]
|
||||||
|
if _, parseErr := pdfgo.ParseDate(normalized); parseErr == nil {
|
||||||
|
return normalized, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
offset := len(normalized) - 5
|
||||||
|
if offset < 6 || normalized[offset] != '+' && normalized[offset] != '-' {
|
||||||
|
return text, err
|
||||||
|
}
|
||||||
|
for _, digit := range normalized[offset+1:] {
|
||||||
|
if digit < '0' || digit > '9' {
|
||||||
|
return text, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
normalized = normalized[:offset+3] + "'" + normalized[offset+3:] + "'"
|
||||||
|
if _, parseErr := pdfgo.ParseDate(normalized); parseErr != nil {
|
||||||
|
return text, err
|
||||||
|
}
|
||||||
|
return normalized, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MetadataDate 保留当地日历日期,PDF省略时区按GMT,XMP省略日或时区时不推算
|
||||||
|
// 入参: text 来源日期, xmp 是否为XMP日期
|
||||||
|
// 返回: time.Time 解析值, bool 是否精确到日, bool 是否可比较绝对时间, error 日期错误
|
||||||
|
func MetadataDate(text string, xmp bool) (time.Time, bool, bool, error) {
|
||||||
|
if text == "" {
|
||||||
|
return time.Time{}, false, false, nil
|
||||||
|
}
|
||||||
|
if !xmp {
|
||||||
|
date, err := pdfgo.ParseDate(text)
|
||||||
|
return date, err == nil && date.Year() > 0, err == nil, err
|
||||||
|
}
|
||||||
|
if !strings.Contains(text, ",") {
|
||||||
|
for _, layout := range []string{time.RFC3339Nano, "2006-01-02T15:04Z07:00", "2006-01-02T15:04:05", "2006-01-02T15:04", "2006-01-02", "2006-01", "2006"} {
|
||||||
|
if date, err := time.Parse(layout, text); err == nil {
|
||||||
|
zoned := strings.Contains(layout, "Z07:00")
|
||||||
|
if zoned && !strings.HasSuffix(text, "Z") {
|
||||||
|
zone := text[len(text)-6:]
|
||||||
|
if zone[1:3] > "23" || zone[4:] > "59" {
|
||||||
|
return time.Time{}, false, false, fmt.Errorf("invalid XMP time zone")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return date, len(text) >= 10 && date.Year() > 0, zoned, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return time.Time{}, false, false, fmt.Errorf("invalid XMP date")
|
||||||
|
}
|
||||||
@@ -0,0 +1,375 @@
|
|||||||
|
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package pdf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"compress/zlib"
|
||||||
|
"context"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"io"
|
||||||
|
"maps"
|
||||||
|
"math"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/xiaoqidun/pdfgo"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PrintPlacement 保存源PDF页索引及毫米纸面上的变换和裁剪
|
||||||
|
type PrintPlacement struct {
|
||||||
|
Page int
|
||||||
|
Matrix [6]float64
|
||||||
|
Clip [4]float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// PrintSheet 保存一个纸面的物理尺寸、放置内容和辅助线
|
||||||
|
type PrintSheet struct {
|
||||||
|
Width, Height float64
|
||||||
|
Placements []PrintPlacement
|
||||||
|
Lines [][4]float64
|
||||||
|
Label string
|
||||||
|
LabelX, LabelY float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// printPDFObjects 写出自有打印对象,原PDF资源仅复制实际引用的部分
|
||||||
|
type printPDFObjects struct {
|
||||||
|
ctx context.Context
|
||||||
|
objects []pdfgo.Object
|
||||||
|
copied map[pdfgo.Reference]pdfgo.Reference
|
||||||
|
source *pdfgo.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
// printPDFNumbers 编码内容流数值,不使用PDF语法不接受的科学记数法
|
||||||
|
// 入参: out 内容流缓冲区, values 待编码数值
|
||||||
|
func printPDFNumbers(out *bytes.Buffer, values ...float64) {
|
||||||
|
for _, value := range values {
|
||||||
|
out.WriteString(strconv.FormatFloat(value, 'f', -1, 64))
|
||||||
|
out.WriteByte(' ')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// add 登记一个独立输出对象
|
||||||
|
// 入参: object 待登记对象
|
||||||
|
// 返回: pdfgo.Reference 输出对象引用
|
||||||
|
func (p *printPDFObjects) add(object pdfgo.Object) pdfgo.Reference {
|
||||||
|
p.objects = append(p.objects, object)
|
||||||
|
return pdfgo.Reference{Number: int64(len(p.objects))}
|
||||||
|
}
|
||||||
|
|
||||||
|
// copy 递归复制资源并改写引用,保留流编码及资源共享
|
||||||
|
// 入参: object 待复制对象, depth 当前递归深度
|
||||||
|
// 返回: pdfgo.Object 改写引用后的对象, error 资源、嵌套或取消错误
|
||||||
|
func (p *printPDFObjects) copy(object pdfgo.Object, depth int) (pdfgo.Object, error) {
|
||||||
|
if err := p.ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if depth > 256 {
|
||||||
|
return nil, fmt.Errorf("print PDF resource nesting too deep")
|
||||||
|
}
|
||||||
|
switch value := object.(type) {
|
||||||
|
case pdfgo.Reference:
|
||||||
|
if next, ok := p.copied[value]; ok {
|
||||||
|
return next, nil
|
||||||
|
}
|
||||||
|
next := p.add(nil)
|
||||||
|
p.copied[value] = next
|
||||||
|
resolved, err := p.source.Object(value)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
copied, err := p.copy(resolved, depth+1)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
p.objects[next.Number-1] = copied
|
||||||
|
return next, nil
|
||||||
|
case pdfgo.Dictionary:
|
||||||
|
result := make(pdfgo.Dictionary, len(value))
|
||||||
|
for key, item := range value {
|
||||||
|
copied, err := p.copy(item, depth+1)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
result[key] = copied
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
case pdfgo.Array:
|
||||||
|
result := make(pdfgo.Array, len(value))
|
||||||
|
for i, item := range value {
|
||||||
|
copied, err := p.copy(item, depth+1)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
result[i] = copied
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
case *pdfgo.Stream:
|
||||||
|
dict := maps.Clone(value.Dictionary)
|
||||||
|
delete(dict, "Length")
|
||||||
|
copied, err := p.copy(dict, depth+1)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &pdfgo.Stream{Dictionary: copied.(pdfgo.Dictionary), Data: value.Data}, nil
|
||||||
|
default:
|
||||||
|
return object, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WritePrintPDF 将源页面作为独立表单放置,保持矢量、文字、资源及透明组
|
||||||
|
// 入参: ctx 输出上下文, writer 输出流, source 源PDF数据, sheets 有序纸面
|
||||||
|
// 返回: error 资源、编码、写入或取消错误
|
||||||
|
func WritePrintPDF(ctx context.Context, writer io.Writer, source []byte, sheets []PrintSheet) error {
|
||||||
|
var reader *pdfgo.Reader
|
||||||
|
if len(source) > 0 {
|
||||||
|
var err error
|
||||||
|
reader, err = pdfgo.NewReader(bytes.NewReader(source), int64(len(source)))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer reader.Close()
|
||||||
|
}
|
||||||
|
p := &printPDFObjects{ctx: ctx, objects: make([]pdfgo.Object, 2), copied: make(map[pdfgo.Reference]pdfgo.Reference), source: reader}
|
||||||
|
var pages []*pdfgo.Page
|
||||||
|
if reader != nil {
|
||||||
|
if err := reader.WalkPages(ctx, func(_ int, page *pdfgo.Page) error { pages = append(pages, page); return nil }); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
forms := make(map[int]pdfgo.Reference)
|
||||||
|
var children pdfgo.Array
|
||||||
|
const pt = 72.0 / 25.4
|
||||||
|
for _, sheet := range sheets {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var content bytes.Buffer
|
||||||
|
objects := make(pdfgo.Dictionary)
|
||||||
|
for _, placement := range sheet.Placements {
|
||||||
|
if placement.Page < 0 || placement.Page >= len(pages) {
|
||||||
|
return fmt.Errorf("print PDF page outside source")
|
||||||
|
}
|
||||||
|
page := pages[placement.Page]
|
||||||
|
if page.Rotation != 0 || page.UserUnit != 1 {
|
||||||
|
return fmt.Errorf("print PDF backend must normalize page rotation and units")
|
||||||
|
}
|
||||||
|
form, ok := forms[placement.Page]
|
||||||
|
if !ok {
|
||||||
|
resources, err := p.copy(page.Resources, 0)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var data bytes.Buffer
|
||||||
|
if _, err := page.WriteContent(ctx, &data); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
box := page.MediaBox
|
||||||
|
dict := pdfgo.Dictionary{"Type": pdfgo.Name("XObject"), "Subtype": pdfgo.Name("Form"), "FormType": pdfgo.Integer(1), "BBox": pdfgo.Array{pdfgo.Real(box.XMin), pdfgo.Real(box.YMin), pdfgo.Real(box.XMax), pdfgo.Real(box.YMax)}, "Resources": resources}
|
||||||
|
if group := page.Dictionary["Group"]; group != nil {
|
||||||
|
copied, err := p.copy(group, 0)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
dict["Group"] = copied
|
||||||
|
}
|
||||||
|
form = p.add(&pdfgo.Stream{Dictionary: dict, Data: data.Bytes()})
|
||||||
|
forms[placement.Page] = form
|
||||||
|
}
|
||||||
|
name := pdfgo.Name(fmt.Sprintf("P%d", placement.Page))
|
||||||
|
objects[name] = form
|
||||||
|
c, m := placement.Clip, placement.Matrix
|
||||||
|
hs := (page.MediaBox.YMax - page.MediaBox.YMin) / pt
|
||||||
|
x0, y0 := page.MediaBox.XMin, page.MediaBox.YMin
|
||||||
|
content.WriteString("q ")
|
||||||
|
printPDFNumbers(&content, c[0]*pt, (sheet.Height-c[1]-c[3])*pt, c[2]*pt, c[3]*pt)
|
||||||
|
content.WriteString("re W n ")
|
||||||
|
printPDFNumbers(&content, m[0], -m[1], -m[2], m[3], (m[2]*hs+m[4])*pt-m[0]*x0+m[2]*y0, (sheet.Height-m[3]*hs-m[5])*pt+m[1]*x0-m[3]*y0)
|
||||||
|
fmt.Fprintf(&content, "cm /%s Do Q\n", name)
|
||||||
|
}
|
||||||
|
for _, line := range sheet.Lines {
|
||||||
|
content.WriteString("q 0 G ")
|
||||||
|
printPDFNumbers(&content, 0.15*pt)
|
||||||
|
content.WriteString("w ")
|
||||||
|
printPDFNumbers(&content, line[0]*pt, (sheet.Height-line[1])*pt)
|
||||||
|
content.WriteString("m ")
|
||||||
|
printPDFNumbers(&content, line[2]*pt, (sheet.Height-line[3])*pt)
|
||||||
|
content.WriteString("l S Q\n")
|
||||||
|
}
|
||||||
|
resources := pdfgo.Dictionary{"XObject": objects}
|
||||||
|
if sheet.Label != "" {
|
||||||
|
content.WriteString("q 0 g BT /Label 7.94 Tf 1 0 0 1 ")
|
||||||
|
printPDFNumbers(&content, sheet.LabelX*pt, (sheet.Height-sheet.LabelY)*pt)
|
||||||
|
content.WriteString("Tm ")
|
||||||
|
if err := printPDFObject(&content, pdfgo.String(sheet.Label), 0); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
content.WriteString(" Tj ET Q\n")
|
||||||
|
resources["Font"] = pdfgo.Dictionary{"Label": pdfgo.Dictionary{"Type": pdfgo.Name("Font"), "Subtype": pdfgo.Name("Type1"), "BaseFont": pdfgo.Name("Helvetica")}}
|
||||||
|
}
|
||||||
|
stream := p.add(&pdfgo.Stream{Dictionary: pdfgo.Dictionary{}, Data: content.Bytes()})
|
||||||
|
children = append(children, p.add(pdfgo.Dictionary{"Type": pdfgo.Name("Page"), "Parent": pdfgo.Reference{Number: 2}, "MediaBox": pdfgo.Array{pdfgo.Integer(0), pdfgo.Integer(0), pdfgo.Real(sheet.Width * pt), pdfgo.Real(sheet.Height * pt)}, "Resources": resources, "Contents": stream}))
|
||||||
|
}
|
||||||
|
return p.write(writer, children)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WritePrintImages 逐纸面消费光栅结果,不在输出对象中保留未压缩像素
|
||||||
|
// 入参: ctx 输出上下文, writer 输出流, sheets 有序纸面, render 按索引渲染纸面
|
||||||
|
// 返回: error 渲染、编码、写入或取消错误
|
||||||
|
func WritePrintImages(ctx context.Context, writer io.Writer, sheets []PrintSheet, render func(int) (image.Image, error)) error {
|
||||||
|
p := &printPDFObjects{ctx: ctx, objects: make([]pdfgo.Object, 2)}
|
||||||
|
var children pdfgo.Array
|
||||||
|
const pt = 72.0 / 25.4
|
||||||
|
for i, sheet := range sheets {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
img, err := render(i)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var data bytes.Buffer
|
||||||
|
compressed := zlib.NewWriter(&data)
|
||||||
|
b := img.Bounds()
|
||||||
|
row := make([]byte, b.Dx()*3)
|
||||||
|
for y := b.Min.Y; y < b.Max.Y; y++ {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for x := b.Min.X; x < b.Max.X; x++ {
|
||||||
|
r, g, blue, _ := img.At(x, y).RGBA()
|
||||||
|
offset := (x - b.Min.X) * 3
|
||||||
|
row[offset], row[offset+1], row[offset+2] = byte(r>>8), byte(g>>8), byte(blue>>8)
|
||||||
|
}
|
||||||
|
if _, err := compressed.Write(row); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := compressed.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
picture := p.add(&pdfgo.Stream{Dictionary: pdfgo.Dictionary{"Type": pdfgo.Name("XObject"), "Subtype": pdfgo.Name("Image"), "Width": pdfgo.Integer(b.Dx()), "Height": pdfgo.Integer(b.Dy()), "ColorSpace": pdfgo.Name("DeviceRGB"), "BitsPerComponent": pdfgo.Integer(8), "Filter": pdfgo.Name("FlateDecode")}, Data: data.Bytes()})
|
||||||
|
var content bytes.Buffer
|
||||||
|
content.WriteString("q ")
|
||||||
|
printPDFNumbers(&content, sheet.Width*pt, 0, 0, sheet.Height*pt, 0, 0)
|
||||||
|
content.WriteString("cm /I Do Q\n")
|
||||||
|
stream := p.add(&pdfgo.Stream{Dictionary: pdfgo.Dictionary{}, Data: content.Bytes()})
|
||||||
|
children = append(children, p.add(pdfgo.Dictionary{"Type": pdfgo.Name("Page"), "Parent": pdfgo.Reference{Number: 2}, "MediaBox": pdfgo.Array{pdfgo.Integer(0), pdfgo.Integer(0), pdfgo.Real(sheet.Width * pt), pdfgo.Real(sheet.Height * pt)}, "Resources": pdfgo.Dictionary{"XObject": pdfgo.Dictionary{"I": picture}}, "Contents": stream}))
|
||||||
|
}
|
||||||
|
return p.write(writer, children)
|
||||||
|
}
|
||||||
|
|
||||||
|
// write 写出完整对象表和交叉引用,失败时由调用方丢弃输出
|
||||||
|
// 入参: writer 输出流, children 页面对象引用
|
||||||
|
// 返回: error 编码、写入或取消错误
|
||||||
|
func (p *printPDFObjects) write(writer io.Writer, children pdfgo.Array) error {
|
||||||
|
p.objects[0] = pdfgo.Dictionary{"Type": pdfgo.Name("Catalog"), "Pages": pdfgo.Reference{Number: 2}}
|
||||||
|
p.objects[1] = pdfgo.Dictionary{"Type": pdfgo.Name("Pages"), "Count": pdfgo.Integer(len(children)), "Kids": children}
|
||||||
|
var out bytes.Buffer
|
||||||
|
out.WriteString("%PDF-1.7\n%\xe2\xe3\xcf\xd3\n")
|
||||||
|
offsets := make([]int, len(p.objects))
|
||||||
|
for i, object := range p.objects {
|
||||||
|
if err := p.ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
offsets[i] = out.Len()
|
||||||
|
fmt.Fprintf(&out, "%d 0 obj\n", i+1)
|
||||||
|
if err := printPDFObject(&out, object, 0); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out.WriteString("\nendobj\n")
|
||||||
|
}
|
||||||
|
xref := out.Len()
|
||||||
|
fmt.Fprintf(&out, "xref\n0 %d\n0000000000 65535 f \n", len(offsets)+1)
|
||||||
|
for _, offset := range offsets {
|
||||||
|
fmt.Fprintf(&out, "%010d 00000 n \n", offset)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&out, "trailer\n<</Size %d/Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n", len(offsets)+1, xref)
|
||||||
|
return Write(p.ctx, out.Bytes(), writer, WriteOptions{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// printPDFObject 编码已复制的标准PDF对象,名称和字符串按字节转义
|
||||||
|
// 入参: out 对象缓冲区, object 待编码对象, depth 当前递归深度
|
||||||
|
// 返回: error 类型或嵌套错误
|
||||||
|
func printPDFObject(out *bytes.Buffer, object pdfgo.Object, depth int) error {
|
||||||
|
if depth > 256 {
|
||||||
|
return fmt.Errorf("print PDF object nesting too deep")
|
||||||
|
}
|
||||||
|
switch value := object.(type) {
|
||||||
|
case nil:
|
||||||
|
out.WriteString("null")
|
||||||
|
case pdfgo.Boolean:
|
||||||
|
fmt.Fprintf(out, "%t", value)
|
||||||
|
case pdfgo.Integer:
|
||||||
|
fmt.Fprintf(out, "%d", value)
|
||||||
|
case pdfgo.Real:
|
||||||
|
if math.IsNaN(float64(value)) || math.IsInf(float64(value), 0) {
|
||||||
|
return fmt.Errorf("invalid print PDF number")
|
||||||
|
}
|
||||||
|
out.WriteString(strconv.FormatFloat(float64(value), 'f', -1, 64))
|
||||||
|
case pdfgo.Reference:
|
||||||
|
fmt.Fprintf(out, "%d %d R", value.Number, value.Generation)
|
||||||
|
case pdfgo.Name:
|
||||||
|
out.WriteByte('/')
|
||||||
|
for _, b := range []byte(value) {
|
||||||
|
if b <= 32 || b >= 127 || strings.ContainsRune("()<>[]{}/%#", rune(b)) {
|
||||||
|
fmt.Fprintf(out, "#%02X", b)
|
||||||
|
} else {
|
||||||
|
out.WriteByte(b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case pdfgo.String:
|
||||||
|
out.WriteByte('<')
|
||||||
|
out.WriteString(hex.EncodeToString(value))
|
||||||
|
out.WriteByte('>')
|
||||||
|
case pdfgo.Array:
|
||||||
|
out.WriteByte('[')
|
||||||
|
for _, item := range value {
|
||||||
|
if err := printPDFObject(out, item, depth+1); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out.WriteByte(' ')
|
||||||
|
}
|
||||||
|
out.WriteByte(']')
|
||||||
|
case pdfgo.Dictionary:
|
||||||
|
out.WriteString("<<")
|
||||||
|
for _, key := range slices.Sorted(maps.Keys(value)) {
|
||||||
|
if err := printPDFObject(out, key, depth+1); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out.WriteByte(' ')
|
||||||
|
if err := printPDFObject(out, value[key], depth+1); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out.WriteByte('\n')
|
||||||
|
}
|
||||||
|
out.WriteString(">>")
|
||||||
|
case *pdfgo.Stream:
|
||||||
|
dict := maps.Clone(value.Dictionary)
|
||||||
|
dict["Length"] = pdfgo.Integer(len(value.Data))
|
||||||
|
if err := printPDFObject(out, dict, depth+1); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out.WriteString("\nstream\n")
|
||||||
|
out.Write(value.Data)
|
||||||
|
out.WriteString("\nendstream")
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unsupported print PDF object %T", object)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package pdf
|
||||||
|
|
||||||
|
import "image"
|
||||||
|
|
||||||
|
// CompositeTileSize 限定单次合成块的像素边长
|
||||||
|
const CompositeTileSize = 256
|
||||||
|
|
||||||
|
// CompositeBuffers 在一次局部合成中保留至多八个块容量内的空闲缓冲
|
||||||
|
type CompositeBuffers[T any] [8][]T
|
||||||
|
|
||||||
|
// RasterBuffers 保存按像素尺寸复用的独占覆盖画布
|
||||||
|
type RasterBuffers [8]*image.RGBA
|
||||||
|
|
||||||
|
// CoverageRow 读取完整范围内的原生覆盖行,其他类型沿用逐点采样
|
||||||
|
// 入参: coverage 覆盖图像, y 行坐标, left 起始列, right 结束列
|
||||||
|
// 返回: []byte RGBA像素或空值
|
||||||
|
func CoverageRow(coverage image.Image, y, left, right int) []byte {
|
||||||
|
buffer, ok := coverage.(*image.RGBA)
|
||||||
|
if !ok || y < buffer.Rect.Min.Y || y >= buffer.Rect.Max.Y || left < buffer.Rect.Min.X || right > buffer.Rect.Max.X || left >= right {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
start := buffer.PixOffset(left, y)
|
||||||
|
return buffer.Pix[start : start+4*(right-left)]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Acquire 借用尚未初始化的独立缓冲,嵌套调用不复用活动缓冲
|
||||||
|
// 入参: count 所需元素数量
|
||||||
|
// 返回: []T 可由当前调用独占的缓冲
|
||||||
|
func (s *CompositeBuffers[T]) Acquire(count int) []T {
|
||||||
|
selected := -1
|
||||||
|
for i, buffer := range s {
|
||||||
|
if cap(buffer) >= count && (selected < 0 || cap(buffer) < cap(s[selected])) {
|
||||||
|
selected = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if selected < 0 {
|
||||||
|
return make([]T, count)
|
||||||
|
}
|
||||||
|
buffer := s[selected]
|
||||||
|
s[selected] = nil
|
||||||
|
return buffer[:count]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Release 归还已不再访问的缓冲,超出块容量或空闲槽数量时直接释放
|
||||||
|
// 入参: buffer 当前调用借用的缓冲
|
||||||
|
func (s *CompositeBuffers[T]) Release(buffer []T) {
|
||||||
|
if len(buffer) == 0 || cap(buffer) > CompositeTileSize*CompositeTileSize {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for i, stored := range s {
|
||||||
|
if stored == nil {
|
||||||
|
s[i] = buffer
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Acquire 借用尺寸相同的独占画布,不清空已有像素
|
||||||
|
// 入参: rect 输出像素范围
|
||||||
|
// 返回: *image.RGBA 当前调用独占的画布
|
||||||
|
func (s *RasterBuffers) Acquire(rect image.Rectangle) *image.RGBA {
|
||||||
|
for i, stored := range s {
|
||||||
|
if stored != nil && stored.Rect == rect {
|
||||||
|
s[i] = nil
|
||||||
|
return stored
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return image.NewRGBA(rect)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Release 归还块容量内的画布,超出容量或空闲槽数量时直接释放
|
||||||
|
// 入参: buffer 当前调用借用的画布
|
||||||
|
func (s *RasterBuffers) Release(buffer *image.RGBA) {
|
||||||
|
if buffer == nil || cap(buffer.Pix) > 4*CompositeTileSize*CompositeTileSize {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for i, stored := range s {
|
||||||
|
if stored == nil {
|
||||||
|
s[i] = buffer
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,6 +18,12 @@ import (
|
|||||||
"github.com/xiaoqidun/pdfgo"
|
"github.com/xiaoqidun/pdfgo"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ShadingPixel 保存抗锯齿覆盖率与混合空间分量
|
||||||
|
type ShadingPixel struct {
|
||||||
|
Values [4]float64
|
||||||
|
Shape float64
|
||||||
|
}
|
||||||
|
|
||||||
// ShadingColorants 复用原始浓度缓冲及原生通道映射,不跨并发采样共享
|
// ShadingColorants 复用原始浓度缓冲及原生通道映射,不跨并发采样共享
|
||||||
type ShadingColorants struct {
|
type ShadingColorants struct {
|
||||||
paint pdfgo.Paint
|
paint pdfgo.Paint
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package pdf
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math"
|
||||||
|
"reflect"
|
||||||
|
|
||||||
|
"github.com/xiaoqidun/pdfgo"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MergeReplacement 统一同一替换区段内的坐标原点,不重新塑形或调整字距
|
||||||
|
// 入参: marks 连续文字图元, replacement 整段原文
|
||||||
|
// 返回: *pdfgo.TextMark 合并文字, bool 是否可等价合并
|
||||||
|
func MergeReplacement(marks []*pdfgo.TextMark, replacement *pdfgo.ReplacementText) (*pdfgo.TextMark, bool) {
|
||||||
|
first := marks[0]
|
||||||
|
style := first.Style
|
||||||
|
paint := style.Fill
|
||||||
|
if first.Font == nil || len(first.Font.Program) == 0 || first.Mode != 0 || first.Size <= 0 || first.HorizontalScale <= 0 || first.Clip != nil || style.SoftMask != nil || style.Transfer != nil || style.AlphaIsShape || style.FillOverprint || paint.Alpha != 1 || !NormalBlend(style.BlendMode) || paint.Tiling != nil || paint.Axial != nil || paint.Radial != nil || paint.Mesh != nil || paint.Function != nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
inverse, ok := first.Matrix.Inverse()
|
||||||
|
if !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
count := 0
|
||||||
|
sequence := first.Sequence
|
||||||
|
for _, mark := range marks {
|
||||||
|
if mark.Font != first.Font || mark.Size != first.Size || mark.HorizontalScale != first.HorizontalScale || mark.Mode != first.Mode || mark.Clip != nil || len(mark.Glyphs) != len(mark.Positions) || !reflect.DeepEqual(mark.Style, style) {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if mark.Matrix[0] != first.Matrix[0] || mark.Matrix[1] != first.Matrix[1] || mark.Matrix[2] != first.Matrix[2] || mark.Matrix[3] != first.Matrix[3] {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
count += len(mark.Glyphs)
|
||||||
|
sequence = CommonSequence(sequence, mark.Sequence)
|
||||||
|
}
|
||||||
|
if count == 0 {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
merged := *first
|
||||||
|
merged.Replacement = replacement
|
||||||
|
merged.Sequence = sequence
|
||||||
|
merged.Glyphs = make([]pdfgo.Glyph, 0, count)
|
||||||
|
merged.Positions = make([]pdfgo.Point, 0, count)
|
||||||
|
for _, mark := range marks {
|
||||||
|
dx, dy := mark.Matrix[4]-first.Matrix[4], mark.Matrix[5]-first.Matrix[5]
|
||||||
|
offset := pdfgo.Point{X: inverse[0]*dx + inverse[2]*dy, Y: inverse[1]*dx + inverse[3]*dy}
|
||||||
|
for _, point := range mark.Positions {
|
||||||
|
point.X += offset.X
|
||||||
|
point.Y += offset.Y
|
||||||
|
if math.IsNaN(point.X) || math.IsNaN(point.Y) || math.IsInf(point.X, 0) || math.IsInf(point.Y, 0) {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
merged.Positions = append(merged.Positions, point)
|
||||||
|
}
|
||||||
|
merged.Glyphs = append(merged.Glyphs, mark.Glyphs...)
|
||||||
|
}
|
||||||
|
return &merged, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// CommonSequence 查找两个内容区段的最近共同外层,不将合并内容归入单个子区段
|
||||||
|
// 入参: first 首个区段, second 后续区段
|
||||||
|
// 返回: *pdfgo.ContentSequence 共同区段,没有共同区段时为空
|
||||||
|
func CommonSequence(first, second *pdfgo.ContentSequence) *pdfgo.ContentSequence {
|
||||||
|
if first == second {
|
||||||
|
return first
|
||||||
|
}
|
||||||
|
if first == nil || second == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
depth := func(sequence *pdfgo.ContentSequence) int {
|
||||||
|
count := 0
|
||||||
|
for ; sequence != nil; sequence = sequence.Parent {
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
a, b := depth(first), depth(second)
|
||||||
|
for ; a > b; a-- {
|
||||||
|
first = first.Parent
|
||||||
|
}
|
||||||
|
for ; b > a; b-- {
|
||||||
|
second = second.Parent
|
||||||
|
}
|
||||||
|
for first != second {
|
||||||
|
first, second = first.Parent, second.Parent
|
||||||
|
}
|
||||||
|
return first
|
||||||
|
}
|
||||||
+1184
-396
File diff suppressed because it is too large.
Load diff
+263
-25
@@ -24,8 +24,10 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"maps"
|
||||||
"math"
|
"math"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
@@ -63,12 +65,17 @@ type NativeOutputTarget struct {
|
|||||||
Base, Name string
|
Base, Name string
|
||||||
}
|
}
|
||||||
|
|
||||||
// NativeEngine 保存独立会话,不同实例可并行,同一实例的回调不可重入Call或Close
|
// NativeEngine 保存独立会话,页面渲染可并行,修改等待已开始的只读任务完成
|
||||||
|
// 同一实例的回调不可重入Call或Close
|
||||||
// hooks应在首次Call前配置,Resolve返回的资源需保持有效直到相应会话关闭
|
// hooks应在首次Call前配置,Resolve返回的资源需保持有效直到相应会话关闭
|
||||||
type NativeEngine struct {
|
type NativeEngine struct {
|
||||||
businessEngine
|
businessEngine
|
||||||
|
// Resources 协调会话的计算与缓存,需在首次Call前配置
|
||||||
|
Resources *ofdgo.Resources
|
||||||
// ConversionPool 协调不同会话的批量转换资源
|
// ConversionPool 协调不同会话的批量转换资源
|
||||||
ConversionPool *ofdgo.ConversionPool
|
ConversionPool *ofdgo.ConversionPool
|
||||||
|
// RenderParallelism 限制同时渲染的页面数,零值使用可用处理器数
|
||||||
|
RenderParallelism int
|
||||||
// Resolve 按授权标识提供资源读取源
|
// Resolve 按授权标识提供资源读取源
|
||||||
Resolve NativeResolver
|
Resolve NativeResolver
|
||||||
// LoadFont 按名称读取系统字体数据
|
// LoadFont 按名称读取系统字体数据
|
||||||
@@ -82,13 +89,19 @@ type NativeEngine struct {
|
|||||||
CleanupOutput func(context.Context, NativeOutputTarget) error
|
CleanupOutput func(context.Context, NativeOutputTarget) error
|
||||||
gate chan struct{}
|
gate chan struct{}
|
||||||
once sync.Once
|
once sync.Once
|
||||||
|
saves sync.WaitGroup
|
||||||
closed bool
|
closed bool
|
||||||
|
renderMu sync.Mutex
|
||||||
|
renderCount int
|
||||||
|
renderDone chan struct{}
|
||||||
|
renderSlots chan struct{}
|
||||||
|
renderIdle []*Session
|
||||||
}
|
}
|
||||||
|
|
||||||
// nativeReader 在会话当前操作上下文中分块读取,不捕获已结束请求的上下文
|
// nativeReader 在会话当前操作上下文中分块读取,不捕获已结束请求的上下文
|
||||||
type nativeReader struct {
|
type nativeReader struct {
|
||||||
engine *NativeEngine
|
engine *NativeEngine
|
||||||
source io.ReaderAt
|
input io.ReaderAt
|
||||||
}
|
}
|
||||||
|
|
||||||
// nativeCall 保存单次worker适配状态
|
// nativeCall 保存单次worker适配状态
|
||||||
@@ -138,24 +151,144 @@ func NewNativeEngine(resolve NativeResolver) *NativeEngine { return &NativeEngin
|
|||||||
func (e *NativeEngine) Call(ctx context.Context, name string, args []any, emit func(any)) (result map[string]any) {
|
func (e *NativeEngine) Call(ctx context.Context, name string, args []any, emit func(any)) (result map[string]any) {
|
||||||
e.once.Do(func() {
|
e.once.Do(func() {
|
||||||
e.gate = make(chan struct{}, 1)
|
e.gate = make(chan struct{}, 1)
|
||||||
e.resolveSource = e.source
|
e.renderSlots = make(chan struct{}, e.renderParallelism())
|
||||||
|
e.resolveInput = e.input
|
||||||
e.conversionPool = e.ConversionPool
|
e.conversionPool = e.ConversionPool
|
||||||
|
e.resources = e.Resources
|
||||||
})
|
})
|
||||||
if ctx == nil {
|
if ctx == nil {
|
||||||
ctx = context.Background()
|
ctx = context.Background()
|
||||||
}
|
}
|
||||||
|
if name == "ofdgoRenderPage" {
|
||||||
|
select {
|
||||||
|
case e.renderSlots <- struct{}{}:
|
||||||
|
defer func() { <-e.renderSlots }()
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nativeFailure(ctx.Err())
|
||||||
|
}
|
||||||
|
if e.resources != nil {
|
||||||
|
release, err := e.resources.Acquire(ctx, 64<<20)
|
||||||
|
if err != nil {
|
||||||
|
return nativeFailure(err)
|
||||||
|
}
|
||||||
|
defer release()
|
||||||
|
}
|
||||||
|
}
|
||||||
select {
|
select {
|
||||||
case e.gate <- struct{}{}:
|
case e.gate <- struct{}{}:
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return nativeFailure(ctx.Err())
|
return nativeFailure(ctx.Err())
|
||||||
}
|
}
|
||||||
defer func() { <-e.gate }()
|
locked := true
|
||||||
|
defer func() {
|
||||||
|
if locked {
|
||||||
|
<-e.gate
|
||||||
|
}
|
||||||
|
}()
|
||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return nativeFailure(err)
|
return nativeFailure(err)
|
||||||
}
|
}
|
||||||
if e.closed {
|
if e.closed {
|
||||||
return nativeFailure(fmt.Errorf("native engine is closed"))
|
return nativeFailure(fmt.Errorf("native engine is closed"))
|
||||||
}
|
}
|
||||||
|
if name == "ofdgoRenderPage" && e.currentSession != nil && e.pdf == nil {
|
||||||
|
defer func() {
|
||||||
|
if failure := recover(); failure != nil {
|
||||||
|
result = nativeFailure(fmt.Errorf("%v", failure))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
worker, err := e.renderSession(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nativeFailure(err)
|
||||||
|
}
|
||||||
|
operation := &businessEngine{currentSession: worker, currentEditor: e.currentEditor, ctx: ctx}
|
||||||
|
values := make([]platformValue, len(args))
|
||||||
|
for i, arg := range args {
|
||||||
|
values[i] = platformValueOf(arg)
|
||||||
|
}
|
||||||
|
if len(values) > 0 && operation.currentEditor != nil {
|
||||||
|
pageErr := e.prepareRender(operation, values[0].Int())
|
||||||
|
if pageErr != nil {
|
||||||
|
return nativeFailure(pageErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
operation.currentEditor = nil
|
||||||
|
e.renderMu.Lock()
|
||||||
|
if e.renderCount == 0 {
|
||||||
|
e.renderDone = make(chan struct{})
|
||||||
|
}
|
||||||
|
e.renderCount++
|
||||||
|
e.renderMu.Unlock()
|
||||||
|
<-e.gate
|
||||||
|
locked = false
|
||||||
|
defer func() {
|
||||||
|
worker.Renderer.OutputContext = context.Background()
|
||||||
|
e.renderMu.Lock()
|
||||||
|
if result != nil && result["ok"] == true && ctx.Err() == nil {
|
||||||
|
e.currentSession.svgFonts = maps.Clone(worker.svgFonts)
|
||||||
|
clear(worker.pageCache)
|
||||||
|
worker.textCache.Clear()
|
||||||
|
clear(worker.svgFonts)
|
||||||
|
e.renderIdle = append(e.renderIdle, worker)
|
||||||
|
}
|
||||||
|
e.renderCount--
|
||||||
|
if e.renderCount == 0 {
|
||||||
|
close(e.renderDone)
|
||||||
|
}
|
||||||
|
e.renderMu.Unlock()
|
||||||
|
}()
|
||||||
|
data, err := operation.safeCall(operation.renderPage, values)
|
||||||
|
if err != nil {
|
||||||
|
return nativeFailure(err)
|
||||||
|
}
|
||||||
|
result = nativePlain(data).(map[string]any)
|
||||||
|
if result["ok"] != true {
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
page := result["data"].(map[string]any)
|
||||||
|
known := make(map[string]bool)
|
||||||
|
if len(args) > 4 {
|
||||||
|
for i := 0; i < values[4].Length(); i++ {
|
||||||
|
known[values[4].Index(i).String()] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, value := range page["fonts"].([]any) {
|
||||||
|
font := value.(map[string]any)
|
||||||
|
if name := font["name"].(string); !known[name] {
|
||||||
|
font["data"] = worker.svgFonts[name]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if e.currentEditor != nil && !(len(values) > 6 && values[6].Bool()) {
|
||||||
|
objects, textErr := e.renderObjects(operation, values[0].Int())
|
||||||
|
if textErr != nil {
|
||||||
|
return nativeFailure(textErr)
|
||||||
|
}
|
||||||
|
page["objects"] = nativePlain(objects)
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nativeFailure(err)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
if err := e.waitRenders(ctx); err != nil {
|
||||||
|
return nativeFailure(err)
|
||||||
|
}
|
||||||
|
e.renderIdle = nil
|
||||||
|
if name == "ofdgoSaveSnapshot" {
|
||||||
|
snapshot := e.saveSnapshot
|
||||||
|
e.saveSnapshot = nil
|
||||||
|
if snapshot == nil {
|
||||||
|
return nativeFailure(fmt.Errorf("save snapshot is not prepared"))
|
||||||
|
}
|
||||||
|
output := &NativeEngine{OpenWriter: e.OpenWriter}
|
||||||
|
output.currentEditor = snapshot
|
||||||
|
e.saves.Add(1)
|
||||||
|
defer e.saves.Done()
|
||||||
|
<-e.gate
|
||||||
|
locked = false
|
||||||
|
defer output.Close()
|
||||||
|
return output.Call(ctx, "ofdgoSaveDocument", args, emit)
|
||||||
|
}
|
||||||
e.ctx = ctx
|
e.ctx = ctx
|
||||||
if e.currentSession != nil {
|
if e.currentSession != nil {
|
||||||
e.currentSession.Renderer.OutputContext = ctx
|
e.currentSession.Renderer.OutputContext = ctx
|
||||||
@@ -177,7 +310,14 @@ func (e *NativeEngine) Call(ctx context.Context, name string, args []any, emit f
|
|||||||
if fn == nil {
|
if fn == nil {
|
||||||
return nativeFailure(fmt.Errorf("unknown operation: %s", name))
|
return nativeFailure(fmt.Errorf("unknown operation: %s", name))
|
||||||
}
|
}
|
||||||
|
if err := e.checkDocument(name); err != nil {
|
||||||
|
return nativeFailure(err)
|
||||||
|
}
|
||||||
call := &nativeCall{engine: e, ctx: ctx, emit: emit}
|
call := &nativeCall{engine: e, ctx: ctx, emit: emit}
|
||||||
|
if e.pdf != nil {
|
||||||
|
e.pdf.progress = platformValueOf(call.progress("conversion", "", true))
|
||||||
|
e.pdf.font = platformValueOf(nativeCallback(call.font))
|
||||||
|
}
|
||||||
defer func() {
|
defer func() {
|
||||||
if err := call.abort(); err != nil {
|
if err := call.abort(); err != nil {
|
||||||
if result == nil || result["ok"] == true {
|
if result == nil || result["ok"] == true {
|
||||||
@@ -195,6 +335,9 @@ func (e *NativeEngine) Call(ctx context.Context, name string, args []any, emit f
|
|||||||
for i, arg := range prepared {
|
for i, arg := range prepared {
|
||||||
values[i] = platformValueOf(arg)
|
values[i] = platformValueOf(arg)
|
||||||
}
|
}
|
||||||
|
if err := e.preparePDF(name, values); err != nil {
|
||||||
|
return nativeFailure(err)
|
||||||
|
}
|
||||||
data, err := e.safeCall(fn, values)
|
data, err := e.safeCall(fn, values)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nativeFailure(err)
|
return nativeFailure(err)
|
||||||
@@ -215,10 +358,20 @@ func (e *NativeEngine) Call(ctx context.Context, name string, args []any, emit f
|
|||||||
|
|
||||||
// Close 释放会话,不关闭宿主持有的ReaderAt资源
|
// Close 释放会话,不关闭宿主持有的ReaderAt资源
|
||||||
func (e *NativeEngine) Close() error {
|
func (e *NativeEngine) Close() error {
|
||||||
e.once.Do(func() { e.gate = make(chan struct{}, 1); e.resolveSource = e.source })
|
e.once.Do(func() {
|
||||||
|
e.gate = make(chan struct{}, 1)
|
||||||
|
e.renderSlots = make(chan struct{}, e.renderParallelism())
|
||||||
|
e.resolveInput = e.input
|
||||||
|
})
|
||||||
e.gate <- struct{}{}
|
e.gate <- struct{}{}
|
||||||
defer func() { <-e.gate }()
|
defer func() { <-e.gate }()
|
||||||
e.closed = true
|
e.closed = true
|
||||||
|
e.clearPDF()
|
||||||
|
_, _ = e.discardPrint(nil)
|
||||||
|
_ = e.waitRenders(context.Background())
|
||||||
|
e.renderIdle = nil
|
||||||
|
e.saveSnapshot = nil
|
||||||
|
e.saves.Wait()
|
||||||
var err error
|
var err error
|
||||||
if e.currentSession != nil {
|
if e.currentSession != nil {
|
||||||
err = e.currentSession.Close()
|
err = e.currentSession.Close()
|
||||||
@@ -226,12 +379,92 @@ func (e *NativeEngine) Close() error {
|
|||||||
if e.pendingImport != nil {
|
if e.pendingImport != nil {
|
||||||
err = errors.Join(err, e.pendingImport.Close())
|
err = errors.Join(err, e.pendingImport.Close())
|
||||||
}
|
}
|
||||||
e.currentSession, e.currentEditor, e.pendingImport, e.copiedObjects, e.copiedStyle = nil, nil, nil, nil, nil
|
e.currentSession, e.currentEditor, e.pendingImport, e.copiedObjects, e.portableObjects, e.copiedStyle = nil, nil, nil, nil, nil, nil
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// source 读取授权源并以宿主报告的大小为准
|
// waitRenders 等待已开始的页面任务,取消等待不修改当前会话
|
||||||
func (e *NativeEngine) source(ctx context.Context, value any) (io.ReaderAt, int64, error) {
|
// 入参: ctx 等待上下文
|
||||||
|
// 返回: error 取消错误
|
||||||
|
func (e *NativeEngine) waitRenders(ctx context.Context) error {
|
||||||
|
e.renderMu.Lock()
|
||||||
|
done, count := e.renderDone, e.renderCount
|
||||||
|
e.renderMu.Unlock()
|
||||||
|
if count == 0 {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
return ctx.Err()
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderParallelism 返回首次调用时采用的页面并行数
|
||||||
|
// 返回: int 同时运行的页面任务数
|
||||||
|
func (e *NativeEngine) renderParallelism() int {
|
||||||
|
if e.RenderParallelism > 0 {
|
||||||
|
return e.RenderParallelism
|
||||||
|
}
|
||||||
|
return runtime.GOMAXPROCS(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderSession 复用独立只读会话,调用时已持有引擎门控
|
||||||
|
// 入参: ctx 渲染上下文
|
||||||
|
// 返回: *Session 渲染会话, error 准备错误
|
||||||
|
func (e *NativeEngine) renderSession(ctx context.Context) (*Session, error) {
|
||||||
|
e.renderMu.Lock()
|
||||||
|
defer e.renderMu.Unlock()
|
||||||
|
if count := len(e.renderIdle); count > 0 {
|
||||||
|
worker := e.renderIdle[count-1]
|
||||||
|
e.renderIdle[count-1] = nil
|
||||||
|
e.renderIdle = e.renderIdle[:count-1]
|
||||||
|
worker.Renderer.OutputContext = ctx
|
||||||
|
return worker, nil
|
||||||
|
}
|
||||||
|
source := e.currentSession
|
||||||
|
renderer, err := source.Renderer.Fork(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Session{Reader: renderer.Reader, Renderer: renderer, doc: source.doc, fontFS: source.fontFS,
|
||||||
|
pageCache: make(map[int]*ofdgo.PageContent), boxCache: append([]pageBoxInfo(nil), source.boxCache...),
|
||||||
|
textCache: ofdgo.NewPageTextCache(sessionTextCacheBytes), svgFonts: make(map[string][]byte), editing: source.editing}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// prepareRender 同步当前编辑页面的图元标识,避免并行访问编辑器缓存
|
||||||
|
// 入参: operation 只读任务, index 页面索引
|
||||||
|
// 返回: error 页面或取消错误
|
||||||
|
func (e *NativeEngine) prepareRender(operation *businessEngine, index int) error {
|
||||||
|
e.renderMu.Lock()
|
||||||
|
defer e.renderMu.Unlock()
|
||||||
|
page, err := operation.currentEditor.Page(index)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return operation.syncEditorPageIDs(index, page)
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderObjects 读取编辑图元信息,渲染状态由当前任务独立持有
|
||||||
|
// 入参: operation 只读任务, index 页面索引
|
||||||
|
// 返回: []any 图元信息, error 提取错误
|
||||||
|
func (e *NativeEngine) renderObjects(operation *businessEngine, index int) ([]any, error) {
|
||||||
|
e.renderMu.Lock()
|
||||||
|
defer e.renderMu.Unlock()
|
||||||
|
operation.currentEditor = e.currentEditor
|
||||||
|
if !reflect.DeepEqual(e.currentEditor.Backends(), operation.currentSession.Renderer.Backends()) {
|
||||||
|
e.currentEditor.SetRenderBackends(operation.currentSession.Renderer.Backends())
|
||||||
|
}
|
||||||
|
text, err := operation.currentSession.PageText(index)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return operation.editorObjects(index, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
// input 读取授权源并以宿主报告的大小为准
|
||||||
|
func (e *NativeEngine) input(ctx context.Context, value any) (io.ReaderAt, int64, error) {
|
||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
@@ -239,7 +472,7 @@ func (e *NativeEngine) source(ctx context.Context, value any) (io.ReaderAt, int6
|
|||||||
value = p.value
|
value = p.value
|
||||||
}
|
}
|
||||||
if data, ok := value.([]byte); ok {
|
if data, ok := value.([]byte); ok {
|
||||||
return nativeReader{engine: e, source: bytes.NewReader(data)}, int64(len(data)), nil
|
return nativeReader{engine: e, input: bytes.NewReader(data)}, int64(len(data)), nil
|
||||||
}
|
}
|
||||||
descriptor, ok := value.(map[string]any)
|
descriptor, ok := value.(map[string]any)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -249,14 +482,14 @@ func (e *NativeEngine) source(ctx context.Context, value any) (io.ReaderAt, int6
|
|||||||
if !ok || token == "" || e.Resolve == nil {
|
if !ok || token == "" || e.Resolve == nil {
|
||||||
return nil, 0, fmt.Errorf("unauthorized native file")
|
return nil, 0, fmt.Errorf("unauthorized native file")
|
||||||
}
|
}
|
||||||
source, size, err := e.Resolve(token)
|
input, size, err := e.Resolve(token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
if source == nil || size < 0 {
|
if input == nil || size < 0 {
|
||||||
return nil, 0, fmt.Errorf("invalid native file source")
|
return nil, 0, fmt.Errorf("invalid native file input")
|
||||||
}
|
}
|
||||||
return nativeReader{engine: e, source: source}, size, nil
|
return nativeReader{engine: e, input: input}, size, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadAt 分块传递取消检查,宿主ReadAt自身阻塞时由宿主控制超时
|
// ReadAt 分块传递取消检查,宿主ReadAt自身阻塞时由宿主控制超时
|
||||||
@@ -267,7 +500,7 @@ func (r nativeReader) ReadAt(data []byte, offset int64) (int, error) {
|
|||||||
return total, err
|
return total, err
|
||||||
}
|
}
|
||||||
n := min(len(data), 256<<10)
|
n := min(len(data), 256<<10)
|
||||||
got, err := r.source.ReadAt(data[:n], offset)
|
got, err := r.input.ReadAt(data[:n], offset)
|
||||||
total += got
|
total += got
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return total, err
|
return total, err
|
||||||
@@ -284,7 +517,7 @@ func (r nativeReader) ReadAt(data []byte, offset int64) (int, error) {
|
|||||||
// 入参: ctx 调用上下文, value 资源参数
|
// 入参: ctx 调用上下文, value 资源参数
|
||||||
// 返回: []byte 资源数据, error 读取错误
|
// 返回: []byte 资源数据, error 读取错误
|
||||||
func (e *NativeEngine) readBytes(ctx context.Context, value any) ([]byte, error) {
|
func (e *NativeEngine) readBytes(ctx context.Context, value any) ([]byte, error) {
|
||||||
source, size, err := e.source(ctx, value)
|
input, size, err := e.input(ctx, value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -297,7 +530,7 @@ func (e *NativeEngine) readBytes(ctx context.Context, value any) ([]byte, error)
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
n := int(min(int64(256<<10), size-offset))
|
n := int(min(int64(256<<10), size-offset))
|
||||||
got, err := source.ReadAt(output[int(offset):int(offset)+n], offset)
|
got, err := input.ReadAt(output[int(offset):int(offset)+n], offset)
|
||||||
if got != n {
|
if got != n {
|
||||||
return nil, io.ErrUnexpectedEOF
|
return nil, io.ErrUnexpectedEOF
|
||||||
}
|
}
|
||||||
@@ -517,7 +750,7 @@ func (c *nativeCall) progress(kind, stage string, phased bool) nativeCallback {
|
|||||||
|
|
||||||
// readCallback 创建有界随机读取回调
|
// readCallback 创建有界随机读取回调
|
||||||
func (c *nativeCall) readCallback(value any) (nativeCallback, int64, error) {
|
func (c *nativeCall) readCallback(value any) (nativeCallback, int64, error) {
|
||||||
source, size, err := c.engine.source(c.ctx, value)
|
input, size, err := c.engine.input(c.ctx, value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
@@ -530,7 +763,7 @@ func (c *nativeCall) readCallback(value any) (nativeCallback, int64, error) {
|
|||||||
return nil, fmt.Errorf("invalid native read range")
|
return nil, fmt.Errorf("invalid native read range")
|
||||||
}
|
}
|
||||||
data := make([]byte, n)
|
data := make([]byte, n)
|
||||||
got, err := source.ReadAt(data, offset)
|
got, err := input.ReadAt(data, offset)
|
||||||
if got != n {
|
if got != n {
|
||||||
return nil, io.ErrUnexpectedEOF
|
return nil, io.ErrUnexpectedEOF
|
||||||
}
|
}
|
||||||
@@ -728,11 +961,11 @@ func (c *nativeCall) prepare(name string, args []any) ([]any, error) {
|
|||||||
args = append(args, c.fileCallback(files))
|
args = append(args, c.fileCallback(files))
|
||||||
}
|
}
|
||||||
switch name {
|
switch name {
|
||||||
case "ofdgoResources":
|
case "ofdgoResources", "ofdgoPrepareSave":
|
||||||
return append(args, checkpoint), nil
|
return append(args, checkpoint), nil
|
||||||
case "ofdgoImportPages", "ofdgoImportDocuments", "ofdgoImportImages":
|
case "ofdgoImportPages", "ofdgoImportDocuments", "ofdgoImportImages":
|
||||||
return append(args, c.progress("import", "", true)), nil
|
return append(args, c.progress("import", "", true)), nil
|
||||||
case "ofdgoConvertPDF":
|
case "ofdgoOpenPDF":
|
||||||
return append(args, c.progress("conversion", "", true), nativeCallback(c.font)), nil
|
return append(args, c.progress("conversion", "", true), nativeCallback(c.font)), nil
|
||||||
case "ofdgoExportImages", "ofdgoExportPage", "ofdgoExportDocument", "ofdgoExportAttachment", "ofdgoExportResource", "ofdgoExportMedia", "ofdgoExportVersion", "ofdgoSaveDocument", "ofdgoSaveSigned":
|
case "ofdgoExportImages", "ofdgoExportPage", "ofdgoExportDocument", "ofdgoExportAttachment", "ofdgoExportResource", "ofdgoExportMedia", "ofdgoExportVersion", "ofdgoSaveDocument", "ofdgoSaveSigned":
|
||||||
if len(args) == 0 {
|
if len(args) == 0 {
|
||||||
@@ -853,9 +1086,13 @@ func nativeOutputBase(value platformValue) string {
|
|||||||
return base
|
return base
|
||||||
}
|
}
|
||||||
|
|
||||||
// sourceFromValue 读取宿主授权的随机读取源
|
// inputFromValue 读取宿主授权的随机读取源
|
||||||
func (e *businessEngine) sourceFromValue(value platformValue) (io.ReaderAt, int64, error) {
|
func (e *businessEngine) inputFromValue(value platformValue) (*ofdgo.Input, error) {
|
||||||
return e.resolveSource(e.operationContext(), value.value)
|
reader, size, err := e.resolveInput(e.operationContext(), value.value)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ofdgo.NewInput(reader, size)
|
||||||
}
|
}
|
||||||
|
|
||||||
// platformValueOf 包装参数
|
// platformValueOf 包装参数
|
||||||
@@ -1001,11 +1238,12 @@ func (e *businessEngine) bytesFromJS(v platformValue) ([]byte, error) {
|
|||||||
if data, ok := v.value.([]byte); ok {
|
if data, ok := v.value.([]byte); ok {
|
||||||
return append([]byte(nil), data...), nil
|
return append([]byte(nil), data...), nil
|
||||||
}
|
}
|
||||||
source, size, err := e.sourceFromValue(v)
|
input, err := e.inputFromValue(v)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return io.ReadAll(io.NewSectionReader(source, 0, size))
|
defer input.Close()
|
||||||
|
return io.ReadAll(io.NewSectionReader(input, 0, input.Size()))
|
||||||
}
|
}
|
||||||
|
|
||||||
// successResult 保留二进制返回结构
|
// successResult 保留二进制返回结构
|
||||||
|
|||||||
@@ -0,0 +1,141 @@
|
|||||||
|
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package webui
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/xiaoqidun/ofdgo"
|
||||||
|
)
|
||||||
|
|
||||||
|
// preparePrint 从当前编辑入口创建独立打印快照,业务选项由公开库统一校验
|
||||||
|
// 入参: args 排版选项及可选输出任务标识
|
||||||
|
// 返回: any 纸面布局, error 快照、权限或排版错误
|
||||||
|
func (e *businessEngine) preparePrint(args []platformValue) (any, error) {
|
||||||
|
if e.currentSession == nil || len(args) == 0 {
|
||||||
|
return nil, fmt.Errorf("ofd document is not opened")
|
||||||
|
}
|
||||||
|
var options ofdgo.PrintOptions
|
||||||
|
if err := json.Unmarshal([]byte(platformJSON(args[0])), &options); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ctx := e.operationContext()
|
||||||
|
if len(args) > 1 {
|
||||||
|
ctx = e.newOutputContext(args[1])
|
||||||
|
}
|
||||||
|
editor := e.currentEditor
|
||||||
|
if editor == nil {
|
||||||
|
var err error
|
||||||
|
editor, err = e.currentSession.Reader.EditorContext(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
source := e.currentSession.Renderer
|
||||||
|
dirs, fonts := source.FontSources()
|
||||||
|
document, err := editor.PreparePrint(ctx, options, ofdgo.WithRenderBackends(source.Backends()), ofdgo.WithFontDirs(dirs...), ofdgo.WithFontFS(fonts...))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if e.printDocument != nil {
|
||||||
|
_ = e.printDocument.Close()
|
||||||
|
}
|
||||||
|
e.printDocument = document
|
||||||
|
data, err := json.Marshal(document.Layout())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return successResult(platformParseJSON(data)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// layoutPrint 在既有快照上调整排版,预览期间不重复复制源包
|
||||||
|
// 入参: args 新排版选项及可选输出任务标识
|
||||||
|
// 返回: any 新纸面布局, error 状态、权限或排版错误
|
||||||
|
func (e *businessEngine) layoutPrint(args []platformValue) (any, error) {
|
||||||
|
if e.printDocument == nil || len(args) == 0 {
|
||||||
|
return nil, fmt.Errorf("print document is not prepared")
|
||||||
|
}
|
||||||
|
var options ofdgo.PrintOptions
|
||||||
|
if err := json.Unmarshal([]byte(platformJSON(args[0])), &options); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ctx := e.operationContext()
|
||||||
|
if len(args) > 1 {
|
||||||
|
ctx = e.newOutputContext(args[1])
|
||||||
|
}
|
||||||
|
next, err := e.printDocument.Reconfigure(ctx, options)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
_ = e.printDocument.Close()
|
||||||
|
e.printDocument = next
|
||||||
|
data, err := json.Marshal(next.Layout())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return successResult(platformParseJSON(data)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// printSide 按需输出一个纸面,不使用阅读区缓存或缩略图
|
||||||
|
// 入参: args 零基纸面索引及可选输出任务标识
|
||||||
|
// 返回: any 内嵌资源的SVG纸面, error 状态或渲染错误
|
||||||
|
func (e *businessEngine) printSide(args []platformValue) (any, error) {
|
||||||
|
if e.printDocument == nil || len(args) == 0 {
|
||||||
|
return nil, fmt.Errorf("print document is not prepared")
|
||||||
|
}
|
||||||
|
ctx := e.operationContext()
|
||||||
|
if len(args) > 1 {
|
||||||
|
ctx = e.newOutputContext(args[1])
|
||||||
|
}
|
||||||
|
var output bytes.Buffer
|
||||||
|
if err := e.printDocument.RenderSVG(ctx, args[0].Int(), &output); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return successResult(map[string]any{"svg": output.String()}), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// printPDF 输出和预览相同的打印布局,便于另存或交给第三方打印系统
|
||||||
|
// 入参: args 可选输出任务标识
|
||||||
|
// 返回: any PDF数据及媒体类型, error 状态或输出错误
|
||||||
|
func (e *businessEngine) printPDF(args []platformValue) (any, error) {
|
||||||
|
if e.printDocument == nil {
|
||||||
|
return nil, fmt.Errorf("print document is not prepared")
|
||||||
|
}
|
||||||
|
ctx := e.operationContext()
|
||||||
|
if len(args) > 0 {
|
||||||
|
ctx = e.newOutputContext(args[0])
|
||||||
|
}
|
||||||
|
var output bytes.Buffer
|
||||||
|
if err := e.printDocument.WritePDF(ctx, &output); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return successResult(map[string]any{"bytes": bytesToJS(output.Bytes()), "mime": "application/pdf"}), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// discardPrint 释放当前打印快照,可重复调用
|
||||||
|
// 入参: _ 保留的调用参数
|
||||||
|
// 返回: any 空结果, error 资源释放错误
|
||||||
|
func (e *businessEngine) discardPrint(_ []platformValue) (any, error) {
|
||||||
|
if e.printDocument != nil {
|
||||||
|
err := e.printDocument.Close()
|
||||||
|
e.printDocument = nil
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return successResult(nil), nil
|
||||||
|
}
|
||||||
+102
-32
@@ -21,8 +21,9 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"syscall/js"
|
"syscall/js"
|
||||||
|
|
||||||
|
"github.com/xiaoqidun/ofdgo"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -36,39 +37,102 @@ const (
|
|||||||
// platformValue 浏览器参数值
|
// platformValue 浏览器参数值
|
||||||
type platformValue = js.Value
|
type platformValue = js.Value
|
||||||
|
|
||||||
|
// wasmEngines 管理共享资源的独立浏览器业务会话
|
||||||
|
type wasmEngines struct {
|
||||||
|
resources *ofdgo.Resources
|
||||||
|
engines map[string]*businessEngine
|
||||||
|
}
|
||||||
|
|
||||||
// RunWASM 注册浏览器WASM接口并阻塞运行
|
// RunWASM 注册浏览器WASM接口并阻塞运行
|
||||||
func RunWASM() {
|
func RunWASM() {
|
||||||
e := &businessEngine{}
|
resources, _ := ofdgo.NewResources(ofdgo.ResourceOptions{Parallelism: 1, MemoryLimit: 64 << 20, CacheBytes: 48 << 20, SnapshotBytes: 32 << 20})
|
||||||
asynchronous := map[string]bool{
|
engines := &wasmEngines{resources: resources, engines: make(map[string]*businessEngine)}
|
||||||
"ofdgoDetectFormat": true,
|
registerCallback("ofdgoEngineOpen", engines.open)
|
||||||
"ofdgoExportVersion": true,
|
registerAsyncCallback("ofdgoEngineCall", engines.call)
|
||||||
"ofdgoConvertPDF": true,
|
registerCallback("ofdgoEngineClose", engines.close)
|
||||||
"ofdgoConvertFile": true,
|
|
||||||
"ofdgoPackFiles": true,
|
|
||||||
"ofdgoExportPage": true,
|
|
||||||
"ofdgoExportDocument": true,
|
|
||||||
"ofdgoExportAttachment": true,
|
|
||||||
"ofdgoExportMedia": true,
|
|
||||||
"ofdgoResources": true,
|
|
||||||
"ofdgoExportResource": true,
|
|
||||||
"ofdgoExportImages": true,
|
|
||||||
"ofdgoImportImages": true,
|
|
||||||
"ofdgoImportPages": true,
|
|
||||||
"ofdgoImportDocuments": true,
|
|
||||||
"ofdgoSaveDocument": true,
|
|
||||||
"ofdgoSetEncryption": true,
|
|
||||||
"ofdgoSaveSigned": true,
|
|
||||||
}
|
|
||||||
for name, callback := range e.businessCommands() {
|
|
||||||
if asynchronous[name] {
|
|
||||||
registerAsyncCallback(name, callback)
|
|
||||||
} else {
|
|
||||||
registerCallback(name, callback)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
select {}
|
select {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// open 创建具有稳定标识的独立业务会话
|
||||||
|
// 入参: args 会话标识
|
||||||
|
// 返回: any 空结果, error 参数或会话错误
|
||||||
|
func (w *wasmEngines) open(args []js.Value) (any, error) {
|
||||||
|
if len(args) != 1 || args[0].Type() != js.TypeString || args[0].String() == "" {
|
||||||
|
return nil, fmt.Errorf("missing engine ID")
|
||||||
|
}
|
||||||
|
id := args[0].String()
|
||||||
|
if w.engines[id] != nil {
|
||||||
|
return nil, fmt.Errorf("engine already exists: %s", id)
|
||||||
|
}
|
||||||
|
w.engines[id] = &businessEngine{resources: w.resources}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// call 按会话标识分派业务命令,统一绑定本次调用的取消上下文
|
||||||
|
// 入参: args 会话标识、命令、取消检查点及业务参数
|
||||||
|
// 返回: any 业务结果, error 调用错误
|
||||||
|
func (w *wasmEngines) call(args []js.Value) (any, error) {
|
||||||
|
if len(args) < 3 || args[0].Type() != js.TypeString || args[1].Type() != js.TypeString {
|
||||||
|
return nil, fmt.Errorf("missing engine ID or operation")
|
||||||
|
}
|
||||||
|
e := w.engines[args[0].String()]
|
||||||
|
if e == nil {
|
||||||
|
return nil, fmt.Errorf("unknown engine: %s", args[0].String())
|
||||||
|
}
|
||||||
|
name := args[1].String()
|
||||||
|
fn := e.businessCommands()[name]
|
||||||
|
if fn == nil {
|
||||||
|
return nil, fmt.Errorf("unknown operation: %s", name)
|
||||||
|
}
|
||||||
|
if err := e.checkDocument(name); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
e.ctx = context.Background()
|
||||||
|
if args[2].Type() == js.TypeFunction {
|
||||||
|
e.ctx = e.newOutputContext(args[2])
|
||||||
|
}
|
||||||
|
ctx := e.ctx
|
||||||
|
if name != "ofdgoSaveSnapshot" && e.currentSession != nil {
|
||||||
|
e.currentSession.Renderer.OutputContext = ctx
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
if e.ctx == ctx {
|
||||||
|
e.ctx = nil
|
||||||
|
}
|
||||||
|
if name != "ofdgoSaveSnapshot" && e.currentSession != nil {
|
||||||
|
e.currentSession.Renderer.OutputContext = context.Background()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := e.preparePDF(name, args[3:]); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return fn(args[3:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// close 释放会话的文档、编辑器、导入及剪贴板,不关闭共享资源
|
||||||
|
// 入参: args 会话标识
|
||||||
|
// 返回: any 空结果, error 参数或关闭错误
|
||||||
|
func (w *wasmEngines) close(args []js.Value) (any, error) {
|
||||||
|
if len(args) != 1 || args[0].Type() != js.TypeString || args[0].String() == "" {
|
||||||
|
return nil, fmt.Errorf("missing engine ID")
|
||||||
|
}
|
||||||
|
id := args[0].String()
|
||||||
|
e := w.engines[id]
|
||||||
|
if e == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
delete(w.engines, id)
|
||||||
|
_, _ = e.discardPrint(nil)
|
||||||
|
e.clearPDF()
|
||||||
|
e.clearImport()
|
||||||
|
err := e.currentSession.Close()
|
||||||
|
*e = businessEngine{}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
// awaitExport 等待浏览器处理导出检查点
|
// awaitExport 等待浏览器处理导出检查点
|
||||||
// 入参: fn 浏览器回调, args 回调参数
|
// 入参: fn 浏览器回调, args 回调参数
|
||||||
// 返回: error 写入错误或取消原因
|
// 返回: error 写入错误或取消原因
|
||||||
@@ -218,8 +282,14 @@ func platformParseJSON(data []byte) map[string]any {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// sourceFromValue 读取浏览器二进制源
|
// inputFromValue 读取浏览器随机输入或二进制数据
|
||||||
func (e *businessEngine) sourceFromValue(value platformValue) (io.ReaderAt, int64, error) {
|
func (e *businessEngine) inputFromValue(value platformValue) (*ofdgo.Input, error) {
|
||||||
|
if value.Type() == platformTypeObject && !value.IsNull() && value.Get("read").Type() == platformTypeFunction {
|
||||||
|
return ofdgo.NewInput(&browserReaderAt{read: value.Get("read"), size: int64(value.Get("size").Float())}, int64(value.Get("size").Float()))
|
||||||
|
}
|
||||||
data, err := e.bytesFromJS(value)
|
data, err := e.bytesFromJS(value)
|
||||||
return bytes.NewReader(data), int64(len(data)), err
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ofdgo.NewInput(bytes.NewReader(data), int64(len(data)))
|
||||||
}
|
}
|
||||||
+441
-38
@@ -20,6 +20,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -28,28 +29,36 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/xiaoqidun/guigo"
|
"github.com/xiaoqidun/guigo"
|
||||||
"github.com/xiaoqidun/ofdgo"
|
"github.com/xiaoqidun/ofdgo"
|
||||||
webuiassets "github.com/xiaoqidun/ofdgo/assets/webui"
|
webuiassets "github.com/xiaoqidun/ofdgo/assets/webui"
|
||||||
|
"github.com/xiaoqidun/ofdgo/internal/build"
|
||||||
"github.com/xiaoqidun/ofdgo/internal/webui"
|
"github.com/xiaoqidun/ofdgo/internal/webui"
|
||||||
)
|
)
|
||||||
|
|
||||||
// applicationID 标识原生应用,与版本及可执行文件路径无关
|
const applicationVersionURL = "https://ofdgo.aite.me/"
|
||||||
const applicationID = "me.aite.ofdgo"
|
const applicationDownloadURL = "https://ofdgo.aite.me/releases/"
|
||||||
|
|
||||||
// Host 连接桌面系统能力和共用文档业务
|
// Host 连接桌面系统能力和共用文档业务
|
||||||
type Host struct {
|
type Host struct {
|
||||||
|
themeMu sync.Mutex
|
||||||
|
theme applicationTheme
|
||||||
|
themePath string
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
window *guigo.Window
|
window *guigo.Window
|
||||||
files *fileStore
|
files *fileStore
|
||||||
engines map[string]*webui.NativeEngine
|
engines map[string]*webui.NativeEngine
|
||||||
engineStops map[string]func() bool
|
engineStops map[string]func() bool
|
||||||
|
closingEngines map[string]*engineClose
|
||||||
conversionPool *ofdgo.ConversionPool
|
conversionPool *ofdgo.ConversionPool
|
||||||
|
resources *ofdgo.Resources
|
||||||
cancels map[string]context.CancelFunc
|
cancels map[string]context.CancelFunc
|
||||||
batchResults map[string]any
|
batchResults map[string]any
|
||||||
fontOnce sync.Once
|
fontOnce sync.Once
|
||||||
@@ -57,6 +66,24 @@ type Host struct {
|
|||||||
fontFiles map[string]string
|
fontFiles map[string]string
|
||||||
fontError error
|
fontError error
|
||||||
pendingPaths []string
|
pendingPaths []string
|
||||||
|
launchMu sync.Mutex
|
||||||
|
launchActivate bool
|
||||||
|
launchClosed bool
|
||||||
|
launchPending int
|
||||||
|
frontendReady bool
|
||||||
|
closeAllowed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// associationState 保存单个范围的登记状态和查询错误
|
||||||
|
type associationState struct {
|
||||||
|
guigo.AssociationStatus
|
||||||
|
Error string `json:"error,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// engineClose 保存并发关闭共享的完成通知及结果
|
||||||
|
type engineClose struct {
|
||||||
|
done chan struct{}
|
||||||
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
// resourceReader 保存资源读取位置及关闭操作
|
// resourceReader 保存资源读取位置及关闭操作
|
||||||
@@ -73,19 +100,56 @@ func Run(ctx context.Context, paths []string, dataDir string) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
paths = append([]string(nil), paths...)
|
||||||
|
for index, path := range paths {
|
||||||
|
paths[index], err = filepath.Abs(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h := &Host{pendingPaths: paths, themePath: filepath.Join(options.UserDataDir, "appearance.json")}
|
||||||
|
if err := h.loadTheme(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
options.TitleBarColors = themeColors(h.theme.Dark)
|
||||||
|
data, err := json.Marshal(paths)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(options.UserDataDir, 0700); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
key, err := instanceDirectory(options.UserDataDir)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
instance, err := guigo.OpenWindowInstance(ctx, "OFDGo:"+key, data, h.receiveLaunch)
|
||||||
|
if err != nil || instance == nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer instance.Close()
|
||||||
|
options.Instance = instance
|
||||||
files, err := newFileStore()
|
files, err := newFileStore()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
h := &Host{files: files, engines: make(map[string]*webui.NativeEngine), cancels: make(map[string]context.CancelFunc), fontFiles: make(map[string]string), pendingPaths: append([]string(nil), paths...)}
|
h.files = files
|
||||||
h.conversionPool, err = ofdgo.NewConversionPool(ofdgo.ConversionPoolOptions{AvailableMemory: conversionMemory})
|
h.engines = make(map[string]*webui.NativeEngine)
|
||||||
|
h.cancels = make(map[string]context.CancelFunc)
|
||||||
|
h.fontFiles = make(map[string]string)
|
||||||
|
cacheBytes := int64(256 << 20)
|
||||||
|
if memory := conversionMemory; memory != nil {
|
||||||
|
cacheBytes = max(32<<20, memory()/8)
|
||||||
|
}
|
||||||
|
h.resources, err = ofdgo.NewResources(ofdgo.ResourceOptions{CacheBytes: cacheBytes, AvailableMemory: conversionMemory})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
files.close()
|
files.close()
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
h.conversionPool = h.resources.ConversionPool()
|
||||||
defer h.close()
|
defer h.close()
|
||||||
bindings := make(map[string]guigo.HandlerFunc)
|
bindings := make(map[string]guigo.HandlerFunc)
|
||||||
for _, name := range []string{"engine.open", "engine.close", "engine.call", "engine.start", "engine.cancel", "engine.finish", "batch", "open", "save", "directory", "file", "release", "child", "remove", "write.begin", "write.data", "write.commit", "write.abort", "fonts", "ready", "title"} {
|
for _, name := range []string{"engine.open", "engine.close", "engine.call", "engine.start", "engine.cancel", "engine.finish", "batch", "open", "save", "directory", "file", "release", "drop.release", "child", "remove", "write.begin", "write.data", "write.commit", "write.abort", "fonts", "ready", "launch.done", "title", "window.info", "window.drag", "window.close", "appearance", "update.check", "update.open", "association.query", "association.register", "association.remove", "print.capabilities", "print.dialog", "print.printers", "print.query", "print.properties", "print"} {
|
||||||
bindings["ofdgo.host."+name] = func(ctx context.Context, args any) (any, error) { return h.call(ctx, name, args) }
|
bindings["ofdgo.host."+name] = func(ctx context.Context, args any) (any, error) { return h.call(ctx, name, args) }
|
||||||
}
|
}
|
||||||
static := http.FileServerFS(webuiassets.NativeFS)
|
static := http.FileServerFS(webuiassets.NativeFS)
|
||||||
@@ -98,7 +162,20 @@ func Run(ctx context.Context, paths []string, dataDir string) error {
|
|||||||
http.NotFound(w, r)
|
http.NotFound(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if r.URL.Path == "/" || r.URL.Path == "/index.html" {
|
||||||
|
data, err := h.themeIndex()
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Header().Set("X-OFDGo-Build-Version", build.Version)
|
||||||
w.Header().Set("Cache-Control", "no-store")
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
w.Write(data)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
w.Header().Set("X-OFDGo-Build-Version", build.Version)
|
||||||
static.ServeHTTP(w, r)
|
static.ServeHTTP(w, r)
|
||||||
})
|
})
|
||||||
options.Handler = handler
|
options.Handler = handler
|
||||||
@@ -110,6 +187,9 @@ func Run(ctx context.Context, paths []string, dataDir string) error {
|
|||||||
h.mu.Unlock()
|
h.mu.Unlock()
|
||||||
}
|
}
|
||||||
options.OnClose = func() {
|
options.OnClose = func() {
|
||||||
|
h.launchMu.Lock()
|
||||||
|
h.launchClosed = true
|
||||||
|
h.launchMu.Unlock()
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
for _, cancel := range h.cancels {
|
for _, cancel := range h.cancels {
|
||||||
cancel()
|
cancel()
|
||||||
@@ -117,6 +197,18 @@ func Run(ctx context.Context, paths []string, dataDir string) error {
|
|||||||
h.mu.Unlock()
|
h.mu.Unlock()
|
||||||
}
|
}
|
||||||
options.OnDrop = h.openPaths
|
options.OnDrop = h.openPaths
|
||||||
|
options.OnTitleBarChanged = func(info guigo.TitleBarInfo) {
|
||||||
|
h.emit("ofdgo.window", info)
|
||||||
|
}
|
||||||
|
options.OnClosing = func(ctx context.Context) bool {
|
||||||
|
h.mu.Lock()
|
||||||
|
allowed := h.closeAllowed || !h.frontendReady
|
||||||
|
h.mu.Unlock()
|
||||||
|
if !allowed {
|
||||||
|
h.emit("ofdgo.closing", nil)
|
||||||
|
}
|
||||||
|
return allowed
|
||||||
|
}
|
||||||
options.OnError = func(err error) {
|
options.OnError = func(err error) {
|
||||||
h.emit("ofdgo.error", err.Error())
|
h.emit("ofdgo.error", err.Error())
|
||||||
}
|
}
|
||||||
@@ -164,7 +256,13 @@ func (h *Host) resource(r *http.Request) (*guigo.Resource, error) {
|
|||||||
if name == "" {
|
if name == "" {
|
||||||
name = "index.html"
|
name = "index.html"
|
||||||
}
|
}
|
||||||
data, err := webuiassets.NativeFS.ReadFile(name)
|
var data []byte
|
||||||
|
var err error
|
||||||
|
if name == "index.html" {
|
||||||
|
data, err = h.themeIndex()
|
||||||
|
} else {
|
||||||
|
data, err = webuiassets.NativeFS.ReadFile(name)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
@@ -180,6 +278,7 @@ func (h *Host) resource(r *http.Request) (*guigo.Resource, error) {
|
|||||||
contentType = http.DetectContentType(header)
|
contentType = http.DetectContentType(header)
|
||||||
}
|
}
|
||||||
headers := http.Header{"Content-Type": {contentType}, "Content-Length": {strconv.FormatInt(size, 10)}, "Cache-Control": {"no-store"}, "Accept-Ranges": {"bytes"}}
|
headers := http.Header{"Content-Type": {contentType}, "Content-Length": {strconv.FormatInt(size, 10)}, "Cache-Control": {"no-store"}, "Accept-Ranges": {"bytes"}}
|
||||||
|
headers.Set("X-OFDGo-Build-Version", build.Version)
|
||||||
start, length, status := int64(0), size, http.StatusOK
|
start, length, status := int64(0), size, http.StatusOK
|
||||||
if value := r.Header.Get("Range"); value != "" && r.Method == http.MethodGet {
|
if value := r.Header.Get("Range"); value != "" && r.Method == http.MethodGet {
|
||||||
if !strings.HasPrefix(value, "bytes=") || strings.Contains(value, ",") {
|
if !strings.HasPrefix(value, "bytes=") || strings.Contains(value, ",") {
|
||||||
@@ -239,19 +338,91 @@ func (h *Host) emit(name string, value any) {
|
|||||||
// openPaths 将操作系统提供的文件登记后交给界面
|
// openPaths 将操作系统提供的文件登记后交给界面
|
||||||
// 入参: names 文件路径列表
|
// 入参: names 文件路径列表
|
||||||
func (h *Host) openPaths(names []string) {
|
func (h *Host) openPaths(names []string) {
|
||||||
|
_ = h.sendPaths(names, "ofdgo.files")
|
||||||
|
}
|
||||||
|
|
||||||
|
// sendPaths 将文件登记后发送到指定界面入口
|
||||||
|
// 入参: names 文件路径列表, event 界面事件名称
|
||||||
|
// 返回: error 投递错误
|
||||||
|
func (h *Host) sendPaths(names []string, event string) error {
|
||||||
files := make([]any, 0, len(names))
|
files := make([]any, 0, len(names))
|
||||||
for _, name := range names {
|
for _, name := range names {
|
||||||
handle, err := h.files.add(name, false)
|
file, err := h.files.addDrop(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.emit("ofdgo.error", err.Error())
|
h.emit("ofdgo.error", err.Error())
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
file, err := h.files.file(handle["nativeHandle"].(string))
|
|
||||||
if err == nil {
|
|
||||||
files = append(files, file)
|
files = append(files, file)
|
||||||
}
|
}
|
||||||
|
h.mu.Lock()
|
||||||
|
w := h.window
|
||||||
|
h.mu.Unlock()
|
||||||
|
var err error
|
||||||
|
if w == nil {
|
||||||
|
err = guigo.ErrClosed
|
||||||
|
} else {
|
||||||
|
err = w.Emit(event, files)
|
||||||
}
|
}
|
||||||
h.emit("ofdgo.files", files)
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, file := range files {
|
||||||
|
h.files.discardDrop(file.(map[string]any)["nativeFile"].(string))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// receiveLaunch 接收已有进程转交的文件及激活请求
|
||||||
|
// 入参: ctx 请求上下文, data 文件路径消息
|
||||||
|
// 返回: error 接收错误
|
||||||
|
func (h *Host) receiveLaunch(ctx context.Context, data []byte) error {
|
||||||
|
var paths []string
|
||||||
|
if err := json.Unmarshal(data, &paths); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, path := range paths {
|
||||||
|
if !filepath.IsAbs(path) {
|
||||||
|
return errors.New("file path must be absolute")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.launchMu.Lock()
|
||||||
|
defer h.launchMu.Unlock()
|
||||||
|
if h.launchClosed {
|
||||||
|
return guigo.ErrClosed
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
h.pendingPaths = append(h.pendingPaths, paths...)
|
||||||
|
h.launchActivate = true
|
||||||
|
return h.flushLaunch()
|
||||||
|
}
|
||||||
|
|
||||||
|
// flushLaunch 在界面就绪后按接收顺序投递外部打开请求,调用方持有launchMu
|
||||||
|
// 返回: error 投递错误
|
||||||
|
func (h *Host) flushLaunch() error {
|
||||||
|
h.mu.Lock()
|
||||||
|
ready, window := h.frontendReady, h.window
|
||||||
|
h.mu.Unlock()
|
||||||
|
if !ready || window == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if h.launchActivate {
|
||||||
|
if err := window.Activate(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
h.launchActivate = false
|
||||||
|
}
|
||||||
|
if len(h.pendingPaths) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
paths := h.pendingPaths
|
||||||
|
h.pendingPaths = nil
|
||||||
|
if err := h.sendPaths(paths, "ofdgo.launch"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
h.launchPending++
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// call 执行宿主协议并保留业务结果结构
|
// call 执行宿主协议并保留业务结果结构
|
||||||
@@ -265,9 +436,56 @@ func (h *Host) call(ctx context.Context, name string, value any) (any, error) {
|
|||||||
text := func(key string) string { value, _ := args[key].(string); return value }
|
text := func(key string) string { value, _ := args[key].(string); return value }
|
||||||
flag := func(key string) bool { value, _ := args[key].(bool); return value }
|
flag := func(key string) bool { value, _ := args[key].(bool); return value }
|
||||||
switch name {
|
switch name {
|
||||||
|
case "appearance":
|
||||||
|
return nil, h.setTheme(applicationTheme{Mode: text("mode"), Dark: flag("dark")})
|
||||||
|
case "print.capabilities", "print.dialog", "print.printers", "print.query", "print.properties", "print":
|
||||||
|
h.mu.Lock()
|
||||||
|
window := h.window
|
||||||
|
h.mu.Unlock()
|
||||||
|
if window == nil {
|
||||||
|
return nil, fmt.Errorf("窗口尚未就绪")
|
||||||
|
}
|
||||||
|
if name == "print.capabilities" {
|
||||||
|
return window.PrintCapabilities(ctx)
|
||||||
|
}
|
||||||
|
if name == "print.dialog" {
|
||||||
|
return nil, window.ShowPrintUI(ctx, text("kind"))
|
||||||
|
}
|
||||||
|
if name == "print.printers" {
|
||||||
|
return window.ListPrinters(ctx)
|
||||||
|
}
|
||||||
|
if name == "print.properties" {
|
||||||
|
return nil, window.ShowPrinterProperties(ctx, text("printer"))
|
||||||
|
}
|
||||||
|
data, err := json.Marshal(args)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var options guigo.PrintOptions
|
||||||
|
if err := json.Unmarshal(data, &options); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
profile, err := window.QueryPrinter(ctx, options)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if name == "print.query" {
|
||||||
|
return profile, nil
|
||||||
|
}
|
||||||
|
if text("fingerprint") == "" || text("fingerprint") != profile.Fingerprint {
|
||||||
|
return nil, fmt.Errorf("打印机设置已变化,请重新预览")
|
||||||
|
}
|
||||||
|
return window.Print(ctx, options)
|
||||||
case "engine.open":
|
case "engine.open":
|
||||||
engine := webui.NewNativeEngine(h.files.resolve)
|
engine := webui.NewNativeEngine(h.files.resolve)
|
||||||
|
parallelism, cacheBytes := runtime.GOMAXPROCS(0), int64(128<<20)
|
||||||
|
if memory := conversionMemory; memory != nil {
|
||||||
|
available := memory()
|
||||||
|
cacheBytes = max(32<<20, available/32)
|
||||||
|
}
|
||||||
|
engine.RenderParallelism = parallelism
|
||||||
engine.ConversionPool = h.conversionPool
|
engine.ConversionPool = h.conversionPool
|
||||||
|
engine.Resources = h.resources
|
||||||
engine.OpenWriter = h.openWriter
|
engine.OpenWriter = h.openWriter
|
||||||
engine.ReserveOutput = h.reserveOutput
|
engine.ReserveOutput = h.reserveOutput
|
||||||
engine.CleanupOutput = h.cleanupOutput
|
engine.CleanupOutput = h.cleanupOutput
|
||||||
@@ -280,9 +498,17 @@ func (h *Host) call(ctx context.Context, name string, value any) (any, error) {
|
|||||||
}
|
}
|
||||||
h.engineStops[id] = context.AfterFunc(guigo.PageContext(ctx), func() { _ = h.closeEngine(id) })
|
h.engineStops[id] = context.AfterFunc(guigo.PageContext(ctx), func() { _ = h.closeEngine(id) })
|
||||||
h.mu.Unlock()
|
h.mu.Unlock()
|
||||||
return guigo.Result{Value: map[string]any{"engine": id}, Discard: func() { _ = h.closeEngine(id) }}, nil
|
return guigo.Result{Value: map[string]any{"engine": id, "parallelism": parallelism, "cacheBytes": cacheBytes}, Discard: func() { _ = h.closeEngine(id) }}, nil
|
||||||
case "batch":
|
case "batch":
|
||||||
return map[string]any{"parallelism": h.conversionPool.Parallelism()}, nil
|
return map[string]any{"parallelism": h.conversionPool.Parallelism()}, nil
|
||||||
|
case "update.check":
|
||||||
|
return applicationUpdate(ctx, build.Version, applicationVersionURL)
|
||||||
|
case "update.open":
|
||||||
|
return nil, guigo.OpenURL(applicationDownloadURL)
|
||||||
|
case "association.query":
|
||||||
|
return queryAssociations()
|
||||||
|
case "association.register", "association.remove":
|
||||||
|
return nil, changeAssociations(text("scope"), name == "association.remove")
|
||||||
case "engine.close":
|
case "engine.close":
|
||||||
return nil, h.closeEngine(text("engine"))
|
return nil, h.closeEngine(text("engine"))
|
||||||
case "engine.finish":
|
case "engine.finish":
|
||||||
@@ -441,6 +667,9 @@ func (h *Host) call(ctx context.Context, name string, value any) (any, error) {
|
|||||||
case "release":
|
case "release":
|
||||||
h.files.release(text("file"))
|
h.files.release(text("file"))
|
||||||
return nil, nil
|
return nil, nil
|
||||||
|
case "drop.release":
|
||||||
|
h.files.discardDrop(text("file"))
|
||||||
|
return nil, nil
|
||||||
case "child":
|
case "child":
|
||||||
value, err := h.files.child(text("handle"), text("name"), flag("directory"), flag("create"))
|
value, err := h.files.child(text("handle"), text("name"), flag("directory"), flag("create"))
|
||||||
if errors.Is(err, os.ErrNotExist) {
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
@@ -450,7 +679,7 @@ func (h *Host) call(ctx context.Context, name string, value any) (any, error) {
|
|||||||
case "remove":
|
case "remove":
|
||||||
return nil, h.files.remove(text("handle"), text("name"), flag("recursive"))
|
return nil, h.files.remove(text("handle"), text("name"), flag("recursive"))
|
||||||
case "write.begin":
|
case "write.begin":
|
||||||
writer, err := h.files.begin(text("handle"))
|
writer, err := h.files.begin(guigo.PageContext(ctx), text("handle"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -475,11 +704,11 @@ func (h *Host) call(ctx context.Context, name string, value any) (any, error) {
|
|||||||
}
|
}
|
||||||
descriptor, _ := args["data"].(map[string]any)
|
descriptor, _ := args["data"].(map[string]any)
|
||||||
key, _ := descriptor["nativeFile"].(string)
|
key, _ := descriptor["nativeFile"].(string)
|
||||||
source, size, err := h.files.resolve(key)
|
input, size, err := h.files.resolve(key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
_, err = io.Copy(writer, io.NewSectionReader(source, 0, size))
|
_, err = io.Copy(writer, io.NewSectionReader(input, 0, size))
|
||||||
return nil, err
|
return nil, err
|
||||||
case "fonts":
|
case "fonts":
|
||||||
h.fontOnce.Do(h.readFonts)
|
h.fontOnce.Do(h.readFonts)
|
||||||
@@ -492,19 +721,160 @@ func (h *Host) call(ctx context.Context, name string, value any) (any, error) {
|
|||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
return nil, window.SetTitle(text("title"))
|
return nil, window.SetTitle(text("title"))
|
||||||
case "ready":
|
case "window.info", "window.drag", "window.close":
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
paths := h.pendingPaths
|
window := h.window
|
||||||
h.pendingPaths = nil
|
|
||||||
h.mu.Unlock()
|
h.mu.Unlock()
|
||||||
if len(paths) != 0 {
|
if window == nil {
|
||||||
h.openPaths(paths)
|
return nil, fmt.Errorf("窗口尚未就绪")
|
||||||
}
|
}
|
||||||
|
if name == "window.info" {
|
||||||
|
return window.TitleBarInfo()
|
||||||
|
}
|
||||||
|
if name == "window.close" {
|
||||||
|
h.launchMu.Lock()
|
||||||
|
defer h.launchMu.Unlock()
|
||||||
|
if h.launchPending != 0 || len(h.pendingPaths) != 0 {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
h.launchClosed = true
|
||||||
|
h.mu.Lock()
|
||||||
|
h.closeAllowed = true
|
||||||
|
h.mu.Unlock()
|
||||||
|
return true, window.Close()
|
||||||
|
}
|
||||||
|
values, ok := args["regions"].([]any)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("拖动区域无效")
|
||||||
|
}
|
||||||
|
regions := make([]guigo.Rect, 0, len(values))
|
||||||
|
for _, value := range values {
|
||||||
|
item, ok := value.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("拖动区域无效")
|
||||||
|
}
|
||||||
|
x, xOK := item["x"].(float64)
|
||||||
|
y, yOK := item["y"].(float64)
|
||||||
|
width, widthOK := item["width"].(float64)
|
||||||
|
height, heightOK := item["height"].(float64)
|
||||||
|
if !xOK || !yOK || !widthOK || !heightOK {
|
||||||
|
return nil, fmt.Errorf("拖动区域无效")
|
||||||
|
}
|
||||||
|
regions = append(regions, guigo.Rect{X: x, Y: y, Width: width, Height: height})
|
||||||
|
}
|
||||||
|
return nil, window.SetDragRegions(regions)
|
||||||
|
case "launch.done":
|
||||||
|
h.launchMu.Lock()
|
||||||
|
if h.launchPending > 0 {
|
||||||
|
h.launchPending--
|
||||||
|
}
|
||||||
|
h.launchMu.Unlock()
|
||||||
return nil, nil
|
return nil, nil
|
||||||
|
case "ready":
|
||||||
|
h.launchMu.Lock()
|
||||||
|
defer h.launchMu.Unlock()
|
||||||
|
h.mu.Lock()
|
||||||
|
h.frontendReady = true
|
||||||
|
h.mu.Unlock()
|
||||||
|
return nil, h.flushLaunch()
|
||||||
}
|
}
|
||||||
return nil, fmt.Errorf("未知宿主操作")
|
return nil, fmt.Errorf("未知宿主操作")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// associationOptions 提供Windows文件关联的固定应用配置
|
||||||
|
// 返回: guigo.AssociationOptions 应用配置, error 路径错误
|
||||||
|
func associationOptions() (guigo.AssociationOptions, error) {
|
||||||
|
executable, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
return guigo.AssociationOptions{}, err
|
||||||
|
}
|
||||||
|
return guigo.AssociationOptions{
|
||||||
|
AppID: "OFDGo", Name: "OFDGo", Description: "OFD、PDF阅读与编辑工具",
|
||||||
|
Executable: executable, Arguments: []string{"--"},
|
||||||
|
Types: []guigo.FileAssociation{
|
||||||
|
{ID: "OFD", Name: "OFD文档", Extensions: []string{".ofd"}},
|
||||||
|
{ID: "PDF", Name: "PDF文档", Extensions: []string{".pdf"}},
|
||||||
|
},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// queryAssociations 分别查询两个范围,不因其中一个失败而隐藏另一个
|
||||||
|
// 返回: any 两个范围的状态, error 配置错误
|
||||||
|
func queryAssociations() (any, error) {
|
||||||
|
options, err := associationOptions()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
result := make(map[string]associationState)
|
||||||
|
for _, scope := range []guigo.AssociationScope{guigo.AssociationUser, guigo.AssociationMachine} {
|
||||||
|
state, err := guigo.QueryFileAssociations(options, scope)
|
||||||
|
row := associationState{AssociationStatus: state}
|
||||||
|
if err != nil {
|
||||||
|
row.Error = associationError(err).Error()
|
||||||
|
}
|
||||||
|
result[string(scope)] = row
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// changeAssociations 执行固定应用配置的单范围注册或撤销
|
||||||
|
// 入参: scope 作用范围, remove 是否撤销
|
||||||
|
// 返回: error 操作错误
|
||||||
|
func changeAssociations(scope string, remove bool) error {
|
||||||
|
options, err := associationOptions()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if remove {
|
||||||
|
err = guigo.UnregisterFileAssociations(options, guigo.AssociationScope(scope))
|
||||||
|
} else {
|
||||||
|
err = guigo.RegisterFileAssociations(options, guigo.AssociationScope(scope))
|
||||||
|
}
|
||||||
|
return associationError(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// associationError 区分未提升权限和实际访问失败,提供简短提示
|
||||||
|
// 入参: err 操作错误
|
||||||
|
// 返回: error 用户提示或原始错误
|
||||||
|
func associationError(err error) error {
|
||||||
|
if errors.Is(err, guigo.ErrAssociationElevationRequired) {
|
||||||
|
return errors.New("需管理员权限")
|
||||||
|
}
|
||||||
|
if errors.Is(err, os.ErrPermission) {
|
||||||
|
return errors.New("无权访问")
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// applicationUpdate 比较官网和当前程序的完整构建版本
|
||||||
|
// 入参: ctx 请求上下文, version 当前版本, endpoint 官网地址
|
||||||
|
// 返回: bool 是否有更新, error 检查错误
|
||||||
|
func applicationUpdate(ctx context.Context, version, endpoint string) (bool, error) {
|
||||||
|
if version == "" {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
request, err := http.NewRequestWithContext(ctx, http.MethodHead, endpoint, nil)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
request.Header.Set("Cache-Control", "no-store")
|
||||||
|
response, err := http.DefaultClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
if response.StatusCode != http.StatusOK {
|
||||||
|
return false, fmt.Errorf("检查更新失败: %s", response.Status)
|
||||||
|
}
|
||||||
|
latest := response.Header.Get("X-OFDGo-Build-Version")
|
||||||
|
if latest == "" {
|
||||||
|
return false, errors.New("缺少构建版本")
|
||||||
|
}
|
||||||
|
return latest != version, nil
|
||||||
|
}
|
||||||
|
|
||||||
// dialogFilters 将共用界面的文件类型映射到系统对话框
|
// dialogFilters 将共用界面的文件类型映射到系统对话框
|
||||||
// 入参: args 对话框参数
|
// 入参: args 对话框参数
|
||||||
// 返回: []guigo.FileFilter 文件类型列表
|
// 返回: []guigo.FileFilter 文件类型列表
|
||||||
@@ -660,7 +1030,7 @@ func (h *Host) openWriter(ctx context.Context, value any, name string) (io.Write
|
|||||||
return nil, fmt.Errorf("输出文件已存在")
|
return nil, fmt.Errorf("输出文件已存在")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return h.files.begin(id)
|
return h.files.begin(ctx, id)
|
||||||
}
|
}
|
||||||
|
|
||||||
// reserveOutput 为一次转换预留独立输出文件或目录
|
// reserveOutput 为一次转换预留独立输出文件或目录
|
||||||
@@ -687,12 +1057,13 @@ func (h *Host) cleanupOutput(ctx context.Context, target webui.NativeOutputTarge
|
|||||||
|
|
||||||
// readFonts 建立系统字体目录并登记按需读取资源
|
// readFonts 建立系统字体目录并登记按需读取资源
|
||||||
func (h *Host) readFonts() {
|
func (h *Host) readFonts() {
|
||||||
|
platform, language := fontNameLanguage()
|
||||||
for _, name := range ofdgo.FontSystemFiles() {
|
for _, name := range ofdgo.FontSystemFiles() {
|
||||||
data, err := os.ReadFile(name)
|
data, err := os.ReadFile(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
faces, err := (ofdgo.FontFile{Name: filepath.Base(name), Data: data}).Faces()
|
faces, err := (ofdgo.FontFile{Name: filepath.Base(name), Data: data}).LocalizedFaces(platform, language)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -705,9 +1076,9 @@ func (h *Host) readFonts() {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for _, face := range faces {
|
for _, face := range faces {
|
||||||
h.fonts = append(h.fonts, map[string]any{"index": face.Index, "postscriptName": face.PostScriptName, "fullName": face.FullName, "family": face.Family, "style": face.Style, "names": face.Names, "file": file})
|
h.fonts = append(h.fonts, map[string]any{"index": face.Index, "postscriptName": face.PostScriptName, "fullName": face.FullName, "family": face.Family, "style": face.Style, "names": face.Names, "menuFamily": face.MenuFamily, "menuStyle": face.MenuStyle, "familyKey": face.FamilyKey, "bold": face.Bold, "italic": face.Italic, "file": file})
|
||||||
for _, alias := range append([]string{face.FullName, face.Family, face.PostScriptName, strings.TrimSpace(face.Family + " " + face.Style)}, face.Names...) {
|
for _, alias := range append([]string{face.FullName, face.Family, face.PostScriptName, strings.TrimSpace(face.Family + " " + face.Style)}, face.Names...) {
|
||||||
if alias != "" {
|
if alias != "" && h.fontFiles[alias+".ttf"] == "" {
|
||||||
h.fontFiles[alias+".ttf"] = name + "\x00" + strconv.Itoa(face.Index)
|
h.fontFiles[alias+".ttf"] = name + "\x00" + strconv.Itoa(face.Index)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -716,7 +1087,7 @@ func (h *Host) readFonts() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// loadFont 按转换请求读取单个系统字体
|
// loadFont 按转换请求读取单个系统字体
|
||||||
// 入参: ctx 调用上下文, name 字体文件路径及字体索引
|
// 入参: ctx 调用上下文, name 字体别名对应的文件名
|
||||||
// 返回: []byte 字体数据, error 读取错误
|
// 返回: []byte 字体数据, error 读取错误
|
||||||
func (h *Host) loadFont(ctx context.Context, name string) ([]byte, error) {
|
func (h *Host) loadFont(ctx context.Context, name string) ([]byte, error) {
|
||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
@@ -741,7 +1112,21 @@ func (h *Host) loadFont(ctx context.Context, name string) ([]byte, error) {
|
|||||||
func (h *Host) closeEngine(id string) error {
|
func (h *Host) closeEngine(id string) error {
|
||||||
var results []any
|
var results []any
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
|
if closing := h.closingEngines[id]; closing != nil {
|
||||||
|
h.mu.Unlock()
|
||||||
|
<-closing.done
|
||||||
|
return closing.err
|
||||||
|
}
|
||||||
engine := h.engines[id]
|
engine := h.engines[id]
|
||||||
|
if engine == nil {
|
||||||
|
h.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
closing := &engineClose{done: make(chan struct{})}
|
||||||
|
if h.closingEngines == nil {
|
||||||
|
h.closingEngines = make(map[string]*engineClose)
|
||||||
|
}
|
||||||
|
h.closingEngines[id] = closing
|
||||||
delete(h.engines, id)
|
delete(h.engines, id)
|
||||||
if stop := h.engineStops[id]; stop != nil {
|
if stop := h.engineStops[id]; stop != nil {
|
||||||
stop()
|
stop()
|
||||||
@@ -762,33 +1147,43 @@ func (h *Host) closeEngine(id string) error {
|
|||||||
for _, result := range results {
|
for _, result := range results {
|
||||||
h.discard(result)
|
h.discard(result)
|
||||||
}
|
}
|
||||||
if engine != nil {
|
err := engine.Close()
|
||||||
return engine.Close()
|
h.mu.Lock()
|
||||||
}
|
closing.err = err
|
||||||
return nil
|
delete(h.closingEngines, id)
|
||||||
|
close(closing.done)
|
||||||
|
h.mu.Unlock()
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// close 取消任务并释放当前窗口持有的会话
|
// close 取消任务并释放当前窗口持有的会话
|
||||||
func (h *Host) close() {
|
func (h *Host) close() {
|
||||||
|
h.launchMu.Lock()
|
||||||
|
h.launchClosed = true
|
||||||
|
h.launchMu.Unlock()
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
for _, cancel := range h.cancels {
|
for _, cancel := range h.cancels {
|
||||||
cancel()
|
cancel()
|
||||||
}
|
}
|
||||||
engines := h.engines
|
engines := make([]string, 0, len(h.engines)+len(h.closingEngines))
|
||||||
|
for id := range h.engines {
|
||||||
|
engines = append(engines, id)
|
||||||
|
}
|
||||||
|
for id := range h.closingEngines {
|
||||||
|
engines = append(engines, id)
|
||||||
|
}
|
||||||
results := h.batchResults
|
results := h.batchResults
|
||||||
h.batchResults = nil
|
h.batchResults = nil
|
||||||
for _, stop := range h.engineStops {
|
|
||||||
stop()
|
|
||||||
}
|
|
||||||
h.engineStops = nil
|
|
||||||
h.engines = make(map[string]*webui.NativeEngine)
|
|
||||||
h.mu.Unlock()
|
h.mu.Unlock()
|
||||||
for _, engine := range engines {
|
for _, id := range engines {
|
||||||
_ = engine.Close()
|
_ = h.closeEngine(id)
|
||||||
}
|
}
|
||||||
for _, result := range results {
|
for _, result := range results {
|
||||||
h.discard(result)
|
h.discard(result)
|
||||||
}
|
}
|
||||||
|
if h.resources != nil {
|
||||||
|
h.resources.Clear()
|
||||||
|
}
|
||||||
_ = h.files.close()
|
_ = h.files.close()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -796,12 +1191,18 @@ func (h *Host) close() {
|
|||||||
// 入参: dataDir 自定义浏览器数据目录
|
// 入参: dataDir 自定义浏览器数据目录
|
||||||
// 返回: guigo.Options 窗口配置, error 配置错误
|
// 返回: guigo.Options 窗口配置, error 配置错误
|
||||||
func windowOptions(dataDir string) (guigo.Options, error) {
|
func windowOptions(dataDir string) (guigo.Options, error) {
|
||||||
|
appID := "ofdgo"
|
||||||
|
cacheName := appID
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
appID = ""
|
||||||
|
cacheName = "OFDGo"
|
||||||
|
}
|
||||||
if dataDir == "" {
|
if dataDir == "" {
|
||||||
cache, err := os.UserCacheDir()
|
cache, err := os.UserCacheDir()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return guigo.Options{}, err
|
return guigo.Options{}, err
|
||||||
}
|
}
|
||||||
dataDir = filepath.Join(cache, "OFDGo")
|
dataDir = filepath.Join(cache, cacheName)
|
||||||
}
|
}
|
||||||
dataDir, err := filepath.Abs(dataDir)
|
dataDir, err := filepath.Abs(dataDir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -812,8 +1213,10 @@ func windowOptions(dataDir string) (guigo.Options, error) {
|
|||||||
return guigo.Options{}, err
|
return guigo.Options{}, err
|
||||||
}
|
}
|
||||||
return guigo.Options{
|
return guigo.Options{
|
||||||
AppID: applicationID,
|
AppID: appID,
|
||||||
Title: "OFDGo - OFD编辑器",
|
Title: "OFDGo - OFD编辑器",
|
||||||
|
TitleBar: guigo.TitleBarContent,
|
||||||
|
TitleBarColors: themeColors(false),
|
||||||
Icon: icon,
|
Icon: icon,
|
||||||
Width: 1440,
|
Width: 1440,
|
||||||
Height: 900,
|
Height: 900,
|
||||||
|
|||||||
@@ -29,6 +29,9 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/xiaoqidun/ofdgo"
|
||||||
|
basefile "github.com/xiaoqidun/ofdgo/internal/base/file"
|
||||||
)
|
)
|
||||||
|
|
||||||
// fileEntry 保存窗口授权的文件或目录
|
// fileEntry 保存窗口授权的文件或目录
|
||||||
@@ -41,6 +44,10 @@ type fileEntry struct {
|
|||||||
directory bool
|
directory bool
|
||||||
owned bool
|
owned bool
|
||||||
temporary bool
|
temporary bool
|
||||||
|
saveTarget ofdgo.Output
|
||||||
|
readers int
|
||||||
|
retired bool
|
||||||
|
dropHandle string
|
||||||
}
|
}
|
||||||
|
|
||||||
// fileStore 管理窗口范围内的文件授权和临时数据
|
// fileStore 管理窗口范围内的文件授权和临时数据
|
||||||
@@ -55,12 +62,8 @@ type fileStore struct {
|
|||||||
// fileWriter 在同目录临时文件中保存输出
|
// fileWriter 在同目录临时文件中保存输出
|
||||||
type fileWriter struct {
|
type fileWriter struct {
|
||||||
id string
|
id string
|
||||||
mu sync.Mutex
|
|
||||||
store *fileStore
|
store *fileStore
|
||||||
file *os.File
|
output ofdgo.WriteTransaction
|
||||||
target string
|
|
||||||
err error
|
|
||||||
closed bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// newFileStore 创建独立文件授权表
|
// newFileStore 创建独立文件授权表
|
||||||
@@ -124,10 +127,70 @@ func (s *fileStore) add(name string, directory bool) (map[string]any, error) {
|
|||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
id := rand.Text()
|
id := rand.Text()
|
||||||
s.entries[id] = &fileEntry{path: name, name: filepath.Base(name), directory: directory}
|
entry := &fileEntry{path: name, name: filepath.Base(name), directory: directory}
|
||||||
|
if !directory {
|
||||||
|
entry.saveTarget, err = ofdgo.NewFileOutput(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.entries[id] = entry
|
||||||
return s.descriptor(id), nil
|
return s.descriptor(id), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// addDrop 登记拖放文件及读取快照,失败时撤销本次授权
|
||||||
|
// 入参: name 拖放文件路径
|
||||||
|
// 返回: map[string]any 文件描述, error 登记错误
|
||||||
|
func (s *fileStore) addDrop(name string) (map[string]any, error) {
|
||||||
|
handle, err := s.add(name, false)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
id := handle["nativeHandle"].(string)
|
||||||
|
file, err := s.file(id)
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
if err == nil && !s.closed {
|
||||||
|
if entry := s.entries[file["nativeFile"].(string)]; entry != nil && s.entries[id] != nil {
|
||||||
|
entry.dropHandle = id
|
||||||
|
file["drop"] = true
|
||||||
|
return file, nil
|
||||||
|
}
|
||||||
|
err = os.ErrNotExist
|
||||||
|
}
|
||||||
|
delete(s.entries, id)
|
||||||
|
if file != nil {
|
||||||
|
key := file["nativeFile"].(string)
|
||||||
|
if entry := s.entries[key]; entry != nil {
|
||||||
|
delete(s.entries, key)
|
||||||
|
if entry.file != nil {
|
||||||
|
entry.file.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
err = os.ErrClosed
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// discardDrop 撤销未接收的拖放文件及其授权,不删除源文件
|
||||||
|
// 入参: id 拖放读取快照标识
|
||||||
|
func (s *fileStore) discardDrop(id string) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
entry := s.entries[id]
|
||||||
|
if entry == nil || entry.dropHandle == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
delete(s.entries, entry.dropHandle)
|
||||||
|
delete(s.entries, id)
|
||||||
|
entry.retired = true
|
||||||
|
if entry.file != nil && entry.readers == 0 {
|
||||||
|
entry.file.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// save 登记用户选择的输出路径
|
// save 登记用户选择的输出路径
|
||||||
// 入参: name 输出文件路径
|
// 入参: name 输出文件路径
|
||||||
// 返回: map[string]any 句柄描述
|
// 返回: map[string]any 句柄描述
|
||||||
@@ -161,9 +224,10 @@ func (s *fileStore) file(id string) (map[string]any, error) {
|
|||||||
if entry == nil || entry.directory {
|
if entry == nil || entry.directory {
|
||||||
return nil, fmt.Errorf("文件授权无效")
|
return nil, fmt.Errorf("文件授权无效")
|
||||||
}
|
}
|
||||||
|
handle := s.descriptor(id)
|
||||||
size := int64(len(entry.data))
|
size := int64(len(entry.data))
|
||||||
if entry.data == nil {
|
if entry.data == nil {
|
||||||
file, err := openReadFile(entry.path)
|
file, err := basefile.Open(entry.path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -177,7 +241,7 @@ func (s *fileStore) file(id string) (map[string]any, error) {
|
|||||||
entry = &fileEntry{path: entry.path, name: entry.name, file: file}
|
entry = &fileEntry{path: entry.path, name: entry.name, file: file}
|
||||||
s.entries[id] = entry
|
s.entries[id] = entry
|
||||||
}
|
}
|
||||||
return map[string]any{"nativeFile": id, "name": entry.name, "size": size, "url": "/__native/data/" + id}, nil
|
return map[string]any{"nativeFile": id, "name": entry.name, "size": size, "url": "/__native/data/" + id, "handle": handle}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// resolve 按授权标识读取文件并保持随机读取句柄
|
// resolve 按授权标识读取文件并保持随机读取句柄
|
||||||
@@ -194,7 +258,7 @@ func (s *fileStore) resolve(id string) (io.ReaderAt, int64, error) {
|
|||||||
return bytes.NewReader(entry.data), int64(len(entry.data)), nil
|
return bytes.NewReader(entry.data), int64(len(entry.data)), nil
|
||||||
}
|
}
|
||||||
if entry.file == nil {
|
if entry.file == nil {
|
||||||
file, err := openReadFile(entry.path)
|
file, err := basefile.Open(entry.path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
@@ -237,7 +301,27 @@ func (s *fileStore) resource(id string) (io.ReaderAt, int64, func() error, error
|
|||||||
if entry.data != nil {
|
if entry.data != nil {
|
||||||
return bytes.NewReader(entry.data), int64(len(entry.data)), nil, nil
|
return bytes.NewReader(entry.data), int64(len(entry.data)), nil, nil
|
||||||
}
|
}
|
||||||
file, err := openReadFile(entry.path)
|
if entry.file != nil && !entry.temporary {
|
||||||
|
info, err := entry.file.Stat()
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, nil, err
|
||||||
|
}
|
||||||
|
entry.readers++
|
||||||
|
var once sync.Once
|
||||||
|
var closeErr error
|
||||||
|
return entry.file, info.Size(), func() error {
|
||||||
|
once.Do(func() {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
entry.readers--
|
||||||
|
if entry.retired && entry.readers == 0 {
|
||||||
|
closeErr = entry.file.Close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return closeErr
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
file, err := basefile.Open(entry.path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, nil, err
|
return nil, 0, nil, err
|
||||||
}
|
}
|
||||||
@@ -249,17 +333,18 @@ func (s *fileStore) resource(id string) (io.ReaderAt, int64, func() error, error
|
|||||||
return file, info.Size(), file.Close, nil
|
return file, info.Size(), file.Close, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// release 释放内存结果或临时文件并取消页面清理回调
|
// release 释放读取快照、内存结果或临时文件,保留在途读取及源文件
|
||||||
// 入参: id 资源标识
|
// 入参: id 资源标识
|
||||||
func (s *fileStore) release(id string) {
|
func (s *fileStore) release(id string) {
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
if entry := s.entries[id]; entry != nil && (entry.data != nil || entry.temporary) {
|
if entry := s.entries[id]; entry != nil && (entry.data != nil || entry.temporary || entry.file != nil) {
|
||||||
delete(s.entries, id)
|
delete(s.entries, id)
|
||||||
|
entry.retired = true
|
||||||
if entry.stop != nil {
|
if entry.stop != nil {
|
||||||
entry.stop()
|
entry.stop()
|
||||||
}
|
}
|
||||||
if entry.file != nil {
|
if entry.file != nil && entry.readers == 0 {
|
||||||
entry.file.Close()
|
entry.file.Close()
|
||||||
}
|
}
|
||||||
if entry.temporary {
|
if entry.temporary {
|
||||||
@@ -374,9 +459,9 @@ func (s *fileStore) reserve(id, base, extension string, directory bool) (string,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// begin 创建文件写入事务
|
// begin 创建文件写入事务
|
||||||
// 入参: id 输出授权标识
|
// 入参: ctx 取消上下文, id 输出授权标识
|
||||||
// 返回: *fileWriter 事务写入器, error 创建错误
|
// 返回: *fileWriter 事务写入器, error 创建错误
|
||||||
func (s *fileStore) begin(id string) (*fileWriter, error) {
|
func (s *fileStore) begin(ctx context.Context, id string) (*fileWriter, error) {
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
defer s.mu.Unlock()
|
defer s.mu.Unlock()
|
||||||
if s.closed {
|
if s.closed {
|
||||||
@@ -386,11 +471,18 @@ func (s *fileStore) begin(id string) (*fileWriter, error) {
|
|||||||
if entry == nil || entry.directory || entry.path == "" {
|
if entry == nil || entry.directory || entry.path == "" {
|
||||||
return nil, fmt.Errorf("输出授权无效")
|
return nil, fmt.Errorf("输出授权无效")
|
||||||
}
|
}
|
||||||
file, err := temporaryFile(filepath.Dir(entry.path), filepath.Base(entry.path)+".")
|
if entry.saveTarget == nil {
|
||||||
|
var err error
|
||||||
|
entry.saveTarget, err = ofdgo.NewFileOutput(entry.path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
writer := &fileWriter{id: rand.Text(), store: s, file: file, target: entry.path}
|
}
|
||||||
|
output, err := entry.saveTarget.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
writer := &fileWriter{id: rand.Text(), store: s, output: output}
|
||||||
s.writers[writer.id] = writer
|
s.writers[writer.id] = writer
|
||||||
return writer, nil
|
return writer, nil
|
||||||
}
|
}
|
||||||
@@ -429,7 +521,8 @@ func (s *fileStore) remove(id, name string, recursive bool) error {
|
|||||||
defer root.Close()
|
defer root.Close()
|
||||||
for key, entry := range s.entries {
|
for key, entry := range s.entries {
|
||||||
if entry.path == target || recursive && strings.HasPrefix(entry.path, target+string(filepath.Separator)) {
|
if entry.path == target || recursive && strings.HasPrefix(entry.path, target+string(filepath.Separator)) {
|
||||||
if entry.file != nil {
|
entry.retired = true
|
||||||
|
if entry.file != nil && entry.readers == 0 {
|
||||||
entry.file.Close()
|
entry.file.Close()
|
||||||
}
|
}
|
||||||
delete(s.entries, key)
|
delete(s.entries, key)
|
||||||
@@ -445,47 +538,15 @@ func (s *fileStore) remove(id, name string, recursive bool) error {
|
|||||||
// 入参: data 输出数据
|
// 入参: data 输出数据
|
||||||
// 返回: int 写入字节数, error 写入错误
|
// 返回: int 写入字节数, error 写入错误
|
||||||
func (w *fileWriter) Write(data []byte) (int, error) {
|
func (w *fileWriter) Write(data []byte) (int, error) {
|
||||||
w.mu.Lock()
|
return w.output.Write(data)
|
||||||
defer w.mu.Unlock()
|
|
||||||
if w.closed {
|
|
||||||
return 0, os.ErrClosed
|
|
||||||
}
|
|
||||||
if w.err != nil {
|
|
||||||
return 0, w.err
|
|
||||||
}
|
|
||||||
n, err := w.file.Write(data)
|
|
||||||
if err == nil && n != len(data) {
|
|
||||||
err = io.ErrShortWrite
|
|
||||||
}
|
|
||||||
w.err = err
|
|
||||||
return n, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close 同步并替换目标文件
|
// Close 同步并替换目标文件
|
||||||
// 返回: error 提交错误
|
// 返回: error 提交错误
|
||||||
func (w *fileWriter) Close() error {
|
func (w *fileWriter) Close() error {
|
||||||
defer w.release()
|
defer w.release()
|
||||||
w.mu.Lock()
|
if err := w.output.Commit(); err != nil {
|
||||||
defer w.mu.Unlock()
|
return errors.Join(err, w.output.Abort())
|
||||||
if w.closed {
|
|
||||||
return os.ErrClosed
|
|
||||||
}
|
|
||||||
w.closed = true
|
|
||||||
if w.err != nil {
|
|
||||||
return errors.Join(w.err, w.file.Close(), os.Remove(w.file.Name()))
|
|
||||||
}
|
|
||||||
if err := w.file.Sync(); err != nil {
|
|
||||||
w.file.Close()
|
|
||||||
os.Remove(w.file.Name())
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := w.file.Close(); err != nil {
|
|
||||||
os.Remove(w.file.Name())
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := replaceFile(w.file.Name(), w.target); err != nil {
|
|
||||||
os.Remove(w.file.Name())
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -494,13 +555,7 @@ func (w *fileWriter) Close() error {
|
|||||||
// 返回: error 清理错误
|
// 返回: error 清理错误
|
||||||
func (w *fileWriter) Abort() error {
|
func (w *fileWriter) Abort() error {
|
||||||
defer w.release()
|
defer w.release()
|
||||||
w.mu.Lock()
|
return w.output.Abort()
|
||||||
defer w.mu.Unlock()
|
|
||||||
if w.closed {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
w.closed = true
|
|
||||||
return errors.Join(w.file.Close(), os.Remove(w.file.Name()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// release 移除已结束的写入事务
|
// release 移除已结束的写入事务
|
||||||
@@ -556,9 +611,12 @@ func (s *fileStore) close() error {
|
|||||||
if entry.stop != nil {
|
if entry.stop != nil {
|
||||||
entry.stop()
|
entry.stop()
|
||||||
}
|
}
|
||||||
if entry.file != nil {
|
s.mu.Lock()
|
||||||
|
entry.retired = true
|
||||||
|
if entry.file != nil && entry.readers == 0 {
|
||||||
err = errors.Join(err, entry.file.Close())
|
err = errors.Join(err, entry.file.Close())
|
||||||
}
|
}
|
||||||
|
s.mu.Unlock()
|
||||||
}
|
}
|
||||||
return errors.Join(err, os.RemoveAll(s.temporary))
|
return errors.Join(err, os.RemoveAll(s.temporary))
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
package webview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// conversionMemory 未提供系统内存探测时仅按并行数调度
|
||||||
|
var conversionMemory func() int64
|
||||||
|
|
||||||
|
// instanceDirectory 解析数据目录的实际路径,使符号链接复用同一实例
|
||||||
|
// 入参: path 数据目录路径
|
||||||
|
// 返回: string 规范路径, error 路径解析错误
|
||||||
|
func instanceDirectory(path string) (string, error) {
|
||||||
|
return filepath.EvalSymlinks(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// fontNameLanguage 获取Linux区域设置对应的OpenType名称表标识
|
||||||
|
// 返回: uint16 名称表平台标识, uint16 显示语言标识
|
||||||
|
func fontNameLanguage() (uint16, uint16) {
|
||||||
|
locale := ""
|
||||||
|
for _, name := range []string{"LC_ALL", "LC_MESSAGES", "LANG"} {
|
||||||
|
if locale = os.Getenv(name); locale != "" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
locale = strings.ToLower(strings.ReplaceAll(locale, "-", "_"))
|
||||||
|
locale, _, _ = strings.Cut(locale, ".")
|
||||||
|
locale, _, _ = strings.Cut(locale, "@")
|
||||||
|
switch locale {
|
||||||
|
case "zh", "zh_cn", "zh_hans":
|
||||||
|
return 3, 0x0804
|
||||||
|
case "zh_hk":
|
||||||
|
return 3, 0x0c04
|
||||||
|
case "zh_mo":
|
||||||
|
return 3, 0x1404
|
||||||
|
case "zh_tw", "zh_hant":
|
||||||
|
return 3, 0x0404
|
||||||
|
case "zh_sg":
|
||||||
|
return 3, 0x1004
|
||||||
|
case "ja", "ja_jp":
|
||||||
|
return 3, 0x0411
|
||||||
|
case "ko", "ko_kr":
|
||||||
|
return 3, 0x0412
|
||||||
|
case "c", "posix", "en", "en_us":
|
||||||
|
return 3, 0x0409
|
||||||
|
}
|
||||||
|
return 0xffff, 0xffff
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
//go:build !windows && !linux
|
||||||
|
|
||||||
|
package webview
|
||||||
|
|
||||||
|
import "path/filepath"
|
||||||
|
|
||||||
|
// conversionMemory 未提供系统内存探测时仅按并行数调度
|
||||||
|
var conversionMemory func() int64
|
||||||
|
|
||||||
|
// instanceDirectory 解析数据目录的实际路径
|
||||||
|
// 入参: path 数据目录路径
|
||||||
|
// 返回: string 规范路径, error 路径解析错误
|
||||||
|
func instanceDirectory(path string) (string, error) {
|
||||||
|
return filepath.EvalSymlinks(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// fontNameLanguage 未指定系统显示语言时沿用字体名称表顺序
|
||||||
|
// 返回: uint16 未指定平台标识, uint16 未指定语言标识
|
||||||
|
func fontNameLanguage() (uint16, uint16) {
|
||||||
|
return 0xffff, 0xffff
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
//go:build !js || !wasm
|
||||||
|
|
||||||
|
package webview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"github.com/xiaoqidun/guigo"
|
||||||
|
webuiassets "github.com/xiaoqidun/ofdgo/assets/webui"
|
||||||
|
)
|
||||||
|
|
||||||
|
// applicationTheme 保存应用主题偏好及最后一次解析的系统外观
|
||||||
|
type applicationTheme struct {
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
Dark bool `json:"dark"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// themeColors 返回应用对应外观的原生标题栏配色
|
||||||
|
// 入参: dark 是否使用深色
|
||||||
|
// 返回: guigo.TitleBarColors 标题栏配色
|
||||||
|
func themeColors(dark bool) guigo.TitleBarColors {
|
||||||
|
if dark {
|
||||||
|
return guigo.TitleBarColors{Background: "#20272b", Foreground: "#e0e7eb", InactiveBackground: "#242b30", InactiveForeground: "#9aa8b1"}
|
||||||
|
}
|
||||||
|
return guigo.TitleBarColors{Background: "#e8edee", Foreground: "#263238", InactiveBackground: "#eef1f3", InactiveForeground: "#728087"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadTheme 在创建窗口前读取用户目录中的主题偏好
|
||||||
|
// 返回: error 读取或解析错误
|
||||||
|
func (h *Host) loadTheme() error {
|
||||||
|
h.theme = applicationTheme{Mode: "system"}
|
||||||
|
data, err := os.ReadFile(h.themePath)
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(data, &h.theme); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return h.theme.validate()
|
||||||
|
}
|
||||||
|
|
||||||
|
// validate 检查应用主题及解析后的配色是否一致
|
||||||
|
// 返回: error 偏好错误
|
||||||
|
func (a applicationTheme) validate() error {
|
||||||
|
if a.Mode != "system" && a.Mode != "light" && a.Mode != "dark" {
|
||||||
|
return fmt.Errorf("主题无效")
|
||||||
|
}
|
||||||
|
if a.Mode == "light" && a.Dark || a.Mode == "dark" && !a.Dark {
|
||||||
|
return fmt.Errorf("主题配色无效")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// themeIndex 在页面首次绘制前提供当前主题偏好
|
||||||
|
// 返回: []byte 页面内容, error 资源读取错误
|
||||||
|
func (h *Host) themeIndex() ([]byte, error) {
|
||||||
|
data, err := webuiassets.NativeFS.ReadFile("index.html")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
h.themeMu.Lock()
|
||||||
|
mode := h.theme.Mode
|
||||||
|
h.themeMu.Unlock()
|
||||||
|
if mode == "" {
|
||||||
|
mode = "system"
|
||||||
|
}
|
||||||
|
return bytes.Replace(data, []byte(`<html lang="zh-CN">`), []byte(`<html lang="zh-CN" data-theme-mode="`+mode+`">`), 1), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// setTheme 串行保存应用偏好并同步当前窗口配色
|
||||||
|
// 入参: value 已解析的主题偏好
|
||||||
|
// 返回: error 校验、持久化或窗口更新错误
|
||||||
|
func (h *Host) setTheme(value applicationTheme) error {
|
||||||
|
if err := value.validate(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
h.themeMu.Lock()
|
||||||
|
defer h.themeMu.Unlock()
|
||||||
|
h.mu.Lock()
|
||||||
|
window := h.window
|
||||||
|
h.mu.Unlock()
|
||||||
|
if window == nil {
|
||||||
|
return fmt.Errorf("窗口尚未就绪")
|
||||||
|
}
|
||||||
|
if h.theme != value {
|
||||||
|
data, err := json.Marshal(value)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
file, err := os.CreateTemp(filepath.Dir(h.themePath), "appearance-*")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer os.Remove(file.Name())
|
||||||
|
_, writeErr := file.Write(data)
|
||||||
|
closeErr := file.Close()
|
||||||
|
if writeErr != nil {
|
||||||
|
return writeErr
|
||||||
|
}
|
||||||
|
if closeErr != nil {
|
||||||
|
return closeErr
|
||||||
|
}
|
||||||
|
if err := os.Rename(file.Name(), h.themePath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
h.theme = value
|
||||||
|
}
|
||||||
|
return window.SetTitleBarColors(themeColors(value.Dark))
|
||||||
|
}
|
||||||
@@ -15,13 +15,46 @@
|
|||||||
package webview
|
package webview
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
)
|
)
|
||||||
|
|
||||||
// memoryStatusProc 查询系统物理内存和提交额度
|
// memoryStatusProc 查询系统物理内存和提交额度
|
||||||
var memoryStatusProc = syscall.NewLazyDLL("kernel32.dll").NewProc("GlobalMemoryStatusEx")
|
var memoryStatusProc = syscall.NewLazyDLL("kernel32.dll").NewProc("GlobalMemoryStatusEx")
|
||||||
|
|
||||||
|
// instanceDirectory 解析数据目录的实际路径,使目录联接及大小写别名复用同一实例
|
||||||
|
// 入参: path 数据目录路径
|
||||||
|
// 返回: string 规范路径, error 路径解析错误
|
||||||
|
func instanceDirectory(path string) (string, error) {
|
||||||
|
dir, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer dir.Close()
|
||||||
|
buffer := make([]uint16, 256)
|
||||||
|
for {
|
||||||
|
n, err := windows.GetFinalPathNameByHandle(windows.Handle(dir.Fd()), &buffer[0], uint32(len(buffer)), 0)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if n < uint32(len(buffer)) {
|
||||||
|
return strings.ToLower(windows.UTF16ToString(buffer[:n])), nil
|
||||||
|
}
|
||||||
|
buffer = make([]uint16, n+1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fontNameLanguage 获取系统显示语言对应的OpenType名称表标识
|
||||||
|
// 返回: uint16 名称表平台标识, uint16 系统显示语言标识
|
||||||
|
func fontNameLanguage() (uint16, uint16) {
|
||||||
|
language, _, _ := syscall.NewLazyDLL("kernel32.dll").NewProc("GetUserDefaultUILanguage").Call()
|
||||||
|
return 3, uint16(language)
|
||||||
|
}
|
||||||
|
|
||||||
// conversionMemory 预留系统内存后返回可用于新增转换的额度
|
// conversionMemory 预留系统内存后返回可用于新增转换的额度
|
||||||
// 返回: int64 可用字节数,查询失败时暂停扩容
|
// 返回: int64 可用字节数,查询失败时暂停扩容
|
||||||
func conversionMemory() int64 {
|
func conversionMemory() int64 {
|
||||||
@@ -17,42 +17,267 @@ package ofdgo
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"archive/zip"
|
"archive/zip"
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
"image"
|
"image"
|
||||||
"io"
|
"io"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
basefile "github.com/xiaoqidun/ofdgo/internal/base/file"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Open 打开OFD文件
|
// Input 统一文件、内存及顺序流的随机读取,可并发读取和关闭,不可复制
|
||||||
// 返回的阅读器持有文件,使用完毕后需调用Close
|
// 调用方应在阅读、编辑及转换结束后调用Close,借入的数据需在此期间保持不变
|
||||||
// 入参: path 文件路径, options 阅读选项
|
// 借入的随机读取器应支持并发ReadAt,Close不会关闭调用方传入的读取器
|
||||||
// 返回: *Reader 阅读器实例, error 错误信息
|
type Input struct {
|
||||||
func Open(path string, options ...ReaderOption) (*Reader, error) {
|
mu sync.RWMutex
|
||||||
r, err := zip.OpenReader(path)
|
reader io.ReaderAt
|
||||||
if err != nil {
|
size int64
|
||||||
return nil, err
|
path string
|
||||||
}
|
file *os.File
|
||||||
reader := &Reader{
|
temp bool
|
||||||
Path: path,
|
|
||||||
Zip: &r.Reader,
|
|
||||||
Closer: r,
|
|
||||||
}
|
|
||||||
if err := reader.open(options); err != nil {
|
|
||||||
reader.Close()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return reader, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewReader 从IO读取器创建OFD阅读器
|
// InputOptions 设置顺序输入的缓存及大小限制,单位为字节
|
||||||
// 读取器的生命周期由调用方管理,Reader.Close不会关闭它
|
// MemoryLimit为0时使用8MiB,浏览器WASM仅用内存;负值表示仅用内存
|
||||||
// 入参: r IO读取器, size 数据大小, options 阅读选项
|
// TempDir为空时使用系统临时目录,不自动创建调用方指定的目录
|
||||||
|
// MaxSize为0时不限制输入大小,OpenFile和ReadInput均检查此限制
|
||||||
|
// 无临时文件系统的平台可显式使用仅内存模式,并通过MaxSize限制输入
|
||||||
|
type InputOptions struct {
|
||||||
|
MemoryLimit int64
|
||||||
|
MaxSize int64
|
||||||
|
TempDir string
|
||||||
|
}
|
||||||
|
|
||||||
|
// OpenFile 打开文件输入,不复制文件内容,Close释放文件句柄
|
||||||
|
// 入参: ctx 取消上下文, path 文件路径, options 输入选项
|
||||||
|
// 返回: *Input 输入源, error 打开或大小错误
|
||||||
|
func OpenFile(ctx context.Context, path string, options InputOptions) (*Input, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
f, err := basefile.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
info, err := f.Stat()
|
||||||
|
if err != nil {
|
||||||
|
f.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !info.Mode().IsRegular() {
|
||||||
|
f.Close()
|
||||||
|
return nil, fmt.Errorf("input is not a regular file")
|
||||||
|
}
|
||||||
|
input, err := NewInput(f, info.Size())
|
||||||
|
if err != nil {
|
||||||
|
f.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
input.file, input.path = f, path
|
||||||
|
if err := input.checkOptions(ctx, options); err != nil {
|
||||||
|
input.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return input, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewInput 借用指定长度的随机读取源,不复制数据或接管其生命周期
|
||||||
|
// 入参: reader 随机读取器, size 数据大小
|
||||||
|
// 返回: *Input 输入源, error 参数错误
|
||||||
|
func NewInput(reader io.ReaderAt, size int64) (*Input, error) {
|
||||||
|
if reader == nil || size < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid input")
|
||||||
|
}
|
||||||
|
return &Input{reader: reader, size: size}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadInput 从当前位置接收顺序输入,超过内存阈值后转入临时文件
|
||||||
|
// 已知大小且支持随机访问的可定位读取器直接复用,不移动其当前位置
|
||||||
|
// 不关闭传入流;取消无法中断阻塞的Read,调用方应自行设置超时或关闭流
|
||||||
|
// 入参: ctx 取消上下文, reader 输入流, options 输入选项
|
||||||
|
// 返回: *Input 输入源, error 读取、缓存或取消错误
|
||||||
|
func ReadInput(ctx context.Context, reader io.Reader, options InputOptions) (*Input, error) {
|
||||||
|
if reader == nil || options.MaxSize < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid input options")
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if random, ok := reader.(io.ReaderAt); ok {
|
||||||
|
if seeker, ok := reader.(io.Seeker); ok {
|
||||||
|
var size int64 = -1
|
||||||
|
if sized, ok := reader.(interface{ Size() int64 }); ok {
|
||||||
|
size = sized.Size()
|
||||||
|
} else if stated, ok := reader.(interface{ Stat() (os.FileInfo, error) }); ok {
|
||||||
|
info, err := stated.Stat()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if info.Mode().IsRegular() {
|
||||||
|
size = info.Size()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if size >= 0 {
|
||||||
|
offset, err := seeker.Seek(0, io.SeekCurrent)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if offset < 0 || offset > size {
|
||||||
|
return nil, fmt.Errorf("invalid input offset")
|
||||||
|
}
|
||||||
|
input, err := NewInput(io.NewSectionReader(random, offset, size-offset), size-offset)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := input.checkOptions(ctx, options); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return input, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
limit := options.MemoryLimit
|
||||||
|
if limit == 0 {
|
||||||
|
limit = 8 << 20
|
||||||
|
if runtime.GOOS == "js" {
|
||||||
|
limit = -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
input := &Input{}
|
||||||
|
success := false
|
||||||
|
defer func() {
|
||||||
|
if !success {
|
||||||
|
input.Close()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
var memory bytes.Buffer
|
||||||
|
buffer := make([]byte, 64<<10)
|
||||||
|
empty := 0
|
||||||
|
for {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
n, err := reader.Read(buffer)
|
||||||
|
if n < 0 || n > len(buffer) {
|
||||||
|
return nil, fmt.Errorf("invalid input read count")
|
||||||
|
}
|
||||||
|
if err != nil && err != io.EOF {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if failure := ctx.Err(); failure != nil {
|
||||||
|
return nil, failure
|
||||||
|
}
|
||||||
|
if n > 0 {
|
||||||
|
empty = 0
|
||||||
|
if input.size > int64(^uint64(0)>>1)-int64(n) || options.MaxSize > 0 && int64(n) > options.MaxSize-input.size {
|
||||||
|
return nil, fmt.Errorf("input exceeds size limit")
|
||||||
|
}
|
||||||
|
if input.file == nil && limit >= 0 && input.size+int64(n) > limit {
|
||||||
|
file, failure := basefile.NewTemp(options.TempDir)
|
||||||
|
if failure != nil {
|
||||||
|
return nil, failure
|
||||||
|
}
|
||||||
|
input.file, input.temp = file, true
|
||||||
|
if _, failure = file.Write(memory.Bytes()); failure != nil {
|
||||||
|
return nil, failure
|
||||||
|
}
|
||||||
|
memory = bytes.Buffer{}
|
||||||
|
}
|
||||||
|
var output io.Writer = &memory
|
||||||
|
if input.file != nil {
|
||||||
|
output = input.file
|
||||||
|
}
|
||||||
|
if _, failure := output.Write(buffer[:n]); failure != nil {
|
||||||
|
return nil, failure
|
||||||
|
}
|
||||||
|
input.size += int64(n)
|
||||||
|
} else if err == nil {
|
||||||
|
empty++
|
||||||
|
if empty >= 100 {
|
||||||
|
return nil, io.ErrNoProgress
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
input.reader = bytes.NewReader(memory.Bytes())
|
||||||
|
if input.file != nil {
|
||||||
|
input.reader = input.file
|
||||||
|
}
|
||||||
|
success = true
|
||||||
|
return input, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkOptions 检查取消状态及输入大小
|
||||||
|
// 入参: ctx 取消上下文, options 输入选项
|
||||||
|
// 返回: error 取消或大小错误
|
||||||
|
func (s *Input) checkOptions(ctx context.Context, options InputOptions) error {
|
||||||
|
if options.MaxSize < 0 || options.MaxSize > 0 && s.size > options.MaxSize {
|
||||||
|
return fmt.Errorf("input exceeds size limit")
|
||||||
|
}
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size 返回输入字节数,关闭后仍可查询
|
||||||
|
// 返回: int64 数据大小
|
||||||
|
func (s *Input) Size() int64 {
|
||||||
|
return s.size
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadAt 读取指定位置的数据,关闭后返回os.ErrClosed
|
||||||
|
// 入参: data 目标缓冲区, offset 字节偏移
|
||||||
|
// 返回: int 读取字节数, error 读取错误
|
||||||
|
func (s *Input) ReadAt(data []byte, offset int64) (int, error) {
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
if s.reader == nil {
|
||||||
|
return 0, os.ErrClosed
|
||||||
|
}
|
||||||
|
return io.NewSectionReader(s.reader, 0, s.size).ReadAt(data, offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close 释放自有文件和缓存,等待正在进行的读取结束,可重复调用
|
||||||
|
// 返回: error 文件关闭或临时文件删除错误
|
||||||
|
func (s *Input) Close() error {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
s.reader = nil
|
||||||
|
if s.file == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
file := s.file
|
||||||
|
s.file = nil
|
||||||
|
err := file.Close()
|
||||||
|
if s.temp {
|
||||||
|
err = errors.Join(err, os.Remove(file.Name()))
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewReader 从统一输入源创建OFD阅读器,不接管输入源生命周期
|
||||||
|
// 阅读器及其派生编辑器使用结束后,调用方再关闭输入源
|
||||||
|
// 入参: input 输入源, options 阅读选项
|
||||||
// 返回: *Reader 阅读器实例, error 错误信息
|
// 返回: *Reader 阅读器实例, error 错误信息
|
||||||
func NewReader(r io.ReaderAt, size int64, options ...ReaderOption) (*Reader, error) {
|
func NewReader(input *Input, options ...ReaderOption) (*Reader, error) {
|
||||||
zr, err := zip.NewReader(r, size)
|
if input == nil {
|
||||||
|
return nil, fmt.Errorf("missing input")
|
||||||
|
}
|
||||||
|
zr, err := zip.NewReader(input, input.Size())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
reader := &Reader{
|
reader := &Reader{
|
||||||
|
Path: input.path,
|
||||||
Zip: zr,
|
Zip: zr,
|
||||||
}
|
}
|
||||||
if err := reader.open(options); err != nil {
|
if err := reader.open(options); err != nil {
|
||||||
@@ -65,6 +290,9 @@ func NewReader(r io.ReaderAt, size int64, options ...ReaderOption) (*Reader, err
|
|||||||
// 入参: reader 阅读器, opts 渲染选项
|
// 入参: reader 阅读器, opts 渲染选项
|
||||||
// 返回: *Renderer 渲染器实例
|
// 返回: *Renderer 渲染器实例
|
||||||
func NewRenderer(reader *Reader, opts ...RendererOption) *Renderer {
|
func NewRenderer(reader *Reader, opts ...RendererOption) *Renderer {
|
||||||
|
if reader.resources == nil {
|
||||||
|
reader.resources, _ = NewResources(ResourceOptions{})
|
||||||
|
}
|
||||||
r := &Renderer{
|
r := &Renderer{
|
||||||
Reader: reader,
|
Reader: reader,
|
||||||
DPI: 300.0,
|
DPI: 300.0,
|
||||||
@@ -72,7 +300,7 @@ func NewRenderer(reader *Reader, opts ...RendererOption) *Renderer {
|
|||||||
DrawParams: reader.drawParamCache,
|
DrawParams: reader.drawParamCache,
|
||||||
CompositeGraphicUnits: reader.compositeGraphicUnitCache,
|
CompositeGraphicUnits: reader.compositeGraphicUnitCache,
|
||||||
templatePageCache: make(map[string]*PageContent),
|
templatePageCache: make(map[string]*PageContent),
|
||||||
imageCache: &renderCache[string, image.Image]{limit: imageCacheLimit},
|
imageCache: resourceCache[string, image.Image](reader.resources, imageCacheLimit),
|
||||||
backends: defaultRenderBackends(),
|
backends: defaultRenderBackends(),
|
||||||
backendStates: make(map[any]any),
|
backendStates: make(map[any]any),
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -276,7 +276,7 @@ func (r *Reader) parseAnnotations(ctx context.Context, doc *Document) error {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
var pageAnnot PageAnnot
|
var pageAnnot PageAnnot
|
||||||
err = xml.NewDecoder(imageInput{ReadCloser: af, context: ctx}).Decode(&pageAnnot)
|
err = xml.NewDecoder(imageInput{ReadCloser: af, ctx: ctx}).Decode(&pageAnnot)
|
||||||
_ = af.Close()
|
_ = af.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
@@ -310,7 +310,7 @@ func (r *Reader) annotationIndexContext(ctx context.Context, doc *Document) (Ann
|
|||||||
}
|
}
|
||||||
defer f.Close()
|
defer f.Close()
|
||||||
var annotations Annotations
|
var annotations Annotations
|
||||||
if err := xml.NewDecoder(imageInput{ReadCloser: f, context: ctx}).Decode(&annotations); err != nil {
|
if err := xml.NewDecoder(imageInput{ReadCloser: f, ctx: ctx}).Decode(&annotations); err != nil {
|
||||||
return Annotations{}, err
|
return Annotations{}, err
|
||||||
}
|
}
|
||||||
pageIDs := make(map[string]string, len(doc.Pages.Page))
|
pageIDs := make(map[string]string, len(doc.Pages.Page))
|
||||||
|
|||||||
+6
-7
@@ -28,8 +28,7 @@ import (
|
|||||||
// ArchiveFile 描述已生成的归档文件,不关闭调用方提供的源读取器
|
// ArchiveFile 描述已生成的归档文件,不关闭调用方提供的源读取器
|
||||||
type ArchiveFile struct {
|
type ArchiveFile struct {
|
||||||
Name string
|
Name string
|
||||||
Source io.ReaderAt
|
Input *Input
|
||||||
Size int64
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ArchiveOptions 设置ZIP封装,压缩不重新编码归档内已生成的文档
|
// ArchiveOptions 设置ZIP封装,压缩不重新编码归档内已生成的文档
|
||||||
@@ -47,13 +46,13 @@ func WriteArchive(ctx context.Context, writer io.Writer, files []ArchiveFile, op
|
|||||||
}
|
}
|
||||||
names := map[string]bool{}
|
names := map[string]bool{}
|
||||||
for _, file := range files {
|
for _, file := range files {
|
||||||
if !fs.ValidPath(file.Name) || file.Name == "." || strings.Contains(file.Name, "\\") || names[file.Name] || file.Source == nil || file.Size < 0 {
|
if !fs.ValidPath(file.Name) || file.Name == "." || strings.Contains(file.Name, "\\") || names[file.Name] || file.Input == nil {
|
||||||
return 0, fmt.Errorf("invalid archive file %q", file.Name)
|
return 0, fmt.Errorf("invalid archive file %q", file.Name)
|
||||||
}
|
}
|
||||||
names[file.Name] = true
|
names[file.Name] = true
|
||||||
}
|
}
|
||||||
var count int64
|
var count int64
|
||||||
archive := zip.NewWriter(convertWriter{context: ctx, writer: writer, count: &count})
|
archive := zip.NewWriter(convertWriter{ctx: ctx, writer: writer, count: &count})
|
||||||
configureArchive(archive, options.Compression)
|
configureArchive(archive, options.Compression)
|
||||||
var buffer []byte
|
var buffer []byte
|
||||||
for i, file := range files {
|
for i, file := range files {
|
||||||
@@ -77,15 +76,15 @@ func WriteArchive(ctx context.Context, writer io.Writer, files []ArchiveFile, op
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return count, err
|
return count, err
|
||||||
}
|
}
|
||||||
input := convertReader{context: ctx, source: file.Source}
|
input := convertReader{ctx: ctx, input: file.Input}
|
||||||
if buffer == nil {
|
if buffer == nil {
|
||||||
buffer = make([]byte, 32<<10)
|
buffer = make([]byte, 32<<10)
|
||||||
}
|
}
|
||||||
written, err := io.CopyBuffer(entry, io.NewSectionReader(input, 0, file.Size), buffer)
|
written, err := io.CopyBuffer(entry, io.NewSectionReader(input, 0, file.Input.Size()), buffer)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return count, err
|
return count, err
|
||||||
}
|
}
|
||||||
if written != file.Size {
|
if written != file.Input.Size() {
|
||||||
return count, io.ErrUnexpectedEOF
|
return count, io.ErrUnexpectedEOF
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-7
@@ -70,6 +70,7 @@ type outputOptimization struct {
|
|||||||
protected bool
|
protected bool
|
||||||
completed int
|
completed int
|
||||||
deflater *flate.Writer
|
deflater *flate.Writer
|
||||||
|
resources *editorResourceSelection
|
||||||
}
|
}
|
||||||
|
|
||||||
// outputCompressionBuffer 限制候选ZIP编码,不能缩小时终止本次压缩
|
// outputCompressionBuffer 限制候选ZIP编码,不能缩小时终止本次压缩
|
||||||
@@ -99,13 +100,16 @@ func (e *Editor) WriteToWithOptions(ctx context.Context, writer io.Writer, optio
|
|||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
var count int64
|
var count int64
|
||||||
return snapshot.WriteTo(convertWriter{context: ctx, writer: writer, count: &count})
|
return snapshot.WriteTo(convertWriter{ctx: ctx, writer: writer, count: &count})
|
||||||
}
|
}
|
||||||
|
|
||||||
// WritePagesToWithOptions 按指定顺序另存页面,仅为所选页面准备资源和压缩计划
|
// WritePagesTo 按指定顺序另存页面,仅为所选页面准备资源和压缩计划
|
||||||
|
// 保留关联资源、目录、注释和签章外观,生成新文档标识,不改变原文档和撤销记录
|
||||||
|
// 签章外观不代表原签名在导出文档中仍有效,页码不可重复或为空
|
||||||
// 入参: ctx 取消上下文, writer 输出流, indexes 零基页码, options 输出配置
|
// 入参: ctx 取消上下文, writer 输出流, indexes 零基页码, options 输出配置
|
||||||
// 返回: int64 已写入字节数, error 错误信息
|
// 返回: int64 已写入字节数, error 错误信息
|
||||||
func (e *Editor) WritePagesToWithOptions(ctx context.Context, writer io.Writer, indexes []int, options WriteOptions) (int64, error) {
|
func (e *Editor) WritePagesTo(ctx context.Context, writer io.Writer, indexes []int, options WriteOptions) (int64, error) {
|
||||||
|
ctx = e.runtimeResources.context(ctx)
|
||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
@@ -116,13 +120,14 @@ func (e *Editor) WritePagesToWithOptions(ctx context.Context, writer io.Writer,
|
|||||||
snapshot.OnWriteProgress = editorProgress(e.OnWriteProgress).withContext(ctx)
|
snapshot.OnWriteProgress = editorProgress(e.OnWriteProgress).withContext(ctx)
|
||||||
snapshot.output = &outputOptimization{ctx: ctx, options: options.Compression}
|
snapshot.output = &outputOptimization{ctx: ctx, options: options.Compression}
|
||||||
var count int64
|
var count int64
|
||||||
return snapshot.WritePagesTo(convertWriter{context: ctx, writer: writer, count: &count}, indexes)
|
return snapshot.writePagesTo(convertWriter{ctx: ctx, writer: writer, count: &count}, indexes)
|
||||||
}
|
}
|
||||||
|
|
||||||
// outputSnapshot 创建只读输出配置,原签名存在时仅调整ZIP封装
|
// outputSnapshot 创建只读输出配置,原签名存在时仅调整ZIP封装
|
||||||
// 入参: ctx 取消上下文, options 输出配置
|
// 入参: ctx 取消上下文, options 输出配置
|
||||||
// 返回: *Editor 输出快照, error 配置或资源错误
|
// 返回: *Editor 输出快照, error 配置或资源错误
|
||||||
func (e *Editor) outputSnapshot(ctx context.Context, options WriteOptions) (*Editor, error) {
|
func (e *Editor) outputSnapshot(ctx context.Context, options WriteOptions) (*Editor, error) {
|
||||||
|
ctx = e.runtimeResources.context(ctx)
|
||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -211,7 +216,7 @@ func (r *Reader) compressionImageSafety(ctx context.Context, images []ImageInfo)
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, false, err
|
return nil, false, err
|
||||||
}
|
}
|
||||||
buffer := bufio.NewReader(imageInput{ReadCloser: input, context: ctx})
|
buffer := bufio.NewReader(imageInput{ReadCloser: input, ctx: ctx})
|
||||||
found, err := editorXMLPrefix(buffer)
|
found, err := editorXMLPrefix(buffer)
|
||||||
if err != nil || !found && (structured || strings.EqualFold(path.Ext(name), ".xml")) {
|
if err != nil || !found && (structured || strings.EqualFold(path.Ext(name), ".xml")) {
|
||||||
safe = false
|
safe = false
|
||||||
@@ -432,7 +437,7 @@ func (e *Editor) compressOutputFile(file *zip.File, buffer []byte, limit int) ([
|
|||||||
deflater.Reset(output)
|
deflater.Reset(output)
|
||||||
}
|
}
|
||||||
defer deflater.Close()
|
defer deflater.Close()
|
||||||
source := imageInput{ReadCloser: input, context: e.output.ctx}
|
source := imageInput{ReadCloser: input, ctx: e.output.ctx}
|
||||||
_, err = io.CopyBuffer(deflater, source, buffer)
|
_, err = io.CopyBuffer(deflater, source, buffer)
|
||||||
if output.exceeded {
|
if output.exceeded {
|
||||||
_, err = io.CopyBuffer(io.Discard, source, buffer)
|
_, err = io.CopyBuffer(io.Discard, source, buffer)
|
||||||
@@ -542,7 +547,7 @@ func (e *Editor) writeOutputFile(archive *zip.Writer, file *zip.File, buffer []b
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err := io.CopyBuffer(entry, imageInput{ReadCloser: io.NopCloser(payload), context: e.output.ctx}, buffer); err != nil {
|
if _, err := io.CopyBuffer(entry, imageInput{ReadCloser: io.NopCloser(payload), ctx: e.output.ctx}, buffer); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
e.output.completed++
|
e.output.completed++
|
||||||
|
|||||||
@@ -1,110 +0,0 @@
|
|||||||
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
package ofdgo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/xml"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// compressionFontUsage 按文档合并共享字体用字,版本编辑仅统计选中入口
|
|
||||||
// 入参: ctx 取消上下文, documents 文档入口, resources 资源索引, references 各文件引用, read 输出文件读取方法
|
|
||||||
// 返回: map[string]*editorFontUsage 各字体文件的用字,无法确定作用域时为空, error 读取或取消错误
|
|
||||||
func (r *Reader) compressionFontUsage(ctx context.Context, documents map[string]bool, resources []string, references map[string]*editorResourceRefs, read func(string) ([]byte, error)) (map[string]*editorFontUsage, error) {
|
|
||||||
selected := ""
|
|
||||||
if r.OFD.DocBody[r.documentIndex].versioned {
|
|
||||||
var err error
|
|
||||||
selected, err = r.DocumentRootContext(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
scoped, err := resourceReferenceScopes(ctx, documents, resources, references, selected)
|
|
||||||
if err != nil || scoped == nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return resourceFontUsage(ctx, resources, scoped, read)
|
|
||||||
}
|
|
||||||
|
|
||||||
// resourceFontUsage 按已确认的文档作用域合并各字体文件的字符和字形引用
|
|
||||||
// 入参: ctx 取消上下文, resources 资源索引, scoped 各索引的用字范围, read 输出文件读取方法
|
|
||||||
// 返回: map[string]*editorFontUsage 各字体文件的用字, error 读取或取消错误
|
|
||||||
func resourceFontUsage(ctx context.Context, resources []string, scoped map[string]*editorResourceRefs, read func(string) ([]byte, error)) (map[string]*editorFontUsage, error) {
|
|
||||||
result := make(map[string]*editorFontUsage)
|
|
||||||
protected := make(map[string]bool)
|
|
||||||
for _, name := range resources {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
refs := scoped[name]
|
|
||||||
if refs == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
data, err := read(name)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
root, err := parseEditorXMLContext(ctx, data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for font := range editorResourceNodes(root, "Fonts", "Font") {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
file := font.child("FontFile")
|
|
||||||
if file == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
var value string
|
|
||||||
if err := xml.Unmarshal(data[file.start:file.end], &value); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
location := editorResourceLocation(name, root.attr("BaseLoc"), value)
|
|
||||||
alternate := cleanPackagePath(resolveResourcePath(name, root.attr("BaseLoc"), value))
|
|
||||||
id, charset := editorResourceID(font.attr("ID")), font.attr("Charset")
|
|
||||||
unsafe := id == "" || charset != "" && !strings.EqualFold(charset, "unicode") || location != alternate
|
|
||||||
for i, path := range [2]string{location, alternate} {
|
|
||||||
if i == 1 && path == location {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if result[path] == nil {
|
|
||||||
result[path] = newEditorFontUsage()
|
|
||||||
}
|
|
||||||
result[path].merge(refs.fonts[id], unsafe)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for media := range editorResourceNodes(root, "MultiMedias", "MultiMedia") {
|
|
||||||
file := media.child("MediaFile")
|
|
||||||
if file == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
var value string
|
|
||||||
if err := xml.Unmarshal(data[file.start:file.end], &value); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
for _, location := range []string{editorResourceLocation(name, root.attr("BaseLoc"), value), cleanPackagePath(resolveResourcePath(name, root.attr("BaseLoc"), value))} {
|
|
||||||
protected[location] = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for location := range protected {
|
|
||||||
if usage := result[location]; usage != nil {
|
|
||||||
usage.unsafe = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result, ctx.Err()
|
|
||||||
}
|
|
||||||
@@ -15,10 +15,17 @@
|
|||||||
package ofdgo
|
package ofdgo
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"image"
|
"image"
|
||||||
|
"io"
|
||||||
"math"
|
"math"
|
||||||
|
|
||||||
|
baseimage "github.com/xiaoqidun/ofdgo/internal/base/image"
|
||||||
|
"github.com/xiaoqidun/pdfgo"
|
||||||
)
|
)
|
||||||
|
|
||||||
// compressionPatternImageLimit 限制底纹尺寸分析的变换组合数,超限时保留原图尺寸
|
// compressionPatternImageLimit 限制底纹尺寸分析的变换组合数,超限时保留原图尺寸
|
||||||
@@ -397,3 +404,173 @@ func (v *compressionImages) patternImages(color *FillColor, object Matrix) error
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// outputImageFormat 识别可由资源压缩生成的图片格式
|
||||||
|
// 入参: data 图片编码
|
||||||
|
// 返回: string 标准资源格式,未识别时为空
|
||||||
|
func outputImageFormat(data []byte) string {
|
||||||
|
if baseimage.IsJPEG(data) {
|
||||||
|
return "JPEG"
|
||||||
|
}
|
||||||
|
if baseimage.IsPNG(data) {
|
||||||
|
return "PNG"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// optimizeImageResource 优化可完整保留的BMP及TIFF,复用图像压缩和降采样策略
|
||||||
|
// 原始模式及无法保留的色彩配置不转换,仅采用小于原始编码的结果
|
||||||
|
// 入参: ctx 取消上下文, data 图片编码, options 压缩选项, size 像素需求
|
||||||
|
// 返回: []byte 图片编码,可能引用输入, error 解码、编码或取消错误
|
||||||
|
func optimizeImageResource(ctx context.Context, data []byte, options CompressionOptions, size image.Point) ([]byte, error) {
|
||||||
|
if err := options.Validate(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if options.Mode != CompressionUnchanged && baseimage.IsTIFF(data) {
|
||||||
|
return optimizeTIFFResource(ctx, data, options, size)
|
||||||
|
}
|
||||||
|
if options.Mode == CompressionUnchanged || !bytes.HasPrefix(data, []byte("BM")) {
|
||||||
|
return pdfgo.OptimizeImageResource(ctx, data, options, size)
|
||||||
|
}
|
||||||
|
return optimizeBMPResource(ctx, data, options, size)
|
||||||
|
}
|
||||||
|
|
||||||
|
// optimizeBMPResource 压缩可保留色彩与密度的位图,未知元数据及高精度位域保持原样
|
||||||
|
// 入参: ctx 取消上下文, data BMP编码, options 压缩选项, size 像素需求
|
||||||
|
// 返回: []byte 图片编码, error 解码、编码或取消错误
|
||||||
|
func optimizeBMPResource(ctx context.Context, data []byte, options CompressionOptions, size image.Point) ([]byte, error) {
|
||||||
|
offset, width, height, depth, compression, err := baseimage.ParseBMPHeader(data)
|
||||||
|
if err != nil {
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
if height < 0 {
|
||||||
|
height = -height
|
||||||
|
}
|
||||||
|
if int64(width)*int64(height) > outputOptimizationBufferLimit/4 || compression != 0 && compression != 3 {
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
header := binary.LittleEndian.Uint32(data[14:18])
|
||||||
|
if header != 40 && header != 108 && header != 124 {
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
if header >= 108 && binary.LittleEndian.Uint32(data[70:74]) != 0x73524742 {
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
if header == 124 && (binary.LittleEndian.Uint32(data[122:126]) != 0 || binary.LittleEndian.Uint32(data[126:130]) != 0 || binary.LittleEndian.Uint32(data[130:134]) != 0) {
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
stride := (int64(width)*int64(depth) + 31) / 32 * 4
|
||||||
|
if int64(offset)+stride*int64(height) != int64(len(data)) {
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
density, ok := baseimage.BMPDensity(data)
|
||||||
|
if !ok {
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
if depth == 16 || depth == 32 {
|
||||||
|
masks, err := baseimage.BMPColorMasks(data, offset, depth, compression)
|
||||||
|
if err != nil {
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
if options.Mode == CompressionLossless {
|
||||||
|
for _, mask := range masks {
|
||||||
|
if mask.Max > 255 {
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var pixels image.Image
|
||||||
|
if depth == 16 || compression == 3 {
|
||||||
|
pixels, err = baseimage.DecodeBMPContext(ctx, data)
|
||||||
|
} else {
|
||||||
|
pixels, _, err = image.Decode(imageInput{ReadCloser: io.NopCloser(bytes.NewReader(data)), ctx: ctx})
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return optimizeRasterResource(ctx, data, pixels, options, size, density)
|
||||||
|
}
|
||||||
|
|
||||||
|
// optimizeRasterResource 编码已解码的资源图片,同步降采样后的像素密度,仅采用更小结果
|
||||||
|
// 先降采样再编码,绝对密度按最终尺寸量化,相对密度保留精确比例
|
||||||
|
// 有密度时保留PNG,未知密度按最终像素选择编码格式
|
||||||
|
// 入参: ctx 取消上下文, data 原编码, pixels 像素, options 压缩选项, size 像素需求, density 像素密度
|
||||||
|
// 返回: []byte 图片编码, error 编码或取消错误
|
||||||
|
func optimizeRasterResource(ctx context.Context, data []byte, pixels image.Image, options CompressionOptions, size image.Point, density baseimage.Density) ([]byte, error) {
|
||||||
|
hasDensity := density.X != 0 || density.Y != 0
|
||||||
|
before := pixels.Bounds().Size()
|
||||||
|
if options.Mode == CompressionLossy {
|
||||||
|
var err error
|
||||||
|
pixels, err = pdfgo.ResizeImage(ctx, pixels, size)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var ok bool
|
||||||
|
density, ok = density.Scale(before, pixels.Bounds().Size())
|
||||||
|
if !ok {
|
||||||
|
return data, ctx.Err()
|
||||||
|
}
|
||||||
|
var candidate []byte
|
||||||
|
var err error
|
||||||
|
if hasDensity {
|
||||||
|
var encoded bytes.Buffer
|
||||||
|
err = pdfgo.EncodePNGWithOptions(ctx, &encoded, pixels, options)
|
||||||
|
candidate = encoded.Bytes()
|
||||||
|
} else {
|
||||||
|
candidate, err = pdfgo.EncodeImageResource(ctx, pixels, options)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, io.ErrShortBuffer) {
|
||||||
|
return data, ctx.Err()
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if hasDensity {
|
||||||
|
if len(candidate) > outputOptimizationBufferLimit-baseimage.PNGDensityChunkSize {
|
||||||
|
return data, ctx.Err()
|
||||||
|
}
|
||||||
|
candidate, ok = baseimage.WithPNGDensity(candidate, density)
|
||||||
|
if !ok {
|
||||||
|
return data, ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(candidate) < len(data) {
|
||||||
|
return candidate, nil
|
||||||
|
}
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// optimizeTIFFResource 压缩单目录TIFF,保留方向、透明度、采样精度及像素密度
|
||||||
|
// 主图或单个瓦片的预计缓冲超限时保留原编码
|
||||||
|
// 入参: ctx 取消上下文, data TIFF编码, options 压缩选项, size 显示像素需求
|
||||||
|
// 返回: []byte 图片编码,不可完整转换时保留原文, error 编码或取消错误
|
||||||
|
func optimizeTIFFResource(ctx context.Context, data []byte, options CompressionOptions, size image.Point) ([]byte, error) {
|
||||||
|
layout, err := baseimage.ReadTIFFLayoutContext(ctx, bytes.NewReader(data))
|
||||||
|
if err != nil {
|
||||||
|
return data, ctx.Err()
|
||||||
|
}
|
||||||
|
pixelSize := int64(layout.DecodedPixelBytes())
|
||||||
|
if int64(layout.Width) > outputOptimizationBufferLimit/pixelSize/int64(layout.Height) {
|
||||||
|
return data, ctx.Err()
|
||||||
|
}
|
||||||
|
if layout.TileWidth != 0 && int64(layout.TileWidth) > outputOptimizationBufferLimit/pixelSize/int64(layout.TileHeight) {
|
||||||
|
return data, ctx.Err()
|
||||||
|
}
|
||||||
|
density, ok := baseimage.TIFFConversionDensity(data, layout)
|
||||||
|
if !ok {
|
||||||
|
return data, ctx.Err()
|
||||||
|
}
|
||||||
|
pixels, err := baseimage.DecodeTIFF(ctx, data, layout)
|
||||||
|
if err != nil {
|
||||||
|
return data, ctx.Err()
|
||||||
|
}
|
||||||
|
return optimizeRasterResource(ctx, data, pixels, options, size, density)
|
||||||
|
}
|
||||||
@@ -20,16 +20,12 @@ import (
|
|||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"image"
|
"image"
|
||||||
"io"
|
"io"
|
||||||
"strconv"
|
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
baseimage "github.com/xiaoqidun/ofdgo/internal/base/image"
|
baseimage "github.com/xiaoqidun/ofdgo/internal/base/image"
|
||||||
)
|
)
|
||||||
|
|
||||||
// outputImageBatchLimit 限制并行任务持有的原始编码,超限图片单独处理
|
// outputImageWorkingSetLimit 指定未提供任务预算时的图像成本估算上限
|
||||||
const outputImageBatchLimit = 16 << 20
|
|
||||||
|
|
||||||
// outputImageWorkingSetLimit 限制64位并行任务的像素工作量总估算,32位使用64MiB,超限图片单独处理
|
|
||||||
const outputImageWorkingSetLimit = 256 << 20
|
const outputImageWorkingSetLimit = 256 << 20
|
||||||
|
|
||||||
// outputImageJob 保存独立图片任务,不访问编辑文档或调用进度回调
|
// outputImageJob 保存独立图片任务,不访问编辑文档或调用进度回调
|
||||||
@@ -82,20 +78,22 @@ func (e *Editor) outputImageOptions(key string) (CompressionOptions, image.Point
|
|||||||
// 入参: keys 资源路径, load 串行读取方法,空值表示跳过, results 候选缓存, sources 原始资源摘要,可为空
|
// 入参: keys 资源路径, load 串行读取方法,空值表示跳过, results 候选缓存, sources 原始资源摘要,可为空
|
||||||
// 返回: error 读取、进度或取消错误
|
// 返回: error 读取、进度或取消错误
|
||||||
func (e *Editor) prepareOutputImages(keys []string, load func(string) ([]byte, error), results map[outputImageKey][]byte, sources map[string]outputImageSource) error {
|
func (e *Editor) prepareOutputImages(keys []string, load func(string) ([]byte, error), results map[outputImageKey][]byte, sources map[string]outputImageSource) error {
|
||||||
workers := conversionWorkers(e.output.ctx, 4)
|
workers := conversionWorkers(e.output.ctx)
|
||||||
if workers < 2 || len(keys) < 2 {
|
if workers < 2 || len(keys) < 2 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
limit, encodedLimit := outputImageWorkingSetLimit, outputImageBatchLimit
|
limit := int(min(int64(workers)*(64<<20), int64(int(^uint(0)>>1)-1)))
|
||||||
|
encodedLimit := limit
|
||||||
if pool, _ := e.output.ctx.Value(conversionPoolKey{}).(*ConversionPool); pool != nil {
|
if pool, _ := e.output.ctx.Value(conversionPoolKey{}).(*ConversionPool); pool != nil {
|
||||||
if available := pool.memoryLimit(); available > 0 {
|
available := pool.memoryLimit()
|
||||||
|
if available == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if available > 0 {
|
||||||
limit = int(min(available, int64(int(^uint(0)>>1))))
|
limit = int(min(available, int64(int(^uint(0)>>1))))
|
||||||
encodedLimit = limit
|
encodedLimit = limit
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if strconv.IntSize == 32 {
|
|
||||||
limit = 64 << 20
|
|
||||||
}
|
|
||||||
base, cancel := context.WithCancel(e.output.ctx)
|
base, cancel := context.WithCancel(e.output.ctx)
|
||||||
ctx := outputImageContext{Context: base, parent: e.output.ctx}
|
ctx := outputImageContext{Context: base, parent: e.output.ctx}
|
||||||
var group sync.WaitGroup
|
var group sync.WaitGroup
|
||||||
@@ -208,7 +206,7 @@ func imageWorkingSet(ctx context.Context, data []byte, limit int) int {
|
|||||||
}
|
}
|
||||||
return len(data) + tiffImageWorkingSet(layout, available)
|
return len(data) + tiffImageWorkingSet(layout, available)
|
||||||
}
|
}
|
||||||
config, _, err := baseimage.DecodeConfig(imageInput{ReadCloser: io.NopCloser(input), context: ctx})
|
config, _, err := baseimage.DecodeConfig(imageInput{ReadCloser: io.NopCloser(input), ctx: ctx})
|
||||||
if err != nil || config.Width <= 0 || config.Height <= 0 {
|
if err != nil || config.Width <= 0 || config.Height <= 0 {
|
||||||
return limit
|
return limit
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ func (e *Editor) compressPatternPaints() error {
|
|||||||
}
|
}
|
||||||
hash := sha256.New()
|
hash := sha256.New()
|
||||||
var size int64
|
var size int64
|
||||||
x := newOFDXML(convertWriter{writer: hash, count: &size, context: e.output.ctx})
|
x := newOFDXML(convertWriter{writer: hash, count: &size, ctx: e.output.ctx})
|
||||||
x.ctx = e.output.ctx
|
x.ctx = e.output.ctx
|
||||||
x.color("FillColor", fill)
|
x.color("FillColor", fill)
|
||||||
x.color("StrokeColor", (*FillColor)(stroke))
|
x.color("StrokeColor", (*FillColor)(stroke))
|
||||||
|
|||||||
@@ -1,136 +0,0 @@
|
|||||||
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
package ofdgo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"maps"
|
|
||||||
"slices"
|
|
||||||
)
|
|
||||||
|
|
||||||
// editorProfileReference 记录颜色配置文件所在的资源索引及颜色空间标识
|
|
||||||
type editorProfileReference struct {
|
|
||||||
index string
|
|
||||||
id string
|
|
||||||
}
|
|
||||||
|
|
||||||
// compactResourceProfiles 合并相同颜色配置文件,保留颜色空间声明和独立文件引用
|
|
||||||
// 入参: ctx 取消上下文, reader 原包,可为空, parts 输出改动, profiles 配置文件引用, protected 不可替换的文件, removed 待移除文件
|
|
||||||
// 返回: error 读取、改写或取消错误
|
|
||||||
func compactResourceProfiles(ctx context.Context, reader *Reader, parts map[string][]byte, profiles map[string][]editorProfileReference, protected, removed map[string]bool) error {
|
|
||||||
if len(profiles) < 2 {
|
|
||||||
return ctx.Err()
|
|
||||||
}
|
|
||||||
seen := make(map[[32]byte]string)
|
|
||||||
aliases := make(map[string]string)
|
|
||||||
indexes := make(map[string]map[string]string)
|
|
||||||
ordered := slices.Sorted(maps.Keys(profiles))
|
|
||||||
sizes := make(map[string]uint64, len(profiles))
|
|
||||||
counts := make(map[uint64]int)
|
|
||||||
for _, name := range ordered {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if protected[name] {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
size, err := outputResourceSize(reader, parts, name)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
sizes[name] = size
|
|
||||||
counts[size]++
|
|
||||||
}
|
|
||||||
var buffer []byte
|
|
||||||
for _, name := range ordered {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if protected[name] || counts[sizes[name]] < 2 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if buffer == nil {
|
|
||||||
buffer = make([]byte, 32*1024)
|
|
||||||
}
|
|
||||||
key, err := outputResourceDigest(ctx, reader, parts, name, buffer)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
first, found := seen[key]
|
|
||||||
if !found {
|
|
||||||
seen[key] = name
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
aliases[name] = first
|
|
||||||
for _, reference := range profiles[name] {
|
|
||||||
if indexes[reference.index] == nil {
|
|
||||||
indexes[reference.index] = make(map[string]string)
|
|
||||||
}
|
|
||||||
indexes[reference.index][reference.id] = first
|
|
||||||
}
|
|
||||||
}
|
|
||||||
updates := make(map[string][]byte, len(indexes))
|
|
||||||
for _, name := range slices.Sorted(maps.Keys(indexes)) {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
data, ok := parts[name]
|
|
||||||
if !ok {
|
|
||||||
if reader == nil {
|
|
||||||
return fmt.Errorf("file not found: %s", name)
|
|
||||||
}
|
|
||||||
var err error
|
|
||||||
data, err = reader.readFileViewContext(ctx, name)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
root, err := parseEditorXMLContext(ctx, data)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var patches []editorXMLPatch
|
|
||||||
for _, group := range root.children {
|
|
||||||
if !group.matchesOFD("ColorSpaces") {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
for _, node := range group.children {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
location := indexes[name][editorResourceID(node.attr("ID"))]
|
|
||||||
if !node.matchesOFD("ColorSpace") || location == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
patch, err := editorXMLAttributePatch(data, node, "Profile", "/"+location)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
patches = append(patches, patch)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
updates[name] = editorPatchXML(data, patches)
|
|
||||||
}
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
maps.Copy(parts, updates)
|
|
||||||
for name := range aliases {
|
|
||||||
removed[name] = true
|
|
||||||
delete(parts, name)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,197 +0,0 @@
|
|||||||
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
package ofdgo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/binary"
|
|
||||||
"errors"
|
|
||||||
"image"
|
|
||||||
"io"
|
|
||||||
|
|
||||||
baseimage "github.com/xiaoqidun/ofdgo/internal/base/image"
|
|
||||||
"github.com/xiaoqidun/pdfgo"
|
|
||||||
)
|
|
||||||
|
|
||||||
// outputImageFormat 识别可由资源压缩生成的图片格式
|
|
||||||
// 入参: data 图片编码
|
|
||||||
// 返回: string 标准资源格式,未识别时为空
|
|
||||||
func outputImageFormat(data []byte) string {
|
|
||||||
if baseimage.IsJPEG(data) {
|
|
||||||
return "JPEG"
|
|
||||||
}
|
|
||||||
if baseimage.IsPNG(data) {
|
|
||||||
return "PNG"
|
|
||||||
}
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// optimizeImageResource 优化可完整保留的BMP及TIFF,复用图像压缩和降采样策略
|
|
||||||
// 原始模式及无法保留的色彩配置不转换,仅采用小于原始编码的结果
|
|
||||||
// 入参: ctx 取消上下文, data 图片编码, options 压缩选项, size 像素需求
|
|
||||||
// 返回: []byte 图片编码,可能引用输入, error 解码、编码或取消错误
|
|
||||||
func optimizeImageResource(ctx context.Context, data []byte, options CompressionOptions, size image.Point) ([]byte, error) {
|
|
||||||
if err := options.Validate(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if options.Mode != CompressionUnchanged && baseimage.IsTIFF(data) {
|
|
||||||
return optimizeTIFFResource(ctx, data, options, size)
|
|
||||||
}
|
|
||||||
if options.Mode == CompressionUnchanged || !bytes.HasPrefix(data, []byte("BM")) {
|
|
||||||
return pdfgo.OptimizeImageResource(ctx, data, options, size)
|
|
||||||
}
|
|
||||||
return optimizeBMPResource(ctx, data, options, size)
|
|
||||||
}
|
|
||||||
|
|
||||||
// optimizeBMPResource 压缩可保留色彩与密度的位图,未知元数据及高精度位域保持原样
|
|
||||||
// 入参: ctx 取消上下文, data BMP编码, options 压缩选项, size 像素需求
|
|
||||||
// 返回: []byte 图片编码, error 解码、编码或取消错误
|
|
||||||
func optimizeBMPResource(ctx context.Context, data []byte, options CompressionOptions, size image.Point) ([]byte, error) {
|
|
||||||
offset, width, height, depth, compression, err := baseimage.ParseBMPHeader(data)
|
|
||||||
if err != nil {
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
if height < 0 {
|
|
||||||
height = -height
|
|
||||||
}
|
|
||||||
if int64(width)*int64(height) > outputOptimizationBufferLimit/4 || compression != 0 && compression != 3 {
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
header := binary.LittleEndian.Uint32(data[14:18])
|
|
||||||
if header != 40 && header != 108 && header != 124 {
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
if header >= 108 && binary.LittleEndian.Uint32(data[70:74]) != 0x73524742 {
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
if header == 124 && (binary.LittleEndian.Uint32(data[122:126]) != 0 || binary.LittleEndian.Uint32(data[126:130]) != 0 || binary.LittleEndian.Uint32(data[130:134]) != 0) {
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
stride := (int64(width)*int64(depth) + 31) / 32 * 4
|
|
||||||
if int64(offset)+stride*int64(height) != int64(len(data)) {
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
density, ok := baseimage.BMPDensity(data)
|
|
||||||
if !ok {
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
if depth == 16 || depth == 32 {
|
|
||||||
masks, err := baseimage.BMPColorMasks(data, offset, depth, compression)
|
|
||||||
if err != nil {
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
if options.Mode == CompressionLossless {
|
|
||||||
for _, mask := range masks {
|
|
||||||
if mask.Max > 255 {
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var pixels image.Image
|
|
||||||
if depth == 16 || compression == 3 {
|
|
||||||
pixels, err = baseimage.DecodeBMPContext(ctx, data)
|
|
||||||
} else {
|
|
||||||
pixels, _, err = image.Decode(imageInput{ReadCloser: io.NopCloser(bytes.NewReader(data)), context: ctx})
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return optimizeRasterResource(ctx, data, pixels, options, size, density)
|
|
||||||
}
|
|
||||||
|
|
||||||
// optimizeRasterResource 编码已解码的资源图片,同步降采样后的像素密度,仅采用更小结果
|
|
||||||
// 先降采样再编码,绝对密度按最终尺寸量化,相对密度保留精确比例
|
|
||||||
// 有密度时保留PNG,未知密度按最终像素选择编码格式
|
|
||||||
// 入参: ctx 取消上下文, data 原编码, pixels 像素, options 压缩选项, size 像素需求, density 像素密度
|
|
||||||
// 返回: []byte 图片编码, error 编码或取消错误
|
|
||||||
func optimizeRasterResource(ctx context.Context, data []byte, pixels image.Image, options CompressionOptions, size image.Point, density baseimage.Density) ([]byte, error) {
|
|
||||||
hasDensity := density.X != 0 || density.Y != 0
|
|
||||||
before := pixels.Bounds().Size()
|
|
||||||
if options.Mode == CompressionLossy {
|
|
||||||
var err error
|
|
||||||
pixels, err = pdfgo.ResizeImage(ctx, pixels, size)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var ok bool
|
|
||||||
density, ok = density.Scale(before, pixels.Bounds().Size())
|
|
||||||
if !ok {
|
|
||||||
return data, ctx.Err()
|
|
||||||
}
|
|
||||||
var candidate []byte
|
|
||||||
var err error
|
|
||||||
if hasDensity {
|
|
||||||
var encoded bytes.Buffer
|
|
||||||
err = pdfgo.EncodePNGWithOptions(ctx, &encoded, pixels, options)
|
|
||||||
candidate = encoded.Bytes()
|
|
||||||
} else {
|
|
||||||
candidate, err = pdfgo.EncodeImageResource(ctx, pixels, options)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, io.ErrShortBuffer) {
|
|
||||||
return data, ctx.Err()
|
|
||||||
}
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if hasDensity {
|
|
||||||
if len(candidate) > outputOptimizationBufferLimit-baseimage.PNGDensityChunkSize {
|
|
||||||
return data, ctx.Err()
|
|
||||||
}
|
|
||||||
candidate, ok = baseimage.WithPNGDensity(candidate, density)
|
|
||||||
if !ok {
|
|
||||||
return data, ctx.Err()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if len(candidate) < len(data) {
|
|
||||||
return candidate, nil
|
|
||||||
}
|
|
||||||
return data, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// optimizeTIFFResource 压缩单目录TIFF,保留方向、透明度、采样精度及像素密度
|
|
||||||
// 主图或单个瓦片的预计缓冲超限时保留原编码
|
|
||||||
// 入参: ctx 取消上下文, data TIFF编码, options 压缩选项, size 显示像素需求
|
|
||||||
// 返回: []byte 图片编码,不可完整转换时保留原文, error 编码或取消错误
|
|
||||||
func optimizeTIFFResource(ctx context.Context, data []byte, options CompressionOptions, size image.Point) ([]byte, error) {
|
|
||||||
layout, err := baseimage.ReadTIFFLayoutContext(ctx, bytes.NewReader(data))
|
|
||||||
if err != nil {
|
|
||||||
return data, ctx.Err()
|
|
||||||
}
|
|
||||||
pixelSize := int64(layout.DecodedPixelBytes())
|
|
||||||
if int64(layout.Width) > outputOptimizationBufferLimit/pixelSize/int64(layout.Height) {
|
|
||||||
return data, ctx.Err()
|
|
||||||
}
|
|
||||||
if layout.TileWidth != 0 && int64(layout.TileWidth) > outputOptimizationBufferLimit/pixelSize/int64(layout.TileHeight) {
|
|
||||||
return data, ctx.Err()
|
|
||||||
}
|
|
||||||
density, ok := baseimage.TIFFConversionDensity(data, layout)
|
|
||||||
if !ok {
|
|
||||||
return data, ctx.Err()
|
|
||||||
}
|
|
||||||
pixels, err := baseimage.DecodeTIFF(ctx, data, layout)
|
|
||||||
if err != nil {
|
|
||||||
return data, ctx.Err()
|
|
||||||
}
|
|
||||||
return optimizeRasterResource(ctx, data, pixels, options, size, density)
|
|
||||||
}
|
|
||||||
@@ -35,6 +35,12 @@ type outputImageKey struct {
|
|||||||
size image.Point
|
size image.Point
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// editorProfileReference 记录颜色配置文件所在的资源索引及颜色空间标识
|
||||||
|
type editorProfileReference struct {
|
||||||
|
index string
|
||||||
|
id string
|
||||||
|
}
|
||||||
|
|
||||||
// compressResourceParts 优化输出图片并合并相同资源文件,保留资源标识及各自属性
|
// compressResourceParts 优化输出图片并合并相同资源文件,保留资源标识及各自属性
|
||||||
// 入参: parts 输出改动, reader 原包,可为空, removed 已移除条目
|
// 入参: parts 输出改动, reader 原包,可为空, removed 已移除条目
|
||||||
// 返回: error 读取或取消错误
|
// 返回: error 读取或取消错误
|
||||||
@@ -460,7 +466,7 @@ func outputResourceDigest(ctx context.Context, reader *Reader, parts map[string]
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
hash := sha256.New()
|
hash := sha256.New()
|
||||||
_, err := io.CopyBuffer(hash, imageInput{ReadCloser: input, context: ctx}, buffer)
|
_, err := io.CopyBuffer(hash, imageInput{ReadCloser: input, ctx: ctx}, buffer)
|
||||||
closeErr := input.Close()
|
closeErr := input.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return [32]byte{}, err
|
return [32]byte{}, err
|
||||||
@@ -470,3 +476,200 @@ func outputResourceDigest(ctx context.Context, reader *Reader, parts map[string]
|
|||||||
}
|
}
|
||||||
return [32]byte(hash.Sum(nil)), ctx.Err()
|
return [32]byte(hash.Sum(nil)), ctx.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// compressionFontUsage 按文档合并共享字体用字,版本编辑仅统计选中入口
|
||||||
|
// 入参: ctx 取消上下文, documents 文档入口, resources 资源索引, references 各文件引用, read 输出文件读取方法
|
||||||
|
// 返回: map[string]*editorFontUsage 各字体文件的用字,无法确定作用域时为空, error 读取或取消错误
|
||||||
|
func (r *Reader) compressionFontUsage(ctx context.Context, documents map[string]bool, resources []string, references map[string]*editorResourceRefs, read func(string) ([]byte, error)) (map[string]*editorFontUsage, error) {
|
||||||
|
selected := ""
|
||||||
|
if r.OFD.DocBody[r.documentIndex].versioned {
|
||||||
|
var err error
|
||||||
|
selected, err = r.DocumentRootContext(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
scoped, err := resourceReferenceScopes(ctx, documents, resources, references, selected)
|
||||||
|
if err != nil || scoped == nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return resourceFontUsage(ctx, resources, scoped, read)
|
||||||
|
}
|
||||||
|
|
||||||
|
// resourceFontUsage 按已确认的文档作用域合并各字体文件的字符和字形引用
|
||||||
|
// 入参: ctx 取消上下文, resources 资源索引, scoped 各索引的用字范围, read 输出文件读取方法
|
||||||
|
// 返回: map[string]*editorFontUsage 各字体文件的用字, error 读取或取消错误
|
||||||
|
func resourceFontUsage(ctx context.Context, resources []string, scoped map[string]*editorResourceRefs, read func(string) ([]byte, error)) (map[string]*editorFontUsage, error) {
|
||||||
|
result := make(map[string]*editorFontUsage)
|
||||||
|
protected := make(map[string]bool)
|
||||||
|
for _, name := range resources {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
refs := scoped[name]
|
||||||
|
if refs == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
data, err := read(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
root, err := parseEditorXMLContext(ctx, data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for font := range editorResourceNodes(root, "Fonts", "Font") {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
file := font.child("FontFile")
|
||||||
|
if file == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var value string
|
||||||
|
if err := xml.Unmarshal(data[file.start:file.end], &value); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
location := editorResourceLocation(name, root.attr("BaseLoc"), value)
|
||||||
|
alternate := cleanPackagePath(resolveResourcePath(name, root.attr("BaseLoc"), value))
|
||||||
|
id, charset := editorResourceID(font.attr("ID")), font.attr("Charset")
|
||||||
|
unsafe := id == "" || charset != "" && !strings.EqualFold(charset, "unicode") || location != alternate
|
||||||
|
for i, path := range [2]string{location, alternate} {
|
||||||
|
if i == 1 && path == location {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if result[path] == nil {
|
||||||
|
result[path] = newEditorFontUsage()
|
||||||
|
}
|
||||||
|
result[path].merge(refs.fonts[id], unsafe)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for media := range editorResourceNodes(root, "MultiMedias", "MultiMedia") {
|
||||||
|
file := media.child("MediaFile")
|
||||||
|
if file == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var value string
|
||||||
|
if err := xml.Unmarshal(data[file.start:file.end], &value); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, location := range []string{editorResourceLocation(name, root.attr("BaseLoc"), value), cleanPackagePath(resolveResourcePath(name, root.attr("BaseLoc"), value))} {
|
||||||
|
protected[location] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for location := range protected {
|
||||||
|
if usage := result[location]; usage != nil {
|
||||||
|
usage.unsafe = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result, ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
// compactResourceProfiles 合并相同颜色配置文件,保留颜色空间声明和独立文件引用
|
||||||
|
// 入参: ctx 取消上下文, reader 原包,可为空, parts 输出改动, profiles 配置文件引用, protected 不可替换的文件, removed 待移除文件
|
||||||
|
// 返回: error 读取、改写或取消错误
|
||||||
|
func compactResourceProfiles(ctx context.Context, reader *Reader, parts map[string][]byte, profiles map[string][]editorProfileReference, protected, removed map[string]bool) error {
|
||||||
|
if len(profiles) < 2 {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
seen := make(map[[32]byte]string)
|
||||||
|
aliases := make(map[string]string)
|
||||||
|
indexes := make(map[string]map[string]string)
|
||||||
|
ordered := slices.Sorted(maps.Keys(profiles))
|
||||||
|
sizes := make(map[string]uint64, len(profiles))
|
||||||
|
counts := make(map[uint64]int)
|
||||||
|
for _, name := range ordered {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if protected[name] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
size, err := outputResourceSize(reader, parts, name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sizes[name] = size
|
||||||
|
counts[size]++
|
||||||
|
}
|
||||||
|
var buffer []byte
|
||||||
|
for _, name := range ordered {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if protected[name] || counts[sizes[name]] < 2 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if buffer == nil {
|
||||||
|
buffer = make([]byte, 32*1024)
|
||||||
|
}
|
||||||
|
key, err := outputResourceDigest(ctx, reader, parts, name, buffer)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
first, found := seen[key]
|
||||||
|
if !found {
|
||||||
|
seen[key] = name
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
aliases[name] = first
|
||||||
|
for _, reference := range profiles[name] {
|
||||||
|
if indexes[reference.index] == nil {
|
||||||
|
indexes[reference.index] = make(map[string]string)
|
||||||
|
}
|
||||||
|
indexes[reference.index][reference.id] = first
|
||||||
|
}
|
||||||
|
}
|
||||||
|
updates := make(map[string][]byte, len(indexes))
|
||||||
|
for _, name := range slices.Sorted(maps.Keys(indexes)) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
data, ok := parts[name]
|
||||||
|
if !ok {
|
||||||
|
if reader == nil {
|
||||||
|
return fmt.Errorf("file not found: %s", name)
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
data, err = reader.readFileViewContext(ctx, name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
root, err := parseEditorXMLContext(ctx, data)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var patches []editorXMLPatch
|
||||||
|
for _, group := range root.children {
|
||||||
|
if !group.matchesOFD("ColorSpaces") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, node := range group.children {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
location := indexes[name][editorResourceID(node.attr("ID"))]
|
||||||
|
if !node.matchesOFD("ColorSpace") || location == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
patch, err := editorXMLAttributePatch(data, node, "Profile", "/"+location)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
patches = append(patches, patch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
updates[name] = editorPatchXML(data, patches)
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
maps.Copy(parts, updates)
|
||||||
|
for name := range aliases {
|
||||||
|
removed[name] = true
|
||||||
|
delete(parts, name)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
+218
-24
@@ -15,11 +15,17 @@
|
|||||||
package ofdgo
|
package ofdgo
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"runtime"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/xiaoqidun/pdfgo"
|
"github.com/xiaoqidun/pdfgo"
|
||||||
)
|
)
|
||||||
@@ -46,6 +52,7 @@ type ConvertProgress struct {
|
|||||||
// PageRange使用一基页码表达式,与Pages互斥,空字符串表示全部页面
|
// PageRange使用一基页码表达式,与Pages互斥,空字符串表示全部页面
|
||||||
// SkipUnchanged仅在未压缩、源格式与目标相同且未选页时不写出数据
|
// SkipUnchanged仅在未压缩、源格式与目标相同且未选页时不写出数据
|
||||||
// Pool可由多个独立转换共享,nil时不限制文件间并发
|
// Pool可由多个独立转换共享,nil时不限制文件间并发
|
||||||
|
// Resources提供共享计算与缓存策略,显式Pool优先控制计算调度
|
||||||
// 整份PDF同格式压缩直接重写PDF对象,其余PDF先转换为OFD对象再输出
|
// 整份PDF同格式压缩直接重写PDF对象,其余PDF先转换为OFD对象再输出
|
||||||
// RendererOptions同时用于PDF局部合成和输出,在PDF.RendererOptions之后应用
|
// RendererOptions同时用于PDF局部合成和输出,在PDF.RendererOptions之后应用
|
||||||
// Backends统一配置转换与输出,优先于PDF和RendererOptions中的后端设置
|
// Backends统一配置转换与输出,优先于PDF和RendererOptions中的后端设置
|
||||||
@@ -54,6 +61,7 @@ type ConvertProgress struct {
|
|||||||
// PageOutput仅用于逐页格式,同步调用export写出一页并自行处理提交或回滚;此时output可为nil
|
// PageOutput仅用于逐页格式,同步调用export写出一页并自行处理提交或回滚;此时output可为nil
|
||||||
// 未提供PageOutput时,逐页格式打包ZIP;所有回调返回错误均会停止转换
|
// 未提供PageOutput时,逐页格式打包ZIP;所有回调返回错误均会停止转换
|
||||||
type ConvertOptions struct {
|
type ConvertOptions struct {
|
||||||
|
Resources *Resources
|
||||||
Input string
|
Input string
|
||||||
Format string
|
Format string
|
||||||
Pages []int
|
Pages []int
|
||||||
@@ -82,19 +90,42 @@ type ConvertReport struct {
|
|||||||
Fonts []FontChange `json:"fonts,omitempty"`
|
Fonts []FontChange `json:"fonts,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ConversionPoolOptions 设置共享转换并行度及图像工作集预算
|
||||||
|
// Parallelism为0时使用GOMAXPROCS,MemoryLimit为0时不指定固定预算
|
||||||
|
// AvailableMemory返回可用于新增任务的字节数,nil表示不探测,回调须支持并发调用
|
||||||
|
// 内存预算用于调度,不限制解析器及运行时的实际分配
|
||||||
|
type ConversionPoolOptions struct {
|
||||||
|
Parallelism int
|
||||||
|
MemoryLimit int64
|
||||||
|
AvailableMemory func() int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConversionPool 协调独立转换和图像任务,配置在创建后不变,可跨会话复用
|
||||||
|
type ConversionPool struct {
|
||||||
|
options ConversionPoolOptions
|
||||||
|
mu sync.Mutex
|
||||||
|
changed chan struct{}
|
||||||
|
active int
|
||||||
|
images int
|
||||||
|
memory int64
|
||||||
|
}
|
||||||
|
|
||||||
// convertReader 将取消上下文传递到随机读取
|
// convertReader 将取消上下文传递到随机读取
|
||||||
type convertReader struct {
|
type convertReader struct {
|
||||||
context context.Context
|
ctx context.Context
|
||||||
source io.ReaderAt
|
input io.ReaderAt
|
||||||
}
|
}
|
||||||
|
|
||||||
// convertWriter 将取消上下文传递到写入并统计实际字节数
|
// convertWriter 将取消上下文传递到写入并统计实际字节数
|
||||||
type convertWriter struct {
|
type convertWriter struct {
|
||||||
context context.Context
|
ctx context.Context
|
||||||
writer io.Writer
|
writer io.Writer
|
||||||
count *int64
|
count *int64
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// conversionPoolKey 标识单次转换使用的共享预算
|
||||||
|
type conversionPoolKey struct{}
|
||||||
|
|
||||||
// OutputFormats 返回独立的输出格式列表,不依赖WebUI或具体渲染后端
|
// OutputFormats 返回独立的输出格式列表,不依赖WebUI或具体渲染后端
|
||||||
// 返回: []OutputFormat 输出格式列表
|
// 返回: []OutputFormat 输出格式列表
|
||||||
func OutputFormats() []OutputFormat {
|
func OutputFormats() []OutputFormat {
|
||||||
@@ -113,9 +144,16 @@ func OutputFormats() []OutputFormat {
|
|||||||
// 原始模式完整OFD另存保持源字节;选页和跨格式输出重新生成文档,压缩仅作用于输出副本
|
// 原始模式完整OFD另存保持源字节;选页和跨格式输出重新生成文档,压缩仅作用于输出副本
|
||||||
// 输入按需随机读取,输出分块写出;解析对象及后端可能缓存资源,不保证恒定内存
|
// 输入按需随机读取,输出分块写出;解析对象及后端可能缓存资源,不保证恒定内存
|
||||||
// 出错时报告保留已有诊断,调用方应丢弃未完成输出;只有返回nil才表示转换成功
|
// 出错时报告保留已有诊断,调用方应丢弃未完成输出;只有返回nil才表示转换成功
|
||||||
// 入参: ctx 取消上下文, source 源数据, size 源字节数, output 输出流, options 转换选项
|
// 入参: ctx 取消上下文, input 输入源, output 输出流, options 转换选项
|
||||||
// 返回: ConvertReport 转换报告, error 错误信息
|
// 返回: ConvertReport 转换报告, error 错误信息
|
||||||
func Convert(ctx context.Context, source io.ReaderAt, size int64, output io.Writer, options ConvertOptions) (report ConvertReport, err error) {
|
func Convert(ctx context.Context, input *Input, output io.Writer, options ConvertOptions) (report ConvertReport, err error) {
|
||||||
|
if options.Resources != nil {
|
||||||
|
if options.Pool == nil {
|
||||||
|
options.Pool = options.Resources.pool
|
||||||
|
}
|
||||||
|
options.ReaderOptions = append(slices.Clone(options.ReaderOptions), WithResources(options.Resources))
|
||||||
|
options.PDF.Resources = options.Resources
|
||||||
|
}
|
||||||
if options.Pool != nil {
|
if options.Pool != nil {
|
||||||
if err = options.Pool.acquire(ctx, false, 0); err != nil {
|
if err = options.Pool.acquire(ctx, false, 0); err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
@@ -174,13 +212,14 @@ func Convert(ctx context.Context, source io.ReaderAt, size int64, output io.Writ
|
|||||||
if err = progress("open", 0, 0); err != nil {
|
if err = progress("open", 0, 0); err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
if source == nil || size <= 0 {
|
if input == nil || input.Size() <= 0 {
|
||||||
return report, fmt.Errorf("empty document source")
|
return report, fmt.Errorf("empty document input")
|
||||||
}
|
}
|
||||||
source = convertReader{context: ctx, source: source}
|
size := input.Size()
|
||||||
|
operationInput := &Input{reader: convertReader{ctx: ctx, input: input}, size: size}
|
||||||
report.Input = strings.ToLower(strings.TrimSpace(options.Input))
|
report.Input = strings.ToLower(strings.TrimSpace(options.Input))
|
||||||
if report.Input == "" {
|
if report.Input == "" {
|
||||||
report.Input, err = DetectFormat(source, size)
|
report.Input, err = DetectFormat(operationInput)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
@@ -199,7 +238,7 @@ func Convert(ctx context.Context, source io.ReaderAt, size int64, output io.Writ
|
|||||||
return report, fmt.Errorf("missing output writer")
|
return report, fmt.Errorf("missing output writer")
|
||||||
}
|
}
|
||||||
if report.Input == "pdf" && format == "pdf" && options.Compression.Mode != CompressionUnchanged && options.Pages == nil && strings.TrimSpace(options.PageRange) == "" {
|
if report.Input == "pdf" && format == "pdf" && options.Compression.Mode != CompressionUnchanged && options.Pages == nil && strings.TrimSpace(options.PageRange) == "" {
|
||||||
pdfReader, openErr := pdfgo.NewReaderWithOptions(source, size, pdfgo.ReaderOptions{Password: options.PDF.Password, PasswordUTF8: options.PDF.PasswordUTF8})
|
pdfReader, openErr := pdfgo.NewReaderWithOptions(operationInput, size, pdfgo.ReaderOptions{Password: options.PDF.Password, PasswordUTF8: options.PDF.PasswordUTF8})
|
||||||
if openErr != nil {
|
if openErr != nil {
|
||||||
return report, openErr
|
return report, openErr
|
||||||
}
|
}
|
||||||
@@ -233,13 +272,13 @@ func Convert(ctx context.Context, source io.ReaderAt, size int64, output io.Writ
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
editor, report.PDF, err = ImportPDF(ctx, source, size, pdfOptions)
|
editor, report.PDF, err = ImportPDF(ctx, operationInput, pdfOptions)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
count = editor.PageCount()
|
count = editor.PageCount()
|
||||||
case "ofd":
|
case "ofd":
|
||||||
reader, err = NewReader(source, size, options.ReaderOptions...)
|
reader, err = NewReader(operationInput, options.ReaderOptions...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
@@ -260,13 +299,13 @@ func Convert(ctx context.Context, source io.ReaderAt, size int64, output io.Writ
|
|||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
report.Pages = len(indices)
|
report.Pages = len(indices)
|
||||||
writer := convertWriter{context: ctx, writer: output, count: &report.Bytes}
|
writer := convertWriter{ctx: ctx, writer: output, count: &report.Bytes}
|
||||||
if format == "ofd" {
|
if format == "ofd" {
|
||||||
if options.Pages == nil && editor == nil && options.Fonts == FontKeep && options.Compression.Mode == CompressionUnchanged {
|
if options.Pages == nil && editor == nil && options.Fonts == FontKeep && options.Compression.Mode == CompressionUnchanged {
|
||||||
if err = progress("write", 0, 0); err != nil {
|
if err = progress("write", 0, 0); err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
_, err = io.Copy(writer, io.NewSectionReader(source, 0, size))
|
_, err = io.Copy(writer, io.NewSectionReader(operationInput, 0, size))
|
||||||
report.Unchanged = err == nil
|
report.Unchanged = err == nil
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
@@ -301,7 +340,7 @@ func Convert(ctx context.Context, source io.ReaderAt, size int64, output io.Writ
|
|||||||
if err = progress("write", 0, 0); err != nil {
|
if err = progress("write", 0, 0); err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
_, err = io.Copy(writer, io.NewSectionReader(source, 0, size))
|
_, err = io.Copy(writer, io.NewSectionReader(operationInput, 0, size))
|
||||||
report.Unchanged = err == nil
|
report.Unchanged = err == nil
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
@@ -309,7 +348,7 @@ func Convert(ctx context.Context, source io.ReaderAt, size int64, output io.Writ
|
|||||||
if options.Pages == nil {
|
if options.Pages == nil {
|
||||||
_, err = editor.WriteToWithOptions(ctx, writer, WriteOptions{Compression: options.Compression})
|
_, err = editor.WriteToWithOptions(ctx, writer, WriteOptions{Compression: options.Compression})
|
||||||
} else {
|
} else {
|
||||||
_, err = editor.WritePagesToWithOptions(ctx, writer, indices, WriteOptions{Compression: options.Compression})
|
_, err = editor.WritePagesTo(ctx, writer, indices, WriteOptions{Compression: options.Compression})
|
||||||
}
|
}
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
@@ -352,7 +391,7 @@ func Convert(ctx context.Context, source io.ReaderAt, size int64, output io.Writ
|
|||||||
return report, readErr
|
return report, readErr
|
||||||
}
|
}
|
||||||
if err = options.PageOutput(index, func(output io.Writer) error {
|
if err = options.PageOutput(index, func(output io.Writer) error {
|
||||||
return renderer.RenderTo(page, convertWriter{context: ctx, writer: output, count: &report.Bytes}, format)
|
return renderer.RenderTo(page, convertWriter{ctx: ctx, writer: output, count: &report.Bytes}, format)
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return report, fmt.Errorf("export page %d: %w", index+1, err)
|
return report, fmt.Errorf("export page %d: %w", index+1, err)
|
||||||
}
|
}
|
||||||
@@ -366,12 +405,12 @@ func Convert(ctx context.Context, source io.ReaderAt, size int64, output io.Writ
|
|||||||
// 入参: data 目标缓冲, offset 源偏移
|
// 入参: data 目标缓冲, offset 源偏移
|
||||||
// 返回: int 读取字节数, error 读取错误
|
// 返回: int 读取字节数, error 读取错误
|
||||||
func (r convertReader) ReadAt(data []byte, offset int64) (int, error) {
|
func (r convertReader) ReadAt(data []byte, offset int64) (int, error) {
|
||||||
if err := r.context.Err(); err != nil {
|
if err := r.ctx.Err(); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
n, err := r.source.ReadAt(data, offset)
|
n, err := r.input.ReadAt(data, offset)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
err = r.context.Err()
|
err = r.ctx.Err()
|
||||||
}
|
}
|
||||||
return n, err
|
return n, err
|
||||||
}
|
}
|
||||||
@@ -380,7 +419,7 @@ func (r convertReader) ReadAt(data []byte, offset int64) (int, error) {
|
|||||||
// 入参: data 待写数据
|
// 入参: data 待写数据
|
||||||
// 返回: int 写入字节数, error 写入错误
|
// 返回: int 写入字节数, error 写入错误
|
||||||
func (w convertWriter) Write(data []byte) (int, error) {
|
func (w convertWriter) Write(data []byte) (int, error) {
|
||||||
if err := w.context.Err(); err != nil {
|
if err := w.ctx.Err(); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
n, err := w.writer.Write(data)
|
n, err := w.writer.Write(data)
|
||||||
@@ -389,7 +428,7 @@ func (w convertWriter) Write(data []byte) (int, error) {
|
|||||||
err = io.ErrShortWrite
|
err = io.ErrShortWrite
|
||||||
}
|
}
|
||||||
if err == nil {
|
if err == nil {
|
||||||
err = w.context.Err()
|
err = w.ctx.Err()
|
||||||
}
|
}
|
||||||
return n, err
|
return n, err
|
||||||
}
|
}
|
||||||
@@ -398,7 +437,7 @@ func (w convertWriter) Write(data []byte) (int, error) {
|
|||||||
// 入参: data 待写文本
|
// 入参: data 待写文本
|
||||||
// 返回: int 写入字节数, error 写入、短写或取消错误
|
// 返回: int 写入字节数, error 写入、短写或取消错误
|
||||||
func (w convertWriter) WriteString(data string) (int, error) {
|
func (w convertWriter) WriteString(data string) (int, error) {
|
||||||
if err := w.context.Err(); err != nil {
|
if err := w.ctx.Err(); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
n, err := io.WriteString(w.writer, data)
|
n, err := io.WriteString(w.writer, data)
|
||||||
@@ -407,7 +446,162 @@ func (w convertWriter) WriteString(data string) (int, error) {
|
|||||||
err = io.ErrShortWrite
|
err = io.ErrShortWrite
|
||||||
}
|
}
|
||||||
if err == nil {
|
if err == nil {
|
||||||
err = w.context.Err()
|
err = w.ctx.Err()
|
||||||
}
|
}
|
||||||
return n, err
|
return n, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DetectFormat 按文件内容识别PDF或OFD,不读取压缩内容或关闭输入
|
||||||
|
// 识别结果不代表文档完整有效,仍需通过对应阅读器解析
|
||||||
|
// 入参: input 输入源
|
||||||
|
// 返回: string 格式标识pdf或ofd, error 读取错误或不支持的格式
|
||||||
|
func DetectFormat(input *Input) (string, error) {
|
||||||
|
if input == nil || input.Size() <= 0 {
|
||||||
|
return "", fmt.Errorf("empty document input")
|
||||||
|
}
|
||||||
|
size := input.Size()
|
||||||
|
var header [1024]byte
|
||||||
|
data := header[:min(size, int64(len(header)))]
|
||||||
|
n, err := input.ReadAt(data, 0)
|
||||||
|
if err != nil && err != io.EOF {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if n != len(data) {
|
||||||
|
return "", io.ErrUnexpectedEOF
|
||||||
|
}
|
||||||
|
if bytes.HasPrefix(data, []byte("%PDF-")) {
|
||||||
|
return "pdf", nil
|
||||||
|
}
|
||||||
|
archive, err := zip.NewReader(input, size)
|
||||||
|
if err == nil {
|
||||||
|
reader := &Reader{Zip: archive}
|
||||||
|
if err := reader.indexPackage(); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if reader.fileNames["OFD.xml"] || reader.fileNames["Encryptions.xml"] {
|
||||||
|
return "ofd", nil
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if !errors.Is(err, zip.ErrFormat) {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if bytes.Contains(data, []byte("%PDF-")) {
|
||||||
|
return "pdf", nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("unsupported input format")
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewConversionPool 创建共享转换调度器,不启动后台任务
|
||||||
|
// 入参: options 并行及内存选项
|
||||||
|
// 返回: *ConversionPool 调度器, error 配置错误
|
||||||
|
func NewConversionPool(options ConversionPoolOptions) (*ConversionPool, error) {
|
||||||
|
if options.Parallelism < 0 || options.MemoryLimit < 0 {
|
||||||
|
return nil, fmt.Errorf("invalid conversion pool options")
|
||||||
|
}
|
||||||
|
if options.Parallelism == 0 {
|
||||||
|
options.Parallelism = runtime.GOMAXPROCS(0)
|
||||||
|
}
|
||||||
|
return &ConversionPool{options: options, changed: make(chan struct{})}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parallelism 返回同时运行的转换数量上限
|
||||||
|
// 返回: int 并行上限
|
||||||
|
func (p *ConversionPool) Parallelism() int { return p.options.Parallelism }
|
||||||
|
|
||||||
|
// memoryLimit 读取当前可分配的图像工作量预算
|
||||||
|
// 返回: int64 可用字节数,负值表示未设置预算
|
||||||
|
func (p *ConversionPool) memoryLimit() int64 {
|
||||||
|
limit := int64(-1)
|
||||||
|
if p.options.MemoryLimit > 0 {
|
||||||
|
limit = p.options.MemoryLimit
|
||||||
|
}
|
||||||
|
if p.options.AvailableMemory != nil {
|
||||||
|
available := max(0, p.options.AvailableMemory())
|
||||||
|
if limit < 0 || available < limit {
|
||||||
|
limit = available
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return limit
|
||||||
|
}
|
||||||
|
|
||||||
|
// acquire 等待转换或图像预算,超预算图像可独占运行
|
||||||
|
// 入参: ctx 取消上下文, image 是否为图像任务, size 图像工作量
|
||||||
|
// 返回: error 取消错误
|
||||||
|
func (p *ConversionPool) acquire(ctx context.Context, image bool, size int64) error {
|
||||||
|
var timer *time.Timer
|
||||||
|
defer func() {
|
||||||
|
if timer != nil {
|
||||||
|
timer.Stop()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
for {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
limit := p.memoryLimit()
|
||||||
|
p.mu.Lock()
|
||||||
|
allowed := p.active < p.options.Parallelism && (p.active == 0 || limit != 0)
|
||||||
|
if image {
|
||||||
|
allowed = p.images < p.options.Parallelism && (p.images == 0 || limit < 0 || size <= limit-p.memory)
|
||||||
|
}
|
||||||
|
if allowed {
|
||||||
|
if image {
|
||||||
|
p.images++
|
||||||
|
p.memory += size
|
||||||
|
} else {
|
||||||
|
p.active++
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
changed := p.changed
|
||||||
|
p.mu.Unlock()
|
||||||
|
var tick <-chan time.Time
|
||||||
|
if p.options.AvailableMemory != nil {
|
||||||
|
if timer == nil {
|
||||||
|
timer = time.NewTimer(250 * time.Millisecond)
|
||||||
|
} else {
|
||||||
|
timer.Reset(250 * time.Millisecond)
|
||||||
|
}
|
||||||
|
tick = timer.C
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
case <-changed:
|
||||||
|
case <-tick:
|
||||||
|
}
|
||||||
|
if timer != nil {
|
||||||
|
timer.Stop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// release 归还任务预算并唤醒等待者
|
||||||
|
// 入参: image 是否为图像任务, size 图像工作量
|
||||||
|
func (p *ConversionPool) release(image bool, size int64) {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
if image {
|
||||||
|
p.images--
|
||||||
|
p.memory -= size
|
||||||
|
} else {
|
||||||
|
p.active--
|
||||||
|
}
|
||||||
|
close(p.changed)
|
||||||
|
p.changed = make(chan struct{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// conversionWorkers 按当前文件数量分配内部计算任务
|
||||||
|
// 入参: ctx 转换上下文
|
||||||
|
// 返回: int 内部并行数
|
||||||
|
func conversionWorkers(ctx context.Context) int {
|
||||||
|
p, _ := ctx.Value(conversionPoolKey{}).(*ConversionPool)
|
||||||
|
if p == nil {
|
||||||
|
return runtime.GOMAXPROCS(0)
|
||||||
|
}
|
||||||
|
p.mu.Lock()
|
||||||
|
active := p.active
|
||||||
|
p.mu.Unlock()
|
||||||
|
return max(1, p.options.Parallelism/max(1, active))
|
||||||
|
}
|
||||||
@@ -1,146 +0,0 @@
|
|||||||
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
package ofdgo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"runtime"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ConversionPoolOptions 设置共享转换并行度及图像工作集预算
|
|
||||||
// Parallelism为0时使用GOMAXPROCS,MemoryLimit为0时不指定固定预算
|
|
||||||
// AvailableMemory返回可用于新增任务的字节数,nil表示不探测,回调须支持并发调用
|
|
||||||
// 内存预算用于调度,不限制解析器及运行时的实际分配
|
|
||||||
type ConversionPoolOptions struct {
|
|
||||||
Parallelism int
|
|
||||||
MemoryLimit int64
|
|
||||||
AvailableMemory func() int64
|
|
||||||
}
|
|
||||||
|
|
||||||
// ConversionPool 协调独立转换和图像任务,配置在创建后不变,可跨会话复用
|
|
||||||
type ConversionPool struct {
|
|
||||||
options ConversionPoolOptions
|
|
||||||
mu sync.Mutex
|
|
||||||
changed chan struct{}
|
|
||||||
active int
|
|
||||||
images int
|
|
||||||
memory int64
|
|
||||||
}
|
|
||||||
|
|
||||||
// conversionPoolKey 标识单次转换使用的共享预算
|
|
||||||
type conversionPoolKey struct{}
|
|
||||||
|
|
||||||
// NewConversionPool 创建共享转换调度器,不启动后台任务
|
|
||||||
// 入参: options 并行及内存选项
|
|
||||||
// 返回: *ConversionPool 调度器, error 配置错误
|
|
||||||
func NewConversionPool(options ConversionPoolOptions) (*ConversionPool, error) {
|
|
||||||
if options.Parallelism < 0 || options.MemoryLimit < 0 {
|
|
||||||
return nil, fmt.Errorf("invalid conversion pool options")
|
|
||||||
}
|
|
||||||
if options.Parallelism == 0 {
|
|
||||||
options.Parallelism = runtime.GOMAXPROCS(0)
|
|
||||||
}
|
|
||||||
return &ConversionPool{options: options, changed: make(chan struct{})}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parallelism 返回同时运行的转换数量上限
|
|
||||||
// 返回: int 并行上限
|
|
||||||
func (p *ConversionPool) Parallelism() int { return p.options.Parallelism }
|
|
||||||
|
|
||||||
// memoryLimit 读取当前可分配的图像工作量预算
|
|
||||||
// 返回: int64 可用字节数,负值表示未设置预算
|
|
||||||
func (p *ConversionPool) memoryLimit() int64 {
|
|
||||||
limit := int64(-1)
|
|
||||||
if p.options.MemoryLimit > 0 {
|
|
||||||
limit = p.options.MemoryLimit
|
|
||||||
}
|
|
||||||
if p.options.AvailableMemory != nil {
|
|
||||||
available := max(0, p.options.AvailableMemory())
|
|
||||||
if limit < 0 || available < limit {
|
|
||||||
limit = available
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return limit
|
|
||||||
}
|
|
||||||
|
|
||||||
// acquire 等待转换或图像预算,超预算图像可独占运行
|
|
||||||
// 入参: ctx 取消上下文, image 是否为图像任务, size 图像工作量
|
|
||||||
// 返回: error 取消错误
|
|
||||||
func (p *ConversionPool) acquire(ctx context.Context, image bool, size int64) error {
|
|
||||||
for {
|
|
||||||
if err := ctx.Err(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
limit := p.memoryLimit()
|
|
||||||
p.mu.Lock()
|
|
||||||
allowed := p.active < p.options.Parallelism && (p.active == 0 || limit != 0)
|
|
||||||
if image {
|
|
||||||
allowed = p.images < runtime.GOMAXPROCS(0) && (p.images == 0 || limit < 0 || size <= limit-p.memory)
|
|
||||||
}
|
|
||||||
if allowed {
|
|
||||||
if image {
|
|
||||||
p.images++
|
|
||||||
p.memory += size
|
|
||||||
} else {
|
|
||||||
p.active++
|
|
||||||
}
|
|
||||||
p.mu.Unlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
changed := p.changed
|
|
||||||
p.mu.Unlock()
|
|
||||||
timer := time.NewTimer(250 * time.Millisecond)
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
timer.Stop()
|
|
||||||
return ctx.Err()
|
|
||||||
case <-changed:
|
|
||||||
case <-timer.C:
|
|
||||||
}
|
|
||||||
timer.Stop()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// release 归还任务预算并唤醒等待者
|
|
||||||
// 入参: image 是否为图像任务, size 图像工作量
|
|
||||||
func (p *ConversionPool) release(image bool, size int64) {
|
|
||||||
p.mu.Lock()
|
|
||||||
defer p.mu.Unlock()
|
|
||||||
if image {
|
|
||||||
p.images--
|
|
||||||
p.memory -= size
|
|
||||||
} else {
|
|
||||||
p.active--
|
|
||||||
}
|
|
||||||
close(p.changed)
|
|
||||||
p.changed = make(chan struct{})
|
|
||||||
}
|
|
||||||
|
|
||||||
// conversionWorkers 按当前文件数量分配内部计算任务
|
|
||||||
// 入参: ctx 转换上下文, fallback 非共享模式并行上限
|
|
||||||
// 返回: int 内部并行数
|
|
||||||
func conversionWorkers(ctx context.Context, fallback int) int {
|
|
||||||
p, _ := ctx.Value(conversionPoolKey{}).(*ConversionPool)
|
|
||||||
if p == nil {
|
|
||||||
return min(fallback, runtime.GOMAXPROCS(0))
|
|
||||||
}
|
|
||||||
p.mu.Lock()
|
|
||||||
active := p.active
|
|
||||||
p.mu.Unlock()
|
|
||||||
return max(1, runtime.GOMAXPROCS(0)/max(1, active))
|
|
||||||
}
|
|
||||||
+176
-7
@@ -17,7 +17,18 @@ package ofdgo
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"crypto"
|
"crypto"
|
||||||
|
"crypto/cipher"
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/rand"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"github.com/emmansun/gmsm/padding"
|
||||||
|
"github.com/emmansun/gmsm/sm2"
|
||||||
|
"github.com/emmansun/gmsm/sm3"
|
||||||
|
"github.com/emmansun/gmsm/sm4"
|
||||||
|
"github.com/emmansun/gmsm/smx509"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 加密错误可通过errors.Is识别,不包含口令或私钥
|
// 加密错误可通过errors.Is识别,不包含口令或私钥
|
||||||
@@ -48,15 +59,9 @@ type CryptoProvider interface {
|
|||||||
EncryptKey(certificate, key []byte) ([]byte, error)
|
EncryptKey(certificate, key []byte) ([]byte, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReaderOption 阅读器的凭据与密码提供者选项
|
// ReaderOption 阅读器的凭据、密码提供者与资源选项
|
||||||
type ReaderOption func(*readerOptions)
|
type ReaderOption func(*readerOptions)
|
||||||
|
|
||||||
// readerOptions 保存打开文档时的会话参数
|
|
||||||
type readerOptions struct {
|
|
||||||
credentials []Credentials
|
|
||||||
provider CryptoProvider
|
|
||||||
}
|
|
||||||
|
|
||||||
// EncryptionRecipient 证书加密接收者,Certificate为SM2公钥证书的DER编码
|
// EncryptionRecipient 证书加密接收者,Certificate为SM2公钥证书的DER编码
|
||||||
type EncryptionRecipient struct {
|
type EncryptionRecipient struct {
|
||||||
UserName string
|
UserName string
|
||||||
@@ -85,12 +90,22 @@ type EncryptionInfo struct {
|
|||||||
PolicyRequired bool
|
PolicyRequired bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// readerOptions 保存打开文档时的会话参数
|
||||||
|
type readerOptions struct {
|
||||||
|
resources *Resources
|
||||||
|
credentials []Credentials
|
||||||
|
provider CryptoProvider
|
||||||
|
}
|
||||||
|
|
||||||
// encryptionState 保存解密来源与可继承的输出策略
|
// encryptionState 保存解密来源与可继承的输出策略
|
||||||
type encryptionState struct {
|
type encryptionState struct {
|
||||||
info EncryptionInfo
|
info EncryptionInfo
|
||||||
options *EncryptionOptions
|
options *EncryptionOptions
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GMCryptoProvider 使用纯Go国密实现,可在原生环境和WASM使用
|
||||||
|
type GMCryptoProvider struct{}
|
||||||
|
|
||||||
// WithCredentials 添加解密凭据,多次调用可解开多层加密
|
// WithCredentials 添加解密凭据,多次调用可解开多层加密
|
||||||
// 入参: credentials 解密凭据
|
// 入参: credentials 解密凭据
|
||||||
// 返回: ReaderOption 阅读选项
|
// 返回: ReaderOption 阅读选项
|
||||||
@@ -145,3 +160,157 @@ func cloneEncryptionOptions(options *EncryptionOptions) *EncryptionOptions {
|
|||||||
}
|
}
|
||||||
return ©
|
return ©
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Encryption 获取当前保存策略,不暴露口令或私钥
|
||||||
|
// 返回: EncryptionInfo 加密状态
|
||||||
|
func (e *Editor) Encryption() EncryptionInfo {
|
||||||
|
return e.encryption.summary()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetEncryption 设置后续保存的加密策略,nil显式选择明文保存
|
||||||
|
// 打开单用户口令或证书加密文档时默认继承原策略;多人口令和多层加密需显式选择输出策略
|
||||||
|
// 新的加密密钥与初始向量在每次保存时独立生成,设置不改变文档内容或撤销历史
|
||||||
|
// 入参: options 加密策略
|
||||||
|
// 返回: error 错误信息
|
||||||
|
func (e *Editor) SetEncryption(options *EncryptionOptions) error {
|
||||||
|
if options == nil {
|
||||||
|
e.encryption = nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := validateEncryptionOptions(*options); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
info := EncryptionInfo{Encrypted: true, Method: "1.1.1", Layers: 1}
|
||||||
|
if len(options.Password) != 0 {
|
||||||
|
info.Users = []string{options.UserName}
|
||||||
|
} else {
|
||||||
|
info.Method = "1.1.2"
|
||||||
|
for _, recipient := range options.Recipients {
|
||||||
|
info.Users = append(info.Users, recipient.UserName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e.encryption = &encryptionState{info: info, options: cloneEncryptionOptions(options)}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeEncrypted 在全部准备及加密成功后写出结果,取消不产生输出
|
||||||
|
// 输出流自身写入失败时调用方仍需丢弃本次输出
|
||||||
|
// 入参: writer 输出流
|
||||||
|
// 返回: int64 写入字节数, error 错误信息
|
||||||
|
func (e *Editor) writeEncrypted(writer io.Writer) (int64, error) {
|
||||||
|
if e.encryption.options == nil {
|
||||||
|
return 0, ErrEncryptionPolicyRequired
|
||||||
|
}
|
||||||
|
var plaintext bytes.Buffer
|
||||||
|
if _, err := e.writePlaintext(&plaintext); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer clear(plaintext.Bytes())
|
||||||
|
r, err := NewReader(&Input{reader: bytes.NewReader(plaintext.Bytes()), size: int64(plaintext.Len())})
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer r.Close()
|
||||||
|
parts, err := r.packageData()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
for _, data := range parts {
|
||||||
|
clear(data)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
data, err := encryptPackageParts(parts, *e.encryption.options, editorProgress(e.OnWriteProgress))
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return io.Copy(writer, bytes.NewReader(data))
|
||||||
|
}
|
||||||
|
|
||||||
|
// EncryptSM4 使用SM4-CBC及PKCS#7填充加密
|
||||||
|
// 入参: key 密钥, iv 初始向量, plaintext 明文
|
||||||
|
// 返回: []byte 密文, error 错误信息
|
||||||
|
func (GMCryptoProvider) EncryptSM4(key, iv, plaintext []byte) ([]byte, error) {
|
||||||
|
block, err := sm4.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(iv) != block.BlockSize() {
|
||||||
|
return nil, fmt.Errorf("invalid SM4 IV length")
|
||||||
|
}
|
||||||
|
out := padding.NewPKCS7Padding(sm4.BlockSize).Pad(bytes.Clone(plaintext))
|
||||||
|
cipher.NewCBCEncrypter(block, iv).CryptBlocks(out, out)
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecryptSM4 解密SM4-CBC并校验PKCS#7填充
|
||||||
|
// 入参: key 密钥, iv 初始向量, ciphertext 密文
|
||||||
|
// 返回: []byte 明文, error 错误信息
|
||||||
|
func (GMCryptoProvider) DecryptSM4(key, iv, ciphertext []byte) ([]byte, error) {
|
||||||
|
block, err := sm4.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(iv) != block.BlockSize() || len(ciphertext) == 0 || len(ciphertext)%block.BlockSize() != 0 {
|
||||||
|
return nil, ErrInvalidCredentials
|
||||||
|
}
|
||||||
|
out := make([]byte, len(ciphertext))
|
||||||
|
cipher.NewCBCDecrypter(block, iv).CryptBlocks(out, ciphertext)
|
||||||
|
plain, err := padding.NewPKCS7Padding(sm4.BlockSize).ConstantTimeUnpad(out)
|
||||||
|
if err != nil {
|
||||||
|
clear(out)
|
||||||
|
return nil, ErrInvalidCredentials
|
||||||
|
}
|
||||||
|
return plain, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PasswordKey 按GB/T32918派生16字节口令密钥
|
||||||
|
// 入参: password UTF-8口令
|
||||||
|
// 返回: []byte 密钥, error 错误信息
|
||||||
|
func (GMCryptoProvider) PasswordKey(password []byte) ([]byte, error) {
|
||||||
|
if len(password) == 0 {
|
||||||
|
return nil, ErrCredentialsRequired
|
||||||
|
}
|
||||||
|
return sm3.Kdf(password, sm4.BlockSize), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EncryptKey 使用SM2公钥证书封装文件密钥
|
||||||
|
// 入参: certificate DER证书, key 文件密钥
|
||||||
|
// 返回: []byte ASN.1密文, error 错误信息
|
||||||
|
func (GMCryptoProvider) EncryptKey(certificate, key []byte) ([]byte, error) {
|
||||||
|
cert, err := parseEncryptionCertificate(certificate)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return sm2.EncryptASN1(rand.Reader, cert.PublicKey.(*ecdsa.PublicKey), key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseEncryptionCertificate 解析单张SM2加密证书并返回DER副本
|
||||||
|
// 仅检查格式、算法和密钥用途,接收者身份及信任应由调用方确认
|
||||||
|
// 入参: certificate PEM或DER证书
|
||||||
|
// 返回: []byte DER证书, error 错误信息
|
||||||
|
func ParseEncryptionCertificate(certificate []byte) ([]byte, error) {
|
||||||
|
cert, err := parseEncryptionCertificate(certificate)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return bytes.Clone(cert.Raw), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseEncryptionCertificate 解析并检查加密证书
|
||||||
|
// 入参: certificate PEM或DER证书
|
||||||
|
// 返回: *smx509.Certificate 证书, error 错误信息
|
||||||
|
func parseEncryptionCertificate(certificate []byte) (*smx509.Certificate, error) {
|
||||||
|
cert, err := parseSignatureCertificate(certificate)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
public, ok := cert.PublicKey.(*ecdsa.PublicKey)
|
||||||
|
if !ok || !sm2.IsSM2PublicKey(public) {
|
||||||
|
return nil, fmt.Errorf("SM2 encryption certificate required")
|
||||||
|
}
|
||||||
|
if cert.KeyUsage != 0 && cert.KeyUsage&(smx509.KeyUsageKeyEncipherment|smx509.KeyUsageDataEncipherment|smx509.KeyUsageKeyAgreement) == 0 {
|
||||||
|
return nil, fmt.Errorf("certificate does not permit encryption")
|
||||||
|
}
|
||||||
|
return cert, nil
|
||||||
|
}
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
package ofdgo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Encryption 获取当前保存策略,不暴露口令或私钥
|
|
||||||
// 返回: EncryptionInfo 加密状态
|
|
||||||
func (e *Editor) Encryption() EncryptionInfo {
|
|
||||||
return e.encryption.summary()
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetEncryption 设置后续保存的加密策略,nil显式选择明文保存
|
|
||||||
// 打开单用户口令或证书加密文档时默认继承原策略;多人口令和多层加密需显式选择输出策略
|
|
||||||
// 新的加密密钥与初始向量在每次保存时独立生成,设置不改变文档内容或撤销历史
|
|
||||||
// 入参: options 加密策略
|
|
||||||
// 返回: error 错误信息
|
|
||||||
func (e *Editor) SetEncryption(options *EncryptionOptions) error {
|
|
||||||
if options == nil {
|
|
||||||
e.encryption = nil
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if err := validateEncryptionOptions(*options); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
info := EncryptionInfo{Encrypted: true, Method: "1.1.1", Layers: 1}
|
|
||||||
if len(options.Password) != 0 {
|
|
||||||
info.Users = []string{options.UserName}
|
|
||||||
} else {
|
|
||||||
info.Method = "1.1.2"
|
|
||||||
for _, recipient := range options.Recipients {
|
|
||||||
info.Users = append(info.Users, recipient.UserName)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
e.encryption = &encryptionState{info: info, options: cloneEncryptionOptions(options)}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// writeEncrypted 在全部准备及加密成功后写出结果,取消不产生输出
|
|
||||||
// 输出流自身写入失败时调用方仍需丢弃本次输出
|
|
||||||
// 入参: writer 输出流
|
|
||||||
// 返回: int64 写入字节数, error 错误信息
|
|
||||||
func (e *Editor) writeEncrypted(writer io.Writer) (int64, error) {
|
|
||||||
if e.encryption.options == nil {
|
|
||||||
return 0, ErrEncryptionPolicyRequired
|
|
||||||
}
|
|
||||||
var plaintext bytes.Buffer
|
|
||||||
if _, err := e.writePlaintext(&plaintext); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
defer clear(plaintext.Bytes())
|
|
||||||
r, err := NewReader(bytes.NewReader(plaintext.Bytes()), int64(plaintext.Len()))
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
defer r.Close()
|
|
||||||
parts, err := r.packageData()
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
defer func() {
|
|
||||||
for _, data := range parts {
|
|
||||||
clear(data)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
data, err := encryptPackageParts(parts, *e.encryption.options, editorProgress(e.OnWriteProgress))
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return io.Copy(writer, bytes.NewReader(data))
|
|
||||||
}
|
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
package ofdgo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"crypto/cipher"
|
|
||||||
"crypto/ecdsa"
|
|
||||||
"crypto/rand"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"github.com/emmansun/gmsm/padding"
|
|
||||||
"github.com/emmansun/gmsm/sm2"
|
|
||||||
"github.com/emmansun/gmsm/sm3"
|
|
||||||
"github.com/emmansun/gmsm/sm4"
|
|
||||||
"github.com/emmansun/gmsm/smx509"
|
|
||||||
)
|
|
||||||
|
|
||||||
// GMCryptoProvider 使用纯Go国密实现,可在原生环境和WASM使用
|
|
||||||
type GMCryptoProvider struct{}
|
|
||||||
|
|
||||||
// EncryptSM4 使用SM4-CBC及PKCS#7填充加密
|
|
||||||
// 入参: key 密钥, iv 初始向量, plaintext 明文
|
|
||||||
// 返回: []byte 密文, error 错误信息
|
|
||||||
func (GMCryptoProvider) EncryptSM4(key, iv, plaintext []byte) ([]byte, error) {
|
|
||||||
block, err := sm4.NewCipher(key)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if len(iv) != block.BlockSize() {
|
|
||||||
return nil, fmt.Errorf("invalid SM4 IV length")
|
|
||||||
}
|
|
||||||
out := padding.NewPKCS7Padding(sm4.BlockSize).Pad(bytes.Clone(plaintext))
|
|
||||||
cipher.NewCBCEncrypter(block, iv).CryptBlocks(out, out)
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecryptSM4 解密SM4-CBC并校验PKCS#7填充
|
|
||||||
// 入参: key 密钥, iv 初始向量, ciphertext 密文
|
|
||||||
// 返回: []byte 明文, error 错误信息
|
|
||||||
func (GMCryptoProvider) DecryptSM4(key, iv, ciphertext []byte) ([]byte, error) {
|
|
||||||
block, err := sm4.NewCipher(key)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if len(iv) != block.BlockSize() || len(ciphertext) == 0 || len(ciphertext)%block.BlockSize() != 0 {
|
|
||||||
return nil, ErrInvalidCredentials
|
|
||||||
}
|
|
||||||
out := make([]byte, len(ciphertext))
|
|
||||||
cipher.NewCBCDecrypter(block, iv).CryptBlocks(out, ciphertext)
|
|
||||||
plain, err := padding.NewPKCS7Padding(sm4.BlockSize).ConstantTimeUnpad(out)
|
|
||||||
if err != nil {
|
|
||||||
clear(out)
|
|
||||||
return nil, ErrInvalidCredentials
|
|
||||||
}
|
|
||||||
return plain, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// PasswordKey 按GB/T32918派生16字节口令密钥
|
|
||||||
// 入参: password UTF-8口令
|
|
||||||
// 返回: []byte 密钥, error 错误信息
|
|
||||||
func (GMCryptoProvider) PasswordKey(password []byte) ([]byte, error) {
|
|
||||||
if len(password) == 0 {
|
|
||||||
return nil, ErrCredentialsRequired
|
|
||||||
}
|
|
||||||
return sm3.Kdf(password, sm4.BlockSize), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// EncryptKey 使用SM2公钥证书封装文件密钥
|
|
||||||
// 入参: certificate DER证书, key 文件密钥
|
|
||||||
// 返回: []byte ASN.1密文, error 错误信息
|
|
||||||
func (GMCryptoProvider) EncryptKey(certificate, key []byte) ([]byte, error) {
|
|
||||||
cert, err := parseEncryptionCertificate(certificate)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return sm2.EncryptASN1(rand.Reader, cert.PublicKey.(*ecdsa.PublicKey), key)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParseEncryptionCertificate 解析单张SM2加密证书并返回DER副本
|
|
||||||
// 仅检查格式、算法和密钥用途,接收者身份及信任应由调用方确认
|
|
||||||
// 入参: certificate PEM或DER证书
|
|
||||||
// 返回: []byte DER证书, error 错误信息
|
|
||||||
func ParseEncryptionCertificate(certificate []byte) ([]byte, error) {
|
|
||||||
cert, err := parseEncryptionCertificate(certificate)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return bytes.Clone(cert.Raw), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseEncryptionCertificate 解析并检查加密证书
|
|
||||||
// 入参: certificate PEM或DER证书
|
|
||||||
// 返回: *smx509.Certificate 证书, error 错误信息
|
|
||||||
func parseEncryptionCertificate(certificate []byte) (*smx509.Certificate, error) {
|
|
||||||
cert, err := parseSignatureCertificate(certificate)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
public, ok := cert.PublicKey.(*ecdsa.PublicKey)
|
|
||||||
if !ok || !sm2.IsSM2PublicKey(public) {
|
|
||||||
return nil, fmt.Errorf("SM2 encryption certificate required")
|
|
||||||
}
|
|
||||||
if cert.KeyUsage != 0 && cert.KeyUsage&(smx509.KeyUsageKeyEncipherment|smx509.KeyUsageDataEncipherment|smx509.KeyUsageKeyAgreement) == 0 {
|
|
||||||
return nil, fmt.Errorf("certificate does not permit encryption")
|
|
||||||
}
|
|
||||||
return cert, nil
|
|
||||||
}
|
|
||||||
@@ -93,7 +93,7 @@ type encryptionEntry struct {
|
|||||||
// 入参: data 明文OFD包, options 加密策略
|
// 入参: data 明文OFD包, options 加密策略
|
||||||
// 返回: []byte 加密OFD包, error 错误信息
|
// 返回: []byte 加密OFD包, error 错误信息
|
||||||
func EncryptPackage(data []byte, options EncryptionOptions) ([]byte, error) {
|
func EncryptPackage(data []byte, options EncryptionOptions) ([]byte, error) {
|
||||||
r, err := NewReader(bytes.NewReader(data), int64(len(data)))
|
r, err := NewReader(&Input{reader: bytes.NewReader(data), size: int64(len(data))})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -113,6 +113,7 @@ func (r *Reader) open(options []ReaderOption) error {
|
|||||||
for _, option := range options {
|
for _, option := range options {
|
||||||
option(&settings)
|
option(&settings)
|
||||||
}
|
}
|
||||||
|
r.resources = settings.resources
|
||||||
if settings.provider == nil {
|
if settings.provider == nil {
|
||||||
settings.provider = GMCryptoProvider{}
|
settings.provider = GMCryptoProvider{}
|
||||||
}
|
}
|
||||||
|
|||||||
+63
-21
@@ -40,7 +40,7 @@ import (
|
|||||||
const editorPathValidationLimit = 1024
|
const editorPathValidationLimit = 1024
|
||||||
|
|
||||||
// Editor 编辑OFD文档,长度单位为毫米,页面索引从0开始,实例需串行使用
|
// Editor 编辑OFD文档,长度单位为毫米,页面索引从0开始,实例需串行使用
|
||||||
// Info可修改文档元数据,通过方法管理页面、对象和资源,WriteTo另存结果,不覆盖输入
|
// Info可修改文档元数据,通过方法管理页面、对象和资源,WriteTo输出副本,Save和SaveAs通过输出事务保存
|
||||||
// OnWriteProgress可选,按fonts、pages、references、resources、compress、write阶段同步回报进度,返回错误则停止保存
|
// OnWriteProgress可选,按fonts、pages、references、resources、compress、write阶段同步回报进度,返回错误则停止保存
|
||||||
// completed和total为当前阶段已处理及总工作项,compress累计完成条目数且total为0,write阶段不计数
|
// completed和total为当前阶段已处理及总工作项,compress累计完成条目数且total为0,write阶段不计数
|
||||||
// 阶段可重复,准备完成不代表保存成功
|
// 阶段可重复,准备完成不代表保存成功
|
||||||
@@ -50,6 +50,7 @@ type Editor struct {
|
|||||||
Info DocInfo
|
Info DocInfo
|
||||||
pages []PageContent
|
pages []PageContent
|
||||||
resources []editorResource
|
resources []editorResource
|
||||||
|
runtimeResources *Resources
|
||||||
fonts map[string]*FontResource
|
fonts map[string]*FontResource
|
||||||
fontRegistration editorFontRegistration
|
fontRegistration editorFontRegistration
|
||||||
fontDirs []string
|
fontDirs []string
|
||||||
@@ -73,7 +74,12 @@ type Editor struct {
|
|||||||
outlines []byte
|
outlines []byte
|
||||||
encryption *encryptionState
|
encryption *encryptionState
|
||||||
output *outputOptimization
|
output *outputOptimization
|
||||||
|
saveTarget Output
|
||||||
|
snapshotArchive *editorSnapshotArchive
|
||||||
validatedPaths *renderCache[string, bool]
|
validatedPaths *renderCache[string, bool]
|
||||||
|
changes EditorChanges
|
||||||
|
transactionChanges *EditorChanges
|
||||||
|
objectIndex *editorObjectIndex
|
||||||
richIndex *richTextIndex
|
richIndex *richTextIndex
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,11 +158,13 @@ func (e *Editor) Backends() RenderBackends {
|
|||||||
// NewEditor 创建空白文档,保存前至少添加一页
|
// NewEditor 创建空白文档,保存前至少添加一页
|
||||||
// 返回: *Editor 文档编辑器
|
// 返回: *Editor 文档编辑器
|
||||||
func NewEditor() *Editor {
|
func NewEditor() *Editor {
|
||||||
|
resources, _ := NewResources(ResourceOptions{})
|
||||||
var id [16]byte
|
var id [16]byte
|
||||||
rand.Read(id[:])
|
rand.Read(id[:])
|
||||||
id[6] = id[6]&0x0f | 0x40
|
id[6] = id[6]&0x0f | 0x40
|
||||||
id[8] = id[8]&0x3f | 0x80
|
id[8] = id[8]&0x3f | 0x80
|
||||||
return &Editor{
|
return &Editor{
|
||||||
|
runtimeResources: resources,
|
||||||
Info: DocInfo{
|
Info: DocInfo{
|
||||||
DocID: hex.EncodeToString(id[:]),
|
DocID: hex.EncodeToString(id[:]),
|
||||||
CreationDate: time.Now().Format("2006-01-02"),
|
CreationDate: time.Now().Format("2006-01-02"),
|
||||||
@@ -170,6 +178,30 @@ func NewEditor() *Editor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetResources 替换后续操作的资源策略,需与编辑操作串行调用
|
||||||
|
// 已创建的阅读器和快照继续使用原策略,不修改文档或撤销记录
|
||||||
|
// 入参: resources 共享策略,nil使用默认策略
|
||||||
|
func (e *Editor) SetResources(resources *Resources) {
|
||||||
|
if resources == nil {
|
||||||
|
resources, _ = NewResources(ResourceOptions{})
|
||||||
|
}
|
||||||
|
if resources == e.runtimeResources {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
e.runtimeResources = resources
|
||||||
|
e.snapshotArchive = nil
|
||||||
|
e.fontRenderer = nil
|
||||||
|
e.fontSourcesCache = newFontSourceCache(resources)
|
||||||
|
e.validatedPaths = nil
|
||||||
|
if e.source != nil {
|
||||||
|
source := *e.source
|
||||||
|
e.source = &source
|
||||||
|
e.source.reader = cloneEditorReader(e.source.reader)
|
||||||
|
e.source.reader.resources = resources
|
||||||
|
e.source.reader.pageContents = resourceCache[pageContentKey, PageContent](resources, 16<<20)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// PageCount 获取当前页数
|
// PageCount 获取当前页数
|
||||||
// 返回: int 页数
|
// 返回: int 页数
|
||||||
func (e *Editor) PageCount() int {
|
func (e *Editor) PageCount() int {
|
||||||
@@ -194,7 +226,14 @@ func (e *Editor) SetInfo(info DocInfo) {
|
|||||||
// 入参: index 页面索引
|
// 入参: index 页面索引
|
||||||
// 返回: *PageContent 页面内容, error 错误信息
|
// 返回: *PageContent 页面内容, error 错误信息
|
||||||
func (e *Editor) Page(index int) (*PageContent, error) {
|
func (e *Editor) Page(index int) (*PageContent, error) {
|
||||||
page, err := e.page(index)
|
return e.PageContext(context.Background(), index)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PageContext 获取独立页面副本,读取、解析及整理对象时响应取消
|
||||||
|
// 入参: ctx 取消上下文, index 页面索引
|
||||||
|
// 返回: *PageContent 页面内容, error 读取或取消错误
|
||||||
|
func (e *Editor) PageContext(ctx context.Context, index int) (*PageContent, error) {
|
||||||
|
page, err := e.pageContext(ctx, index)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -204,9 +243,11 @@ func (e *Editor) Page(index int) (*PageContent, error) {
|
|||||||
layer := &result.Content.Layer[i]
|
layer := &result.Content.Layer[i]
|
||||||
layer.TextObject, layer.PathObject, layer.ImageObject, layer.CompositeGraphicUnit = nil, nil, nil, nil
|
layer.TextObject, layer.PathObject, layer.ImageObject, layer.CompositeGraphicUnit = nil, nil, nil, nil
|
||||||
for _, object := range layer.Objects {
|
for _, object := range layer.Objects {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
switch object.Type {
|
switch object.Type {
|
||||||
case "TextObject":
|
case "TextObject":
|
||||||
object.TextObject.layout = nil
|
|
||||||
layer.TextObject = append(layer.TextObject, object.TextObject)
|
layer.TextObject = append(layer.TextObject, object.TextObject)
|
||||||
case "PathObject":
|
case "PathObject":
|
||||||
layer.PathObject = append(layer.PathObject, object.PathObject)
|
layer.PathObject = append(layer.PathObject, object.PathObject)
|
||||||
@@ -589,7 +630,9 @@ func (e *Editor) Object(page int, id string) (GraphicObject, error) {
|
|||||||
}
|
}
|
||||||
object, err := cloneEditorObject(layer.Objects[index])
|
object, err := cloneEditorObject(layer.Objects[index])
|
||||||
object.origin = e.objectOrigin(id)
|
object.origin = e.objectOrigin(id)
|
||||||
e.attachRichTextSnapshot(page, &object)
|
if err := e.attachRichTextSnapshot(page, &object); err != nil {
|
||||||
|
return GraphicObject{}, err
|
||||||
|
}
|
||||||
return object, err
|
return object, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -757,13 +800,7 @@ func (e *Editor) LayoutText(obj *TextObject, value string, options TextLayout) e
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err := LayoutText(obj, value, options, metrics); err != nil {
|
return LayoutText(obj, value, options, metrics)
|
||||||
return err
|
|
||||||
}
|
|
||||||
if obj.layout == nil && e.objectOrigin(obj.ID) != nil {
|
|
||||||
obj.layout = &textLayout{value: obj.Text(), options: options}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// newRenderer 使用编辑器字体来源和完整后端配置创建资源度量器
|
// newRenderer 使用编辑器字体来源和完整后端配置创建资源度量器
|
||||||
@@ -771,7 +808,7 @@ func (e *Editor) LayoutText(obj *TextObject, value string, options TextLayout) e
|
|||||||
// 返回: *Renderer 度量器
|
// 返回: *Renderer 度量器
|
||||||
func (e *Editor) newRenderer(reader *Reader) *Renderer {
|
func (e *Editor) newRenderer(reader *Reader) *Renderer {
|
||||||
if e.fontSourcesCache == nil {
|
if e.fontSourcesCache == nil {
|
||||||
e.fontSourcesCache = newFontSourceCache()
|
e.fontSourcesCache = newFontSourceCache(e.runtimeResources)
|
||||||
}
|
}
|
||||||
renderer := NewRenderer(reader, WithFontDirs(e.fontDirs...), WithFontFS(e.fontFS...), WithRenderBackends(e.backends))
|
renderer := NewRenderer(reader, WithFontDirs(e.fontDirs...), WithFontFS(e.fontFS...), WithRenderBackends(e.backends))
|
||||||
renderer.fontSourcesCache = e.fontSourcesCache.child()
|
renderer.fontSourcesCache = e.fontSourcesCache.child()
|
||||||
@@ -791,11 +828,21 @@ func (r editorResource) definition() string {
|
|||||||
// 入参: index 页面索引
|
// 入参: index 页面索引
|
||||||
// 返回: *PageContent 页面内容, error 错误信息
|
// 返回: *PageContent 页面内容, error 错误信息
|
||||||
func (e *Editor) page(index int) (*PageContent, error) {
|
func (e *Editor) page(index int) (*PageContent, error) {
|
||||||
|
return e.pageContext(context.Background(), index)
|
||||||
|
}
|
||||||
|
|
||||||
|
// pageContext 按索引加载内部页面并响应取消
|
||||||
|
// 入参: ctx 取消上下文, index 页面索引
|
||||||
|
// 返回: *PageContent 页面内容, error 读取或取消错误
|
||||||
|
func (e *Editor) pageContext(ctx context.Context, index int) (*PageContent, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
if index < 0 || index >= len(e.pages) {
|
if index < 0 || index >= len(e.pages) {
|
||||||
return nil, fmt.Errorf("page index %d out of range", index)
|
return nil, fmt.Errorf("page index %d out of range", index)
|
||||||
}
|
}
|
||||||
if e.source != nil {
|
if e.source != nil {
|
||||||
if err := e.loadSourcePage(index); err != nil {
|
if err := e.loadSourcePageContext(ctx, index); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -843,13 +890,8 @@ func (e *Editor) findObject(page int, id string) (*Layer, int, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, 0, err
|
return nil, 0, err
|
||||||
}
|
}
|
||||||
for i := range content.Content.Layer {
|
if position, ok := e.objectPositions(content)[id]; ok {
|
||||||
layer := &content.Content.Layer[i]
|
return &content.Content.Layer[position.layer], position.index, nil
|
||||||
for index, object := range layer.Objects {
|
|
||||||
if editorObjectID(object) == id && id != "" {
|
|
||||||
return layer, index, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return nil, 0, fmt.Errorf("object %q not found on page %d", id, page)
|
return nil, 0, fmt.Errorf("object %q not found on page %d", id, page)
|
||||||
}
|
}
|
||||||
@@ -1323,7 +1365,7 @@ func (v *editorValidation) creationPath(value string) error {
|
|||||||
// 返回: *renderCache[string, bool] 校验缓存
|
// 返回: *renderCache[string, bool] 校验缓存
|
||||||
func (e *Editor) pathValidationCache() *renderCache[string, bool] {
|
func (e *Editor) pathValidationCache() *renderCache[string, bool] {
|
||||||
if e.validatedPaths == nil {
|
if e.validatedPaths == nil {
|
||||||
e.validatedPaths = &renderCache[string, bool]{limit: 8 << 20}
|
e.validatedPaths = resourceCache[string, bool](e.runtimeResources, 8<<20)
|
||||||
}
|
}
|
||||||
return e.validatedPaths
|
return e.validatedPaths
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,10 +66,10 @@ func (e *Editor) SetDocumentActions(actions []Action) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
patch := editorXMLPatch{root.close, root.close, encoded}
|
patch := editorXMLPatch{root.close, root.close, encoded}
|
||||||
context := root
|
ctx := root
|
||||||
if node := root.child("Actions"); node != nil {
|
if node := root.child("Actions"); node != nil {
|
||||||
patch.start, patch.end = node.start, node.end
|
patch.start, patch.end = node.start, node.end
|
||||||
context = node
|
ctx = node
|
||||||
} else {
|
} else {
|
||||||
for _, child := range root.children {
|
for _, child := range root.children {
|
||||||
if child.matchesOFD(child.name.Local) && slices.Contains([]string{"VPreferences", "Bookmarks", "Annotations", "CustomTags", "Attachments", "Extensions"}, child.name.Local) {
|
if child.matchesOFD(child.name.Local) && slices.Contains([]string{"VPreferences", "Bookmarks", "Annotations", "CustomTags", "Attachments", "Extensions"}, child.name.Local) {
|
||||||
@@ -78,7 +78,7 @@ func (e *Editor) SetDocumentActions(actions []Action) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
patch.data, err = editorXMLGenerated(encoded, context.name.Space)
|
patch.data, err = editorXMLGenerated(encoded, ctx.name.Space)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -101,7 +101,7 @@ func (e *Editor) SetPageActions(index int, actions []Action) error {
|
|||||||
}
|
}
|
||||||
before, after := cloneEditorData(page.Actions), cloneEditorData(actions)
|
before, after := cloneEditorData(page.Actions), cloneEditorData(actions)
|
||||||
page.Actions = cloneEditorData(after)
|
page.Actions = cloneEditorData(after)
|
||||||
if change := e.recordChange(); change != nil {
|
if change := e.recordChange(index); change != nil {
|
||||||
change.undo = func(e *Editor) { e.pages[index].Actions = cloneEditorData(before) }
|
change.undo = func(e *Editor) { e.pages[index].Actions = cloneEditorData(before) }
|
||||||
change.redo = func(e *Editor) { e.pages[index].Actions = cloneEditorData(after) }
|
change.redo = func(e *Editor) { e.pages[index].Actions = cloneEditorData(after) }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,11 +18,23 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"encoding/xml"
|
"encoding/xml"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"maps"
|
||||||
"path"
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// AnnotationSelection 保存当前编辑器内可重复粘贴的注解原文及资源上下文
|
||||||
|
// 来源修改或删除不影响快照,不用于跨文档传输
|
||||||
|
type AnnotationSelection struct {
|
||||||
|
editor *Editor
|
||||||
|
document editorDocumentIdentity
|
||||||
|
data [][]byte
|
||||||
|
resources []string
|
||||||
|
states map[string]map[string]editorCompositeState
|
||||||
|
richText map[int]*richTextSnapshot
|
||||||
|
}
|
||||||
|
|
||||||
// Annotations 获取指定页面的注解信息,包含不可见注解,返回值与编辑器相互独立
|
// Annotations 获取指定页面的注解信息,包含不可见注解,返回值与编辑器相互独立
|
||||||
// 入参: index 页面索引
|
// 入参: index 页面索引
|
||||||
// 返回: []AnnotationInfo 注解信息, error 错误信息
|
// 返回: []AnnotationInfo 注解信息, error 错误信息
|
||||||
@@ -297,3 +309,297 @@ func (e *Editor) editAnnotations(index int, ids []string, edit func([]byte, *edi
|
|||||||
}
|
}
|
||||||
return e.commitAnnotationParts(base, parts)
|
return e.commitAnnotationParts(base, parts)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CaptureAnnotations 捕获注解选区,保留未知字段、外观及动作
|
||||||
|
// 入参: page 页面索引, ids 不重复的注解标识
|
||||||
|
// 返回: *AnnotationSelection 独立快照, error 错误信息
|
||||||
|
func (e *Editor) CaptureAnnotations(page int, ids []string) (*AnnotationSelection, error) {
|
||||||
|
content, err := e.page(page)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
selection := &AnnotationSelection{editor: e, document: e.documentIdentity(), states: make(map[string]map[string]editorCompositeState), richText: make(map[int]*richTextSnapshot)}
|
||||||
|
seen := make(map[string]bool)
|
||||||
|
for _, id := range ids {
|
||||||
|
key := editorResourceID(id)
|
||||||
|
if seen[key] {
|
||||||
|
return nil, fmt.Errorf("duplicate annotation ID %q", id)
|
||||||
|
}
|
||||||
|
seen[key] = true
|
||||||
|
data, err := e.annotationXML(page, id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
root, err := parseEditorXML(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !editorXMLCopyable(root) {
|
||||||
|
return nil, fmt.Errorf("annotation contains unsupported identifiers")
|
||||||
|
}
|
||||||
|
annotation, err := e.Annotation(page, id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
snapshot, err := e.captureRichTextSnapshot(page, GraphicObject{Type: "CompositeGraphicUnit", CompositeGraphicUnit: CompositeGraphicUnit{Objects: annotation.Appearance.Objects}})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if snapshot != nil {
|
||||||
|
selection.richText[len(selection.data)] = snapshot
|
||||||
|
}
|
||||||
|
selection.data = append(selection.data, data)
|
||||||
|
selection.states[key] = maps.Clone(e.source.annotationStates[e.pages[page].ID+"/"+key])
|
||||||
|
}
|
||||||
|
if e.originalPage(page) {
|
||||||
|
origin := e.source.pages[e.pages[page].ID]
|
||||||
|
for _, name := range content.PageRes {
|
||||||
|
selection.resources = append(selection.resources, resolveResourcePath(e.source.reader.ResPath(origin.ref.BaseLoc), "", name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return selection, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PasteAnnotations 将注解快照粘贴到指定页并平移,保留动作目标和原有外观
|
||||||
|
// 全部标识重新分配,页级资源提升为文档资源,一次操作计入一条撤销记录
|
||||||
|
// 入参: page 目标页面索引, selection 当前编辑器快照, dx 横向位移,单位为毫米, dy 纵向位移,单位为毫米
|
||||||
|
// 返回: []string 新注解标识, error 错误信息
|
||||||
|
func (e *Editor) PasteAnnotations(page int, selection *AnnotationSelection, dx, dy float64) ([]string, error) {
|
||||||
|
if selection == nil || selection.editor != e || !e.documentIdentity().matches(selection.document) || !finite(dx) || !finite(dy) {
|
||||||
|
return nil, fmt.Errorf("invalid annotation selection or offset")
|
||||||
|
}
|
||||||
|
var result []string
|
||||||
|
err := e.Transaction(func(edit *Editor) error {
|
||||||
|
if page < 0 || page >= len(edit.pages) {
|
||||||
|
return fmt.Errorf("page index %d out of range", page)
|
||||||
|
}
|
||||||
|
if len(selection.data) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err := edit.prepareSourceIDs(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var content []byte
|
||||||
|
var states map[string]map[string]editorCompositeState
|
||||||
|
if edit.source != nil {
|
||||||
|
states = maps.Clone(edit.source.annotationStates)
|
||||||
|
}
|
||||||
|
if states == nil {
|
||||||
|
states = make(map[string]map[string]editorCompositeState)
|
||||||
|
}
|
||||||
|
for _, data := range selection.data {
|
||||||
|
root, err := parseEditorXML(data)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ids := make(map[string]string)
|
||||||
|
if err := edit.collectCompositeIDs(root, ids); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
id := ids[editorResourceID(root.attr("ID"))]
|
||||||
|
states[edit.pages[page].ID+"/"+id] = remapCompositeStates(selection.states[editorResourceID(root.attr("ID"))], ids)
|
||||||
|
data, err = editorXMLRemapIDs(data, root, ids)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
root, err = parseEditorXML(data)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
appearance := root.child("Appearance")
|
||||||
|
if appearance == nil {
|
||||||
|
return fmt.Errorf("annotation has no appearance")
|
||||||
|
}
|
||||||
|
box, err := ParseBox(appearance.attr("Boundary"))
|
||||||
|
if err != nil || !finite(box.X+dx) || !finite(box.Y+dy) {
|
||||||
|
return fmt.Errorf("invalid annotation boundary")
|
||||||
|
}
|
||||||
|
box.X, box.Y = box.X+dx, box.Y+dy
|
||||||
|
fragment, err := editorXMLAttribute(data, appearance, "Boundary", editorBoxString(box))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
data, err = editorAnnotationDate(editorPatchXML(data, []editorXMLPatch{{appearance.start, appearance.end, fragment}}))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
content = append(content, bytes.TrimPrefix(data, []byte(xml.Header))...)
|
||||||
|
result = append(result, id)
|
||||||
|
}
|
||||||
|
if err := edit.appendAnnotations(page, content, false); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
edit.source.annotationStates = states
|
||||||
|
if len(selection.resources) != 0 {
|
||||||
|
reader := edit.source.reader
|
||||||
|
name := reader.documentRoot
|
||||||
|
data, err := reader.readFile(name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
root, err := parseEditorXML(data)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
common := root.child("CommonData")
|
||||||
|
registered := make(map[string]bool)
|
||||||
|
for _, name := range edit.source.document.CommonData.PublicRes {
|
||||||
|
registered[reader.ResPath(name)] = true
|
||||||
|
}
|
||||||
|
for _, name := range edit.source.document.CommonData.DocumentRes {
|
||||||
|
registered[reader.ResPath(name)] = true
|
||||||
|
}
|
||||||
|
var added []byte
|
||||||
|
for _, name := range selection.resources {
|
||||||
|
if !registered[name] {
|
||||||
|
added = append(added, common.textXML("DocumentRes", "/"+name)...)
|
||||||
|
registered[name] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(added) != 0 {
|
||||||
|
position := common.close
|
||||||
|
for _, node := range common.children {
|
||||||
|
if node.name.Local == "TemplatePage" || node.name.Local == "DefaultCS" {
|
||||||
|
position = node.start
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := edit.commitAnnotationParts(edit.source, map[string][]byte{name: editorPatchXML(data, []editorXMLPatch{{position, position, added}})}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i, id := range result {
|
||||||
|
if snapshot := selection.richText[i]; snapshot != nil {
|
||||||
|
annotation, err := edit.Annotation(page, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := edit.putRichTextSnapshot(page, GraphicObject{Type: "CompositeGraphicUnit", CompositeGraphicUnit: CompositeGraphicUnit{Objects: annotation.Appearance.Objects}}, snapshot); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TransformAnnotations 对注解选区施加页面仿射变换,保持内部图元与外观边界同步
|
||||||
|
// 入参: page 页面索引, ids 注解标识, matrix 可逆页面变换
|
||||||
|
// 返回: error 错误信息
|
||||||
|
func (e *Editor) TransformAnnotations(page int, ids []string, matrix Matrix) error {
|
||||||
|
if _, ok := matrix.Invert(); !ok {
|
||||||
|
return fmt.Errorf("annotation transform must be finite and invertible")
|
||||||
|
}
|
||||||
|
return e.Transaction(func(edit *Editor) error {
|
||||||
|
seen := make(map[string]bool)
|
||||||
|
for _, id := range ids {
|
||||||
|
if seen[id] {
|
||||||
|
return fmt.Errorf("duplicate annotation ID %q", id)
|
||||||
|
}
|
||||||
|
seen[id] = true
|
||||||
|
annotation, err := edit.Annotation(page, id)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if matrix == IdentityMatrix {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
box, err := ParseBox(annotation.Appearance.Boundary)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
bounds := matrix.TransformBox(box)
|
||||||
|
if !finite(bounds.X) || !finite(bounds.Y) || !finite(bounds.W) || !finite(bounds.H) || bounds.W < 0 || bounds.H < 0 {
|
||||||
|
return fmt.Errorf("annotation transform exceeds finite range")
|
||||||
|
}
|
||||||
|
path := ObjectPath{Annotation: id}
|
||||||
|
reader, _, _, members, err := edit.compositeScope(page, path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
reader.Close()
|
||||||
|
indexes := make([]int, len(members))
|
||||||
|
for i := range indexes {
|
||||||
|
indexes[i] = i
|
||||||
|
}
|
||||||
|
local := TranslationMatrix(box.X-bounds.X, box.Y-bounds.Y).Multiply(matrix)
|
||||||
|
if err := edit.changeCompositeObjects(page, path, indexes, func(Box) Matrix { return local }); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := edit.editAnnotations(page, []string{id}, func(data []byte, node *editorXML) ([]byte, error) {
|
||||||
|
fragment, err := editorXMLStandalone(data[node.start:node.end], node)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
root, err := parseEditorXML(fragment)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
appearance := root.child("Appearance")
|
||||||
|
updated, err := editorXMLAttribute(fragment, appearance, "Boundary", editorBoxString(bounds))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return editorAnnotationDate(editorPatchXML(fragment, []editorXMLPatch{{appearance.start, appearance.end, updated}}))
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReplaceAnnotationText 修改注解内部匹配的普通文字,保留各成员位置、旋转及未修改属性
|
||||||
|
// 入参: page 页面索引, id 注解标识, old 原文字, value 新文字, style 文字样式增量
|
||||||
|
// 返回: int 修改数量, error 错误信息
|
||||||
|
func (e *Editor) ReplaceAnnotationText(page int, id, old, value string, style TextStyle) (int, error) {
|
||||||
|
count := 0
|
||||||
|
err := e.Transaction(func(edit *Editor) error {
|
||||||
|
return edit.editCompositeScope(page, ObjectPath{Annotation: id}, func(renderer *Renderer, _ *editorCompositeNode, nodes []*editorCompositeNode) error {
|
||||||
|
visiting := make(map[string]bool)
|
||||||
|
var replace func([]*editorCompositeNode) error
|
||||||
|
replace = func(nodes []*editorCompositeNode) error {
|
||||||
|
members, err := edit.measureCompositeMembers(renderer, nodes)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for i, member := range members {
|
||||||
|
if member.Object.Type == "TextObject" && member.Object.TextObject.Text() == old {
|
||||||
|
if err := edit.updateCompositeText(nodes[i], member, &value, style, nil, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
count++
|
||||||
|
} else if member.Object.Type == "CompositeObject" || member.Object.Type == "CompositeGraphicUnit" {
|
||||||
|
resource := member.Object.CompositeGraphicUnit.ResourceID
|
||||||
|
if id := editorResourceID(resource); id != "" {
|
||||||
|
resource = id
|
||||||
|
}
|
||||||
|
if resource != "" && visiting[resource] {
|
||||||
|
return fmt.Errorf("cyclic composite resource %q", resource)
|
||||||
|
}
|
||||||
|
children, err := edit.compositeMembers(nodes[i], renderer.Reader, renderer, visiting)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
visiting[resource] = true
|
||||||
|
if err := replace(children); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
delete(visiting, resource)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return replace(nodes)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return count, nil
|
||||||
|
}
|
||||||
@@ -163,7 +163,7 @@ func (e *Editor) AnnotationTexts(index int, id string) ([]string, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
reader, err := e.Reader()
|
reader, err := e.reader(nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -548,7 +548,7 @@ func (e *Editor) annotationScope(page int, path ObjectPath) (*Reader, *Renderer,
|
|||||||
return nil, nil, nil, nil, err
|
return nil, nil, nil, nil, err
|
||||||
}
|
}
|
||||||
root.setStates(e.source.annotationStates[e.pages[page].ID+"/"+editorResourceID(path.Annotation)])
|
root.setStates(e.source.annotationStates[e.pages[page].ID+"/"+editorResourceID(path.Annotation)])
|
||||||
reader, err := e.Reader()
|
reader, err := e.reader(nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, nil, nil, err
|
return nil, nil, nil, nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,302 +0,0 @@
|
|||||||
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
package ofdgo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/xml"
|
|
||||||
"fmt"
|
|
||||||
"maps"
|
|
||||||
)
|
|
||||||
|
|
||||||
// AnnotationSelection 保存当前编辑器内可重复粘贴的注解原文及资源上下文
|
|
||||||
// 来源修改或删除不影响快照,不用于跨文档传输
|
|
||||||
type AnnotationSelection struct {
|
|
||||||
editor *Editor
|
|
||||||
document editorDocumentIdentity
|
|
||||||
data [][]byte
|
|
||||||
resources []string
|
|
||||||
states map[string]map[string]editorCompositeState
|
|
||||||
}
|
|
||||||
|
|
||||||
// CaptureAnnotations 捕获注解选区,保留未知字段、外观及动作
|
|
||||||
// 入参: page 页面索引, ids 不重复的注解标识
|
|
||||||
// 返回: *AnnotationSelection 独立快照, error 错误信息
|
|
||||||
func (e *Editor) CaptureAnnotations(page int, ids []string) (*AnnotationSelection, error) {
|
|
||||||
content, err := e.page(page)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
selection := &AnnotationSelection{editor: e, document: e.documentIdentity(), states: make(map[string]map[string]editorCompositeState)}
|
|
||||||
seen := make(map[string]bool)
|
|
||||||
for _, id := range ids {
|
|
||||||
key := editorResourceID(id)
|
|
||||||
if seen[key] {
|
|
||||||
return nil, fmt.Errorf("duplicate annotation ID %q", id)
|
|
||||||
}
|
|
||||||
seen[key] = true
|
|
||||||
data, err := e.annotationXML(page, id)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
root, err := parseEditorXML(data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if !editorXMLCopyable(root) {
|
|
||||||
return nil, fmt.Errorf("annotation contains unsupported identifiers")
|
|
||||||
}
|
|
||||||
selection.data = append(selection.data, data)
|
|
||||||
selection.states[key] = maps.Clone(e.source.annotationStates[e.pages[page].ID+"/"+key])
|
|
||||||
}
|
|
||||||
if e.originalPage(page) {
|
|
||||||
origin := e.source.pages[e.pages[page].ID]
|
|
||||||
for _, name := range content.PageRes {
|
|
||||||
selection.resources = append(selection.resources, resolveResourcePath(e.source.reader.ResPath(origin.ref.BaseLoc), "", name))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return selection, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// PasteAnnotations 将注解快照粘贴到指定页并平移,保留动作目标和原有外观
|
|
||||||
// 全部标识重新分配,页级资源提升为文档资源,一次操作计入一条撤销记录
|
|
||||||
// 入参: page 目标页面索引, selection 当前编辑器快照, dx 横向位移,单位为毫米, dy 纵向位移,单位为毫米
|
|
||||||
// 返回: []string 新注解标识, error 错误信息
|
|
||||||
func (e *Editor) PasteAnnotations(page int, selection *AnnotationSelection, dx, dy float64) ([]string, error) {
|
|
||||||
if selection == nil || selection.editor != e || !e.documentIdentity().matches(selection.document) || !finite(dx) || !finite(dy) {
|
|
||||||
return nil, fmt.Errorf("invalid annotation selection or offset")
|
|
||||||
}
|
|
||||||
var result []string
|
|
||||||
err := e.Transaction(func(edit *Editor) error {
|
|
||||||
if page < 0 || page >= len(edit.pages) {
|
|
||||||
return fmt.Errorf("page index %d out of range", page)
|
|
||||||
}
|
|
||||||
if len(selection.data) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if err := edit.prepareSourceIDs(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var content []byte
|
|
||||||
var states map[string]map[string]editorCompositeState
|
|
||||||
if edit.source != nil {
|
|
||||||
states = maps.Clone(edit.source.annotationStates)
|
|
||||||
}
|
|
||||||
if states == nil {
|
|
||||||
states = make(map[string]map[string]editorCompositeState)
|
|
||||||
}
|
|
||||||
for _, data := range selection.data {
|
|
||||||
root, err := parseEditorXML(data)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
ids := make(map[string]string)
|
|
||||||
if err := edit.collectCompositeIDs(root, ids); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
id := ids[editorResourceID(root.attr("ID"))]
|
|
||||||
states[edit.pages[page].ID+"/"+id] = remapCompositeStates(selection.states[editorResourceID(root.attr("ID"))], ids)
|
|
||||||
data, err = editorXMLRemapIDs(data, root, ids)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
root, err = parseEditorXML(data)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
appearance := root.child("Appearance")
|
|
||||||
if appearance == nil {
|
|
||||||
return fmt.Errorf("annotation has no appearance")
|
|
||||||
}
|
|
||||||
box, err := ParseBox(appearance.attr("Boundary"))
|
|
||||||
if err != nil || !finite(box.X+dx) || !finite(box.Y+dy) {
|
|
||||||
return fmt.Errorf("invalid annotation boundary")
|
|
||||||
}
|
|
||||||
box.X, box.Y = box.X+dx, box.Y+dy
|
|
||||||
fragment, err := editorXMLAttribute(data, appearance, "Boundary", editorBoxString(box))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
data, err = editorAnnotationDate(editorPatchXML(data, []editorXMLPatch{{appearance.start, appearance.end, fragment}}))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
content = append(content, bytes.TrimPrefix(data, []byte(xml.Header))...)
|
|
||||||
result = append(result, id)
|
|
||||||
}
|
|
||||||
if err := edit.appendAnnotations(page, content, false); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
edit.source.annotationStates = states
|
|
||||||
if len(selection.resources) != 0 {
|
|
||||||
reader := edit.source.reader
|
|
||||||
name := reader.documentRoot
|
|
||||||
data, err := reader.readFile(name)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
root, err := parseEditorXML(data)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
common := root.child("CommonData")
|
|
||||||
registered := make(map[string]bool)
|
|
||||||
for _, name := range edit.source.document.CommonData.PublicRes {
|
|
||||||
registered[reader.ResPath(name)] = true
|
|
||||||
}
|
|
||||||
for _, name := range edit.source.document.CommonData.DocumentRes {
|
|
||||||
registered[reader.ResPath(name)] = true
|
|
||||||
}
|
|
||||||
var added []byte
|
|
||||||
for _, name := range selection.resources {
|
|
||||||
if !registered[name] {
|
|
||||||
added = append(added, common.textXML("DocumentRes", "/"+name)...)
|
|
||||||
registered[name] = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(added) != 0 {
|
|
||||||
position := common.close
|
|
||||||
for _, node := range common.children {
|
|
||||||
if node.name.Local == "TemplatePage" || node.name.Local == "DefaultCS" {
|
|
||||||
position = node.start
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return edit.commitAnnotationParts(edit.source, map[string][]byte{name: editorPatchXML(data, []editorXMLPatch{{position, position, added}})})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// TransformAnnotations 对注解选区施加页面仿射变换,保持内部图元与外观边界同步
|
|
||||||
// 入参: page 页面索引, ids 注解标识, matrix 可逆页面变换
|
|
||||||
// 返回: error 错误信息
|
|
||||||
func (e *Editor) TransformAnnotations(page int, ids []string, matrix Matrix) error {
|
|
||||||
if _, ok := matrix.Invert(); !ok {
|
|
||||||
return fmt.Errorf("annotation transform must be finite and invertible")
|
|
||||||
}
|
|
||||||
return e.Transaction(func(edit *Editor) error {
|
|
||||||
seen := make(map[string]bool)
|
|
||||||
for _, id := range ids {
|
|
||||||
if seen[id] {
|
|
||||||
return fmt.Errorf("duplicate annotation ID %q", id)
|
|
||||||
}
|
|
||||||
seen[id] = true
|
|
||||||
annotation, err := edit.Annotation(page, id)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if matrix == IdentityMatrix {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
box, err := ParseBox(annotation.Appearance.Boundary)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
bounds := matrix.TransformBox(box)
|
|
||||||
if !finite(bounds.X) || !finite(bounds.Y) || !finite(bounds.W) || !finite(bounds.H) || bounds.W < 0 || bounds.H < 0 {
|
|
||||||
return fmt.Errorf("annotation transform exceeds finite range")
|
|
||||||
}
|
|
||||||
path := ObjectPath{Annotation: id}
|
|
||||||
reader, _, _, members, err := edit.compositeScope(page, path)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
reader.Close()
|
|
||||||
indexes := make([]int, len(members))
|
|
||||||
for i := range indexes {
|
|
||||||
indexes[i] = i
|
|
||||||
}
|
|
||||||
local := TranslationMatrix(box.X-bounds.X, box.Y-bounds.Y).Multiply(matrix)
|
|
||||||
if err := edit.changeCompositeObjects(page, path, indexes, func(Box) Matrix { return local }); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := edit.editAnnotations(page, []string{id}, func(data []byte, node *editorXML) ([]byte, error) {
|
|
||||||
fragment, err := editorXMLStandalone(data[node.start:node.end], node)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
root, err := parseEditorXML(fragment)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
appearance := root.child("Appearance")
|
|
||||||
updated, err := editorXMLAttribute(fragment, appearance, "Boundary", editorBoxString(bounds))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return editorAnnotationDate(editorPatchXML(fragment, []editorXMLPatch{{appearance.start, appearance.end, updated}}))
|
|
||||||
}); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ReplaceAnnotationText 修改注解内部匹配的普通文字,保留各成员位置、旋转及未修改属性
|
|
||||||
// 入参: page 页面索引, id 注解标识, old 原文字, value 新文字, style 文字样式增量
|
|
||||||
// 返回: int 修改数量, error 错误信息
|
|
||||||
func (e *Editor) ReplaceAnnotationText(page int, id, old, value string, style TextStyle) (int, error) {
|
|
||||||
count := 0
|
|
||||||
err := e.Transaction(func(edit *Editor) error {
|
|
||||||
return edit.editCompositeScope(page, ObjectPath{Annotation: id}, func(renderer *Renderer, _ *editorCompositeNode, nodes []*editorCompositeNode) error {
|
|
||||||
visiting := make(map[string]bool)
|
|
||||||
var replace func([]*editorCompositeNode) error
|
|
||||||
replace = func(nodes []*editorCompositeNode) error {
|
|
||||||
members, err := edit.measureCompositeMembers(renderer, nodes)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
for i, member := range members {
|
|
||||||
if member.Object.Type == "TextObject" && member.Object.TextObject.Text() == old {
|
|
||||||
if err := edit.updateCompositeText(nodes[i], member, &value, style, nil, nil); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
count++
|
|
||||||
} else if member.Object.Type == "CompositeObject" || member.Object.Type == "CompositeGraphicUnit" {
|
|
||||||
resource := member.Object.CompositeGraphicUnit.ResourceID
|
|
||||||
if id := editorResourceID(resource); id != "" {
|
|
||||||
resource = id
|
|
||||||
}
|
|
||||||
if resource != "" && visiting[resource] {
|
|
||||||
return fmt.Errorf("cyclic composite resource %q", resource)
|
|
||||||
}
|
|
||||||
children, err := edit.compositeMembers(nodes[i], renderer.Reader, renderer, visiting)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
visiting[resource] = true
|
|
||||||
if err := replace(children); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
delete(visiting, resource)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return replace(nodes)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return count, nil
|
|
||||||
}
|
|
||||||
+59
-25
@@ -30,6 +30,36 @@ type editorObjectPosition struct {
|
|||||||
index int
|
index int
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// editorObjectIndex 复用最近页面的只读对象位置,图层容器替换后重新建立
|
||||||
|
type editorObjectIndex struct {
|
||||||
|
layers []Layer
|
||||||
|
positions map[string]editorObjectPosition
|
||||||
|
}
|
||||||
|
|
||||||
|
// objectPositions 获取页面的对象位置索引,重复编号保留第一个匹配
|
||||||
|
// 入参: page 内部只读页面
|
||||||
|
// 返回: map[string]editorObjectPosition 只读索引
|
||||||
|
func (e *Editor) objectPositions(page *PageContent) map[string]editorObjectPosition {
|
||||||
|
layers := page.Content.Layer
|
||||||
|
if len(layers) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if cached := e.objectIndex; cached != nil && len(cached.layers) == len(layers) && &cached.layers[0] == &layers[0] {
|
||||||
|
return cached.positions
|
||||||
|
}
|
||||||
|
positions := make(map[string]editorObjectPosition)
|
||||||
|
for i, layer := range layers {
|
||||||
|
for j, object := range layer.Objects {
|
||||||
|
id := editorObjectID(object)
|
||||||
|
if _, exists := positions[id]; id != "" && !exists {
|
||||||
|
positions[id] = editorObjectPosition{i, j}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e.objectIndex = &editorObjectIndex{layers: layers, positions: positions}
|
||||||
|
return positions
|
||||||
|
}
|
||||||
|
|
||||||
// ObjectPosition 对象在图层或页块直接成员中的位置,Index从0开始,Count不含嵌套页块的对象
|
// ObjectPosition 对象在图层或页块直接成员中的位置,Index从0开始,Count不含嵌套页块的对象
|
||||||
type ObjectPosition struct {
|
type ObjectPosition struct {
|
||||||
Layer string
|
Layer string
|
||||||
@@ -66,7 +96,9 @@ func (e *Editor) Objects(page int, ids []string) ([]GraphicObject, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
objects[i].origin = e.objectOrigin(editorObjectID(object))
|
objects[i].origin = e.objectOrigin(editorObjectID(object))
|
||||||
e.attachRichTextSnapshot(page, &objects[i])
|
if err := e.attachRichTextSnapshot(page, &objects[i]); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return objects, nil
|
return objects, nil
|
||||||
}
|
}
|
||||||
@@ -105,7 +137,11 @@ func (e *Editor) CopyObjectsContext(ctx context.Context, page int, objects []Gra
|
|||||||
if err := ctx.Err(); err != nil {
|
if err := ctx.Err(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err := e.putRichTextMetadata(page, ids[i], meta, -1); err != nil {
|
object, err := e.Object(page, ids[i])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := e.putRichTextSnapshot(page, object, meta); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -709,7 +745,7 @@ func (e *Editor) replaceLayers(page int, layers []Layer) {
|
|||||||
func (e *Editor) replacePreparedLayers(page int, after []Layer) {
|
func (e *Editor) replacePreparedLayers(page int, after []Layer) {
|
||||||
if e.historyLimit == 0 {
|
if e.historyLimit == 0 {
|
||||||
e.pages[page].Content.Layer = after
|
e.pages[page].Content.Layer = after
|
||||||
e.recordChange()
|
e.recordChange(page)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
before := copyEditorPage(e.pages[page])
|
before := copyEditorPage(e.pages[page])
|
||||||
@@ -738,7 +774,7 @@ func (e *Editor) replacePreparedLayers(page int, after []Layer) {
|
|||||||
e.pages[page].Content.Layer = copyEditorPage(PageContent{Content: Content{Layer: layers}}).Content.Layer
|
e.pages[page].Content.Layer = copyEditorPage(PageContent{Content: Content{Layer: layers}}).Content.Layer
|
||||||
}
|
}
|
||||||
apply(e, after)
|
apply(e, after)
|
||||||
if change := e.recordChange(); change != nil {
|
if change := e.recordChange(page); change != nil {
|
||||||
change.undo = func(e *Editor) { apply(e, before.Content.Layer) }
|
change.undo = func(e *Editor) { apply(e, before.Content.Layer) }
|
||||||
change.redo = func(e *Editor) { apply(e, after) }
|
change.redo = func(e *Editor) { apply(e, after) }
|
||||||
}
|
}
|
||||||
@@ -835,6 +871,15 @@ func (e *Editor) updateObjectOrigins(page int, objects []GraphicObject, preserve
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
apply := func(e *Editor, objects []GraphicObject, origins map[string]*editorObjectOrigin) {
|
apply := func(e *Editor, objects []GraphicObject, origins map[string]*editorObjectOrigin) {
|
||||||
|
layers := slices.Clone(e.pages[page].Content.Layer)
|
||||||
|
cloned := make(map[int]bool)
|
||||||
|
for _, index := range indexes {
|
||||||
|
if !cloned[index.layer] {
|
||||||
|
layers[index.layer].Objects = slices.Clone(layers[index.layer].Objects)
|
||||||
|
cloned[index.layer] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e.pages[page].Content.Layer = layers
|
||||||
for i, index := range indexes {
|
for i, index := range indexes {
|
||||||
e.pages[page].Content.Layer[index.layer].Objects[index.index] = objects[i]
|
e.pages[page].Content.Layer[index.layer].Objects[index.index] = objects[i]
|
||||||
}
|
}
|
||||||
@@ -843,7 +888,7 @@ func (e *Editor) updateObjectOrigins(page int, objects []GraphicObject, preserve
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
apply(e, after, afterOrigins)
|
apply(e, after, afterOrigins)
|
||||||
if change := e.recordChange(); change != nil {
|
if change := e.recordChange(page); change != nil {
|
||||||
change.undo = func(e *Editor) { apply(e, before, beforeOrigins) }
|
change.undo = func(e *Editor) { apply(e, before, beforeOrigins) }
|
||||||
change.redo = func(e *Editor) { apply(e, after, afterOrigins) }
|
change.redo = func(e *Editor) { apply(e, after, afterOrigins) }
|
||||||
}
|
}
|
||||||
@@ -891,30 +936,19 @@ func (e *Editor) selectedObjects(page int, ids []string) ([]GraphicObject, []edi
|
|||||||
if len(ids) == 0 {
|
if len(ids) == 0 {
|
||||||
return objects, indexes, nil
|
return objects, indexes, nil
|
||||||
}
|
}
|
||||||
selected := make(map[string]int, len(ids))
|
positions := e.objectPositions(content)
|
||||||
|
selected := make(map[string]bool, len(ids))
|
||||||
for i, id := range ids {
|
for i, id := range ids {
|
||||||
if _, exists := selected[id]; exists {
|
if selected[id] {
|
||||||
return nil, nil, fmt.Errorf("duplicate object %q", id)
|
return nil, nil, fmt.Errorf("duplicate object %q", id)
|
||||||
}
|
}
|
||||||
selected[id] = i
|
selected[id] = true
|
||||||
}
|
position, ok := positions[id]
|
||||||
for i, layer := range content.Content.Layer {
|
if !ok {
|
||||||
for j, object := range layer.Objects {
|
|
||||||
id := editorObjectID(object)
|
|
||||||
if index, ok := selected[id]; ok && id != "" {
|
|
||||||
objects[index] = object
|
|
||||||
indexes[index] = editorObjectPosition{i, j}
|
|
||||||
delete(selected, id)
|
|
||||||
if len(selected) == 0 {
|
|
||||||
return objects, indexes, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, id := range ids {
|
|
||||||
if _, missing := selected[id]; missing {
|
|
||||||
return nil, nil, fmt.Errorf("object %q not found on page %d", id, page)
|
return nil, nil, fmt.Errorf("object %q not found on page %d", id, page)
|
||||||
}
|
}
|
||||||
|
indexes[i] = position
|
||||||
|
objects[i] = content.Content.Layer[position.layer].Objects[position.index]
|
||||||
}
|
}
|
||||||
return objects, indexes, nil
|
return objects, indexes, nil
|
||||||
}
|
}
|
||||||
@@ -947,7 +981,7 @@ func (e *Editor) objectBounds(page int, objects []GraphicObject) ([]Box, error)
|
|||||||
return nil, fmt.Errorf("object %q cannot be arranged: %w", editorObjectID(object), capability.editError())
|
return nil, fmt.Errorf("object %q cannot be arranged: %w", editorObjectID(object), capability.editError())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
reader, err := e.Reader()
|
reader, err := e.reader(nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -396,19 +396,19 @@ func editorBookmarkDefinition(data []byte, name string, next *Bookmark, add bool
|
|||||||
}
|
}
|
||||||
container := root.child("Bookmarks")
|
container := root.child("Bookmarks")
|
||||||
if add {
|
if add {
|
||||||
context := container
|
ctx := container
|
||||||
if context == nil {
|
if ctx == nil {
|
||||||
context = root
|
ctx = root
|
||||||
}
|
}
|
||||||
attrs, err := next.Dest.attributes()
|
attrs, err := next.Dest.attributes()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
dest, err := context.containerXML("Dest", attrs, nil)
|
dest, err := ctx.containerXML("Dest", attrs, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
item, err := context.containerXML("Bookmark", ofdAttrs{{Name: xml.Name{Local: "Name"}, Value: next.Name}}, dest)
|
item, err := ctx.containerXML("Bookmark", ofdAttrs{{Name: xml.Name{Local: "Name"}, Value: next.Name}}, dest)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,123 +0,0 @@
|
|||||||
// Copyright 2025-2026 肖其顿 (XIAO QI DUN)
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
package ofdgo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"reflect"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
// editorClonePlans 仅共享类型的可变字段索引,不持有文档对象或资源
|
|
||||||
var editorClonePlans sync.Map
|
|
||||||
|
|
||||||
// cloneEditorData 深复制编辑快照,未导出的排版及原文来源保持不可变共享
|
|
||||||
// 入参: value 原值
|
|
||||||
// 返回: T 独立副本
|
|
||||||
func cloneEditorData[T any](value T) T {
|
|
||||||
source := reflect.ValueOf(value)
|
|
||||||
if !source.IsValid() {
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
return cloneEditorValue(source).Interface().(T)
|
|
||||||
}
|
|
||||||
|
|
||||||
// cloneEditorValue 复制公开指针、切片及数组,纯值数据不创建额外结构
|
|
||||||
// 入参: value 原值
|
|
||||||
// 返回: reflect.Value 独立副本
|
|
||||||
func cloneEditorValue(value reflect.Value) reflect.Value {
|
|
||||||
if !value.IsValid() || !editorCloneMutable(value.Type()) {
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
switch value.Kind() {
|
|
||||||
case reflect.Pointer:
|
|
||||||
if value.IsNil() {
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
result := reflect.New(value.Type().Elem())
|
|
||||||
cloneEditorInto(result.Elem(), value.Elem())
|
|
||||||
return result
|
|
||||||
case reflect.Slice:
|
|
||||||
if value.IsNil() {
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
result := reflect.MakeSlice(value.Type(), value.Len(), value.Len())
|
|
||||||
if !editorCloneMutable(value.Type().Elem()) {
|
|
||||||
reflect.Copy(result, value)
|
|
||||||
} else {
|
|
||||||
for i := range value.Len() {
|
|
||||||
cloneEditorInto(result.Index(i), value.Index(i))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
default:
|
|
||||||
result := reflect.New(value.Type()).Elem()
|
|
||||||
cloneEditorInto(result, value)
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// cloneEditorInto 直接填充目标结构,避免指针及切片成员的二次结构分配
|
|
||||||
// 入参: target 可写目标, source 原值
|
|
||||||
func cloneEditorInto(target, source reflect.Value) {
|
|
||||||
switch source.Kind() {
|
|
||||||
case reflect.Struct:
|
|
||||||
target.Set(source)
|
|
||||||
for _, i := range editorCloneFields(source.Type()) {
|
|
||||||
cloneEditorInto(target.Field(i), source.Field(i))
|
|
||||||
}
|
|
||||||
case reflect.Array:
|
|
||||||
target.Set(source)
|
|
||||||
if editorCloneMutable(source.Type().Elem()) {
|
|
||||||
for i := range source.Len() {
|
|
||||||
cloneEditorInto(target.Index(i), source.Index(i))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
target.Set(cloneEditorValue(source))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// editorCloneMutable 判断类型是否含有需要隔离的公开可变成员
|
|
||||||
// 入参: kind 数据类型
|
|
||||||
// 返回: bool 是否需要独立复制
|
|
||||||
func editorCloneMutable(kind reflect.Type) bool {
|
|
||||||
switch kind.Kind() {
|
|
||||||
case reflect.Pointer, reflect.Slice:
|
|
||||||
return true
|
|
||||||
case reflect.Array:
|
|
||||||
return editorCloneMutable(kind.Elem())
|
|
||||||
case reflect.Struct:
|
|
||||||
return len(editorCloneFields(kind)) != 0
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// editorCloneFields 按类型复用公开可变字段,索引发布后保持只读
|
|
||||||
// 入参: kind 结构类型
|
|
||||||
// 返回: []int 可变字段索引
|
|
||||||
func editorCloneFields(kind reflect.Type) []int {
|
|
||||||
if cached, ok := editorClonePlans.Load(kind); ok {
|
|
||||||
return cached.([]int)
|
|
||||||
}
|
|
||||||
var fields []int
|
|
||||||
for i := range kind.NumField() {
|
|
||||||
field := kind.Field(i)
|
|
||||||
if field.IsExported() && editorCloneMutable(field.Type) {
|
|
||||||
fields = append(fields, i)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
actual, _ := editorClonePlans.LoadOrStore(kind, fields)
|
|
||||||
return actual.([]int)
|
|
||||||
}
|
|
||||||
@@ -119,6 +119,13 @@ func (e *Editor) CompositeObjectsAt(page int, path ObjectPath, indexes []int) ([
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer reader.Close()
|
defer reader.Close()
|
||||||
|
return e.measureCompositeSelection(renderer, nodes, indexes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// measureCompositeSelection 复用已解析范围,按输入索引度量成员并保留容器位置
|
||||||
|
// 入参: renderer 资源渲染器, nodes 范围内全部成员, indexes 不重复的成员序号
|
||||||
|
// 返回: []CompositeMember 独立成员快照, error 索引或度量错误
|
||||||
|
func (e *Editor) measureCompositeSelection(renderer *Renderer, nodes []*editorCompositeNode, indexes []int) ([]CompositeMember, error) {
|
||||||
selected := make([]*editorCompositeNode, len(indexes))
|
selected := make([]*editorCompositeNode, len(indexes))
|
||||||
seen := make(map[int]bool, len(indexes))
|
seen := make(map[int]bool, len(indexes))
|
||||||
for i, index := range indexes {
|
for i, index := range indexes {
|
||||||
@@ -327,7 +334,9 @@ func (n *editorCompositeNode) setStates(states map[string]editorCompositeState)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
visit(n.node)
|
visit(n.node)
|
||||||
n.object.TextObject.layout = n.states[editorObjectID(n.object)].layout
|
if state, ok := n.states[editorObjectID(n.object)]; ok {
|
||||||
|
n.object.TextObject.layout = state.layout
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// setState 替换当前对象的会话记录并计入本次事务
|
// setState 替换当前对象的会话记录并计入本次事务
|
||||||
@@ -411,8 +420,9 @@ func (e *Editor) compositeScope(page int, path ObjectPath) (*Reader, *Renderer,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, nil, nil, err
|
return nil, nil, nil, nil, err
|
||||||
}
|
}
|
||||||
|
root.node.parent = &editorXML{name: xml.Name{Local: "Layer"}, attrs: []xml.Attr{{Name: xml.Name{Local: "ID"}, Value: layer.ID}, {Name: xml.Name{Local: "DrawParam"}, Value: layer.DrawParam}}, parent: &editorXML{name: xml.Name{Local: "Content"}}}
|
||||||
root.setStates(object.CompositeGraphicUnit.states)
|
root.setStates(object.CompositeGraphicUnit.states)
|
||||||
reader, err := e.Reader()
|
reader, err := e.reader(nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, nil, nil, err
|
return nil, nil, nil, nil, err
|
||||||
}
|
}
|
||||||
@@ -841,6 +851,7 @@ func (e *Editor) editCompositeScope(page int, path ObjectPath, edit func(*Render
|
|||||||
next.setStates(root.states)
|
next.setStates(root.states)
|
||||||
next.object.CompositeGraphicUnit.states = next.states
|
next.object.CompositeGraphicUnit.states = next.states
|
||||||
origin := e.objectOrigin(path.ID)
|
origin := e.objectOrigin(path.ID)
|
||||||
|
next.node.parent = root.node.parent
|
||||||
updated := &editorObjectOrigin{data: data, node: next.node, object: next.object}
|
updated := &editorObjectOrigin{data: data, node: next.node, object: next.object}
|
||||||
if origin != nil {
|
if origin != nil {
|
||||||
next.node.parent = origin.node.parent
|
next.node.parent = origin.node.parent
|
||||||
|
|||||||
@@ -18,9 +18,10 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"encoding/xml"
|
"encoding/xml"
|
||||||
"fmt"
|
"fmt"
|
||||||
basegeom "github.com/xiaoqidun/ofdgo/internal/base/geom"
|
|
||||||
"maps"
|
"maps"
|
||||||
"slices"
|
"slices"
|
||||||
|
|
||||||
|
basegeom "github.com/xiaoqidun/ofdgo/internal/base/geom"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CompositeSelection 同一内部容器的独立选区快照,共享不可变字体和图片资源
|
// CompositeSelection 同一内部容器的独立选区快照,共享不可变字体和图片资源
|
||||||
@@ -35,6 +36,7 @@ type CompositeSelection struct {
|
|||||||
containers []int
|
containers []int
|
||||||
nodes []*editorCompositeNode
|
nodes []*editorCompositeNode
|
||||||
source *editorSourcePage
|
source *editorSourcePage
|
||||||
|
richText map[int]*richTextSnapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
// PasteCompositeSelection 将内部对象快照粘贴到页面顶层,保持嵌套结构、源继承外观和裁剪
|
// PasteCompositeSelection 将内部对象快照粘贴到页面顶层,保持嵌套结构、源继承外观和裁剪
|
||||||
@@ -72,9 +74,11 @@ func (e *Editor) CaptureCompositeObjects(page int, path ObjectPath, indexes []in
|
|||||||
slices.Sort(indexes)
|
slices.Sort(indexes)
|
||||||
var owner *editorCompositeNode
|
var owner *editorCompositeNode
|
||||||
var container *editorXML
|
var container *editorXML
|
||||||
selection := &CompositeSelection{editor: e, document: e.documentIdentity(), page: e.pages[page].ID, path: ObjectPath{ID: path.ID, Annotation: path.Annotation, Children: slices.Clone(path.Children)}}
|
selection := &CompositeSelection{richText: make(map[int]*richTextSnapshot), editor: e, document: e.documentIdentity(), page: e.pages[page].ID, path: ObjectPath{ID: path.ID, Annotation: path.Annotation, Children: slices.Clone(path.Children)}}
|
||||||
if path.Annotation == "" {
|
if path.Annotation == "" {
|
||||||
selection.source = e.objectOrigin(path.ID).page
|
if origin := e.objectOrigin(path.ID); origin != nil {
|
||||||
|
selection.source = origin.page
|
||||||
|
}
|
||||||
} else if e.source != nil {
|
} else if e.source != nil {
|
||||||
selection.source = e.source.pages[e.pages[page].ID]
|
selection.source = e.source.pages[e.pages[page].ID]
|
||||||
}
|
}
|
||||||
@@ -94,6 +98,13 @@ func (e *Editor) CaptureCompositeObjects(page int, path ObjectPath, indexes []in
|
|||||||
copy := *node
|
copy := *node
|
||||||
copy.owner, copy.span = nil, nil
|
copy.owner, copy.span = nil, nil
|
||||||
selection.nodes = append(selection.nodes, ©)
|
selection.nodes = append(selection.nodes, ©)
|
||||||
|
snapshot, err := e.captureRichTextSnapshot(page, node.object)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if snapshot != nil {
|
||||||
|
selection.richText[j] = snapshot
|
||||||
|
}
|
||||||
}
|
}
|
||||||
scope := root.loadedScope(path.Children)
|
scope := root.loadedScope(path.Children)
|
||||||
for scope != owner {
|
for scope != owner {
|
||||||
@@ -133,6 +144,7 @@ func (e *Editor) PasteCompositeObjects(page int, path ObjectPath, selection *Com
|
|||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
var result []int
|
var result []int
|
||||||
|
err := e.Transaction(func(e *Editor) error {
|
||||||
err := e.editCompositeScope(page, path, func(renderer *Renderer, root *editorCompositeNode, _ []*editorCompositeNode) error {
|
err := e.editCompositeScope(page, path, func(renderer *Renderer, root *editorCompositeNode, _ []*editorCompositeNode) error {
|
||||||
scope := root.loadedScope(path.Children)
|
scope := root.loadedScope(path.Children)
|
||||||
owner := scope
|
owner := scope
|
||||||
@@ -190,6 +202,11 @@ func (e *Editor) PasteCompositeObjects(page int, path ObjectPath, selection *Com
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return e.putCompositeRichTextCopies(page, path, result, selection.richText)
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -217,7 +234,7 @@ func (e *Editor) pasteCompositeSelection(selection *CompositeSelection, paste fu
|
|||||||
if err := e.prepareSourceIDs(); err != nil {
|
if err := e.prepareSourceIDs(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
reader, err := e.Reader()
|
reader, err := e.reader(nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -225,7 +242,7 @@ func (e *Editor) pasteCompositeSelection(selection *CompositeSelection, paste fu
|
|||||||
renderer := e.newRenderer(reader)
|
renderer := e.newRenderer(reader)
|
||||||
var objects []GraphicObject
|
var objects []GraphicObject
|
||||||
var remaps []map[string]string
|
var remaps []map[string]string
|
||||||
for _, source := range selection.nodes {
|
for i, source := range selection.nodes {
|
||||||
copy, err := newEditorCompositeNode(source.data)
|
copy, err := newEditorCompositeNode(source.data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -321,13 +338,16 @@ func (e *Editor) pasteCompositeSelection(selection *CompositeSelection, paste fu
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
object.state = copy.states[editorObjectID(copy.object)]
|
object.state = copy.states[editorObjectID(copy.object)]
|
||||||
|
if object.state.layout != nil {
|
||||||
object.TextObject.layout = object.state.layout
|
object.TextObject.layout = object.state.layout
|
||||||
|
}
|
||||||
copy.object.TextObject.layout = object.TextObject.layout
|
copy.object.TextObject.layout = object.TextObject.layout
|
||||||
if object.Type == "CompositeObject" || object.Type == "CompositeGraphicUnit" {
|
if object.Type == "CompositeObject" || object.Type == "CompositeGraphicUnit" {
|
||||||
object.CompositeGraphicUnit.states = maps.Clone(copy.states)
|
object.CompositeGraphicUnit.states = maps.Clone(copy.states)
|
||||||
copy.object.CompositeGraphicUnit.states = object.CompositeGraphicUnit.states
|
copy.object.CompositeGraphicUnit.states = object.CompositeGraphicUnit.states
|
||||||
}
|
}
|
||||||
object.origin = &editorObjectOrigin{editor: e, document: e.documentIdentity(), page: selection.source, data: copy.data, node: copy.node, object: copy.object}
|
object.origin = &editorObjectOrigin{editor: e, document: e.documentIdentity(), page: selection.source, data: copy.data, node: copy.node, object: copy.object}
|
||||||
|
object.richText = selection.richText[i]
|
||||||
objects = append(objects, object)
|
objects = append(objects, object)
|
||||||
remaps = append(remaps, copy.remaps...)
|
remaps = append(remaps, copy.remaps...)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -251,7 +251,9 @@ func (e *Editor) ungroupCompositeNode(renderer *Renderer, node *editorCompositeN
|
|||||||
}
|
}
|
||||||
member.node.parent = &editorXML{name: xml.Name{Local: "Layer"}, parent: &editorXML{name: xml.Name{Local: "Content"}}}
|
member.node.parent = &editorXML{name: xml.Name{Local: "Layer"}, parent: &editorXML{name: xml.Name{Local: "Content"}}}
|
||||||
member.object.state = states[editorObjectID(member.object)]
|
member.object.state = states[editorObjectID(member.object)]
|
||||||
|
if member.object.state.layout != nil {
|
||||||
member.object.TextObject.layout = member.object.state.layout
|
member.object.TextObject.layout = member.object.state.layout
|
||||||
|
}
|
||||||
member.object.CompositeGraphicUnit.states = states
|
member.object.CompositeGraphicUnit.states = states
|
||||||
member.object.origin = &editorObjectOrigin{editor: e, document: e.documentIdentity(), data: member.data, node: member.node, object: member.object}
|
member.object.origin = &editorObjectOrigin{editor: e, document: e.documentIdentity(), data: member.data, node: member.node, object: member.object}
|
||||||
objects[i] = member.object
|
objects[i] = member.object
|
||||||
|
|||||||
@@ -40,6 +40,29 @@ func (e *Editor) AddCompositeObject(page int, path ObjectPath, object GraphicObj
|
|||||||
// 入参: page 页面索引, path 父路径, objects 当前文档快照或基本对象, dx 页面横向位移, dy 页面纵向位移
|
// 入参: page 页面索引, path 父路径, objects 当前文档快照或基本对象, dx 页面横向位移, dy 页面纵向位移
|
||||||
// 返回: []int 新成员序号, error 错误信息
|
// 返回: []int 新成员序号, error 错误信息
|
||||||
func (e *Editor) CopyObjectsToComposite(page int, path ObjectPath, objects []GraphicObject, dx, dy float64) ([]int, error) {
|
func (e *Editor) CopyObjectsToComposite(page int, path ObjectPath, objects []GraphicObject, dx, dy float64) ([]int, error) {
|
||||||
|
metadata, err := e.copiedRichTextMetadata(objects)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(metadata) == 0 {
|
||||||
|
return e.copyObjectsToComposite(page, path, objects, dx, dy)
|
||||||
|
}
|
||||||
|
var indexes []int
|
||||||
|
err = e.Transaction(func(e *Editor) error {
|
||||||
|
var err error
|
||||||
|
indexes, err = e.copyObjectsToComposite(page, path, objects, dx, dy)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return e.putCompositeRichTextCopies(page, path, indexes, metadata)
|
||||||
|
})
|
||||||
|
return indexes, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// copyObjectsToComposite 插入对象原文,由调用方同步富文本语义
|
||||||
|
// 入参: page 页面索引, path 父路径, objects 对象快照, dx 横向位移, dy 纵向位移
|
||||||
|
// 返回: []int 成员序号, error 校验或提交错误
|
||||||
|
func (e *Editor) copyObjectsToComposite(page int, path ObjectPath, objects []GraphicObject, dx, dy float64) ([]int, error) {
|
||||||
if !finite(dx) || !finite(dy) {
|
if !finite(dx) || !finite(dy) {
|
||||||
return nil, fmt.Errorf("copy requires finite offsets")
|
return nil, fmt.Errorf("copy requires finite offsets")
|
||||||
}
|
}
|
||||||
@@ -49,6 +72,9 @@ func (e *Editor) CopyObjectsToComposite(page int, path ObjectPath, objects []Gra
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
owner := root.loadedScope(path.Children)
|
owner := root.loadedScope(path.Children)
|
||||||
|
if owner.ref != nil {
|
||||||
|
owner = owner.ref
|
||||||
|
}
|
||||||
box, _ := ParseBox(owner.object.CompositeGraphicUnit.Boundary)
|
box, _ := ParseBox(owner.object.CompositeGraphicUnit.Boundary)
|
||||||
parent := owner.parent.Multiply(TranslationMatrix(box.X, box.Y)).Multiply(NewMatrix(owner.object.CompositeGraphicUnit.CTM))
|
parent := owner.parent.Multiply(TranslationMatrix(box.X, box.Y)).Multiply(NewMatrix(owner.object.CompositeGraphicUnit.CTM))
|
||||||
inverse, ok := parent.Invert()
|
inverse, ok := parent.Invert()
|
||||||
|
|||||||
@@ -45,6 +45,8 @@ func (e *Editor) CopyCompositeObjects(page int, path ObjectPath, indexes []int,
|
|||||||
return nil, fmt.Errorf("copy requires finite offsets")
|
return nil, fmt.Errorf("copy requires finite offsets")
|
||||||
}
|
}
|
||||||
var result []int
|
var result []int
|
||||||
|
metadata := make(map[int]*richTextSnapshot)
|
||||||
|
err := e.Transaction(func(e *Editor) error {
|
||||||
err := e.editCompositeObjects(page, path, indexes, func(renderer *Renderer, nodes []*editorCompositeNode, members []CompositeMember) error {
|
err := e.editCompositeObjects(page, path, indexes, func(renderer *Renderer, nodes []*editorCompositeNode, members []CompositeMember) error {
|
||||||
container := nodes[0].span.parent
|
container := nodes[0].span.parent
|
||||||
for i, node := range nodes {
|
for i, node := range nodes {
|
||||||
@@ -53,6 +55,15 @@ func (e *Editor) CopyCompositeObjects(page int, path ObjectPath, indexes []int,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
slices.SortFunc(nodes, func(a, b *editorCompositeNode) int { return a.index - b.index })
|
slices.SortFunc(nodes, func(a, b *editorCompositeNode) int { return a.index - b.index })
|
||||||
|
for i, node := range nodes {
|
||||||
|
snapshot, err := e.captureRichTextSnapshot(page, node.object)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if snapshot != nil {
|
||||||
|
metadata[i] = snapshot
|
||||||
|
}
|
||||||
|
}
|
||||||
data, states, err := e.copyCompositeNodes(renderer, nodes, dx, dy)
|
data, states, err := e.copyCompositeNodes(renderer, nodes, dx, dy)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -71,6 +82,11 @@ func (e *Editor) CopyCompositeObjects(page int, path ObjectPath, indexes []int,
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return e.putCompositeRichTextCopies(page, path, result, metadata)
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
Loaded 100 of 246 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user