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.
Files changed (66) hide show
  1. odforge/__init__.py +1 -0
  2. odforge/benchmark.py +287 -0
  3. odforge/check.py +416 -0
  4. odforge/cli.py +1027 -0
  5. odforge/components.py +270 -0
  6. odforge/critic.py +1260 -0
  7. odforge/docfonts.py +104 -0
  8. odforge/editor_api.py +33 -0
  9. odforge/editor_launch.py +134 -0
  10. odforge/editor_routes.py +131 -0
  11. odforge/extract.py +478 -0
  12. odforge/feedback.py +86 -0
  13. odforge/fontembed.py +166 -0
  14. odforge/ir.py +1181 -0
  15. odforge/layoutcheck.py +602 -0
  16. odforge/llm.py +1865 -0
  17. odforge/localguard.py +42 -0
  18. odforge/mcp_server.py +552 -0
  19. odforge/media.py +352 -0
  20. odforge/odpedit.py +1219 -0
  21. odforge/package.py +114 -0
  22. odforge/pagefacts.py +388 -0
  23. odforge/preview.py +104 -0
  24. odforge/references.py +153 -0
  25. odforge/render/__init__.py +40 -0
  26. odforge/render/odp.py +5687 -0
  27. odforge/render/ods.py +155 -0
  28. odforge/render/odt.py +223 -0
  29. odforge/scene.py +657 -0
  30. odforge/setup_agents.py +274 -0
  31. odforge/skills/odforge-design/SKILL.md +298 -0
  32. odforge/skills/odforge-design/themes/academic.md +52 -0
  33. odforge/skills/odforge-design/themes/clay.md +53 -0
  34. odforge/skills/odforge-design/themes/color-system.md +59 -0
  35. odforge/skills/odforge-design/themes/crimson.md +53 -0
  36. odforge/skills/odforge-design/themes/dark.md +53 -0
  37. odforge/skills/odforge-design/themes/forest.md +54 -0
  38. odforge/skills/odforge-design/themes/gold.md +53 -0
  39. odforge/skills/odforge-design/themes/minimal.md +53 -0
  40. odforge/skills/odforge-design/themes/navy.md +56 -0
  41. odforge/skills/odforge-design/themes/plum.md +53 -0
  42. odforge/skills/odforge-design/themes/sky.md +53 -0
  43. odforge/skills/odforge-design/themes/slate.md +53 -0
  44. odforge/skills/odforge-design/themes/teal.md +53 -0
  45. odforge/skills/odforge-design/themes/violet.md +56 -0
  46. odforge/templates.py +250 -0
  47. odforge/textmetrics.py +616 -0
  48. odforge/textutil.py +24 -0
  49. odforge/themes.py +886 -0
  50. odforge/validate.py +403 -0
  51. odforge/watch.py +266 -0
  52. odforge/webapi.py +2617 -0
  53. odforge/webui/assets/editor-CjpYXM1a.css +1 -0
  54. odforge/webui/assets/editor-DPToJGio.js +3 -0
  55. odforge/webui/assets/jsx-runtime-C7KMcVI_.js +8 -0
  56. odforge/webui/assets/main-BLOs7Hnk.js +7 -0
  57. odforge/webui/assets/main-D21yFVE6.css +1 -0
  58. odforge/webui/editor.html +14 -0
  59. odforge/webui/index.html +25 -0
  60. odforge/xmlsafe.py +46 -0
  61. odforge/zipguard.py +91 -0
  62. odforge-0.3.0.dist-info/METADATA +95 -0
  63. odforge-0.3.0.dist-info/RECORD +66 -0
  64. odforge-0.3.0.dist-info/WHEEL +4 -0
  65. odforge-0.3.0.dist-info/entry_points.txt +3 -0
  66. odforge-0.3.0.dist-info/licenses/LICENSE +21 -0
odforge/scene.py ADDED
@@ -0,0 +1,657 @@
1
+ """An ``.odp`` as a scene the browser can draw and edit (網頁編輯器的資料來源).
2
+
3
+ The web editor does not show pictures of slides; it draws each slide from the
4
+ document itself — every rectangle, line, image and text frame at its own place,
5
+ with its own fill, stroke, font and paragraph settings — so that a person can
6
+ grab a frame and move it, or click into text and type. This module reads an
7
+ ``.odp`` package and returns that description as plain JSON-able data.
8
+
9
+ Element ids are positions: ``"<page>/<index>"``, the index counting the page's
10
+ drawable children in document (paint) order. They are stable across edits that
11
+ only change geometry or text, and the editor re-reads the scene after anything
12
+ structural (add, delete, reorder), so positions are all an id needs to be.
13
+
14
+ Anything this module cannot faithfully draw (custom shapes, tables, groups,
15
+ rotated objects, embedded objects) still appears, as an ``unsupported`` box at
16
+ its declared place: the editor shows it, can move it, and never touches its
17
+ content.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import re
23
+ import zipfile
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path
26
+ from typing import Any, Dict, Iterable, List, Optional, Tuple
27
+
28
+ from lxml import etree
29
+
30
+ from .xmlsafe import safe_fromstring
31
+
32
+ NS = {
33
+ "office": "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
34
+ "style": "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
35
+ "text": "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
36
+ "draw": "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
37
+ "fo": "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
38
+ "svg": "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
39
+ "xlink": "http://www.w3.org/1999/xlink",
40
+ "presentation": "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0",
41
+ "loext": "urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0",
42
+ # Impress stores slide comments as officeooo:annotation inside draw:page.
43
+ "officeooo": "http://openoffice.org/2009/office",
44
+ "dc": "http://purl.org/dc/elements/1.1/",
45
+ # Which element a comment is about (by draw:name); ODF has no word for it.
46
+ "odforge": "urn:odforge:editor:1",
47
+ }
48
+
49
+
50
+ def q(prefix: str, local: str) -> str:
51
+ """Clark-notation name: ``q("draw", "frame")`` → ``{urn…drawing…}frame``."""
52
+ return f"{{{NS[prefix]}}}{local}"
53
+
54
+
55
+ PT_TO_CM = 2.54 / 72
56
+
57
+ # Drawable children of a page, by what the editor can do with them.
58
+ _SHAPES = {
59
+ q("draw", "rect"): "rect",
60
+ q("draw", "ellipse"): "ellipse",
61
+ q("draw", "circle"): "ellipse",
62
+ }
63
+ _LINE = q("draw", "line")
64
+ _FRAME = q("draw", "frame")
65
+ _NOTES = q("presentation", "notes")
66
+ _FORMS = q("office", "forms")
67
+ ANNOTATION = q("officeooo", "annotation")
68
+
69
+
70
+ def cm(value: Optional[str], default: float = 0.0) -> float:
71
+ """An ODF length in centimetres (``"6.8cm"``, ``"12pt"``, ``"3mm"``, ``"1in"``)."""
72
+ if not value:
73
+ return default
74
+ match = re.match(r"^\s*(-?[0-9.]+)\s*([a-z%]*)\s*$", value)
75
+ if not match:
76
+ return default
77
+ number, unit = float(match.group(1)), match.group(2)
78
+ return {
79
+ "cm": number,
80
+ "": number,
81
+ "mm": number / 10,
82
+ "in": number * 2.54,
83
+ "pt": number * PT_TO_CM,
84
+ "pc": number * 12 * PT_TO_CM,
85
+ "px": number * 2.54 / 96,
86
+ }.get(unit, default)
87
+
88
+
89
+ def pt(value: Optional[str]) -> Optional[float]:
90
+ """A font size in points; ``None`` for relative (``%``) or missing sizes."""
91
+ if not value:
92
+ return None
93
+ match = re.match(r"^\s*([0-9.]+)\s*(pt|cm|mm|in|px)\s*$", value)
94
+ if not match:
95
+ return None
96
+ if match.group(2) == "pt":
97
+ return float(match.group(1))
98
+ return cm(value) / PT_TO_CM
99
+
100
+
101
+ # ---------------------------------------------------------------------------
102
+ # Styles
103
+ # ---------------------------------------------------------------------------
104
+
105
+
106
+ class Styles:
107
+ """Every named style in the package, resolved through ``parent-style-name``.
108
+
109
+ Lookups merge a style's property sets with its ancestors' and the family's
110
+ default style, nearest first — what LibreOffice does when it lays a page out.
111
+ """
112
+
113
+ _KINDS = (
114
+ "graphic-properties",
115
+ "paragraph-properties",
116
+ "text-properties",
117
+ "drawing-page-properties",
118
+ "list-level-properties",
119
+ )
120
+
121
+ def __init__(self, roots: Iterable[etree._Element]) -> None:
122
+ self.styles: Dict[Tuple[str, str], etree._Element] = {}
123
+ self.defaults: Dict[str, etree._Element] = {}
124
+ self.list_styles: Dict[str, etree._Element] = {}
125
+ self.fonts: Dict[str, str] = {}
126
+ for root in roots:
127
+ for el in root.iter(q("style", "style")):
128
+ name = el.get(q("style", "name"))
129
+ family = el.get(q("style", "family"), "")
130
+ if name:
131
+ self.styles.setdefault((family, name), el)
132
+ for el in root.iter(q("style", "default-style")):
133
+ self.defaults.setdefault(el.get(q("style", "family"), ""), el)
134
+ for el in root.iter(q("text", "list-style")):
135
+ name = el.get(q("style", "name"))
136
+ if name:
137
+ self.list_styles.setdefault(name, el)
138
+ for el in root.iter(q("style", "font-face")):
139
+ name = el.get(q("style", "name"))
140
+ family = el.get(q("svg", "font-family"), name or "")
141
+ if name:
142
+ self.fonts[name] = family.strip("'\"")
143
+
144
+ def _chain(self, family: str, name: Optional[str]) -> List[etree._Element]:
145
+ chain: List[etree._Element] = []
146
+ seen = set()
147
+ while name and (family, name) not in seen:
148
+ seen.add((family, name))
149
+ el = self.styles.get((family, name))
150
+ if el is None:
151
+ break
152
+ chain.append(el)
153
+ name = el.get(q("style", "parent-style-name"))
154
+ if family in self.defaults:
155
+ chain.append(self.defaults[family])
156
+ return chain
157
+
158
+ def props(self, family: str, name: Optional[str], kind: str) -> Dict[str, str]:
159
+ """Merged ``{"ns:attr": value}`` of one property set, nearest style wins."""
160
+ merged: Dict[str, str] = {}
161
+ for el in reversed(self._chain(family, name)):
162
+ for props in el.findall(q("style", kind)):
163
+ for key, value in props.attrib.items():
164
+ merged[_short(key)] = value
165
+ return merged
166
+
167
+
168
+ def _short(clark: str) -> str:
169
+ """``{urn…fo…}color`` → ``fo:color``."""
170
+ uri, _, local = clark[1:].partition("}")
171
+ for prefix, value in NS.items():
172
+ if value == uri:
173
+ return f"{prefix}:{local}"
174
+ return local
175
+
176
+
177
+ # ---------------------------------------------------------------------------
178
+ # Text
179
+ # ---------------------------------------------------------------------------
180
+
181
+
182
+ def _text_style(props: Dict[str, str], fonts: Dict[str, str]) -> Dict[str, Any]:
183
+ """CSS-ready text settings from merged ``text-properties``."""
184
+ out: Dict[str, Any] = {}
185
+ size = pt(props.get("fo:font-size")) or pt(props.get("style:font-size-asian"))
186
+ if size:
187
+ out["size"] = size
188
+ if "fo:color" in props:
189
+ out["color"] = props["fo:color"]
190
+ weight = props.get("fo:font-weight") or props.get("style:font-weight-asian")
191
+ if weight:
192
+ out["weight"] = 700 if weight == "bold" else 400 if weight == "normal" else int(weight)
193
+ if props.get("fo:font-style") == "italic":
194
+ out["italic"] = True
195
+ families = []
196
+ for key in ("style:font-name", "style:font-name-asian"):
197
+ name = props.get(key)
198
+ if name:
199
+ families.append(fonts.get(name, name))
200
+ if not families and props.get("fo:font-family"):
201
+ families.append(props["fo:font-family"].strip("'\""))
202
+ if families:
203
+ out["family"] = list(dict.fromkeys(families))
204
+ spacing = props.get("fo:letter-spacing")
205
+ if spacing and spacing != "normal":
206
+ out["letterSpacing"] = cm(spacing)
207
+ if props.get("style:text-underline-style", "none") != "none":
208
+ out["underline"] = True
209
+ return out
210
+
211
+
212
+ def _paragraph_style(props: Dict[str, str]) -> Dict[str, Any]:
213
+ out: Dict[str, Any] = {}
214
+ align = props.get("fo:text-align")
215
+ if align:
216
+ out["align"] = {"start": "left", "end": "right"}.get(align, align)
217
+ height = props.get("fo:line-height")
218
+ if height and height != "normal":
219
+ if height.endswith("%"):
220
+ out["lineHeight"] = float(height[:-1]) / 100
221
+ else:
222
+ out["lineHeightCm"] = cm(height)
223
+ for key, name in (
224
+ ("fo:margin-top", "marginTop"),
225
+ ("fo:margin-bottom", "marginBottom"),
226
+ ("fo:margin-left", "marginLeft"),
227
+ ("fo:text-indent", "indent"),
228
+ ):
229
+ if key in props:
230
+ out[name] = cm(props[key])
231
+ return out
232
+
233
+
234
+ @dataclass
235
+ class _Run:
236
+ text: str
237
+ style: Dict[str, Any] = field(default_factory=dict)
238
+
239
+
240
+ def _runs(
241
+ paragraph: etree._Element, styles: Styles, base: Dict[str, str], page_no: int
242
+ ) -> List[_Run]:
243
+ """The paragraph's text as styled runs; line breaks become ``"\\n"``."""
244
+ runs: List[_Run] = []
245
+
246
+ def add(text: str, props: Dict[str, str]) -> None:
247
+ if not text:
248
+ return
249
+ style = _text_style(props, styles.fonts)
250
+ if runs and runs[-1].style == style:
251
+ runs[-1].text += text
252
+ else:
253
+ runs.append(_Run(text, style))
254
+
255
+ def walk(el: etree._Element, props: Dict[str, str]) -> None:
256
+ add(el.text or "", props)
257
+ for child in el:
258
+ tag = child.tag
259
+ if tag == q("text", "span"):
260
+ merged = {
261
+ **props,
262
+ **styles.props("text", child.get(q("text", "style-name")), "text-properties"),
263
+ }
264
+ walk(child, merged)
265
+ elif tag == q("text", "s"):
266
+ add(" " * int(child.get(q("text", "c"), "1")), props)
267
+ elif tag == q("text", "tab"):
268
+ add("\t", props)
269
+ elif tag == q("text", "line-break"):
270
+ add("\n", props)
271
+ elif tag == q("text", "page-number"):
272
+ add(str(page_no), props)
273
+ else:
274
+ walk(child, props)
275
+ add(child.tail or "", props)
276
+
277
+ walk(paragraph, base)
278
+ return runs
279
+
280
+
281
+ def _bullet(
282
+ list_style: Optional[etree._Element], level: int, styles: Styles
283
+ ) -> Optional[Dict[str, Any]]:
284
+ if list_style is None:
285
+ return {"char": "•", "indent": 0.6 * level, "width": 0.6}
286
+ for child in list_style:
287
+ if child.get(q("text", "level")) != str(level):
288
+ continue
289
+ props: Dict[str, str] = {}
290
+ for p in child.findall(q("style", "list-level-properties")):
291
+ props.update({_short(k): v for k, v in p.attrib.items()})
292
+ before = cm(props.get("text:space-before"))
293
+ width = cm(props.get("text:min-label-width"), 0.6)
294
+ if child.tag == q("text", "list-level-style-bullet"):
295
+ return {
296
+ "char": child.get(q("text", "bullet-char"), "•"),
297
+ "indent": before,
298
+ "width": width,
299
+ }
300
+ if child.tag == q("text", "list-level-style-number"):
301
+ return {
302
+ "char": "#",
303
+ "number": True,
304
+ "suffix": child.get(q("style", "num-suffix"), "."),
305
+ "indent": before,
306
+ "width": width,
307
+ }
308
+ return None
309
+ return {"char": "•", "indent": 0.6 * level, "width": 0.6}
310
+
311
+
312
+ def text_paragraphs(box: etree._Element, styles: Styles, page_no: int) -> List[Dict[str, Any]]:
313
+ """Every paragraph of a text box in document order, lists included."""
314
+ out: List[Dict[str, Any]] = []
315
+
316
+ def visit(
317
+ el: etree._Element, list_style: Optional[etree._Element], level: int, counters: List[int]
318
+ ) -> None:
319
+ for child in el:
320
+ if child.tag in (q("text", "p"), q("text", "h")):
321
+ name = child.get(q("text", "style-name"))
322
+ para = _paragraph_style(styles.props("paragraph", name, "paragraph-properties"))
323
+ base = styles.props("paragraph", name, "text-properties")
324
+ runs = _runs(child, styles, base, page_no)
325
+ entry: Dict[str, Any] = {
326
+ **para,
327
+ "runs": [{"text": r.text, **r.style} for r in runs],
328
+ "style": _text_style(base, styles.fonts),
329
+ }
330
+ if level:
331
+ bullet = _bullet(list_style, level, styles)
332
+ if bullet is not None:
333
+ if bullet.get("number"):
334
+ counters[level - 1] += 1
335
+ bullet = {**bullet, "char": f"{counters[level - 1]}{bullet['suffix']}"}
336
+ entry["bullet"] = bullet
337
+ out.append(entry)
338
+ elif child.tag == q("text", "list"):
339
+ name = child.get(q("text", "style-name"))
340
+ nested = styles.list_styles.get(name) if name else list_style
341
+ visit(
342
+ child, nested, level + 1, [*counters, 0] if len(counters) <= level else counters
343
+ )
344
+ elif child.tag in (q("text", "list-item"), q("text", "list-header")):
345
+ visit(child, list_style, level, counters)
346
+
347
+ visit(box, None, 0, [])
348
+ return out
349
+
350
+
351
+ def plain_text(paragraph: Dict[str, Any]) -> str:
352
+ return "".join(run["text"] for run in paragraph["runs"])
353
+
354
+
355
+ # ---------------------------------------------------------------------------
356
+ # Shapes
357
+ # ---------------------------------------------------------------------------
358
+
359
+
360
+ def _box(el: etree._Element) -> Dict[str, float]:
361
+ return {
362
+ "x": cm(el.get(q("svg", "x"))),
363
+ "y": cm(el.get(q("svg", "y"))),
364
+ "w": cm(el.get(q("svg", "width"))),
365
+ "h": cm(el.get(q("svg", "height"))),
366
+ }
367
+
368
+
369
+ def _paint(props: Dict[str, str]) -> Dict[str, Any]:
370
+ out: Dict[str, Any] = {}
371
+ fill = props.get("draw:fill", "solid" if "draw:fill-color" in props else "none")
372
+ if fill == "solid":
373
+ out["fill"] = props.get("draw:fill-color", "#729fcf")
374
+ opacity = props.get("draw:opacity")
375
+ if opacity and opacity.endswith("%"):
376
+ out["fillOpacity"] = float(opacity[:-1]) / 100
377
+ elif fill == "gradient":
378
+ out["fill"] = props.get("draw:fill-color", "#cccccc")
379
+ stroke = props.get("draw:stroke", "solid" if "svg:stroke-color" in props else "none")
380
+ if stroke != "none":
381
+ out["stroke"] = props.get("svg:stroke-color", "#3465a4")
382
+ out["strokeWidth"] = cm(props.get("svg:stroke-width"), 0.0)
383
+ if stroke == "dash":
384
+ out["dashed"] = True
385
+ return out
386
+
387
+
388
+ # LibreOffice's built-in text-area insets, used when no style in the chain sets
389
+ # padding: a quarter centimetre left and right, an eighth top and bottom.
390
+ _DEFAULT_PADDING = {"top": 0.125, "right": 0.25, "bottom": 0.125, "left": 0.25}
391
+
392
+
393
+ def _text_frame_settings(props: Dict[str, str]) -> Dict[str, Any]:
394
+ pad = props.get("fo:padding")
395
+ out: Dict[str, Any] = {
396
+ "padding": {
397
+ side: cm(props.get(f"fo:padding-{side}", pad), _DEFAULT_PADDING[side])
398
+ if props.get(f"fo:padding-{side}", pad) is not None
399
+ else _DEFAULT_PADDING[side]
400
+ for side in ("top", "right", "bottom", "left")
401
+ },
402
+ "valign": props.get("draw:textarea-vertical-align", "top"),
403
+ }
404
+ if props.get("draw:auto-grow-height") == "false":
405
+ out["clip"] = True
406
+ return out
407
+
408
+
409
+ def element(el: etree._Element, styles: Styles, page_no: int, element_id: str) -> Dict[str, Any]:
410
+ """One drawable element of a page as JSON-able data."""
411
+ style_name = el.get(q("draw", "style-name")) or el.get(q("presentation", "style-name"))
412
+ family = (
413
+ "presentation"
414
+ if el.get(q("presentation", "style-name")) and not el.get(q("draw", "style-name"))
415
+ else "graphic"
416
+ )
417
+ graphic = styles.props(family, style_name, "graphic-properties")
418
+ out: Dict[str, Any] = {"id": element_id}
419
+ name = el.get(q("draw", "name"))
420
+ if name:
421
+ out["name"] = name
422
+ if el.get(q("draw", "transform")):
423
+ out.update(kind="unsupported", reason="旋轉或變形的物件", **_box(el))
424
+ return out
425
+
426
+ if el.tag in _SHAPES:
427
+ out.update(kind=_SHAPES[el.tag], **_box(el), **_paint(graphic))
428
+ radius = el.get(q("draw", "corner-radius"))
429
+ if radius:
430
+ out["radius"] = cm(radius)
431
+ paragraphs = text_paragraphs(el, styles, page_no)
432
+ if paragraphs:
433
+ out["text"] = {"paragraphs": paragraphs, **_text_frame_settings(graphic)}
434
+ out["text"]["valign"] = graphic.get("draw:textarea-vertical-align", "middle")
435
+ return out
436
+
437
+ if el.tag == _LINE:
438
+ out.update(
439
+ kind="line",
440
+ x1=cm(el.get(q("svg", "x1"))),
441
+ y1=cm(el.get(q("svg", "y1"))),
442
+ x2=cm(el.get(q("svg", "x2"))),
443
+ y2=cm(el.get(q("svg", "y2"))),
444
+ **_paint({**graphic, "draw:fill": "none"}),
445
+ )
446
+ return out
447
+
448
+ if el.tag == _FRAME:
449
+ out.update(_box(el))
450
+ box = el.find(q("draw", "text-box"))
451
+ image = el.find(q("draw", "image"))
452
+ if box is not None:
453
+ out["kind"] = "text"
454
+ out["text"] = {
455
+ "paragraphs": text_paragraphs(box, styles, page_no),
456
+ **_text_frame_settings(graphic),
457
+ }
458
+ out.update(_paint(graphic))
459
+ placeholder = el.get(q("presentation", "class"))
460
+ if placeholder:
461
+ out["placeholder"] = placeholder
462
+ return out
463
+ if image is not None:
464
+ href = image.get(q("xlink", "href"), "")
465
+ if href and not href.startswith(("http:", "https:", "/")) and ".." not in href:
466
+ out.update(kind="image", href=href.lstrip("./"))
467
+ return out
468
+ out.update(kind="unsupported", reason="表格、圖表或內嵌物件")
469
+ return out
470
+
471
+ if el.tag == q("draw", "g"):
472
+ children = [
473
+ element(child, styles, page_no, f"{element_id}.{k}")
474
+ for k, child in enumerate(drawables(el))
475
+ ]
476
+ if children:
477
+ boxes = [_bounds(c) for c in children]
478
+ x = min(b[0] for b in boxes)
479
+ y = min(b[1] for b in boxes)
480
+ out.update(
481
+ kind="group",
482
+ x=x,
483
+ y=y,
484
+ w=max(b[0] + b[2] for b in boxes) - x,
485
+ h=max(b[1] + b[3] for b in boxes) - y,
486
+ children=children,
487
+ )
488
+ return out
489
+
490
+ out.update(kind="unsupported", reason="自訂圖形", **_box(el))
491
+ return out
492
+
493
+
494
+ def _bounds(el: Dict[str, Any]) -> Tuple[float, float, float, float]:
495
+ if el["kind"] == "line":
496
+ x, y = min(el["x1"], el["x2"]), min(el["y1"], el["y2"])
497
+ return x, y, abs(el["x2"] - el["x1"]), abs(el["y2"] - el["y1"])
498
+ return el["x"], el["y"], el["w"], el["h"]
499
+
500
+
501
+ def walk_ids(container: etree._Element, prefix: str):
502
+ """Every drawable under ``container`` with its id, groups descended."""
503
+ for j, el in enumerate(drawables(container)):
504
+ element_id = f"{prefix}{j}" if prefix.endswith("/") else f"{prefix}.{j}"
505
+ yield element_id, el
506
+ if el.tag == q("draw", "g"):
507
+ yield from walk_ids(el, element_id)
508
+
509
+
510
+ def drawables(page: etree._Element) -> List[etree._Element]:
511
+ """The page's drawable children in paint order (speaker notes and forms excluded)."""
512
+ return [
513
+ child
514
+ for child in page
515
+ if isinstance(child.tag, str) and child.tag not in (_NOTES, _FORMS, ANNOTATION)
516
+ ]
517
+
518
+
519
+ def annotations(page: etree._Element) -> List[etree._Element]:
520
+ return [child for child in page if child.tag == ANNOTATION]
521
+
522
+
523
+ def comments_of(page: etree._Element, index: int) -> List[Dict[str, Any]]:
524
+ """The page's comments, each tied to the element it names when that still exists."""
525
+ names = {
526
+ el.get(q("draw", "name")): element_id
527
+ for element_id, el in walk_ids(page, f"{index}/")
528
+ if el.get(q("draw", "name"))
529
+ }
530
+ out = []
531
+ for k, note in enumerate(annotations(page)):
532
+ text = "\n".join("".join(p.itertext()) for p in note.iter(q("text", "p")))
533
+ creator = note.find(q("dc", "creator"))
534
+ date = note.find(q("dc", "date"))
535
+ out.append(
536
+ {
537
+ "id": f"c{index}/{k}",
538
+ "text": text,
539
+ "author": (creator.text or "") if creator is not None else "",
540
+ "date": (date.text or "") if date is not None else "",
541
+ "x": cm(note.get(q("svg", "x"))),
542
+ "y": cm(note.get(q("svg", "y"))),
543
+ "target": names.get(note.get(q("odforge", "target"))),
544
+ # draft: still being written; submitted: handed to the AI to act on.
545
+ "state": note.get(q("odforge", "state"), "draft"),
546
+ }
547
+ )
548
+ return out
549
+
550
+
551
+ # ---------------------------------------------------------------------------
552
+ # The scene
553
+ # ---------------------------------------------------------------------------
554
+
555
+
556
+ def _page_settings(page: etree._Element, styles: Styles) -> Dict[str, Any]:
557
+ props = styles.props(
558
+ "drawing-page", page.get(q("draw", "style-name")), "drawing-page-properties"
559
+ )
560
+ out: Dict[str, Any] = {}
561
+ if props.get("draw:fill", "solid" if "draw:fill-color" in props else "none") != "none":
562
+ out["background"] = props.get("draw:fill-color", "#ffffff")
563
+ if "presentation:display-page-number" in props:
564
+ out["showPageNumber"] = props["presentation:display-page-number"] == "true"
565
+ return out
566
+
567
+
568
+ def build_scene(content: etree._Element, styles_root: etree._Element) -> Dict[str, Any]:
569
+ """The whole presentation as the editor needs it."""
570
+ styles = Styles((content, styles_root))
571
+
572
+ width, height = 28.0, 15.75
573
+ layouts = {el.get(q("style", "name")): el for el in styles_root.iter(q("style", "page-layout"))}
574
+ masters: Dict[str, etree._Element] = {
575
+ el.get(q("style", "name")): el for el in styles_root.iter(q("style", "master-page"))
576
+ }
577
+ first_master = next(iter(masters.values()), None)
578
+ if first_master is not None:
579
+ layout = layouts.get(first_master.get(q("style", "page-layout-name")))
580
+ if layout is not None:
581
+ props = layout.find(q("style", "page-layout-properties"))
582
+ if props is not None:
583
+ width = cm(props.get(q("fo", "page-width")), width)
584
+ height = cm(props.get(q("fo", "page-height")), height)
585
+
586
+ pages: List[Dict[str, Any]] = []
587
+ for index, page in enumerate(content.iter(q("draw", "page"))):
588
+ page_no = index + 1
589
+ master_name = page.get(q("draw", "master-page-name"))
590
+ master = masters.get(master_name) if master_name else first_master
591
+ settings = _page_settings(page, styles)
592
+ if "background" not in settings and master is not None:
593
+ master_settings = _page_settings(master, styles)
594
+ settings.setdefault("background", master_settings.get("background"))
595
+ settings.setdefault("showPageNumber", master_settings.get("showPageNumber", False))
596
+ background_elements: List[Dict[str, Any]] = []
597
+ if master is not None:
598
+ for j, el in enumerate(drawables(master)):
599
+ if el.get(q("presentation", "class")) == "page-number" and not settings.get(
600
+ "showPageNumber"
601
+ ):
602
+ continue
603
+ if (
604
+ el.get(q("presentation", "class"))
605
+ and el.get(q("presentation", "class")) != "page-number"
606
+ ):
607
+ # Title/outline placeholders on a master are prompts, not content.
608
+ continue
609
+ background_elements.append(element(el, styles, page_no, f"m{index}/{j}"))
610
+ pages.append(
611
+ {
612
+ "id": str(index),
613
+ "name": page.get(q("draw", "name"), f"page{page_no}"),
614
+ "background": settings.get("background") or "#ffffff",
615
+ "master": background_elements,
616
+ "elements": [
617
+ element(el, styles, page_no, f"{index}/{j}")
618
+ for j, el in enumerate(drawables(page))
619
+ ],
620
+ "comments": comments_of(page, index),
621
+ }
622
+ )
623
+
624
+ fonts = []
625
+ seen_hrefs = set()
626
+ faces = [*content.iter(q("style", "font-face")), *styles_root.iter(q("style", "font-face"))]
627
+ for face in faces:
628
+ family = face.get(q("svg", "font-family"), face.get(q("style", "name"), "")).strip("'\"")
629
+ for uri in face.iter(q("svg", "font-face-uri")):
630
+ href = uri.get(q("xlink", "href"), "")
631
+ if href.startswith("Fonts/") and ".." not in href and href not in seen_hrefs:
632
+ seen_hrefs.add(href)
633
+ fonts.append(
634
+ {
635
+ "family": family,
636
+ "href": href,
637
+ "weight": 700 if uri.get(q("loext", "font-weight")) == "bold" else 400,
638
+ "italic": uri.get(q("loext", "font-style")) == "italic",
639
+ }
640
+ )
641
+ return {"width": width, "height": height, "pages": pages, "fonts": fonts}
642
+
643
+
644
+ def read_package(path: Path) -> Tuple[etree._Element, etree._Element]:
645
+ with zipfile.ZipFile(path) as package:
646
+ content = safe_fromstring(package.read("content.xml"))
647
+ try:
648
+ styles = safe_fromstring(package.read("styles.xml"))
649
+ except KeyError:
650
+ styles = etree.Element(q("office", "document-styles"))
651
+ return content, styles
652
+
653
+
654
+ def scene_of(path: Path) -> Dict[str, Any]:
655
+ """Convenience: the scene of an ``.odp`` on disk."""
656
+ content, styles = read_package(Path(path))
657
+ return build_scene(content, styles)