Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Improve pasting WPS comments https://github.com/siyuan-note/siyuan/issues/18748

Danielc26b9295e3a8
diff --git a/app/electron/main.js b/app/electron/main.js
index e2b774c1cc..a8e9980be3 100644
--- a/app/electron/main.js
+++ b/app/electron/main.js
@@ -1645,6 +1645,26 @@ app.whenReady().then(() => {
if (data.cmd === "clipboardRead") {
return clipboard.read(data.format);
}
+ if (data.cmd === "clipboardReadWPS") {
+ if (typeof data.text !== "string" ||
+ normalizeClipboardText(clipboard.readText()) !== normalizeClipboardText(data.text)) {
+ return "";
+ }
+ const formats = clipboard.availableFormats().filter((format) =>
+ /kingsoft.*wps.*format/i.test(format));
+ formats.push("Kingsoft WPS Format");
+ for (let version = 6; version <= 20; version++) {
+ formats.push(`Kingsoft WPS ${version}.0 Format`);
+ }
+ // availableFormats 可能不包含 WPS 原生格式,需要尝试常见格式名
+ for (const format of new Set(formats)) {
+ const buffer = clipboard.readBuffer(format);
+ if (buffer.length <= 8 * 1024 * 1024 && buffer[0] === 0x50 && buffer[1] === 0x4b) {
+ return buffer.toString("base64");
+ }
+ }
+ return "";
+ }
if (data.cmd === "beginRichClipboard") {
richClipboardOperation = undefined;
const text = clipboard.readText();
diff --git a/app/src/protyle/util/paste.ts b/app/src/protyle/util/paste.ts
index 49b3272890..f5b6541862 100644
--- a/app/src/protyle/util/paste.ts
+++ b/app/src/protyle/util/paste.ts
@@ -26,6 +26,9 @@ import {refreshSbAndPersistWidth} from "../../block/util";
import {extractCrossBlockPasteContext, shouldPreservePastedBlockStructure} from "./pasteSource";
import {normalizePasteResponse} from "./pasteResponse";
import {applyLuteMarkdownSyntax} from "../render/luteMarkdownSyntax";
+/// #if !BROWSER
+import {ipcRenderer} from "electron";
+/// #endif
export const beforePaste = (protyle: IProtyle, blockElement: HTMLElement) => {
// 链接,备注,样式,引用,pdf标注粘贴 https://github.com/siyuan-note/siyuan/issues/11572
@@ -498,6 +501,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
let siyuanHTML: string;
let files: FileList | DataTransferItemList | File[];
let vscodeEditorData = "";
+ let wps = "";
if ("clipboardData" in event) {
textHTML = event.clipboardData.getData("text/html");
textPlain = event.clipboardData.getData("text/plain");
@@ -527,6 +531,12 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
textPlain = textPlain.replace(/\r\n|\r|\u2028|\u2029/g, "\n");
/// #if !BROWSER
+ if (!("dataTransfer" in event) && !siyuanHTML && textHTML && textPlain) {
+ wps = await ipcRenderer.invoke(Constants.SIYUAN_GET, {
+ cmd: "clipboardReadWPS",
+ text: textPlain,
+ });
+ }
if (!siyuanHTML && !textHTML && !textPlain && ("clipboardData" in event)) {
const localFiles: ILocalFiles[] = await getLocalFiles();
if (localFiles.length > 0) {
@@ -601,6 +611,7 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
siyuanHTML = normalizedResponse.siyuanHTML;
files = normalizedResponse.files;
originalTextHTML = textHTML;
+ wps = "";
}
}
}
@@ -903,7 +914,9 @@ export const paste = async (protyle: IProtyle, event: (ClipboardEvent | DragEven
return;
}
fetchPost("/api/lute/html2BlockDOM", {
- dom: tempElement.innerHTML
+ dom: tempElement.innerHTML,
+ text: textPlain,
+ wps,
}, (response) => {
insertHTML(response.data, protyle, false, false, true);
protyle.wysiwyg.element.querySelectorAll('[data-type~="block-ref"]').forEach(item => {
diff --git a/kernel/api/lute.go b/kernel/api/lute.go
index 46a98f7e10..ec3a7cb722 100644
--- a/kernel/api/lute.go
+++ b/kernel/api/lute.go
@@ -105,10 +105,13 @@ func html2BlockDOM(c *gin.Context) {
ret.Msg = err.Error()
return
}
+ text, _ := arg["text"].(string)
+ wps, _ := arg["wps"].(string)
luteEngine := util.NewLute()
luteEngine.SetHTMLTag2TextMark(true)
luteEngine.SetHTML2MarkdownAttrs([]string{"alias", "memo", "bookmark", "custom-*"})
- // 将 Word 批注转换为行级备注 https://github.com/siyuan-note/siyuan/issues/18748
+ // 将 Word 和 WPS 批注转换为行级备注 https://github.com/siyuan-note/siyuan/issues/18748
+ dom = normalizeWPSComments(dom, text, wps)
dom = normalizeMSWordComments(dom)
tree, _ := model.HTML2Tree(dom, luteEngine, boxID)
if nil == tree {
diff --git a/kernel/api/lute_wps_comment.go b/kernel/api/lute_wps_comment.go
new file mode 100644
index 0000000000..03932a7499
--- /dev/null
+++ b/kernel/api/lute_wps_comment.go
@@ -0,0 +1,311 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package api
+
+import (
+ archivezip "archive/zip"
+ "bytes"
+ "encoding/base64"
+ "encoding/xml"
+ "io"
+ "sort"
+ "strings"
+
+ "github.com/PuerkitoBio/goquery"
+ nethtml "golang.org/x/net/html"
+ "golang.org/x/net/html/atom"
+)
+
+const maxWPSClipboardBytes = 8 * 1024 * 1024
+
+type wpsCommentRange struct {
+ id string
+ start int
+ end int
+}
+
+type wpsHTMLChar struct {
+ node *nethtml.Node
+ offset int
+}
+
+type wpsNodeRange struct {
+ start int
+ end int
+ memo string
+}
+
+func normalizeWPSComments(dom, text, encoded string) string {
+ if encoded == "" || len(encoded) > base64.StdEncoding.EncodedLen(maxWPSClipboardBytes) {
+ return dom
+ }
+ data, err := base64.StdEncoding.DecodeString(encoded)
+ if err != nil || len(data) > maxWPSClipboardBytes {
+ return dom
+ }
+ archive, err := archivezip.NewReader(bytes.NewReader(data), int64(len(data)))
+ if err != nil {
+ return dom
+ }
+ documentXML, err := readWPSClipboardFile(archive, "word/document.xml")
+ if err != nil {
+ return dom
+ }
+ commentsXML, err := readWPSClipboardFile(archive, "word/comments.xml")
+ if err != nil {
+ return dom
+ }
+
+ documentText, ranges, err := parseWPSDocumentComments(documentXML)
+ if err != nil || len(ranges) == 0 {
+ return dom
+ }
+ comments, err := parseWPSCommentTexts(commentsXML)
+ if err != nil || len(comments) == 0 {
+ return dom
+ }
+ doc, err := goquery.NewDocumentFromReader(strings.NewReader(dom))
+ if err != nil {
+ return dom
+ }
+ htmlText, positions := wpsHTMLTextPositions(doc.Find("body").Get(0))
+ if documentText != htmlText || documentText != normalizeWPSClipboardText(text) {
+ return dom
+ }
+
+ nodeRanges := map[*nethtml.Node][]wpsNodeRange{}
+ for _, commentRange := range ranges {
+ memo := comments[commentRange.id]
+ if memo == "" || commentRange.start < 0 || commentRange.start >= commentRange.end || len(positions) < commentRange.end {
+ continue
+ }
+ start := positions[commentRange.start]
+ end := positions[commentRange.end-1]
+ if start.node != end.node {
+ continue
+ }
+ nodeRanges[start.node] = append(nodeRanges[start.node], wpsNodeRange{
+ start: start.offset,
+ end: end.offset + 1,
+ memo: memo,
+ })
+ }
+ if len(nodeRanges) == 0 {
+ return dom
+ }
+ for node, ranges := range nodeRanges {
+ wrapWPSCommentRanges(node, ranges)
+ }
+
+ ret, err := doc.Find("body").Html()
+ if err != nil {
+ return dom
+ }
+ return ret
+}
+
+func readWPSClipboardFile(archive *archivezip.Reader, name string) ([]byte, error) {
+ for _, file := range archive.File {
+ if file.Name != name {
+ continue
+ }
+ if file.UncompressedSize64 > maxWPSClipboardBytes {
+ return nil, io.ErrUnexpectedEOF
+ }
+ reader, err := file.Open()
+ if err != nil {
+ return nil, err
+ }
+ defer reader.Close()
+ return io.ReadAll(io.LimitReader(reader, maxWPSClipboardBytes+1))
+ }
+ return nil, io.EOF
+}
+
+func parseWPSDocumentComments(data []byte) (string, []wpsCommentRange, error) {
+ decoder := xml.NewDecoder(bytes.NewReader(data))
+ starts := map[string]int{}
+ var text []rune
+ var ranges []wpsCommentRange
+ for {
+ token, err := decoder.Token()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return "", nil, err
+ }
+ start, ok := token.(xml.StartElement)
+ if !ok {
+ continue
+ }
+ switch start.Name.Local {
+ case "commentRangeStart":
+ starts[xmlAttribute(start.Attr, "id")] = len(text)
+ case "commentRangeEnd":
+ id := xmlAttribute(start.Attr, "id")
+ if offset, exists := starts[id]; exists {
+ ranges = append(ranges, wpsCommentRange{id: id, start: offset, end: len(text)})
+ }
+ case "t":
+ var value string
+ if err = decoder.DecodeElement(&value, &start); err != nil {
+ return "", nil, err
+ }
+ text = appendNormalizedWPSRunes(text, value)
+ }
+ }
+ return string(text), ranges, nil
+}
+
+func parseWPSCommentTexts(data []byte) (map[string]string, error) {
+ decoder := xml.NewDecoder(bytes.NewReader(data))
+ comments := map[string]string{}
+ currentID := ""
+ var text []rune
+ paragraphHasText := false
+ for {
+ token, err := decoder.Token()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return nil, err
+ }
+ switch element := token.(type) {
+ case xml.StartElement:
+ switch element.Name.Local {
+ case "comment":
+ currentID = xmlAttribute(element.Attr, "id")
+ text = nil
+ paragraphHasText = false
+ case "p":
+ if currentID != "" && paragraphHasText {
+ text = append(text, '\n')
+ paragraphHasText = false
+ }
+ case "t":
+ if currentID == "" {
+ continue
+ }
+ var value string
+ if err = decoder.DecodeElement(&value, &element); err != nil {
+ return nil, err
+ }
+ text = append(text, []rune(value)...)
+ paragraphHasText = true
+ }
+ case xml.EndElement:
+ if element.Name.Local == "comment" && currentID != "" {
+ if value := strings.TrimSpace(string(text)); value != "" {
+ comments[currentID] = value
+ }
+ currentID = ""
+ }
+ }
+ }
+ return comments, nil
+}
+
+func xmlAttribute(attributes []xml.Attr, name string) string {
+ for _, attribute := range attributes {
+ if attribute.Name.Local == name {
+ return attribute.Value
+ }
+ }
+ return ""
+}
+
+func normalizeWPSClipboardText(text string) string {
+ return string(appendNormalizedWPSRunes(nil, text))
+}
+
+func appendNormalizedWPSRunes(dest []rune, text string) []rune {
+ for _, char := range text {
+ switch char {
+ case '\r', '\n':
+ continue
+ case '\u00a0':
+ char = ' '
+ }
+ dest = append(dest, char)
+ }
+ return dest
+}
+
+func wpsHTMLTextPositions(root *nethtml.Node) (string, []wpsHTMLChar) {
+ if root == nil {
+ return "", nil
+ }
+ var text []rune
+ var positions []wpsHTMLChar
+ var walk func(*nethtml.Node)
+ walk = func(node *nethtml.Node) {
+ if node.Type == nethtml.TextNode {
+ for offset, char := range []rune(node.Data) {
+ if char == '\r' || char == '\n' {
+ continue
+ }
+ if char == '\u00a0' {
+ char = ' '
+ }
+ text = append(text, char)
+ positions = append(positions, wpsHTMLChar{node: node, offset: offset})
+ }
+ }
+ for child := node.FirstChild; child != nil; child = child.NextSibling {
+ walk(child)
+ }
+ }
+ walk(root)
+ return string(text), positions
+}
+
+func wrapWPSCommentRanges(node *nethtml.Node, ranges []wpsNodeRange) {
+ if node.Parent == nil {
+ return
+ }
+ sort.Slice(ranges, func(i, j int) bool {
+ return ranges[i].start < ranges[j].start
+ })
+ text := []rune(node.Data)
+ cursor := 0
+ for _, commentRange := range ranges {
+ if commentRange.start < cursor || len(text) < commentRange.end {
+ continue
+ }
+ if cursor < commentRange.start {
+ node.Parent.InsertBefore(&nethtml.Node{Type: nethtml.TextNode, Data: string(text[cursor:commentRange.start])}, node)
+ }
+ span := &nethtml.Node{
+ Type: nethtml.ElementNode,
+ DataAtom: atom.Span,
+ Data: "span",
+ Attr: []nethtml.Attribute{{Key: "title", Val: commentRange.memo}},
+ }
+ span.AppendChild(&nethtml.Node{Type: nethtml.TextNode, Data: string(text[commentRange.start:commentRange.end])})
+ node.Parent.InsertBefore(span, node)
+ cursor = commentRange.end
+ }
+ if cursor == 0 {
+ return
+ }
+ if cursor < len(text) {
+ node.Parent.InsertBefore(&nethtml.Node{Type: nethtml.TextNode, Data: string(text[cursor:])}, node)
+ }
+ node.Parent.RemoveChild(node)
+}
diff --git a/kernel/api/lute_wps_comment_test.go b/kernel/api/lute_wps_comment_test.go
new file mode 100644
index 0000000000..51d64f4eb7
--- /dev/null
+++ b/kernel/api/lute_wps_comment_test.go
@@ -0,0 +1,83 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package api
+
+import (
+ archivezip "archive/zip"
+ "bytes"
+ "encoding/base64"
+ "strings"
+ "testing"
+
+ "github.com/PuerkitoBio/goquery"
+)
+
+func TestNormalizeWPSComments(t *testing.T) {
+ document := `<?xml version="1.0"?><w:document xmlns:w="urn:w"><w:body><w:p><w:r><w:t>11111</w:t></w:r>` +
+ `<w:commentRangeStart w:id="0"/><w:r><w:t>111</w:t></w:r><w:commentRangeEnd w:id="0"/>` +
+ `<w:r><w:commentReference w:id="0"/></w:r><w:r><w:t>1111111111</w:t></w:r></w:p></w:body></w:document>`
+ comments := `<?xml version="1.0"?><w:comments xmlns:w="urn:w"><w:comment w:id="0"><w:p><w:r>` +
+ `<w:t>22222222222222</w:t></w:r></w:p></w:comment></w:comments>`
+ encoded := buildWPSClipboard(t, document, comments)
+ dom := `<p><span>11111111</span><span>1111111111</span></p>`
+
+ normalized := normalizeWPSComments(dom, "111111111111111111", encoded)
+ doc, err := goquery.NewDocumentFromReader(strings.NewReader(normalized))
+ if err != nil {
+ t.Fatal(err)
+ }
+ memo := doc.Find(`span[title="22222222222222"]`)
+ if memo.Length() != 1 || memo.Text() != "111" {
+ t.Fatalf("unexpected normalized WPS memo: %s", normalized)
+ }
+ if doc.Find("body").Text() != "111111111111111111" {
+ t.Fatalf("unexpected normalized text: %s", doc.Find("body").Text())
+ }
+}
+
+func TestNormalizeWPSCommentsRequiresMatchingText(t *testing.T) {
+ encoded := buildWPSClipboard(t,
+ `<w:document xmlns:w="urn:w"><w:body><w:p><w:commentRangeStart w:id="0"/><w:r><w:t>text</w:t></w:r>`+
+ `<w:commentRangeEnd w:id="0"/></w:p></w:body></w:document>`,
+ `<w:comments xmlns:w="urn:w"><w:comment w:id="0"><w:p><w:r><w:t>memo</w:t></w:r></w:p></w:comment></w:comments>`)
+ dom := `<p>different</p>`
+ if normalized := normalizeWPSComments(dom, "different", encoded); normalized != dom {
+ t.Fatalf("mismatched WPS content was modified: %s", normalized)
+ }
+}
+
+func buildWPSClipboard(t *testing.T, document, comments string) string {
+ t.Helper()
+ var buffer bytes.Buffer
+ writer := archivezip.NewWriter(&buffer)
+ for name, content := range map[string]string{
+ "word/document.xml": document,
+ "word/comments.xml": comments,
+ } {
+ file, err := writer.Create(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = file.Write([]byte(content)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := writer.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return base64.StdEncoding.EncodeToString(buffer.Bytes())
+}