odforge 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- odforge/__init__.py +1 -0
- odforge/benchmark.py +287 -0
- odforge/check.py +416 -0
- odforge/cli.py +1027 -0
- odforge/components.py +270 -0
- odforge/critic.py +1260 -0
- odforge/docfonts.py +104 -0
- odforge/editor_api.py +33 -0
- odforge/editor_launch.py +134 -0
- odforge/editor_routes.py +131 -0
- odforge/extract.py +478 -0
- odforge/feedback.py +86 -0
- odforge/fontembed.py +166 -0
- odforge/ir.py +1181 -0
- odforge/layoutcheck.py +602 -0
- odforge/llm.py +1865 -0
- odforge/localguard.py +42 -0
- odforge/mcp_server.py +552 -0
- odforge/media.py +352 -0
- odforge/odpedit.py +1219 -0
- odforge/package.py +114 -0
- odforge/pagefacts.py +388 -0
- odforge/preview.py +104 -0
- odforge/references.py +153 -0
- odforge/render/__init__.py +40 -0
- odforge/render/odp.py +5687 -0
- odforge/render/ods.py +155 -0
- odforge/render/odt.py +223 -0
- odforge/scene.py +657 -0
- odforge/setup_agents.py +274 -0
- odforge/skills/odforge-design/SKILL.md +298 -0
- odforge/skills/odforge-design/themes/academic.md +52 -0
- odforge/skills/odforge-design/themes/clay.md +53 -0
- odforge/skills/odforge-design/themes/color-system.md +59 -0
- odforge/skills/odforge-design/themes/crimson.md +53 -0
- odforge/skills/odforge-design/themes/dark.md +53 -0
- odforge/skills/odforge-design/themes/forest.md +54 -0
- odforge/skills/odforge-design/themes/gold.md +53 -0
- odforge/skills/odforge-design/themes/minimal.md +53 -0
- odforge/skills/odforge-design/themes/navy.md +56 -0
- odforge/skills/odforge-design/themes/plum.md +53 -0
- odforge/skills/odforge-design/themes/sky.md +53 -0
- odforge/skills/odforge-design/themes/slate.md +53 -0
- odforge/skills/odforge-design/themes/teal.md +53 -0
- odforge/skills/odforge-design/themes/violet.md +56 -0
- odforge/templates.py +250 -0
- odforge/textmetrics.py +616 -0
- odforge/textutil.py +24 -0
- odforge/themes.py +886 -0
- odforge/validate.py +403 -0
- odforge/watch.py +266 -0
- odforge/webapi.py +2617 -0
- odforge/webui/assets/editor-CjpYXM1a.css +1 -0
- odforge/webui/assets/editor-DPToJGio.js +3 -0
- odforge/webui/assets/jsx-runtime-C7KMcVI_.js +8 -0
- odforge/webui/assets/main-BLOs7Hnk.js +7 -0
- odforge/webui/assets/main-D21yFVE6.css +1 -0
- odforge/webui/editor.html +14 -0
- odforge/webui/index.html +25 -0
- odforge/xmlsafe.py +46 -0
- odforge/zipguard.py +91 -0
- odforge-0.3.0.dist-info/METADATA +95 -0
- odforge-0.3.0.dist-info/RECORD +66 -0
- odforge-0.3.0.dist-info/WHEEL +4 -0
- odforge-0.3.0.dist-info/entry_points.txt +3 -0
- odforge-0.3.0.dist-info/licenses/LICENSE +21 -0
odforge/odpedit.py
ADDED
|
@@ -0,0 +1,1219 @@
|
|
|
1
|
+
"""Edit an ``.odp`` in place: the operations behind the web editor.
|
|
2
|
+
|
|
3
|
+
The editor sends small operations — move this frame, replace that text, add a
|
|
4
|
+
page — and this module applies them to the document's ``content.xml`` and
|
|
5
|
+
writes the package back to disk. Only what an operation names is touched;
|
|
6
|
+
everything else in the file (styles, fonts, pictures, speaker notes, elements
|
|
7
|
+
the editor cannot draw) passes through byte for byte.
|
|
8
|
+
|
|
9
|
+
Undo keeps whole copies of ``content.xml`` rather than inverse operations: a
|
|
10
|
+
slide deck's content is a few hundred kilobytes, and a snapshot can never be
|
|
11
|
+
subtly wrong the way a hand-derived inverse can.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import copy
|
|
17
|
+
import hashlib
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import tempfile
|
|
21
|
+
import threading
|
|
22
|
+
import zipfile
|
|
23
|
+
from collections import Counter
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
26
|
+
|
|
27
|
+
from lxml import etree
|
|
28
|
+
|
|
29
|
+
from . import docfonts
|
|
30
|
+
from .scene import (
|
|
31
|
+
ANNOTATION,
|
|
32
|
+
NS,
|
|
33
|
+
Styles,
|
|
34
|
+
_paragraph_style,
|
|
35
|
+
_text_style,
|
|
36
|
+
annotations,
|
|
37
|
+
build_scene,
|
|
38
|
+
cm,
|
|
39
|
+
drawables,
|
|
40
|
+
q,
|
|
41
|
+
)
|
|
42
|
+
from .xmlsafe import safe_fromstring
|
|
43
|
+
|
|
44
|
+
MAX_HISTORY = 200
|
|
45
|
+
MAX_IMAGE_BYTES = 15 * 1024 * 1024
|
|
46
|
+
|
|
47
|
+
_TEXT_STYLE = "OEdP1"
|
|
48
|
+
_FRAME_STYLE = "OEdG1"
|
|
49
|
+
_RECT_STYLE = "OEdG2"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class EditError(ValueError):
|
|
53
|
+
"""An operation that cannot be applied (shown to the user as is)."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _len(value: float) -> str:
|
|
57
|
+
return f"{round(value, 4):g}cm"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Document:
|
|
61
|
+
"""One ``.odp`` open for editing. Thread-safe; every method saves to disk."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, path: Path) -> None:
|
|
64
|
+
self.path = Path(path)
|
|
65
|
+
self._lock = threading.Lock()
|
|
66
|
+
self.version = 0
|
|
67
|
+
self._load()
|
|
68
|
+
|
|
69
|
+
def _stamp(self) -> Tuple[int, int]:
|
|
70
|
+
stat = self.path.stat()
|
|
71
|
+
return stat.st_mtime_ns, stat.st_size
|
|
72
|
+
|
|
73
|
+
def _load(self) -> None:
|
|
74
|
+
"""(Re)read the package from disk; history starts over."""
|
|
75
|
+
self._members: List[Tuple[zipfile.ZipInfo, bytes]] = []
|
|
76
|
+
self._disk = self._stamp()
|
|
77
|
+
with zipfile.ZipFile(self.path) as package:
|
|
78
|
+
for info in package.infolist():
|
|
79
|
+
self._members.append((info, package.read(info.filename)))
|
|
80
|
+
names = [info.filename for info, _ in self._members]
|
|
81
|
+
if "content.xml" not in names:
|
|
82
|
+
raise EditError("這不是可以編輯的 ODF 簡報(缺少 content.xml)")
|
|
83
|
+
self.content = safe_fromstring(self._member("content.xml"))
|
|
84
|
+
styles = self._member("styles.xml")
|
|
85
|
+
self.styles = (
|
|
86
|
+
safe_fromstring(styles)
|
|
87
|
+
if styles is not None
|
|
88
|
+
else etree.Element(q("office", "document-styles"))
|
|
89
|
+
)
|
|
90
|
+
if self._presentation() is None:
|
|
91
|
+
raise EditError("這份檔案不是簡報(.odp)")
|
|
92
|
+
self.undo_stack: List[bytes] = []
|
|
93
|
+
self.redo_stack: List[bytes] = []
|
|
94
|
+
|
|
95
|
+
def _sync(self) -> None:
|
|
96
|
+
"""Pick up changes someone else (an agent, another tool) wrote to the file.
|
|
97
|
+
|
|
98
|
+
Undo history belongs to the version it was recorded against, so it is
|
|
99
|
+
dropped: undoing back across another writer's edit would silently revert
|
|
100
|
+
their work.
|
|
101
|
+
"""
|
|
102
|
+
try:
|
|
103
|
+
stamp = self._stamp()
|
|
104
|
+
except OSError:
|
|
105
|
+
return
|
|
106
|
+
if stamp == self._disk:
|
|
107
|
+
return
|
|
108
|
+
try:
|
|
109
|
+
self._load()
|
|
110
|
+
except (OSError, zipfile.BadZipFile, etree.XMLSyntaxError, EditError):
|
|
111
|
+
# Caught mid-write: keep what we have and try again next time.
|
|
112
|
+
return
|
|
113
|
+
self.version += 1
|
|
114
|
+
|
|
115
|
+
def poll(self) -> int:
|
|
116
|
+
"""The current version, after picking up outside changes (cheap when none)."""
|
|
117
|
+
with self._lock:
|
|
118
|
+
self._sync()
|
|
119
|
+
return self.version
|
|
120
|
+
|
|
121
|
+
# -- package ----------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
def _member(self, name: str) -> Optional[bytes]:
|
|
124
|
+
for info, data in self._members:
|
|
125
|
+
if info.filename == name:
|
|
126
|
+
return data
|
|
127
|
+
return None
|
|
128
|
+
|
|
129
|
+
def member(self, name: str) -> Optional[bytes]:
|
|
130
|
+
"""A file inside the package (fonts and pictures for the browser)."""
|
|
131
|
+
if ".." in name or name.startswith("/"):
|
|
132
|
+
return None
|
|
133
|
+
with self._lock:
|
|
134
|
+
return self._member(name)
|
|
135
|
+
|
|
136
|
+
def _serialise(self) -> bytes:
|
|
137
|
+
return etree.tostring(self.content, xml_declaration=True, encoding="UTF-8")
|
|
138
|
+
|
|
139
|
+
def _save(self) -> None:
|
|
140
|
+
content = self._serialise()
|
|
141
|
+
self._members = [
|
|
142
|
+
(info, content if info.filename == "content.xml" else data)
|
|
143
|
+
for info, data in self._members
|
|
144
|
+
]
|
|
145
|
+
fd, tmp = tempfile.mkstemp(prefix=".odforge-edit-", suffix=".odp", dir=self.path.parent)
|
|
146
|
+
os.close(fd)
|
|
147
|
+
try:
|
|
148
|
+
with zipfile.ZipFile(tmp, "w") as out:
|
|
149
|
+
for info, data in self._members:
|
|
150
|
+
# mimetype must stay first and stored; every other member keeps
|
|
151
|
+
# the compression it came with.
|
|
152
|
+
out.writestr(info, data, compress_type=info.compress_type)
|
|
153
|
+
os.replace(tmp, self.path)
|
|
154
|
+
finally:
|
|
155
|
+
if os.path.exists(tmp):
|
|
156
|
+
os.unlink(tmp)
|
|
157
|
+
self._disk = self._stamp()
|
|
158
|
+
self.version += 1
|
|
159
|
+
|
|
160
|
+
# -- reading ----------------------------------------------------------------
|
|
161
|
+
|
|
162
|
+
def _presentation(self) -> Optional[etree._Element]:
|
|
163
|
+
return self.content.find(f".//{q('office', 'presentation')}")
|
|
164
|
+
|
|
165
|
+
def _pages(self) -> List[etree._Element]:
|
|
166
|
+
presentation = self._presentation()
|
|
167
|
+
return [] if presentation is None else presentation.findall(q("draw", "page"))
|
|
168
|
+
|
|
169
|
+
def state(self) -> Dict[str, Any]:
|
|
170
|
+
with self._lock:
|
|
171
|
+
self._sync()
|
|
172
|
+
return self._state()
|
|
173
|
+
|
|
174
|
+
def _state(self, created: Optional[List[str]] = None) -> Dict[str, Any]:
|
|
175
|
+
scene = build_scene(self.content, self.styles)
|
|
176
|
+
for font in scene["fonts"]:
|
|
177
|
+
data = self._member(font["href"])
|
|
178
|
+
# A re-subset font keeps its path; the revision makes browsers refetch it.
|
|
179
|
+
font["rev"] = hashlib.sha1(data).hexdigest()[:10] if data else ""
|
|
180
|
+
presentation = self._presentation()
|
|
181
|
+
return {
|
|
182
|
+
"name": self.path.name,
|
|
183
|
+
"version": self.version,
|
|
184
|
+
"scene": scene,
|
|
185
|
+
"session": presentation.get(q("odforge", "session"), "open"),
|
|
186
|
+
"theme": _theme_summary(self.content, self.styles),
|
|
187
|
+
"fontChoices": docfonts.choices([self.content, self.styles]),
|
|
188
|
+
"canUndo": bool(self.undo_stack),
|
|
189
|
+
"canRedo": bool(self.redo_stack),
|
|
190
|
+
"created": created or [],
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
def _page(self, index: Any) -> etree._Element:
|
|
194
|
+
pages = self._pages()
|
|
195
|
+
try:
|
|
196
|
+
i = int(index)
|
|
197
|
+
except (TypeError, ValueError) as exc:
|
|
198
|
+
raise EditError(f"頁碼不正確:{index!r}") from exc
|
|
199
|
+
if not 0 <= i < len(pages):
|
|
200
|
+
raise EditError(f"沒有第 {i + 1} 頁")
|
|
201
|
+
return pages[i]
|
|
202
|
+
|
|
203
|
+
def _element(self, element_id: Any) -> Tuple[int, int, etree._Element]:
|
|
204
|
+
"""``"7/2"`` is the third drawable of page 8; ``"7/2.1"`` the second inside that group."""
|
|
205
|
+
try:
|
|
206
|
+
page_part, path = str(element_id).split("/")
|
|
207
|
+
page_i = int(page_part)
|
|
208
|
+
indices = [int(part) for part in path.split(".")]
|
|
209
|
+
except ValueError as exc:
|
|
210
|
+
raise EditError(f"元素代號不正確:{element_id!r}") from exc
|
|
211
|
+
container = self._page(page_i)
|
|
212
|
+
el = container
|
|
213
|
+
for depth, index in enumerate(indices):
|
|
214
|
+
if depth and el.tag != q("draw", "g"):
|
|
215
|
+
raise EditError(f"找不到元素 {element_id}")
|
|
216
|
+
items = drawables(el)
|
|
217
|
+
if not 0 <= index < len(items):
|
|
218
|
+
raise EditError(f"找不到元素 {element_id}")
|
|
219
|
+
el = items[index]
|
|
220
|
+
return page_i, indices[0], el
|
|
221
|
+
|
|
222
|
+
# -- history ----------------------------------------------------------------
|
|
223
|
+
|
|
224
|
+
def apply(self, ops: List[Dict[str, Any]]) -> Dict[str, Any]:
|
|
225
|
+
"""Apply a batch atomically: all of it lands, or none of it does."""
|
|
226
|
+
with self._lock:
|
|
227
|
+
self._sync()
|
|
228
|
+
before = self._serialise()
|
|
229
|
+
created: List[str] = []
|
|
230
|
+
try:
|
|
231
|
+
for op in ops:
|
|
232
|
+
created.extend(self._apply_one(op))
|
|
233
|
+
except EditError:
|
|
234
|
+
self.content = safe_fromstring(before)
|
|
235
|
+
raise
|
|
236
|
+
except Exception as exc:
|
|
237
|
+
self.content = safe_fromstring(before)
|
|
238
|
+
raise EditError(f"無法套用這個修改:{type(exc).__name__}: {exc}") from exc
|
|
239
|
+
if self._serialise() == before:
|
|
240
|
+
return self._state(created)
|
|
241
|
+
self._refresh_fonts()
|
|
242
|
+
self.undo_stack.append(before)
|
|
243
|
+
del self.undo_stack[:-MAX_HISTORY]
|
|
244
|
+
self.redo_stack.clear()
|
|
245
|
+
self._save()
|
|
246
|
+
return self._state(created)
|
|
247
|
+
|
|
248
|
+
def undo(self) -> Dict[str, Any]:
|
|
249
|
+
with self._lock:
|
|
250
|
+
self._sync()
|
|
251
|
+
if self.undo_stack:
|
|
252
|
+
self.redo_stack.append(self._serialise())
|
|
253
|
+
self.content = safe_fromstring(self.undo_stack.pop())
|
|
254
|
+
self._save()
|
|
255
|
+
return self._state()
|
|
256
|
+
|
|
257
|
+
def redo(self) -> Dict[str, Any]:
|
|
258
|
+
with self._lock:
|
|
259
|
+
self._sync()
|
|
260
|
+
if self.redo_stack:
|
|
261
|
+
self.undo_stack.append(self._serialise())
|
|
262
|
+
self.content = safe_fromstring(self.redo_stack.pop())
|
|
263
|
+
self._save()
|
|
264
|
+
return self._state()
|
|
265
|
+
|
|
266
|
+
# -- operations -------------------------------------------------------------
|
|
267
|
+
|
|
268
|
+
def _apply_one(self, op: Dict[str, Any]) -> List[str]:
|
|
269
|
+
kind = op.get("op")
|
|
270
|
+
handler = getattr(self, f"_op_{kind}", None) if isinstance(kind, str) else None
|
|
271
|
+
if handler is None:
|
|
272
|
+
raise EditError(f"不認得的操作:{kind!r}")
|
|
273
|
+
return handler(op) or []
|
|
274
|
+
|
|
275
|
+
def _op_geom(self, op: Dict[str, Any]) -> None:
|
|
276
|
+
_, _, el = self._element(op.get("id"))
|
|
277
|
+
if el.tag == q("draw", "g"):
|
|
278
|
+
# A group has no box of its own: move and scale what is inside it.
|
|
279
|
+
ox, oy, ow, oh = _group_box(el)
|
|
280
|
+
nx, ny = float(op.get("x", ox)), float(op.get("y", oy))
|
|
281
|
+
nw, nh = float(op.get("w", ow)), float(op.get("h", oh))
|
|
282
|
+
if nw < 0.05 or nh < 0.05:
|
|
283
|
+
raise EditError("寬度和高度至少要 0.05 cm")
|
|
284
|
+
_transform(el, ox, oy, nx, ny, nw / ow if ow else 1.0, nh / oh if oh else 1.0)
|
|
285
|
+
return
|
|
286
|
+
if el.tag == q("draw", "line"):
|
|
287
|
+
for key in ("x1", "y1", "x2", "y2"):
|
|
288
|
+
if key in op:
|
|
289
|
+
el.set(q("svg", key), _len(float(op[key])))
|
|
290
|
+
return
|
|
291
|
+
for key, attr in (("x", "x"), ("y", "y"), ("w", "width"), ("h", "height")):
|
|
292
|
+
if key in op:
|
|
293
|
+
value = float(op[key])
|
|
294
|
+
if key in ("w", "h") and value < 0.05:
|
|
295
|
+
raise EditError("寬度和高度至少要 0.05 cm")
|
|
296
|
+
el.set(q("svg", attr), _len(value))
|
|
297
|
+
|
|
298
|
+
def _text_root(self, el: etree._Element) -> etree._Element:
|
|
299
|
+
if el.tag == q("draw", "frame"):
|
|
300
|
+
box = el.find(q("draw", "text-box"))
|
|
301
|
+
if box is None:
|
|
302
|
+
raise EditError("這個元素不是文字框")
|
|
303
|
+
return box
|
|
304
|
+
return el
|
|
305
|
+
|
|
306
|
+
def _op_text(self, op: Dict[str, Any]) -> None:
|
|
307
|
+
_, _, el = self._element(op.get("id"))
|
|
308
|
+
paragraphs = op.get("paragraphs")
|
|
309
|
+
if not isinstance(paragraphs, list) or not all(
|
|
310
|
+
isinstance(p, str) or (isinstance(p, dict) and isinstance(p.get("runs", []), list))
|
|
311
|
+
for p in paragraphs
|
|
312
|
+
):
|
|
313
|
+
raise EditError("文字內容格式不正確")
|
|
314
|
+
styles = Styles((self.content, self.styles))
|
|
315
|
+
root = self._text_root(el)
|
|
316
|
+
existing = list(root.iter(q("text", "p"), q("text", "h")))
|
|
317
|
+
if not paragraphs:
|
|
318
|
+
paragraphs = [""]
|
|
319
|
+
if not existing:
|
|
320
|
+
template = etree.SubElement(root, q("text", "p"))
|
|
321
|
+
style = self._ensure_text_style()
|
|
322
|
+
template.set(q("text", "style-name"), style)
|
|
323
|
+
existing = [template]
|
|
324
|
+
|
|
325
|
+
def write(paragraph: etree._Element, value: Any) -> None:
|
|
326
|
+
if isinstance(value, str):
|
|
327
|
+
_set_paragraph_text(paragraph, value)
|
|
328
|
+
else:
|
|
329
|
+
self._set_paragraph_rich(paragraph, value, styles)
|
|
330
|
+
|
|
331
|
+
for i, text in enumerate(paragraphs):
|
|
332
|
+
if i < len(existing):
|
|
333
|
+
if not isinstance(text, str) or _paragraph_text(existing[i]) != text:
|
|
334
|
+
write(existing[i], text)
|
|
335
|
+
else:
|
|
336
|
+
last = existing[-1]
|
|
337
|
+
holder = last.getparent()
|
|
338
|
+
if holder is not None and holder.tag == q("text", "list-item"):
|
|
339
|
+
clone = copy.deepcopy(holder)
|
|
340
|
+
holder.addnext(clone)
|
|
341
|
+
paragraph = clone.find(q("text", "p"))
|
|
342
|
+
else:
|
|
343
|
+
paragraph = copy.deepcopy(last)
|
|
344
|
+
last.addnext(paragraph)
|
|
345
|
+
write(paragraph, text)
|
|
346
|
+
existing.append(paragraph)
|
|
347
|
+
for paragraph in existing[len(paragraphs) :]:
|
|
348
|
+
holder = paragraph.getparent()
|
|
349
|
+
if holder is not None and holder.tag == q("text", "list-item") and len(holder) == 1:
|
|
350
|
+
holder.getparent().remove(holder)
|
|
351
|
+
elif holder is not None:
|
|
352
|
+
holder.remove(paragraph)
|
|
353
|
+
|
|
354
|
+
# -- fonts -------------------------------------------------------------------
|
|
355
|
+
|
|
356
|
+
def _font_decls(self) -> etree._Element:
|
|
357
|
+
decls = self.content.find(q("office", "font-face-decls"))
|
|
358
|
+
if decls is None:
|
|
359
|
+
decls = etree.Element(q("office", "font-face-decls"))
|
|
360
|
+
anchor = self.content.find(q("office", "automatic-styles"))
|
|
361
|
+
if anchor is None:
|
|
362
|
+
anchor = self.content.find(q("office", "body"))
|
|
363
|
+
anchor.addprevious(decls)
|
|
364
|
+
return decls
|
|
365
|
+
|
|
366
|
+
def _ensure_font(self, family: str) -> str:
|
|
367
|
+
"""The font-face name for ``family``, declaring it when the document has none."""
|
|
368
|
+
for face in docfonts.font_faces([self.content, self.styles]):
|
|
369
|
+
if docfonts._family_of(face) == family:
|
|
370
|
+
return face.get(q("style", "name"))
|
|
371
|
+
face = etree.SubElement(self._font_decls(), q("style", "font-face"))
|
|
372
|
+
face.set(q("style", "name"), family)
|
|
373
|
+
face.set(q("svg", "font-family"), f"'{family}'")
|
|
374
|
+
face.set(q("style", "font-pitch"), "variable")
|
|
375
|
+
return family
|
|
376
|
+
|
|
377
|
+
def _refresh_fonts(self) -> None:
|
|
378
|
+
"""Re-embed fonts whose subsets lack characters the text now uses."""
|
|
379
|
+
roots = [self.content, self.styles]
|
|
380
|
+
text = docfonts.document_text(roots)
|
|
381
|
+
needed = docfonts.needed_chars(text)
|
|
382
|
+
for family in docfonts.referenced_families(roots):
|
|
383
|
+
face = next(
|
|
384
|
+
(
|
|
385
|
+
f
|
|
386
|
+
for f in docfonts.font_faces([self.content])
|
|
387
|
+
if docfonts._family_of(f) == family
|
|
388
|
+
),
|
|
389
|
+
None,
|
|
390
|
+
)
|
|
391
|
+
if face is None:
|
|
392
|
+
continue
|
|
393
|
+
parts = [
|
|
394
|
+
uri.get(q("xlink", "href"), "") for uri in face.iter(q("svg", "font-face-uri"))
|
|
395
|
+
]
|
|
396
|
+
stale = not parts
|
|
397
|
+
for part in parts:
|
|
398
|
+
data = self._member(part)
|
|
399
|
+
covered = docfonts.coverage(data) if data else None
|
|
400
|
+
if covered is None or not needed <= covered:
|
|
401
|
+
stale = True
|
|
402
|
+
if not stale:
|
|
403
|
+
continue
|
|
404
|
+
fonts = docfonts.rebuild(family, text)
|
|
405
|
+
if not fonts:
|
|
406
|
+
continue
|
|
407
|
+
for font in fonts:
|
|
408
|
+
self._put_member(font.part, font.data, "application/x-font-otf")
|
|
409
|
+
for child in list(face):
|
|
410
|
+
face.remove(child)
|
|
411
|
+
src = etree.SubElement(face, q("svg", "font-face-src"))
|
|
412
|
+
for font in fonts:
|
|
413
|
+
uri = etree.SubElement(src, q("svg", "font-face-uri"))
|
|
414
|
+
uri.set(q("xlink", "href"), font.part)
|
|
415
|
+
uri.set(q("xlink", "type"), "simple")
|
|
416
|
+
uri.set(q("loext", "font-style"), "normal")
|
|
417
|
+
uri.set(q("loext", "font-weight"), "bold" if font.bold else "normal")
|
|
418
|
+
fmt = etree.SubElement(uri, q("svg", "font-face-format"))
|
|
419
|
+
fmt.set(q("svg", "string"), font.fmt)
|
|
420
|
+
|
|
421
|
+
def _put_member(self, path: str, data: bytes, media: str) -> None:
|
|
422
|
+
for i, (info, _) in enumerate(self._members):
|
|
423
|
+
if info.filename == path:
|
|
424
|
+
self._members[i] = (info, data)
|
|
425
|
+
return
|
|
426
|
+
info = zipfile.ZipInfo(path)
|
|
427
|
+
info.compress_type = zipfile.ZIP_DEFLATED
|
|
428
|
+
self._members.append((info, data))
|
|
429
|
+
self._add_manifest_entry(path, media)
|
|
430
|
+
|
|
431
|
+
# -- rich text ---------------------------------------------------------------
|
|
432
|
+
|
|
433
|
+
def _set_paragraph_rich(
|
|
434
|
+
self, paragraph: etree._Element, value: Dict[str, Any], styles: Styles
|
|
435
|
+
) -> None:
|
|
436
|
+
"""Rewrite a paragraph from styled runs; only differences from its style become spans."""
|
|
437
|
+
name = paragraph.get(q("text", "style-name"))
|
|
438
|
+
base = _text_style(styles.props("paragraph", name, "text-properties"), styles.fonts)
|
|
439
|
+
for child in list(paragraph):
|
|
440
|
+
paragraph.remove(child)
|
|
441
|
+
paragraph.text = None
|
|
442
|
+
for run in value.get("runs", []):
|
|
443
|
+
if not isinstance(run, dict):
|
|
444
|
+
raise EditError("文字內容格式不正確")
|
|
445
|
+
text = str(run.get("text", ""))
|
|
446
|
+
if not text:
|
|
447
|
+
continue
|
|
448
|
+
diff = _run_diff(run, base)
|
|
449
|
+
if diff:
|
|
450
|
+
span = etree.SubElement(paragraph, q("text", "span"))
|
|
451
|
+
span.set(q("text", "style-name"), self._span_style(diff))
|
|
452
|
+
_write_lines(span, text)
|
|
453
|
+
else:
|
|
454
|
+
_append_lines(paragraph, text)
|
|
455
|
+
align = value.get("align")
|
|
456
|
+
if align:
|
|
457
|
+
current = _paragraph_style(styles.props("paragraph", name, "paragraph-properties"))
|
|
458
|
+
if current.get("align", "left") != align:
|
|
459
|
+
paragraph.set(q("text", "style-name"), self._aligned_style(name, align))
|
|
460
|
+
|
|
461
|
+
def _span_style(self, diff: Dict[str, Any]) -> str:
|
|
462
|
+
digest = hashlib.sha1(json.dumps(diff, sort_keys=True).encode()).hexdigest()[:8]
|
|
463
|
+
name = f"OEdT{digest}"
|
|
464
|
+
if not self._has_style(name):
|
|
465
|
+
style = etree.SubElement(self._automatic_styles(), q("style", "style"))
|
|
466
|
+
style.set(q("style", "name"), name)
|
|
467
|
+
style.set(q("style", "family"), "text")
|
|
468
|
+
props = etree.SubElement(style, q("style", "text-properties"))
|
|
469
|
+
if "weight" in diff:
|
|
470
|
+
value = "bold" if diff["weight"] >= 600 else "normal"
|
|
471
|
+
for attr in (
|
|
472
|
+
q("fo", "font-weight"),
|
|
473
|
+
q("style", "font-weight-asian"),
|
|
474
|
+
q("style", "font-weight-complex"),
|
|
475
|
+
):
|
|
476
|
+
props.set(attr, value)
|
|
477
|
+
if "italic" in diff:
|
|
478
|
+
value = "italic" if diff["italic"] else "normal"
|
|
479
|
+
for attr in (
|
|
480
|
+
q("fo", "font-style"),
|
|
481
|
+
q("style", "font-style-asian"),
|
|
482
|
+
q("style", "font-style-complex"),
|
|
483
|
+
):
|
|
484
|
+
props.set(attr, value)
|
|
485
|
+
if "size" in diff:
|
|
486
|
+
value = f"{float(diff['size']):g}pt"
|
|
487
|
+
for attr in (
|
|
488
|
+
q("fo", "font-size"),
|
|
489
|
+
q("style", "font-size-asian"),
|
|
490
|
+
q("style", "font-size-complex"),
|
|
491
|
+
):
|
|
492
|
+
props.set(attr, value)
|
|
493
|
+
if "color" in diff:
|
|
494
|
+
props.set(q("fo", "color"), str(diff["color"]))
|
|
495
|
+
if "family" in diff:
|
|
496
|
+
face = self._ensure_font(str(diff["family"]))
|
|
497
|
+
for attr in ("font-name", "font-name-asian", "font-name-complex"):
|
|
498
|
+
props.set(q("style", attr), face)
|
|
499
|
+
if "underline" in diff:
|
|
500
|
+
props.set(
|
|
501
|
+
q("style", "text-underline-style"), "solid" if diff["underline"] else "none"
|
|
502
|
+
)
|
|
503
|
+
if diff["underline"]:
|
|
504
|
+
props.set(q("style", "text-underline-width"), "auto")
|
|
505
|
+
props.set(q("style", "text-underline-color"), "font-color")
|
|
506
|
+
return name
|
|
507
|
+
|
|
508
|
+
def _aligned_style(self, name: Optional[str], align: str) -> str:
|
|
509
|
+
if align not in ("left", "center", "right", "justify"):
|
|
510
|
+
raise EditError(f"不認得的對齊方式:{align!r}")
|
|
511
|
+
odf_align = {"left": "start", "right": "end"}.get(align, align)
|
|
512
|
+
digest = hashlib.sha1(f"{name}|{align}".encode()).hexdigest()[:8]
|
|
513
|
+
new_name = f"OEdA{digest}"
|
|
514
|
+
if self._has_style(new_name):
|
|
515
|
+
return new_name
|
|
516
|
+
auto = self._automatic_styles()
|
|
517
|
+
original = (
|
|
518
|
+
next(
|
|
519
|
+
(
|
|
520
|
+
el
|
|
521
|
+
for el in auto.iter(q("style", "style"))
|
|
522
|
+
if el.get(q("style", "name")) == name
|
|
523
|
+
and el.get(q("style", "family")) == "paragraph"
|
|
524
|
+
),
|
|
525
|
+
None,
|
|
526
|
+
)
|
|
527
|
+
if name
|
|
528
|
+
else None
|
|
529
|
+
)
|
|
530
|
+
if original is not None:
|
|
531
|
+
style = copy.deepcopy(original)
|
|
532
|
+
auto.append(style)
|
|
533
|
+
else:
|
|
534
|
+
style = etree.SubElement(auto, q("style", "style"))
|
|
535
|
+
style.set(q("style", "family"), "paragraph")
|
|
536
|
+
if name:
|
|
537
|
+
style.set(q("style", "parent-style-name"), name)
|
|
538
|
+
style.set(q("style", "name"), new_name)
|
|
539
|
+
props = style.find(q("style", "paragraph-properties"))
|
|
540
|
+
if props is None:
|
|
541
|
+
props = etree.Element(q("style", "paragraph-properties"))
|
|
542
|
+
style.insert(0, props)
|
|
543
|
+
props.set(q("fo", "text-align"), odf_align)
|
|
544
|
+
return new_name
|
|
545
|
+
|
|
546
|
+
# -- ready-made parts (元素) -------------------------------------------------
|
|
547
|
+
|
|
548
|
+
def _op_add_component(self, op: Dict[str, Any]) -> List[str]:
|
|
549
|
+
from .components import KINDS, build, infer_theme
|
|
550
|
+
|
|
551
|
+
kind = op.get("kind")
|
|
552
|
+
if kind not in KINDS:
|
|
553
|
+
raise EditError(f"不認得的元素:{kind!r}")
|
|
554
|
+
page_i = int(op.get("page", 0))
|
|
555
|
+
page = self._page(page_i)
|
|
556
|
+
theme = infer_theme(self.content, self.styles)
|
|
557
|
+
specs = build(kind, float(op.get("x", 2)), float(op.get("y", 2)), theme)
|
|
558
|
+
elements = [self._from_spec(spec) for spec in specs]
|
|
559
|
+
if len(elements) == 1:
|
|
560
|
+
node = elements[0]
|
|
561
|
+
else:
|
|
562
|
+
node = etree.Element(q("draw", "g"))
|
|
563
|
+
for el in elements:
|
|
564
|
+
node.append(el)
|
|
565
|
+
self._insert_on_top(page, node)
|
|
566
|
+
return [f"{page_i}/{drawables(page).index(node)}"]
|
|
567
|
+
|
|
568
|
+
def _from_spec(self, spec: Dict[str, Any]) -> etree._Element:
|
|
569
|
+
tag = spec["tag"]
|
|
570
|
+
if tag == "line":
|
|
571
|
+
el = etree.Element(q("draw", "line"))
|
|
572
|
+
el.set(q("draw", "style-name"), self._graphic_style(stroke=spec.get("stroke")))
|
|
573
|
+
for key in ("x1", "y1", "x2", "y2"):
|
|
574
|
+
el.set(q("svg", key), _len(spec[key]))
|
|
575
|
+
return el
|
|
576
|
+
if tag == "text":
|
|
577
|
+
el = etree.Element(q("draw", "frame"))
|
|
578
|
+
el.set(q("draw", "style-name"), self._graphic_style(valign=spec.get("valign", "top")))
|
|
579
|
+
box = etree.SubElement(el, q("draw", "text-box"))
|
|
580
|
+
self._styled_paragraph(box, spec)
|
|
581
|
+
else:
|
|
582
|
+
el = etree.Element(q("draw", "rect" if tag == "rect" else "ellipse"))
|
|
583
|
+
style = spec.get("style") or self._graphic_style(
|
|
584
|
+
fill=spec.get("fill"), stroke=spec.get("stroke")
|
|
585
|
+
)
|
|
586
|
+
el.set(q("draw", "style-name"), style)
|
|
587
|
+
if spec.get("radius") and tag == "rect":
|
|
588
|
+
el.set(q("draw", "corner-radius"), _len(spec["radius"]))
|
|
589
|
+
if spec.get("label"):
|
|
590
|
+
self._styled_paragraph(el, spec["label"])
|
|
591
|
+
for key, attr in (("x", "x"), ("y", "y"), ("w", "width"), ("h", "height")):
|
|
592
|
+
el.set(q("svg", attr), _len(spec[key]))
|
|
593
|
+
return el
|
|
594
|
+
|
|
595
|
+
def _styled_paragraph(self, parent: etree._Element, spec: Dict[str, Any]) -> None:
|
|
596
|
+
paragraph = etree.SubElement(parent, q("text", "p"))
|
|
597
|
+
paragraph.set(q("text", "style-name"), self._paragraph_style(spec))
|
|
598
|
+
_append_lines(paragraph, spec["text"])
|
|
599
|
+
|
|
600
|
+
def _paragraph_style(self, spec: Dict[str, Any]) -> str:
|
|
601
|
+
key = {
|
|
602
|
+
k: spec.get(k)
|
|
603
|
+
for k in ("size", "color", "weight", "font", "align", "italic", "spacing")
|
|
604
|
+
}
|
|
605
|
+
name = "OEdP" + hashlib.sha1(json.dumps(key, sort_keys=True).encode()).hexdigest()[:8]
|
|
606
|
+
if self._has_style(name):
|
|
607
|
+
return name
|
|
608
|
+
style = etree.SubElement(self._automatic_styles(), q("style", "style"))
|
|
609
|
+
style.set(q("style", "name"), name)
|
|
610
|
+
style.set(q("style", "family"), "paragraph")
|
|
611
|
+
para = etree.SubElement(style, q("style", "paragraph-properties"))
|
|
612
|
+
para.set(
|
|
613
|
+
q("fo", "text-align"), {"left": "start", "right": "end"}.get(key["align"], key["align"])
|
|
614
|
+
)
|
|
615
|
+
text = etree.SubElement(style, q("style", "text-properties"))
|
|
616
|
+
for attr in (
|
|
617
|
+
q("fo", "font-size"),
|
|
618
|
+
q("style", "font-size-asian"),
|
|
619
|
+
q("style", "font-size-complex"),
|
|
620
|
+
):
|
|
621
|
+
text.set(attr, f"{float(key['size']):g}pt")
|
|
622
|
+
text.set(q("fo", "color"), key["color"])
|
|
623
|
+
if key["weight"] and key["weight"] >= 600:
|
|
624
|
+
for attr in (
|
|
625
|
+
q("fo", "font-weight"),
|
|
626
|
+
q("style", "font-weight-asian"),
|
|
627
|
+
q("style", "font-weight-complex"),
|
|
628
|
+
):
|
|
629
|
+
text.set(attr, "bold")
|
|
630
|
+
if key["italic"]:
|
|
631
|
+
text.set(q("fo", "font-style"), "italic")
|
|
632
|
+
if key["spacing"]:
|
|
633
|
+
text.set(q("fo", "letter-spacing"), _len(key["spacing"]))
|
|
634
|
+
if key["font"]:
|
|
635
|
+
text.set(q("style", "font-name"), key["font"])
|
|
636
|
+
text.set(q("style", "font-name-asian"), key["font"])
|
|
637
|
+
return name
|
|
638
|
+
|
|
639
|
+
def _graphic_style(
|
|
640
|
+
self, fill: Optional[str] = None, stroke: Optional[str] = None, valign: Optional[str] = None
|
|
641
|
+
) -> str:
|
|
642
|
+
key = json.dumps([fill, stroke, valign])
|
|
643
|
+
name = "OEdG" + hashlib.sha1(key.encode()).hexdigest()[:8]
|
|
644
|
+
if self._has_style(name):
|
|
645
|
+
return name
|
|
646
|
+
style = etree.SubElement(self._automatic_styles(), q("style", "style"))
|
|
647
|
+
style.set(q("style", "name"), name)
|
|
648
|
+
style.set(q("style", "family"), "graphic")
|
|
649
|
+
props = etree.SubElement(style, q("style", "graphic-properties"))
|
|
650
|
+
props.set(q("draw", "fill"), "solid" if fill else "none")
|
|
651
|
+
if fill:
|
|
652
|
+
props.set(q("draw", "fill-color"), fill)
|
|
653
|
+
props.set(q("draw", "stroke"), "solid" if stroke else "none")
|
|
654
|
+
if stroke:
|
|
655
|
+
props.set(q("svg", "stroke-color"), stroke)
|
|
656
|
+
props.set(q("svg", "stroke-width"), "0.75pt")
|
|
657
|
+
if valign:
|
|
658
|
+
props.set(q("draw", "textarea-vertical-align"), valign)
|
|
659
|
+
props.set(q("draw", "auto-grow-height"), "true")
|
|
660
|
+
for side in ("top", "right", "bottom", "left"):
|
|
661
|
+
props.set(q("fo", f"padding-{side}"), "0cm")
|
|
662
|
+
return name
|
|
663
|
+
|
|
664
|
+
def _op_group(self, op: Dict[str, Any]) -> List[str]:
|
|
665
|
+
"""Wrap top-level elements of one page into a ``draw:g``, where the topmost was."""
|
|
666
|
+
ids = op.get("ids")
|
|
667
|
+
if not isinstance(ids, list) or len(ids) < 2:
|
|
668
|
+
raise EditError("至少要選兩個物件才能組成群組")
|
|
669
|
+
found = [self._element(i) for i in ids]
|
|
670
|
+
pages = {page_i for page_i, _, _ in found}
|
|
671
|
+
if len(pages) != 1 or any("." in str(i) for i in ids):
|
|
672
|
+
raise EditError("只能把同一頁、不在其他群組裡的物件組成群組")
|
|
673
|
+
page = self._page(pages.pop())
|
|
674
|
+
members = sorted((index, el) for _, index, el in found)
|
|
675
|
+
group = etree.Element(q("draw", "g"))
|
|
676
|
+
members[-1][1].addnext(group)
|
|
677
|
+
for _, el in members:
|
|
678
|
+
group.append(el)
|
|
679
|
+
page_i = self._pages().index(page)
|
|
680
|
+
return [f"{page_i}/{drawables(page).index(group)}"]
|
|
681
|
+
|
|
682
|
+
def _op_ungroup(self, op: Dict[str, Any]) -> List[str]:
|
|
683
|
+
page_i, _, group = self._element(op.get("id"))
|
|
684
|
+
if group.tag != q("draw", "g") or "." in str(op.get("id")):
|
|
685
|
+
raise EditError("這不是可以解散的群組")
|
|
686
|
+
parent = group.getparent()
|
|
687
|
+
children = list(drawables(group))
|
|
688
|
+
for child in children:
|
|
689
|
+
group.addprevious(child)
|
|
690
|
+
parent.remove(group)
|
|
691
|
+
page = self._page(page_i)
|
|
692
|
+
items = drawables(page)
|
|
693
|
+
return [f"{page_i}/{items.index(child)}" for child in children]
|
|
694
|
+
|
|
695
|
+
def _op_delete(self, op: Dict[str, Any]) -> None:
|
|
696
|
+
_, _, el = self._element(op.get("id"))
|
|
697
|
+
parent = el.getparent()
|
|
698
|
+
parent.remove(el)
|
|
699
|
+
# A group emptied by the delete goes too; it would be an invisible box.
|
|
700
|
+
while parent.tag == q("draw", "g") and not drawables(parent):
|
|
701
|
+
grand = parent.getparent()
|
|
702
|
+
grand.remove(parent)
|
|
703
|
+
parent = grand
|
|
704
|
+
|
|
705
|
+
def _op_duplicate(self, op: Dict[str, Any]) -> List[str]:
|
|
706
|
+
page_i, _, el = self._element(op.get("id"))
|
|
707
|
+
clone = copy.deepcopy(el)
|
|
708
|
+
dx, dy = float(op.get("dx", 0.5)), float(op.get("dy", 0.5))
|
|
709
|
+
_offset(clone, dx, dy)
|
|
710
|
+
clone.attrib.pop(q("draw", "name"), None)
|
|
711
|
+
clone.attrib.pop(q("presentation", "class"), None)
|
|
712
|
+
page = self._page(page_i)
|
|
713
|
+
self._insert_on_top(page, clone)
|
|
714
|
+
return [f"{page_i}/{drawables(page).index(clone)}"]
|
|
715
|
+
|
|
716
|
+
def _insert_on_top(self, page: etree._Element, el: etree._Element) -> None:
|
|
717
|
+
# Above every drawable, below comments and speaker notes (which are not drawn).
|
|
718
|
+
anchor = next((c for c in page if c.tag in (ANNOTATION, q("presentation", "notes"))), None)
|
|
719
|
+
if anchor is not None:
|
|
720
|
+
anchor.addprevious(el)
|
|
721
|
+
else:
|
|
722
|
+
page.append(el)
|
|
723
|
+
|
|
724
|
+
def _op_order(self, op: Dict[str, Any]) -> List[str]:
|
|
725
|
+
page_i, _, el = self._element(op.get("id"))
|
|
726
|
+
page = self._page(page_i)
|
|
727
|
+
to = op.get("to")
|
|
728
|
+
items = drawables(page)
|
|
729
|
+
if to == "front":
|
|
730
|
+
page.remove(el)
|
|
731
|
+
self._insert_on_top(page, el)
|
|
732
|
+
elif to == "back":
|
|
733
|
+
page.remove(el)
|
|
734
|
+
first = drawables(page)
|
|
735
|
+
if first:
|
|
736
|
+
first[0].addprevious(el)
|
|
737
|
+
else:
|
|
738
|
+
page.insert(0, el)
|
|
739
|
+
elif to == "forward":
|
|
740
|
+
i = items.index(el)
|
|
741
|
+
if i + 1 < len(items):
|
|
742
|
+
items[i + 1].addnext(el)
|
|
743
|
+
elif to == "backward":
|
|
744
|
+
i = items.index(el)
|
|
745
|
+
if i > 0:
|
|
746
|
+
items[i - 1].addprevious(el)
|
|
747
|
+
else:
|
|
748
|
+
raise EditError(f"不認得的圖層方向:{to!r}")
|
|
749
|
+
return [f"{page_i}/{drawables(page).index(el)}"]
|
|
750
|
+
|
|
751
|
+
def _op_add_text(self, op: Dict[str, Any]) -> List[str]:
|
|
752
|
+
page_i = int(op.get("page", 0))
|
|
753
|
+
page = self._page(page_i)
|
|
754
|
+
frame = etree.Element(q("draw", "frame"))
|
|
755
|
+
frame.set(q("draw", "style-name"), self._ensure_frame_style())
|
|
756
|
+
for key, attr, default in (
|
|
757
|
+
("x", "x", 2),
|
|
758
|
+
("y", "y", 2),
|
|
759
|
+
("w", "width", 10),
|
|
760
|
+
("h", "height", 1.5),
|
|
761
|
+
):
|
|
762
|
+
frame.set(q("svg", attr), _len(float(op.get(key, default))))
|
|
763
|
+
box = etree.SubElement(frame, q("draw", "text-box"))
|
|
764
|
+
paragraph = etree.SubElement(box, q("text", "p"))
|
|
765
|
+
paragraph.set(q("text", "style-name"), self._ensure_text_style())
|
|
766
|
+
paragraph.text = str(op.get("text", ""))
|
|
767
|
+
self._insert_on_top(page, frame)
|
|
768
|
+
return [f"{page_i}/{drawables(page).index(frame)}"]
|
|
769
|
+
|
|
770
|
+
# -- comments ----------------------------------------------------------------
|
|
771
|
+
|
|
772
|
+
def _op_comment_add(self, op: Dict[str, Any]) -> List[str]:
|
|
773
|
+
"""A comment on an element (``id``) or on a spot of a page (``page``, ``x``, ``y``)."""
|
|
774
|
+
import datetime
|
|
775
|
+
import uuid
|
|
776
|
+
|
|
777
|
+
text = str(op.get("text", "")).strip()
|
|
778
|
+
if not text:
|
|
779
|
+
raise EditError("留言不能是空的")
|
|
780
|
+
target_name = None
|
|
781
|
+
if op.get("id"):
|
|
782
|
+
page_i, _, el = self._element(op["id"])
|
|
783
|
+
target_name = el.get(q("draw", "name"))
|
|
784
|
+
if not target_name:
|
|
785
|
+
target_name = f"odforge-{uuid.uuid4().hex[:8]}"
|
|
786
|
+
el.set(q("draw", "name"), target_name)
|
|
787
|
+
if el.tag == q("draw", "line"):
|
|
788
|
+
x = max(cm(el.get(q("svg", "x1"))), cm(el.get(q("svg", "x2"))))
|
|
789
|
+
y = min(cm(el.get(q("svg", "y1"))), cm(el.get(q("svg", "y2"))))
|
|
790
|
+
else:
|
|
791
|
+
x = cm(el.get(q("svg", "x"))) + cm(el.get(q("svg", "width")))
|
|
792
|
+
y = cm(el.get(q("svg", "y")))
|
|
793
|
+
else:
|
|
794
|
+
page_i = int(op.get("page", 0))
|
|
795
|
+
x, y = float(op.get("x", 1)), float(op.get("y", 1))
|
|
796
|
+
page = self._page(page_i)
|
|
797
|
+
note = etree.Element(ANNOTATION)
|
|
798
|
+
note.set(q("svg", "x"), _len(x))
|
|
799
|
+
note.set(q("svg", "y"), _len(y))
|
|
800
|
+
if target_name:
|
|
801
|
+
note.set(q("odforge", "target"), target_name)
|
|
802
|
+
creator = etree.SubElement(note, q("dc", "creator"))
|
|
803
|
+
creator.text = str(op.get("author") or "我")
|
|
804
|
+
date = etree.SubElement(note, q("dc", "date"))
|
|
805
|
+
date.text = datetime.datetime.now().replace(microsecond=0).isoformat()
|
|
806
|
+
for line in text.split("\n"):
|
|
807
|
+
etree.SubElement(note, q("text", "p")).text = line
|
|
808
|
+
notes = page.find(q("presentation", "notes"))
|
|
809
|
+
if notes is not None:
|
|
810
|
+
notes.addprevious(note)
|
|
811
|
+
else:
|
|
812
|
+
page.append(note)
|
|
813
|
+
return [f"c{page_i}/{annotations(page).index(note)}"]
|
|
814
|
+
|
|
815
|
+
def _op_comments_submit(self, op: Dict[str, Any]) -> List[str]:
|
|
816
|
+
"""Hand every draft comment to the AI (``wait_for_feedback`` picks them up)."""
|
|
817
|
+
submitted = []
|
|
818
|
+
for page_i, page in enumerate(self._pages()):
|
|
819
|
+
for k, note in enumerate(annotations(page)):
|
|
820
|
+
if note.get(q("odforge", "state"), "draft") == "draft":
|
|
821
|
+
note.set(q("odforge", "state"), "submitted")
|
|
822
|
+
submitted.append(f"c{page_i}/{k}")
|
|
823
|
+
if not submitted:
|
|
824
|
+
raise EditError("沒有要交給 AI 的留言")
|
|
825
|
+
return submitted
|
|
826
|
+
|
|
827
|
+
def _op_session(self, op: Dict[str, Any]) -> None:
|
|
828
|
+
"""``{"op": "session", "state": "done" | "open"}``: end (or resume) the AI session."""
|
|
829
|
+
presentation = self._presentation()
|
|
830
|
+
state = op.get("state")
|
|
831
|
+
if state == "done":
|
|
832
|
+
presentation.set(q("odforge", "session"), "done")
|
|
833
|
+
elif state == "open":
|
|
834
|
+
presentation.attrib.pop(q("odforge", "session"), None)
|
|
835
|
+
else:
|
|
836
|
+
raise EditError(f"不認得的協作狀態:{state!r}")
|
|
837
|
+
|
|
838
|
+
def _op_comment_delete(self, op: Dict[str, Any]) -> None:
|
|
839
|
+
try:
|
|
840
|
+
page_part, index_part = str(op.get("comment", "")).lstrip("c").split("/")
|
|
841
|
+
page_i, k = int(page_part), int(index_part)
|
|
842
|
+
except ValueError as exc:
|
|
843
|
+
raise EditError(f"留言代號不正確:{op.get('comment')!r}") from exc
|
|
844
|
+
notes = annotations(self._page(page_i))
|
|
845
|
+
if not 0 <= k < len(notes):
|
|
846
|
+
raise EditError(f"找不到留言 {op.get('comment')}")
|
|
847
|
+
notes[k].getparent().remove(notes[k])
|
|
848
|
+
|
|
849
|
+
# -- clipboard ---------------------------------------------------------------
|
|
850
|
+
|
|
851
|
+
def clip(self, ids: List[str]) -> List[str]:
|
|
852
|
+
"""The XML of elements, for pasting later (on any page of this document)."""
|
|
853
|
+
with self._lock:
|
|
854
|
+
self._sync()
|
|
855
|
+
return [
|
|
856
|
+
etree.tostring(self._element(element_id)[2], encoding="unicode")
|
|
857
|
+
for element_id in ids
|
|
858
|
+
]
|
|
859
|
+
|
|
860
|
+
def _op_paste(self, op: Dict[str, Any]) -> List[str]:
|
|
861
|
+
page_i = int(op.get("page", 0))
|
|
862
|
+
page = self._page(page_i)
|
|
863
|
+
items = op.get("items")
|
|
864
|
+
if not isinstance(items, list) or not items:
|
|
865
|
+
raise EditError("沒有可以貼上的內容")
|
|
866
|
+
dx, dy = float(op.get("dx", 0)), float(op.get("dy", 0))
|
|
867
|
+
created: List[str] = []
|
|
868
|
+
for item in items:
|
|
869
|
+
try:
|
|
870
|
+
el = safe_fromstring(str(item).encode("utf-8"))
|
|
871
|
+
except etree.XMLSyntaxError as exc:
|
|
872
|
+
raise EditError("剪貼簿的內容無法貼上") from exc
|
|
873
|
+
if etree.QName(el).namespace != NS["draw"] or etree.QName(el).localname == "page":
|
|
874
|
+
raise EditError("剪貼簿的內容不是投影片上的物件")
|
|
875
|
+
el.attrib.pop(q("presentation", "class"), None)
|
|
876
|
+
el.attrib.pop(q("draw", "name"), None)
|
|
877
|
+
_offset(el, dx, dy)
|
|
878
|
+
self._insert_on_top(page, el)
|
|
879
|
+
created.append(el)
|
|
880
|
+
return [f"{page_i}/{drawables(page).index(el)}" for el in created]
|
|
881
|
+
|
|
882
|
+
# -- pictures ------------------------------------------------------------------
|
|
883
|
+
|
|
884
|
+
def _op_add_image(self, op: Dict[str, Any]) -> List[str]:
|
|
885
|
+
import base64
|
|
886
|
+
|
|
887
|
+
page_i = int(op.get("page", 0))
|
|
888
|
+
page = self._page(page_i)
|
|
889
|
+
try:
|
|
890
|
+
data = base64.b64decode(str(op.get("data", "")), validate=True)
|
|
891
|
+
except ValueError as exc:
|
|
892
|
+
raise EditError("圖片資料不正確") from exc
|
|
893
|
+
if len(data) > MAX_IMAGE_BYTES:
|
|
894
|
+
raise EditError("圖片太大(上限 15 MB)")
|
|
895
|
+
if data.startswith(b"\x89PNG\r\n\x1a\n"):
|
|
896
|
+
ext, media = "png", "image/png"
|
|
897
|
+
elif data.startswith(b"\xff\xd8\xff"):
|
|
898
|
+
ext, media = "jpg", "image/jpeg"
|
|
899
|
+
else:
|
|
900
|
+
raise EditError("只支援 PNG 或 JPEG 圖片")
|
|
901
|
+
href = f"Pictures/{hashlib.sha1(data).hexdigest()[:16]}.{ext}"
|
|
902
|
+
if self._member(href) is None:
|
|
903
|
+
info = zipfile.ZipInfo(href)
|
|
904
|
+
info.compress_type = zipfile.ZIP_STORED
|
|
905
|
+
self._members.append((info, data))
|
|
906
|
+
self._add_manifest_entry(href, media)
|
|
907
|
+
frame = etree.Element(q("draw", "frame"))
|
|
908
|
+
frame.set(q("draw", "style-name"), self._ensure_frame_style())
|
|
909
|
+
for key, attr, default in (
|
|
910
|
+
("x", "x", 2),
|
|
911
|
+
("y", "y", 2),
|
|
912
|
+
("w", "width", 8),
|
|
913
|
+
("h", "height", 6),
|
|
914
|
+
):
|
|
915
|
+
frame.set(q("svg", attr), _len(float(op.get(key, default))))
|
|
916
|
+
image = etree.SubElement(frame, q("draw", "image"))
|
|
917
|
+
image.set(q("xlink", "href"), href)
|
|
918
|
+
image.set(q("xlink", "type"), "simple")
|
|
919
|
+
image.set(q("xlink", "show"), "embed")
|
|
920
|
+
image.set(q("xlink", "actuate"), "onLoad")
|
|
921
|
+
self._insert_on_top(page, frame)
|
|
922
|
+
return [f"{page_i}/{drawables(page).index(frame)}"]
|
|
923
|
+
|
|
924
|
+
def _add_manifest_entry(self, path: str, media: str) -> None:
|
|
925
|
+
manifest_ns = "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"
|
|
926
|
+
raw = self._member("META-INF/manifest.xml")
|
|
927
|
+
if raw is None:
|
|
928
|
+
return
|
|
929
|
+
manifest = safe_fromstring(raw)
|
|
930
|
+
entry = etree.SubElement(manifest, f"{{{manifest_ns}}}file-entry")
|
|
931
|
+
entry.set(f"{{{manifest_ns}}}full-path", path)
|
|
932
|
+
entry.set(f"{{{manifest_ns}}}media-type", media)
|
|
933
|
+
data = etree.tostring(manifest, xml_declaration=True, encoding="UTF-8")
|
|
934
|
+
self._members = [
|
|
935
|
+
(info, data if info.filename == "META-INF/manifest.xml" else body)
|
|
936
|
+
for info, body in self._members
|
|
937
|
+
]
|
|
938
|
+
|
|
939
|
+
def _op_add_rect(self, op: Dict[str, Any]) -> List[str]:
|
|
940
|
+
page_i = int(op.get("page", 0))
|
|
941
|
+
page = self._page(page_i)
|
|
942
|
+
rect = etree.Element(q("draw", "rect"))
|
|
943
|
+
rect.set(q("draw", "style-name"), self._ensure_rect_style())
|
|
944
|
+
for key, attr, default in (
|
|
945
|
+
("x", "x", 4),
|
|
946
|
+
("y", "y", 4),
|
|
947
|
+
("w", "width", 6),
|
|
948
|
+
("h", "height", 4),
|
|
949
|
+
):
|
|
950
|
+
rect.set(q("svg", attr), _len(float(op.get(key, default))))
|
|
951
|
+
self._insert_on_top(page, rect)
|
|
952
|
+
return [f"{page_i}/{drawables(page).index(rect)}"]
|
|
953
|
+
|
|
954
|
+
# -- pages --------------------------------------------------------------------
|
|
955
|
+
|
|
956
|
+
def _unique_page_name(self) -> str:
|
|
957
|
+
names = {p.get(q("draw", "name")) for p in self._pages()}
|
|
958
|
+
n = len(names) + 1
|
|
959
|
+
while f"page{n}" in names:
|
|
960
|
+
n += 1
|
|
961
|
+
return f"page{n}"
|
|
962
|
+
|
|
963
|
+
def _op_page_add(self, op: Dict[str, Any]) -> List[str]:
|
|
964
|
+
pages = self._pages()
|
|
965
|
+
after = int(op.get("after", len(pages) - 1))
|
|
966
|
+
anchor = self._page(after)
|
|
967
|
+
page = etree.Element(q("draw", "page"))
|
|
968
|
+
for attr in (
|
|
969
|
+
q("draw", "style-name"),
|
|
970
|
+
q("draw", "master-page-name"),
|
|
971
|
+
q("presentation", "presentation-page-layout-name"),
|
|
972
|
+
):
|
|
973
|
+
if anchor.get(attr):
|
|
974
|
+
page.set(attr, anchor.get(attr))
|
|
975
|
+
page.set(q("draw", "name"), self._unique_page_name())
|
|
976
|
+
anchor.addnext(page)
|
|
977
|
+
return [f"page:{after + 1}"]
|
|
978
|
+
|
|
979
|
+
def _op_page_duplicate(self, op: Dict[str, Any]) -> List[str]:
|
|
980
|
+
index = int(op.get("page", 0))
|
|
981
|
+
source = self._page(index)
|
|
982
|
+
clone = copy.deepcopy(source)
|
|
983
|
+
clone.set(q("draw", "name"), self._unique_page_name())
|
|
984
|
+
source.addnext(clone)
|
|
985
|
+
return [f"page:{index + 1}"]
|
|
986
|
+
|
|
987
|
+
def _op_page_delete(self, op: Dict[str, Any]) -> None:
|
|
988
|
+
if len(self._pages()) <= 1:
|
|
989
|
+
raise EditError("簡報至少要留一頁")
|
|
990
|
+
page = self._page(op.get("page"))
|
|
991
|
+
page.getparent().remove(page)
|
|
992
|
+
|
|
993
|
+
def _op_page_move(self, op: Dict[str, Any]) -> List[str]:
|
|
994
|
+
pages = self._pages()
|
|
995
|
+
page = self._page(op.get("page"))
|
|
996
|
+
to = int(op.get("to", 0))
|
|
997
|
+
if not 0 <= to < len(pages):
|
|
998
|
+
raise EditError(f"沒有第 {to + 1} 頁")
|
|
999
|
+
others = [p for p in pages if p is not page]
|
|
1000
|
+
page.getparent().remove(page)
|
|
1001
|
+
if to < len(others):
|
|
1002
|
+
others[to].addprevious(page)
|
|
1003
|
+
else:
|
|
1004
|
+
others[-1].addnext(page)
|
|
1005
|
+
return [f"page:{to}"]
|
|
1006
|
+
|
|
1007
|
+
# -- styles for new elements -------------------------------------------------
|
|
1008
|
+
|
|
1009
|
+
def _automatic_styles(self) -> etree._Element:
|
|
1010
|
+
auto = self.content.find(q("office", "automatic-styles"))
|
|
1011
|
+
if auto is None:
|
|
1012
|
+
auto = etree.Element(q("office", "automatic-styles"))
|
|
1013
|
+
body = self.content.find(q("office", "body"))
|
|
1014
|
+
body.addprevious(auto)
|
|
1015
|
+
return auto
|
|
1016
|
+
|
|
1017
|
+
def _has_style(self, name: str) -> bool:
|
|
1018
|
+
return any(
|
|
1019
|
+
el.get(q("style", "name")) == name
|
|
1020
|
+
for el in self._automatic_styles().iter(q("style", "style"))
|
|
1021
|
+
)
|
|
1022
|
+
|
|
1023
|
+
def _ensure_text_style(self) -> str:
|
|
1024
|
+
if not self._has_style(_TEXT_STYLE):
|
|
1025
|
+
font = self._common_font()
|
|
1026
|
+
style = etree.SubElement(self._automatic_styles(), q("style", "style"))
|
|
1027
|
+
style.set(q("style", "name"), _TEXT_STYLE)
|
|
1028
|
+
style.set(q("style", "family"), "paragraph")
|
|
1029
|
+
text = etree.SubElement(style, q("style", "text-properties"))
|
|
1030
|
+
for attr in (
|
|
1031
|
+
q("fo", "font-size"),
|
|
1032
|
+
q("style", "font-size-asian"),
|
|
1033
|
+
q("style", "font-size-complex"),
|
|
1034
|
+
):
|
|
1035
|
+
text.set(attr, "18pt")
|
|
1036
|
+
text.set(q("fo", "color"), "#1F2733")
|
|
1037
|
+
if font:
|
|
1038
|
+
text.set(q("style", "font-name"), font)
|
|
1039
|
+
text.set(q("style", "font-name-asian"), font)
|
|
1040
|
+
return _TEXT_STYLE
|
|
1041
|
+
|
|
1042
|
+
def _ensure_frame_style(self) -> str:
|
|
1043
|
+
if not self._has_style(_FRAME_STYLE):
|
|
1044
|
+
style = etree.SubElement(self._automatic_styles(), q("style", "style"))
|
|
1045
|
+
style.set(q("style", "name"), _FRAME_STYLE)
|
|
1046
|
+
style.set(q("style", "family"), "graphic")
|
|
1047
|
+
props = etree.SubElement(style, q("style", "graphic-properties"))
|
|
1048
|
+
props.set(q("draw", "fill"), "none")
|
|
1049
|
+
props.set(q("draw", "stroke"), "none")
|
|
1050
|
+
props.set(q("draw", "auto-grow-height"), "true")
|
|
1051
|
+
for side in ("top", "right", "bottom", "left"):
|
|
1052
|
+
props.set(q("fo", f"padding-{side}"), "0cm")
|
|
1053
|
+
return _FRAME_STYLE
|
|
1054
|
+
|
|
1055
|
+
def _ensure_rect_style(self) -> str:
|
|
1056
|
+
if not self._has_style(_RECT_STYLE):
|
|
1057
|
+
style = etree.SubElement(self._automatic_styles(), q("style", "style"))
|
|
1058
|
+
style.set(q("style", "name"), _RECT_STYLE)
|
|
1059
|
+
style.set(q("style", "family"), "graphic")
|
|
1060
|
+
props = etree.SubElement(style, q("style", "graphic-properties"))
|
|
1061
|
+
props.set(q("draw", "fill"), "solid")
|
|
1062
|
+
props.set(q("draw", "fill-color"), "#E8ECF4")
|
|
1063
|
+
props.set(q("draw", "stroke"), "none")
|
|
1064
|
+
return _RECT_STYLE
|
|
1065
|
+
|
|
1066
|
+
def _common_font(self) -> Optional[str]:
|
|
1067
|
+
counts: Counter[str] = Counter()
|
|
1068
|
+
for el in self.content.iter(q("style", "text-properties")):
|
|
1069
|
+
name = el.get(q("style", "font-name"))
|
|
1070
|
+
if name:
|
|
1071
|
+
counts[name] += 1
|
|
1072
|
+
return counts.most_common(1)[0][0] if counts else None
|
|
1073
|
+
|
|
1074
|
+
|
|
1075
|
+
def _paragraph_text(paragraph: etree._Element) -> str:
|
|
1076
|
+
parts: List[str] = []
|
|
1077
|
+
|
|
1078
|
+
def walk(el: etree._Element) -> None:
|
|
1079
|
+
parts.append(el.text or "")
|
|
1080
|
+
for child in el:
|
|
1081
|
+
if child.tag == q("text", "s"):
|
|
1082
|
+
parts.append(" " * int(child.get(q("text", "c"), "1")))
|
|
1083
|
+
elif child.tag == q("text", "tab"):
|
|
1084
|
+
parts.append("\t")
|
|
1085
|
+
elif child.tag == q("text", "line-break"):
|
|
1086
|
+
parts.append("\n")
|
|
1087
|
+
else:
|
|
1088
|
+
walk(child)
|
|
1089
|
+
parts.append(child.tail or "")
|
|
1090
|
+
|
|
1091
|
+
walk(paragraph)
|
|
1092
|
+
return "".join(parts)
|
|
1093
|
+
|
|
1094
|
+
|
|
1095
|
+
def _set_paragraph_text(paragraph: etree._Element, text: str) -> None:
|
|
1096
|
+
"""Replace a paragraph's text, keeping its paragraph style and first span's look."""
|
|
1097
|
+
span_style = None
|
|
1098
|
+
first_span = paragraph.find(q("text", "span"))
|
|
1099
|
+
if first_span is not None and len(paragraph) == 1 and not (paragraph.text or "").strip():
|
|
1100
|
+
span_style = first_span.get(q("text", "style-name"))
|
|
1101
|
+
for child in list(paragraph):
|
|
1102
|
+
paragraph.remove(child)
|
|
1103
|
+
paragraph.text = None
|
|
1104
|
+
target = paragraph
|
|
1105
|
+
if span_style:
|
|
1106
|
+
target = etree.SubElement(paragraph, q("text", "span"))
|
|
1107
|
+
target.set(q("text", "style-name"), span_style)
|
|
1108
|
+
lines = text.split("\n")
|
|
1109
|
+
target.text = lines[0]
|
|
1110
|
+
for line in lines[1:]:
|
|
1111
|
+
br = etree.SubElement(target, q("text", "line-break"))
|
|
1112
|
+
br.tail = line
|
|
1113
|
+
|
|
1114
|
+
|
|
1115
|
+
_RUN_DEFAULTS: Dict[str, Any] = {"weight": 400, "italic": False, "underline": False}
|
|
1116
|
+
|
|
1117
|
+
|
|
1118
|
+
def _run_diff(run: Dict[str, Any], base: Dict[str, Any]) -> Dict[str, Any]:
|
|
1119
|
+
"""The run's look where it differs from its paragraph's own style."""
|
|
1120
|
+
diff: Dict[str, Any] = {}
|
|
1121
|
+
for key in ("weight", "italic", "underline", "color", "size", "family"):
|
|
1122
|
+
if key not in run or run[key] is None:
|
|
1123
|
+
continue
|
|
1124
|
+
value = run[key]
|
|
1125
|
+
if key == "family":
|
|
1126
|
+
current_family = (base.get("family") or [None])[0]
|
|
1127
|
+
if str(value) != current_family:
|
|
1128
|
+
diff["family"] = str(value)
|
|
1129
|
+
continue
|
|
1130
|
+
if key == "weight":
|
|
1131
|
+
value = 700 if float(value) >= 600 else 400
|
|
1132
|
+
elif key == "size":
|
|
1133
|
+
value = round(float(value) * 2) / 2
|
|
1134
|
+
elif key == "color":
|
|
1135
|
+
value = str(value).upper()
|
|
1136
|
+
current = base.get(key, _RUN_DEFAULTS.get(key))
|
|
1137
|
+
if key == "weight" and current is not None:
|
|
1138
|
+
current = 700 if float(current) >= 600 else 400
|
|
1139
|
+
if key == "color" and current:
|
|
1140
|
+
current = str(current).upper()
|
|
1141
|
+
if key == "size" and current is not None:
|
|
1142
|
+
current = round(float(current) * 2) / 2
|
|
1143
|
+
if value != current:
|
|
1144
|
+
diff[key] = value
|
|
1145
|
+
return diff
|
|
1146
|
+
|
|
1147
|
+
|
|
1148
|
+
def _append_lines(parent: etree._Element, text: str) -> None:
|
|
1149
|
+
"""Append text (with ``\n`` as line breaks) after the parent's last child."""
|
|
1150
|
+
lines = text.split("\n")
|
|
1151
|
+
for i, line in enumerate(lines):
|
|
1152
|
+
if i:
|
|
1153
|
+
etree.SubElement(parent, q("text", "line-break"))
|
|
1154
|
+
if not line:
|
|
1155
|
+
continue
|
|
1156
|
+
if len(parent):
|
|
1157
|
+
parent[-1].tail = (parent[-1].tail or "") + line
|
|
1158
|
+
else:
|
|
1159
|
+
parent.text = (parent.text or "") + line
|
|
1160
|
+
|
|
1161
|
+
|
|
1162
|
+
def _write_lines(target: etree._Element, text: str) -> None:
|
|
1163
|
+
target.text = None
|
|
1164
|
+
_append_lines(target, text)
|
|
1165
|
+
|
|
1166
|
+
|
|
1167
|
+
def _theme_summary(content: etree._Element, styles: etree._Element) -> Dict[str, Any]:
|
|
1168
|
+
from .components import infer_theme
|
|
1169
|
+
|
|
1170
|
+
theme = infer_theme(content, styles)
|
|
1171
|
+
return {"accent": theme.accent, "ink": theme.ink, "muted": theme.muted}
|
|
1172
|
+
|
|
1173
|
+
|
|
1174
|
+
def _group_box(group: etree._Element) -> Tuple[float, float, float, float]:
|
|
1175
|
+
xs: List[float] = []
|
|
1176
|
+
ys: List[float] = []
|
|
1177
|
+
for el in group.iter():
|
|
1178
|
+
if el is group or not isinstance(el.tag, str):
|
|
1179
|
+
continue
|
|
1180
|
+
if el.get(q("svg", "x1")) is not None:
|
|
1181
|
+
xs += [cm(el.get(q("svg", "x1"))), cm(el.get(q("svg", "x2")))]
|
|
1182
|
+
ys += [cm(el.get(q("svg", "y1"))), cm(el.get(q("svg", "y2")))]
|
|
1183
|
+
elif el.get(q("svg", "x")) is not None and el.get(q("svg", "width")) is not None:
|
|
1184
|
+
x, y = cm(el.get(q("svg", "x"))), cm(el.get(q("svg", "y")))
|
|
1185
|
+
xs += [x, x + cm(el.get(q("svg", "width")))]
|
|
1186
|
+
ys += [y, y + cm(el.get(q("svg", "height")))]
|
|
1187
|
+
if not xs:
|
|
1188
|
+
raise EditError("空的群組")
|
|
1189
|
+
return min(xs), min(ys), max(xs) - min(xs), max(ys) - min(ys)
|
|
1190
|
+
|
|
1191
|
+
|
|
1192
|
+
def _transform(
|
|
1193
|
+
group: etree._Element, ox: float, oy: float, nx: float, ny: float, sx: float, sy: float
|
|
1194
|
+
) -> None:
|
|
1195
|
+
"""Map every child box from the old group box onto the new one."""
|
|
1196
|
+
for el in group.iter():
|
|
1197
|
+
if el is group or not isinstance(el.tag, str):
|
|
1198
|
+
continue
|
|
1199
|
+
for x_attr, y_attr in (("x", "y"), ("x1", "y1"), ("x2", "y2")):
|
|
1200
|
+
if el.get(q("svg", x_attr)) is not None:
|
|
1201
|
+
el.set(q("svg", x_attr), _len(nx + (cm(el.get(q("svg", x_attr))) - ox) * sx))
|
|
1202
|
+
if el.get(q("svg", y_attr)) is not None:
|
|
1203
|
+
el.set(q("svg", y_attr), _len(ny + (cm(el.get(q("svg", y_attr))) - oy) * sy))
|
|
1204
|
+
if el.get(q("svg", "width")) is not None:
|
|
1205
|
+
el.set(q("svg", "width"), _len(max(0.05, cm(el.get(q("svg", "width"))) * sx)))
|
|
1206
|
+
if el.get(q("svg", "height")) is not None:
|
|
1207
|
+
el.set(q("svg", "height"), _len(max(0.05, cm(el.get(q("svg", "height"))) * sy)))
|
|
1208
|
+
|
|
1209
|
+
|
|
1210
|
+
def _offset(el: etree._Element, dx: float, dy: float) -> None:
|
|
1211
|
+
from .scene import cm
|
|
1212
|
+
|
|
1213
|
+
for attr, delta in (("x", dx), ("y", dy), ("x1", dx), ("x2", dx), ("y1", dy), ("y2", dy)):
|
|
1214
|
+
value = el.get(q("svg", attr))
|
|
1215
|
+
if value is not None:
|
|
1216
|
+
el.set(q("svg", attr), _len(cm(value) + delta))
|
|
1217
|
+
|
|
1218
|
+
|
|
1219
|
+
__all__ = ["NS", "Document", "EditError"]
|