@mutallip/google-workspace-mcp 0.0.0-stage → 2.8.0

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 (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +353 -2
  3. package/README.npm.md +28 -0
  4. package/auth/__init__.py +1 -0
  5. package/auth/auth_info_middleware.py +419 -0
  6. package/auth/client_secrets.py +76 -0
  7. package/auth/credential_store.py +598 -0
  8. package/auth/external_oauth_provider.py +369 -0
  9. package/auth/gateway_identity.py +164 -0
  10. package/auth/google_auth.py +1550 -0
  11. package/auth/google_oauth_provider.py +20 -0
  12. package/auth/mcp_session_middleware.py +95 -0
  13. package/auth/oauth21_session_store.py +1332 -0
  14. package/auth/oauth_callback_server.py +466 -0
  15. package/auth/oauth_config.py +693 -0
  16. package/auth/oauth_proxy_config.py +122 -0
  17. package/auth/oauth_responses.py +230 -0
  18. package/auth/oauth_types.py +92 -0
  19. package/auth/permissions.py +330 -0
  20. package/auth/port_resolver.py +153 -0
  21. package/auth/request_identity.py +89 -0
  22. package/auth/scopes.py +369 -0
  23. package/auth/service_decorator.py +1109 -0
  24. package/bin/google-workspace-mcp.cjs +123 -0
  25. package/core/__init__.py +1 -0
  26. package/core/api_enablement.py +108 -0
  27. package/core/attachment_storage.py +496 -0
  28. package/core/camel_case_middleware.py +98 -0
  29. package/core/cli.py +161 -0
  30. package/core/comments.py +609 -0
  31. package/core/config.py +57 -0
  32. package/core/context.py +43 -0
  33. package/core/file_limits.py +632 -0
  34. package/core/gcs_attachment_storage.py +253 -0
  35. package/core/http_utils.py +339 -0
  36. package/core/log_formatter.py +270 -0
  37. package/core/portable_schema_middleware.py +67 -0
  38. package/core/server.py +1192 -0
  39. package/core/startup_ui.py +239 -0
  40. package/core/storage.py +23 -0
  41. package/core/telemetry.py +194 -0
  42. package/core/tool_descriptions.py +19 -0
  43. package/core/tool_registry.py +311 -0
  44. package/core/tool_tier_loader.py +197 -0
  45. package/core/tool_tiers.yaml +179 -0
  46. package/core/toolset_header_middleware.py +67 -0
  47. package/core/utils.py +1537 -0
  48. package/core/valkey_storage.py +271 -0
  49. package/core/warning_filters.py +19 -0
  50. package/fastmcp_server.py +198 -0
  51. package/gappsscript/README.md +512 -0
  52. package/gappsscript/TESTING.md +254 -0
  53. package/gappsscript/__init__.py +0 -0
  54. package/gappsscript/apps_script_tools.py +1940 -0
  55. package/gcalendar/__init__.py +1 -0
  56. package/gcalendar/calendar_helpers.py +1323 -0
  57. package/gcalendar/calendar_tools.py +2252 -0
  58. package/gchat/__init__.py +7 -0
  59. package/gchat/chat_helpers.py +410 -0
  60. package/gchat/chat_tools.py +798 -0
  61. package/gcontacts/__init__.py +1 -0
  62. package/gcontacts/contacts_helpers.py +765 -0
  63. package/gcontacts/contacts_tools.py +1685 -0
  64. package/gdocs/__init__.py +0 -0
  65. package/gdocs/docs_anchors.py +163 -0
  66. package/gdocs/docs_comments.py +89 -0
  67. package/gdocs/docs_helpers.py +2201 -0
  68. package/gdocs/docs_links.py +87 -0
  69. package/gdocs/docs_markdown.py +828 -0
  70. package/gdocs/docs_markdown_writer.py +592 -0
  71. package/gdocs/docs_plain_text.py +463 -0
  72. package/gdocs/docs_structure.py +621 -0
  73. package/gdocs/docs_tables.py +425 -0
  74. package/gdocs/docs_tools.py +3300 -0
  75. package/gdocs/managers/__init__.py +18 -0
  76. package/gdocs/managers/batch_operation_manager.py +1694 -0
  77. package/gdocs/managers/header_footer_manager.py +526 -0
  78. package/gdocs/managers/table_operation_manager.py +488 -0
  79. package/gdocs/managers/validation_manager.py +1504 -0
  80. package/gdocs/operation_schemas.py +594 -0
  81. package/gdrive/__init__.py +0 -0
  82. package/gdrive/drive_helpers.py +1738 -0
  83. package/gdrive/drive_tools.py +3085 -0
  84. package/gforms/__init__.py +3 -0
  85. package/gforms/forms_tools.py +575 -0
  86. package/gmail/__init__.py +1 -0
  87. package/gmail/gmail_helpers.py +2107 -0
  88. package/gmail/gmail_tools.py +4895 -0
  89. package/gmail/gmail_web_mime.py +441 -0
  90. package/gsearch/__init__.py +0 -0
  91. package/gsearch/search_tools.py +253 -0
  92. package/gsheets/__init__.py +31 -0
  93. package/gsheets/sheets_helpers.py +2236 -0
  94. package/gsheets/sheets_tools.py +3280 -0
  95. package/gslides/__init__.py +0 -0
  96. package/gslides/slides_digest.py +390 -0
  97. package/gslides/slides_helpers.py +392 -0
  98. package/gslides/slides_markup.py +770 -0
  99. package/gslides/slides_tools.py +376 -0
  100. package/gtasks/__init__.py +5 -0
  101. package/gtasks/tasks_tools.py +936 -0
  102. package/main.py +1170 -0
  103. package/package.json +43 -4
  104. package/pyproject.toml +173 -0
  105. package/uv.lock +2504 -0
@@ -0,0 +1,770 @@
1
+ """
2
+ Google Slides markup: the JSON projection of a page that
3
+ ``get_presentation(action="markup")`` returns.
4
+
5
+ Turns a Slides API ``Page`` resource into compact, index-free and matrix-free
6
+ JSON: points instead of EMU, a resolved ``box`` instead of a transform,
7
+ paragraphs and runs instead of indexed text elements, and a style table so a
8
+ style shared by many runs is written once. Values the API reports but that
9
+ carry no information (editor defaults on shapes with no placeholder, styling a
10
+ link or bold implies) are left out. Each element carries ``v``, a short hash of
11
+ its canonical projection, so a later edit can tell whether it changed.
12
+
13
+ Autofit is reported as displayed: a shape the API reports with a font scale
14
+ below 1 is shrunk, whether its autofit is set locally or inherited.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import json
21
+ import math
22
+ from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple
23
+
24
+ EMU_PER_PT = 12700
25
+ _BULLET_INDENT_PT = 36.0
26
+
27
+
28
+ def _pt(value: Optional[float]) -> Optional[float]:
29
+ """Round a point value to 0.01 pt; integers print without a fraction."""
30
+ if value is None:
31
+ return None
32
+ rounded = round(value, 2)
33
+ return int(rounded) if rounded == int(rounded) else rounded
34
+
35
+
36
+ def _geo_pt(value: float) -> int:
37
+ """Geometry is whole points: finer than the editor's 0.01 inch (0.72 pt)."""
38
+ return int(round(value))
39
+
40
+
41
+ def _dim_pt(dim: Optional[Dict[str, Any]]) -> Optional[float]:
42
+ if not dim or "magnitude" not in dim:
43
+ return None
44
+ mag = dim["magnitude"]
45
+ if dim.get("unit", "EMU") == "EMU":
46
+ mag = mag / EMU_PER_PT
47
+ return _pt(mag)
48
+
49
+
50
+ # --- Geometry --------------------------------------------------------------
51
+
52
+
53
+ def _matrix(transform: Optional[Dict[str, Any]]) -> Tuple[float, ...]:
54
+ """(a, b, c, d, tx, ty) in EMU, where x' = a*x + c*y + tx, y' = b*x + d*y + ty.
55
+
56
+ The API omits zero-valued fields, so a missing scale is 0, not 1.
57
+ """
58
+ if not transform:
59
+ return (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)
60
+ t = transform
61
+ scale = EMU_PER_PT if t.get("unit") == "PT" else 1
62
+ return (
63
+ t.get("scaleX", 0.0),
64
+ t.get("shearY", 0.0),
65
+ t.get("shearX", 0.0),
66
+ t.get("scaleY", 0.0),
67
+ t.get("translateX", 0.0) * scale,
68
+ t.get("translateY", 0.0) * scale,
69
+ )
70
+
71
+
72
+ def _compose(parent: Tuple[float, ...], child: Tuple[float, ...]) -> Tuple[float, ...]:
73
+ """Parent applied after child."""
74
+ a1, b1, c1, d1, e1, f1 = parent
75
+ a2, b2, c2, d2, e2, f2 = child
76
+ return (
77
+ a1 * a2 + c1 * b2,
78
+ b1 * a2 + d1 * b2,
79
+ a1 * c2 + c1 * d2,
80
+ b1 * c2 + d1 * d2,
81
+ a1 * e2 + c1 * f2 + e1,
82
+ b1 * e2 + d1 * f2 + f1,
83
+ )
84
+
85
+
86
+ def project_box(
87
+ matrix: Tuple[float, ...], size: Optional[Dict[str, Any]]
88
+ ) -> Dict[str, Any]:
89
+ """The element's unrotated bounding box on the page, in points."""
90
+ a, b, c, d, tx, ty = matrix
91
+ width = (size or {}).get("width", {}).get("magnitude", 0) or 0
92
+ height = (size or {}).get("height", {}).get("magnitude", 0) or 0
93
+
94
+ sx = math.hypot(a, b)
95
+ det = a * d - b * c
96
+ box: Dict[str, Any] = {}
97
+ if sx == 0:
98
+ return {
99
+ "x": _geo_pt(tx / EMU_PER_PT),
100
+ "y": _geo_pt(ty / EMU_PER_PT),
101
+ "w": 0,
102
+ "h": 0,
103
+ }
104
+ sy = det / sx
105
+ # Shear left after removing rotation: zero for scale + rotation + flip.
106
+ skew = (a * c + b * d) / (sx * sx)
107
+ rot = math.degrees(math.atan2(b, a))
108
+ flip = ""
109
+ if sy < 0:
110
+ # A mirror plus a rotation; report it as a vertical flip plus the
111
+ # remaining rotation, which is one canonical form of the same matrix.
112
+ flip = "v"
113
+ sy = -sy
114
+ w = width * sx
115
+ h = height * sy
116
+ cx = a * width / 2 + c * height / 2 + tx
117
+ cy = b * width / 2 + d * height / 2 + ty
118
+ box["x"] = _geo_pt((cx - w / 2) / EMU_PER_PT)
119
+ box["y"] = _geo_pt((cy - h / 2) / EMU_PER_PT)
120
+ box["w"] = _geo_pt(w / EMU_PER_PT)
121
+ box["h"] = _geo_pt(h / EMU_PER_PT)
122
+ rot = round(rot, 2) % 360
123
+ if rot and abs(rot - 360) > 0.005:
124
+ box["rot"] = _pt(rot)
125
+ if flip:
126
+ box["flip"] = flip
127
+ if abs(skew) > 1e-6:
128
+ box["skewed"] = True
129
+ return box
130
+
131
+
132
+ # --- Colours, links, styles -------------------------------------------------
133
+
134
+
135
+ def _color(color: Optional[Dict[str, Any]]) -> Optional[str]:
136
+ if not color:
137
+ return None
138
+ opaque = color.get("opaqueColor", color)
139
+ if "themeColor" in opaque:
140
+ return opaque["themeColor"]
141
+ rgb = opaque.get("rgbColor")
142
+ if rgb is not None:
143
+ return "#" + "".join(
144
+ f"{round(rgb.get(ch, 0) * 255):02x}" for ch in ("red", "green", "blue")
145
+ )
146
+ if color == {}:
147
+ return "transparent"
148
+ return None
149
+
150
+
151
+ def _link(link: Optional[Dict[str, Any]]) -> Optional[str]:
152
+ if not link:
153
+ return None
154
+ if "url" in link:
155
+ return link["url"]
156
+ if "pageObjectId" in link:
157
+ return f"slide:{link['pageObjectId']}"
158
+ if "relativeLink" in link:
159
+ return link["relativeLink"]
160
+ if "slideIndex" in link:
161
+ return f"slide_index:{link['slideIndex']}"
162
+ return None
163
+
164
+
165
+ def project_text_style(
166
+ style: Optional[Dict[str, Any]], inherits: bool = False
167
+ ) -> Dict[str, Any]:
168
+ """Locally set run style fields, in projection names.
169
+
170
+ Text with no placeholder parent reports every flag resolved, so only true
171
+ is information; text that ``inherits`` reports overrides, so false is too.
172
+ """
173
+ s = style or {}
174
+ out: Dict[str, Any] = {}
175
+ for api, name in (
176
+ ("bold", "bold"),
177
+ ("italic", "italic"),
178
+ ("underline", "underline"),
179
+ ("strikethrough", "strike"),
180
+ ("smallCaps", "small_caps"),
181
+ ):
182
+ if s.get(api) or (inherits and api in s):
183
+ out[name] = bool(s[api])
184
+ if s.get("baselineOffset") in ("SUPERSCRIPT", "SUBSCRIPT"):
185
+ out["baseline"] = s["baselineOffset"]
186
+ weighted = s.get("weightedFontFamily") or {}
187
+ font = weighted.get("fontFamily") or s.get("fontFamily")
188
+ if font:
189
+ out["font"] = font
190
+ weight = weighted.get("weight")
191
+ # The API reports weight 700 alongside bold; bold already says it.
192
+ if weight and weight != 400 and not (out.get("bold") and weight == 700):
193
+ out["weight"] = weight
194
+ size = _dim_pt(s.get("fontSize"))
195
+ if size is not None:
196
+ out["size"] = size
197
+ if "foregroundColor" in s:
198
+ color = _color(s["foregroundColor"])
199
+ if color:
200
+ out["color"] = color
201
+ if "backgroundColor" in s:
202
+ bg = _color(s["backgroundColor"])
203
+ if bg and bg != "transparent":
204
+ out["bg"] = bg
205
+ link = _link(s.get("link"))
206
+ if link:
207
+ out["link"] = link
208
+ # Setting a link applies underline and the HYPERLINK colour.
209
+ if out.get("underline"):
210
+ out.pop("underline")
211
+ if out.get("color") == "HYPERLINK":
212
+ out.pop("color")
213
+ return out
214
+
215
+
216
+ class StyleTable:
217
+ """Interns run styles as s1, s2, ... in first-use order."""
218
+
219
+ def __init__(self) -> None:
220
+ self._by_key: Dict[str, str] = {}
221
+ self.entries: Dict[str, Dict[str, Any]] = {}
222
+
223
+ def ref(self, style: Dict[str, Any]) -> str:
224
+ key = json.dumps(style, sort_keys=True)
225
+ if key not in self._by_key:
226
+ alias = f"s{len(self._by_key) + 1}"
227
+ self._by_key[key] = alias
228
+ self.entries[alias] = style
229
+ return self._by_key[key]
230
+
231
+
232
+ class ListTable:
233
+ """Interns API list IDs as L1, L2, ... within one response."""
234
+
235
+ def __init__(self) -> None:
236
+ self._by_id: Dict[str, str] = {}
237
+
238
+ def ref(self, list_id: str) -> str:
239
+ if list_id not in self._by_id:
240
+ self._by_id[list_id] = f"L{len(self._by_id) + 1}"
241
+ return self._by_id[list_id]
242
+
243
+
244
+ # --- Text -------------------------------------------------------------------
245
+
246
+
247
+ _PARA_FIELDS = (
248
+ ("alignment", "align"),
249
+ ("spaceAbove", "space_above"),
250
+ ("spaceBelow", "space_below"),
251
+ ("lineSpacing", "line_spacing"),
252
+ ("indentStart", "indent_start"),
253
+ ("indentFirstLine", "indent_first_line"),
254
+ ("indentEnd", "indent_end"),
255
+ ("direction", "direction"),
256
+ )
257
+
258
+
259
+ def _paragraph_props(
260
+ style: Dict[str, Any],
261
+ level: Optional[int],
262
+ defaults: Optional[Dict[str, Any]] = None,
263
+ inherits: bool = False,
264
+ ) -> Dict[str, Any]:
265
+ props: Dict[str, Any] = {}
266
+ for api, name in _PARA_FIELDS:
267
+ if api not in style:
268
+ continue
269
+ value = style[api]
270
+ if isinstance(value, dict):
271
+ # A dimension with no magnitude is zero: an override only on
272
+ # inheriting text, the editor default elsewhere.
273
+ value = _dim_pt({"magnitude": 0, **value} if inherits else value)
274
+ if value is None:
275
+ continue
276
+ elif api == "lineSpacing":
277
+ value = _pt(value)
278
+ elif api == "direction" and value == "LEFT_TO_RIGHT":
279
+ continue
280
+ if defaults and defaults.get(name) == value:
281
+ continue
282
+ props[name] = value
283
+ if level is not None:
284
+ # The indent a bullet puts there is not a paragraph prop.
285
+ if props.get("indent_start") == _pt(_BULLET_INDENT_PT * (level + 1)):
286
+ props.pop("indent_start")
287
+ if props.get("indent_first_line") == _pt(_BULLET_INDENT_PT * level + 18):
288
+ props.pop("indent_first_line")
289
+ return props
290
+
291
+
292
+ def _run_style(
293
+ style: Optional[Dict[str, Any]], scale: float, inherits: bool
294
+ ) -> Dict[str, Any]:
295
+ out = project_text_style(style, inherits)
296
+ if scale != 1.0 and "size" in out:
297
+ out["size"] = _pt(out["size"] * scale)
298
+ return out
299
+
300
+
301
+ def project_text(
302
+ text: Optional[Dict[str, Any]],
303
+ styles: StyleTable,
304
+ lists: ListTable,
305
+ glyphs: Optional[Dict[str, Dict[str, str]]] = None,
306
+ scale: float = 1.0,
307
+ para_defaults: Optional[Dict[str, Any]] = None,
308
+ inherits: bool = False,
309
+ ) -> List[Any]:
310
+ """A text body as a list of paragraphs, terminal newline implicit.
311
+
312
+ ``para_defaults`` are paragraph props the API reports on every paragraph of
313
+ a shape with no placeholder, which are omitted when they match.
314
+ ``inherits`` marks text in a placeholder, whose false and zero values are
315
+ overrides of its parent.
316
+ """
317
+ elements = (text or {}).get("textElements", [])
318
+ paragraphs: List[Dict[str, Any]] = []
319
+ current: Optional[Dict[str, Any]] = None
320
+
321
+ for te in elements:
322
+ if "paragraphMarker" in te:
323
+ marker = te["paragraphMarker"]
324
+ bullet = marker.get("bullet")
325
+ level = None
326
+ props: Dict[str, Any] = {}
327
+ if bullet is not None:
328
+ level = bullet.get("nestingLevel", 0)
329
+ alias = lists.ref(bullet.get("listId", ""))
330
+ props["bullet"] = {"list": alias, "level": level}
331
+ glyph = (bullet.get("glyph") or "").strip()
332
+ if glyphs is not None and glyph:
333
+ glyphs.setdefault(alias, {}).setdefault(str(level), glyph)
334
+ props.update(
335
+ _paragraph_props(
336
+ marker.get("style", {}), level, para_defaults, inherits
337
+ )
338
+ )
339
+ current = {"runs": [], "props": props}
340
+ paragraphs.append(current)
341
+ continue
342
+ if current is None:
343
+ current = {"runs": [], "props": {}}
344
+ paragraphs.append(current)
345
+ if "textRun" in te:
346
+ run = te["textRun"]
347
+ content = run.get("content", "")
348
+ if content.endswith("\n"):
349
+ content = content[:-1]
350
+ if not content:
351
+ continue
352
+ style = _run_style(run.get("style"), scale, inherits)
353
+ current["runs"].append((content, style))
354
+ elif "autoText" in te:
355
+ auto = te["autoText"]
356
+ style = _run_style(auto.get("style"), scale, inherits)
357
+ current["runs"].append(({"auto": auto.get("type", "SLIDE_NUMBER")}, style))
358
+
359
+ out: List[Any] = []
360
+ for para in paragraphs:
361
+ runs: List[Any] = []
362
+ for content, style in _merge_runs(para["runs"]):
363
+ if isinstance(content, dict):
364
+ run_out = dict(content)
365
+ if style:
366
+ run_out["s"] = styles.ref(style)
367
+ runs.append(run_out)
368
+ elif style:
369
+ runs.append({"text": content, "s": styles.ref(style)})
370
+ else:
371
+ runs.append(content)
372
+ props = para["props"]
373
+ if not props and len(runs) <= 1:
374
+ if not runs:
375
+ out.append("")
376
+ elif isinstance(runs[0], str):
377
+ out.append(runs[0])
378
+ else:
379
+ out.append(runs[0] if "auto" not in runs[0] else {"runs": runs})
380
+ continue
381
+ if len(runs) == 1 and isinstance(runs[0], dict) and "text" in runs[0]:
382
+ out.append({**runs[0], **props})
383
+ elif len(runs) == 1 and isinstance(runs[0], str):
384
+ out.append({"text": runs[0], **props})
385
+ elif not runs:
386
+ out.append({"text": "", **props})
387
+ else:
388
+ out.append({"runs": runs, **props})
389
+ # An empty body is [""]; a body that is only an empty paragraph is too.
390
+ return out or [""]
391
+
392
+
393
+ def _merge_runs(
394
+ runs: Iterable[Tuple[Any, Dict[str, Any]]],
395
+ ) -> List[Tuple[Any, Dict[str, Any]]]:
396
+ merged: List[Tuple[Any, Dict[str, Any]]] = []
397
+ for content, style in runs:
398
+ if (
399
+ merged
400
+ and isinstance(content, str)
401
+ and isinstance(merged[-1][0], str)
402
+ and merged[-1][1] == style
403
+ ):
404
+ merged[-1] = (merged[-1][0] + content, style)
405
+ else:
406
+ merged.append((content, style))
407
+ return merged
408
+
409
+
410
+ # --- Elements ---------------------------------------------------------------
411
+
412
+
413
+ def _solid(solid: Dict[str, Any]) -> Any:
414
+ """A solid fill: a colour, {"color", "alpha"} when translucent, or "none".
415
+
416
+ A fill with alpha 0 draws nothing, so it reads as "none", the same as a
417
+ fill that is not rendered.
418
+ """
419
+ alpha = solid.get("alpha", 1)
420
+ if alpha == 0:
421
+ return "none"
422
+ color = _color(solid.get("color"))
423
+ if not color:
424
+ return None
425
+ if alpha < 1:
426
+ return {"color": color, "alpha": _pt(alpha)}
427
+ return color
428
+
429
+
430
+ def _shape_props(props: Dict[str, Any]) -> Dict[str, Any]:
431
+ out: Dict[str, Any] = {}
432
+ fill = props.get("shapeBackgroundFill") or {}
433
+ state = fill.get("propertyState")
434
+ if state == "NOT_RENDERED":
435
+ out["fill"] = "none"
436
+ elif state != "INHERIT" and "solidFill" in fill:
437
+ solid = _solid(fill["solidFill"])
438
+ if solid:
439
+ out["fill"] = solid
440
+ outline = props.get("outline") or {}
441
+ state = outline.get("propertyState")
442
+ if state == "NOT_RENDERED":
443
+ out["outline"] = "none"
444
+ elif state != "INHERIT" and outline:
445
+ o: Dict[str, Any] = {}
446
+ solid = _solid((outline.get("outlineFill") or {}).get("solidFill", {}))
447
+ if solid == "none":
448
+ out["outline"] = "none"
449
+ elif isinstance(solid, dict):
450
+ o.update(solid)
451
+ elif solid:
452
+ o["color"] = solid
453
+ weight = _dim_pt(outline.get("weight"))
454
+ if weight is not None:
455
+ o["weight"] = weight
456
+ if outline.get("dashStyle") and outline["dashStyle"] != "SOLID":
457
+ o["dash"] = outline["dashStyle"]
458
+ if o and out.get("outline") != "none":
459
+ out["outline"] = o
460
+ if props.get("contentAlignment"):
461
+ out["content_align"] = props["contentAlignment"]
462
+ link = _link(props.get("link"))
463
+ if link:
464
+ out["link"] = link
465
+ autofit = props.get("autofit") or {}
466
+ kind = autofit.get("autofitType")
467
+ scale = autofit.get("fontScale", 1)
468
+ if kind == "SHAPE_AUTOFIT":
469
+ out["autofit"] = "grow"
470
+ elif kind == "TEXT_AUTOFIT" or (scale is not None and scale < 1):
471
+ # The slide shape reports the scale it is displayed at even when the
472
+ # shrink setting is inherited from its placeholder parent.
473
+ shrink: Dict[str, Any] = {"type": "shrink", "scale": _pt(scale)}
474
+ if autofit.get("lineSpacingReduction"):
475
+ shrink["line_spacing_reduction"] = _pt(autofit["lineSpacingReduction"])
476
+ out["autofit"] = shrink
477
+ return out
478
+
479
+
480
+ def iter_elements(
481
+ elements: Iterable[Dict[str, Any]], ancestors: Tuple[Dict[str, Any], ...] = ()
482
+ ) -> Iterator[Tuple[Dict[str, Any], Tuple[Dict[str, Any], ...]]]:
483
+ """Every page element in z-order, groups before their children, with the
484
+ groups it sits in (outermost first). The one walker the Slides tools use."""
485
+ for el in elements:
486
+ yield el, ancestors
487
+ children = (el.get("elementGroup") or {}).get("children", [])
488
+ if children:
489
+ yield from iter_elements(children, ancestors + (el,))
490
+
491
+
492
+ def placeholder_key(el: Dict[str, Any]) -> Optional[str]:
493
+ """A placeholder's type, with its index when the layout repeats the type."""
494
+ ph = (el.get("shape") or {}).get("placeholder")
495
+ if not ph:
496
+ return None
497
+ return f"{ph.get('type')}:{ph['index']}" if ph.get("index") else ph.get("type")
498
+
499
+
500
+ def element_kind(el: Dict[str, Any]) -> str:
501
+ for api, kind in (
502
+ ("shape", "shape"),
503
+ ("table", "table"),
504
+ ("image", "image"),
505
+ ("line", "line"),
506
+ ("elementGroup", "group"),
507
+ ("sheetsChart", "chart"),
508
+ ("video", "video"),
509
+ ("wordArt", "wordArt"),
510
+ ("speakerSpotlight", "speakerSpotlight"),
511
+ ):
512
+ if api in el:
513
+ return kind
514
+ return "unknown"
515
+
516
+
517
+ def _bullet_shorthand(body: List[Any]) -> List[Any]:
518
+ """``"bullet": level`` when every bulleted paragraph is in one list."""
519
+ lists = {
520
+ p["bullet"]["list"]
521
+ for p in body
522
+ if isinstance(p, dict) and isinstance(p.get("bullet"), dict)
523
+ }
524
+ if len(lists) != 1:
525
+ return body
526
+ return [
527
+ {**p, "bullet": p["bullet"]["level"]}
528
+ if isinstance(p, dict) and isinstance(p.get("bullet"), dict)
529
+ else p
530
+ for p in body
531
+ ]
532
+
533
+
534
+ class Projector:
535
+ def __init__(self) -> None:
536
+ self.styles = StyleTable()
537
+ self.lists = ListTable()
538
+
539
+ def element(
540
+ self,
541
+ el: Dict[str, Any],
542
+ parent: Tuple[float, ...] = (1, 0, 0, 1, 0, 0),
543
+ group_id: Optional[str] = None,
544
+ ) -> Dict[str, Any]:
545
+ matrix = _compose(parent, _matrix(el.get("transform")))
546
+ kind = element_kind(el)
547
+ # A shape's kind is implied by its "shape" type; other kinds name it.
548
+ out: Dict[str, Any] = {"id": el.get("objectId")}
549
+ if kind != "shape":
550
+ out["kind"] = kind
551
+ if group_id:
552
+ out["group"] = group_id
553
+
554
+ if kind == "group":
555
+ out["children"] = [
556
+ self.element(child, matrix)
557
+ for child in el["elementGroup"].get("children", [])
558
+ ]
559
+ elif kind == "table":
560
+ out.update(self._table(el, matrix))
561
+ else:
562
+ out["box"] = project_box(matrix, el.get("size"))
563
+
564
+ if kind == "shape":
565
+ shape = el["shape"]
566
+ shape_type = shape.get("shapeType")
567
+ # No "shape" means TEXT_BOX, the commonest type.
568
+ if shape_type != "TEXT_BOX":
569
+ out["shape"] = shape_type
570
+ ph = shape.get("placeholder")
571
+ if ph:
572
+ out["placeholder"] = placeholder_key(el)
573
+ props = _shape_props(shape.get("shapeProperties", {}))
574
+ if not ph:
575
+ # A shape with no placeholder parent reports the editor's
576
+ # default for a new shape: only a change from it is information.
577
+ default_align = (
578
+ "TOP" if shape.get("shapeType") == "TEXT_BOX" else "MIDDLE"
579
+ )
580
+ if props.get("content_align") == default_align:
581
+ props.pop("content_align")
582
+ if shape.get("shapeType") == "TEXT_BOX":
583
+ # New text boxes have no fill and no outline.
584
+ for key in ("fill", "outline"):
585
+ if props.get(key) == "none":
586
+ props.pop(key)
587
+ scale = 1.0
588
+ af = props.get("autofit")
589
+ if isinstance(af, dict):
590
+ scale = af.get("scale", 1.0) or 1.0
591
+ out.update(props)
592
+ if "text" in shape:
593
+ glyphs: Dict[str, Dict[str, str]] = {}
594
+ para_defaults = None
595
+ if not ph:
596
+ # Resolved values the API reports on a shape with no
597
+ # placeholder: the editor's defaults.
598
+ para_defaults = {
599
+ "align": "START" if shape_type == "TEXT_BOX" else "CENTER",
600
+ "line_spacing": 100,
601
+ }
602
+ out["text"] = _bullet_shorthand(
603
+ project_text(
604
+ shape["text"],
605
+ self.styles,
606
+ self.lists,
607
+ glyphs,
608
+ scale,
609
+ para_defaults,
610
+ inherits=bool(ph),
611
+ )
612
+ )
613
+ if glyphs:
614
+ out["lists"] = {k: {"glyphs": v} for k, v in glyphs.items()}
615
+ elif kind == "image":
616
+ src = el["image"].get("sourceUrl")
617
+ if src:
618
+ out["src"] = src
619
+ elif kind == "line":
620
+ category = el["line"].get("lineCategory")
621
+ if category and category != "STRAIGHT":
622
+ out["category"] = category
623
+
624
+ alt = {}
625
+ if el.get("title"):
626
+ alt["title"] = el["title"]
627
+ if el.get("description"):
628
+ alt["description"] = el["description"]
629
+ if alt:
630
+ out["alt"] = alt
631
+ out["v"] = version(out, self.styles.entries)
632
+ return {"id": out.pop("id"), "v": out.pop("v"), **out}
633
+
634
+ def _table(self, el: Dict[str, Any], matrix: Tuple[float, ...]) -> Dict[str, Any]:
635
+ table = el["table"]
636
+ a, b, c, d, tx, ty = matrix
637
+ out: Dict[str, Any] = {
638
+ "box": {"x": _geo_pt(tx / EMU_PER_PT), "y": _geo_pt(ty / EMU_PER_PT)},
639
+ "col_widths": [
640
+ _geo_pt(_dim_pt(col.get("columnWidth")) or 0)
641
+ for col in table.get("tableColumns", [])
642
+ ],
643
+ "row_heights": [
644
+ _geo_pt(_dim_pt(row.get("rowHeight")) or 0)
645
+ for row in table.get("tableRows", [])
646
+ ],
647
+ "columns": list(range(table.get("columns", 0))),
648
+ }
649
+ covered = set()
650
+ rows = []
651
+ for r, row in enumerate(table.get("tableRows", [])):
652
+ # The API returns a merged cell once and omits the cells it covers.
653
+ cells: List[Any] = [None] * table.get("columns", 0)
654
+ for cell in row.get("tableCells", []):
655
+ loc = cell.get("location", {})
656
+ key = (loc.get("rowIndex", r), loc.get("columnIndex", 0))
657
+ if key in covered:
658
+ continue
659
+ body = project_text(cell.get("text"), self.styles, self.lists)
660
+ rs, cs = cell.get("rowSpan", 1), cell.get("columnSpan", 1)
661
+ if rs > 1 or cs > 1:
662
+ for i in range(rs):
663
+ for j in range(cs):
664
+ if i or j:
665
+ covered.add((key[0] + i, key[1] + j))
666
+ if rs > 1 or cs > 1:
667
+ cells[key[1]] = {"text": body, "span": [rs, cs]}
668
+ elif len(body) == 1 and isinstance(body[0], str):
669
+ cells[key[1]] = body[0]
670
+ else:
671
+ cells[key[1]] = {"text": body}
672
+ rows.append({"r": r, "cells": cells})
673
+ out["rows"] = rows
674
+ return out
675
+
676
+
677
+ def _resolve(
678
+ value: Any,
679
+ styles: Dict[str, Dict[str, Any]],
680
+ lists: Optional[Dict[str, Any]] = None,
681
+ ) -> Any:
682
+ """Canonical form: style aliases resolved, string and object runs unified,
683
+ and each bullet's list alias replaced by the glyph it renders."""
684
+ if isinstance(value, dict):
685
+ lists = value.get("lists", lists)
686
+ out = {}
687
+ for k, v in value.items():
688
+ if k in ("v", "group", "lists"):
689
+ continue
690
+ if k == "s" and isinstance(v, str):
691
+ out.update(styles.get(v, {}))
692
+ elif k == "bullet":
693
+ alias, level = (
694
+ (next(iter(lists or {}), None), v)
695
+ if isinstance(v, int)
696
+ else (v.get("list"), v.get("level"))
697
+ )
698
+ glyphs = (lists or {}).get(alias, {}).get("glyphs", {})
699
+ out["bullet"] = {"level": level, "glyph": glyphs.get(str(level))}
700
+ else:
701
+ out[k] = _resolve(v, styles, lists)
702
+ return out
703
+ if isinstance(value, list):
704
+ return [_resolve(v, styles, lists) for v in value]
705
+ return value
706
+
707
+
708
+ def version(element: Dict[str, Any], styles: Dict[str, Dict[str, Any]]) -> str:
709
+ canonical = json.dumps(
710
+ _resolve(element, styles), sort_keys=True, separators=(",", ":")
711
+ )
712
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:8]
713
+
714
+
715
+ def project_page(
716
+ page: Dict[str, Any],
717
+ page_size: Optional[Dict[str, Any]] = None,
718
+ targets: Optional[List[str]] = None,
719
+ ) -> Dict[str, Any]:
720
+ """The editable projection of a page, whole or scoped to ``targets``.
721
+
722
+ ``targets`` are element IDs and ``"notes"``. A target inside a group comes
723
+ back with absolute geometry and its ``group`` ID; a target that is a group
724
+ comes back with its descendants.
725
+ """
726
+ proj = Projector()
727
+ out: Dict[str, Any] = {"page_id": page.get("objectId")}
728
+ if page_size:
729
+ out["page_size"] = {
730
+ "w": _dim_pt(page_size.get("width")),
731
+ "h": _dim_pt(page_size.get("height")),
732
+ }
733
+ elements = page.get("pageElements", [])
734
+ if targets is None:
735
+ out["elements"] = [proj.element(el) for el in elements]
736
+ want_notes = True
737
+ else:
738
+ wanted = set(targets)
739
+ out["elements"] = []
740
+ for el, ancestors in iter_elements(elements):
741
+ if el.get("objectId") not in wanted or any(
742
+ group.get("objectId") in wanted for group in ancestors
743
+ ):
744
+ continue
745
+ parent: Tuple[float, ...] = (1, 0, 0, 1, 0, 0)
746
+ for group in ancestors:
747
+ parent = _compose(parent, _matrix(group.get("transform")))
748
+ group_id = ancestors[-1].get("objectId") if ancestors else None
749
+ out["elements"].append(proj.element(el, parent, group_id))
750
+ want_notes = "notes" in wanted
751
+
752
+ if want_notes:
753
+ notes_page = (page.get("slideProperties") or {}).get("notesPage") or {}
754
+ notes_id = (notes_page.get("notesProperties") or {}).get("speakerNotesObjectId")
755
+ for el in notes_page.get("pageElements", []):
756
+ if el.get("objectId") == notes_id and "shape" in el:
757
+ body = project_text(
758
+ el["shape"].get("text"), proj.styles, proj.lists, inherits=True
759
+ )
760
+ if body != [""]:
761
+ notes = {"text": body}
762
+ out["notes"] = {"v": version(notes, proj.styles.entries), **notes}
763
+ styles = proj.styles.entries
764
+ if styles:
765
+ return {
766
+ **{k: out[k] for k in ("page_id", "page_size") if k in out},
767
+ "styles": styles,
768
+ **{k: v for k, v in out.items() if k not in ("page_id", "page_size")},
769
+ }
770
+ return out